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": "hal.js (http://narwhaljs.org)\n# Copyright (c) 2009 Thomas Robinson <280north.com>\n#\n# Permission is hereby granted, ",
"end": 193,
"score": 0.9998441338539124,
"start": 178,
"tag": "NAME",
"value": "Thomas Robinson"
},
{
"context": "haljs.org)\n# Copyright (c) 2009 T... | lib/assert.coffee | lxe/io.coffee | 0 | # http://wiki.commonjs.org/wiki/Unit_Testing/1.0
#
# THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
#
# Originally from narwhal.js (http://narwhaljs.org)
# Copyright (c) 2009 Thomas Robinson <280north.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS 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.
# UTILITY
# 1. The assert module provides functions that throw
# AssertionError's when particular conditions are not met. The
# assert module must conform to the following interface.
# 2. The AssertionError is defined in assert.
# new assert.AssertionError({ message: message,
# actual: actual,
# expected: expected })
# assert.AssertionError instanceof Error
replacer = (key, value) ->
return "" + value if util.isUndefined(value)
return value.toString() if util.isNumber(value) and not isFinite(value)
return value.toString() if util.isFunction(value) or util.isRegExp(value)
value
truncate = (s, n) ->
if util.isString(s)
(if s.length < n then s else s.slice(0, n))
else
s
getMessage = (self) ->
truncate(JSON.stringify(self.actual, replacer), 128) + " " + self.operator + " " + truncate(JSON.stringify(self.expected, replacer), 128)
# At present only the three keys mentioned above are used and
# understood by the spec. Implementations or sub modules can pass
# other keys to the AssertionError's constructor - they will be
# ignored.
# 3. All of the following functions must throw an AssertionError
# when a corresponding condition is not met, with a message that
# may be undefined if not provided. All assertion methods provide
# both the actual and expected values to the assertion error for
# display purposes.
fail = (actual, expected, message, operator, stackStartFunction) ->
throw new assert.AssertionError(
message: message
actual: actual
expected: expected
operator: operator
stackStartFunction: stackStartFunction
)return
# EXTENSION! allows for well behaved errors defined elsewhere.
# 4. Pure assertion tests whether a value is truthy, as determined
# by !!guard.
# assert.ok(guard, message_opt);
# This statement is equivalent to assert.equal(true, !!guard,
# message_opt);. To test strictly for the value true, use
# assert.strictEqual(true, guard, message_opt);.
ok = (value, message) ->
fail value, true, message, "==", assert.ok unless value
return
# 5. The equality assertion tests shallow, coercive equality with
# ==.
# assert.equal(actual, expected, message_opt);
# 6. The non-equality assertion tests for whether two objects are not equal
# with != assert.notEqual(actual, expected, message_opt);
# 7. The equivalence assertion tests a deep equality relation.
# assert.deepEqual(actual, expected, message_opt);
_deepEqual = (actual, expected) ->
# 7.1. All identical values are equivalent, as determined by ===.
if actual is expected
true
else if util.isBuffer(actual) and util.isBuffer(expected)
return false unless actual.length is expected.length
i = 0
while i < actual.length
return false if actual[i] isnt expected[i]
i++
true
# 7.2. If the expected value is a Date object, the actual value is
# equivalent if it is also a Date object that refers to the same time.
else if util.isDate(actual) and util.isDate(expected)
actual.getTime() is expected.getTime()
# 7.3 If the expected value is a RegExp object, the actual value is
# equivalent if it is also a RegExp object with the same source and
# properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
else if util.isRegExp(actual) and util.isRegExp(expected)
actual.source is expected.source and actual.global is expected.global and actual.multiline is expected.multiline and actual.lastIndex is expected.lastIndex and actual.ignoreCase is expected.ignoreCase
# 7.4. Other pairs that do not both pass typeof value == 'object',
# equivalence is determined by ==.
else if not util.isObject(actual) and not util.isObject(expected)
actual is expected
# 7.5 For all other Object pairs, including Array objects, equivalence is
# determined by having the same number of owned properties (as verified
# with Object.prototype.hasOwnProperty.call), the same set of keys
# (although not necessarily the same order), equivalent values for every
# corresponding key, and an identical 'prototype' property. Note: this
# accounts for both named and indexed properties on Arrays.
else
objEquiv actual, expected
isArguments = (object) ->
Object::toString.call(object) is "[object Arguments]"
objEquiv = (a, b) ->
return false if util.isNullOrUndefined(a) or util.isNullOrUndefined(b)
# an identical 'prototype' property.
return false if a:: isnt b::
#~~~I've managed to break Object.keys through screwy arguments passing.
# Converting to array solves the problem.
aIsArgs = isArguments(a)
bIsArgs = isArguments(b)
return false if (aIsArgs and not bIsArgs) or (not aIsArgs and bIsArgs)
if aIsArgs
a = pSlice.call(a)
b = pSlice.call(b)
return _deepEqual(a, b)
try
ka = Object.keys(a)
kb = Object.keys(b)
key = undefined
i = undefined
catch e #happens when one is a string literal and the other isn't
return false
# having the same number of owned properties (keys incorporates
# hasOwnProperty)
return false unless ka.length is kb.length
#the same set of keys (although not necessarily the same order),
ka.sort()
kb.sort()
#~~~cheap key test
i = ka.length - 1
while i >= 0
return false unless ka[i] is kb[i]
i--
#equivalent values for every corresponding key, and
#~~~possibly expensive deep test
i = ka.length - 1
while i >= 0
key = ka[i]
return false unless _deepEqual(a[key], b[key])
i--
true
# 8. The non-equivalence assertion tests for any deep inequality.
# assert.notDeepEqual(actual, expected, message_opt);
# 9. The strict equality assertion tests strict equality, as determined by ===.
# assert.strictEqual(actual, expected, message_opt);
# 10. The strict non-equality assertion tests for strict inequality, as
# determined by !==. assert.notStrictEqual(actual, expected, message_opt);
expectedException = (actual, expected) ->
return false if not actual or not expected
if Object::toString.call(expected) is "[object RegExp]"
return expected.test(actual)
else if actual instanceof expected
return true
else return true if expected.call({}, actual) is true
false
_throws = (shouldThrow, block, expected, message) ->
actual = undefined
if util.isString(expected)
message = expected
expected = null
try
block()
catch e
actual = e
message = ((if expected and expected.name then " (" + expected.name + ")." else ".")) + ((if message then " " + message else "."))
fail actual, expected, "Missing expected exception" + message if shouldThrow and not actual
fail actual, expected, "Got unwanted exception" + message if not shouldThrow and expectedException(actual, expected)
throw actual if (shouldThrow and actual and expected and not expectedException(actual, expected)) or (not shouldThrow and actual)
return
"use strict"
util = require("util")
pSlice = Array::slice
assert = module.exports = ok
assert.AssertionError = AssertionError = (options) ->
@name = "AssertionError"
@actual = options.actual
@expected = options.expected
@operator = options.operator
if options.message
@message = options.message
@generatedMessage = false
else
@message = getMessage(this)
@generatedMessage = true
stackStartFunction = options.stackStartFunction or fail
Error.captureStackTrace this, stackStartFunction
return
util.inherits assert.AssertionError, Error
assert.fail = fail
assert.ok = ok
assert.equal = equal = (actual, expected, message) ->
fail actual, expected, message, "==", assert.equal unless actual is expected
return
assert.notEqual = notEqual = (actual, expected, message) ->
fail actual, expected, message, "!=", assert.notEqual if actual is expected
return
assert.deepEqual = deepEqual = (actual, expected, message) ->
fail actual, expected, message, "deepEqual", assert.deepEqual unless _deepEqual(actual, expected)
return
assert.notDeepEqual = notDeepEqual = (actual, expected, message) ->
fail actual, expected, message, "notDeepEqual", assert.notDeepEqual if _deepEqual(actual, expected)
return
assert.strictEqual = strictEqual = (actual, expected, message) ->
fail actual, expected, message, "===", assert.strictEqual if actual isnt expected
return
assert.notStrictEqual = notStrictEqual = (actual, expected, message) ->
fail actual, expected, message, "!==", assert.notStrictEqual if actual is expected
return
# 11. Expected to throw an error:
# assert.throws(block, Error_opt, message_opt);
assert.throws = (block, error, message) -> #optional
#optional
_throws.apply this, [true].concat(pSlice.call(arguments))
return
# EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = (block, message) -> #optional
_throws.apply this, [false].concat(pSlice.call(arguments))
return
assert.ifError = (err) ->
throw err if err
return
| 210526 | # http://wiki.commonjs.org/wiki/Unit_Testing/1.0
#
# THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
#
# Originally from narwhal.js (http://narwhaljs.org)
# Copyright (c) 2009 <NAME> <2<EMAIL>>
#
# 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 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.
# UTILITY
# 1. The assert module provides functions that throw
# AssertionError's when particular conditions are not met. The
# assert module must conform to the following interface.
# 2. The AssertionError is defined in assert.
# new assert.AssertionError({ message: message,
# actual: actual,
# expected: expected })
# assert.AssertionError instanceof Error
replacer = (key, value) ->
return "" + value if util.isUndefined(value)
return value.toString() if util.isNumber(value) and not isFinite(value)
return value.toString() if util.isFunction(value) or util.isRegExp(value)
value
truncate = (s, n) ->
if util.isString(s)
(if s.length < n then s else s.slice(0, n))
else
s
getMessage = (self) ->
truncate(JSON.stringify(self.actual, replacer), 128) + " " + self.operator + " " + truncate(JSON.stringify(self.expected, replacer), 128)
# At present only the three keys mentioned above are used and
# understood by the spec. Implementations or sub modules can pass
# other keys to the AssertionError's constructor - they will be
# ignored.
# 3. All of the following functions must throw an AssertionError
# when a corresponding condition is not met, with a message that
# may be undefined if not provided. All assertion methods provide
# both the actual and expected values to the assertion error for
# display purposes.
fail = (actual, expected, message, operator, stackStartFunction) ->
throw new assert.AssertionError(
message: message
actual: actual
expected: expected
operator: operator
stackStartFunction: stackStartFunction
)return
# EXTENSION! allows for well behaved errors defined elsewhere.
# 4. Pure assertion tests whether a value is truthy, as determined
# by !!guard.
# assert.ok(guard, message_opt);
# This statement is equivalent to assert.equal(true, !!guard,
# message_opt);. To test strictly for the value true, use
# assert.strictEqual(true, guard, message_opt);.
ok = (value, message) ->
fail value, true, message, "==", assert.ok unless value
return
# 5. The equality assertion tests shallow, coercive equality with
# ==.
# assert.equal(actual, expected, message_opt);
# 6. The non-equality assertion tests for whether two objects are not equal
# with != assert.notEqual(actual, expected, message_opt);
# 7. The equivalence assertion tests a deep equality relation.
# assert.deepEqual(actual, expected, message_opt);
_deepEqual = (actual, expected) ->
# 7.1. All identical values are equivalent, as determined by ===.
if actual is expected
true
else if util.isBuffer(actual) and util.isBuffer(expected)
return false unless actual.length is expected.length
i = 0
while i < actual.length
return false if actual[i] isnt expected[i]
i++
true
# 7.2. If the expected value is a Date object, the actual value is
# equivalent if it is also a Date object that refers to the same time.
else if util.isDate(actual) and util.isDate(expected)
actual.getTime() is expected.getTime()
# 7.3 If the expected value is a RegExp object, the actual value is
# equivalent if it is also a RegExp object with the same source and
# properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
else if util.isRegExp(actual) and util.isRegExp(expected)
actual.source is expected.source and actual.global is expected.global and actual.multiline is expected.multiline and actual.lastIndex is expected.lastIndex and actual.ignoreCase is expected.ignoreCase
# 7.4. Other pairs that do not both pass typeof value == 'object',
# equivalence is determined by ==.
else if not util.isObject(actual) and not util.isObject(expected)
actual is expected
# 7.5 For all other Object pairs, including Array objects, equivalence is
# determined by having the same number of owned properties (as verified
# with Object.prototype.hasOwnProperty.call), the same set of keys
# (although not necessarily the same order), equivalent values for every
# corresponding key, and an identical 'prototype' property. Note: this
# accounts for both named and indexed properties on Arrays.
else
objEquiv actual, expected
isArguments = (object) ->
Object::toString.call(object) is "[object Arguments]"
objEquiv = (a, b) ->
return false if util.isNullOrUndefined(a) or util.isNullOrUndefined(b)
# an identical 'prototype' property.
return false if a:: isnt b::
#~~~I've managed to break Object.keys through screwy arguments passing.
# Converting to array solves the problem.
aIsArgs = isArguments(a)
bIsArgs = isArguments(b)
return false if (aIsArgs and not bIsArgs) or (not aIsArgs and bIsArgs)
if aIsArgs
a = pSlice.call(a)
b = pSlice.call(b)
return _deepEqual(a, b)
try
ka = Object.keys(a)
kb = Object.keys(b)
key = undefined
i = undefined
catch e #happens when one is a string literal and the other isn't
return false
# having the same number of owned properties (keys incorporates
# hasOwnProperty)
return false unless ka.length is kb.length
#the same set of keys (although not necessarily the same order),
ka.sort()
kb.sort()
#~~~cheap key test
i = ka.length - 1
while i >= 0
return false unless ka[i] is kb[i]
i--
#equivalent values for every corresponding key, and
#~~~possibly expensive deep test
i = ka.length - 1
while i >= 0
key = ka[i]
return false unless _deepEqual(a[key], b[key])
i--
true
# 8. The non-equivalence assertion tests for any deep inequality.
# assert.notDeepEqual(actual, expected, message_opt);
# 9. The strict equality assertion tests strict equality, as determined by ===.
# assert.strictEqual(actual, expected, message_opt);
# 10. The strict non-equality assertion tests for strict inequality, as
# determined by !==. assert.notStrictEqual(actual, expected, message_opt);
expectedException = (actual, expected) ->
return false if not actual or not expected
if Object::toString.call(expected) is "[object RegExp]"
return expected.test(actual)
else if actual instanceof expected
return true
else return true if expected.call({}, actual) is true
false
_throws = (shouldThrow, block, expected, message) ->
actual = undefined
if util.isString(expected)
message = expected
expected = null
try
block()
catch e
actual = e
message = ((if expected and expected.name then " (" + expected.name + ")." else ".")) + ((if message then " " + message else "."))
fail actual, expected, "Missing expected exception" + message if shouldThrow and not actual
fail actual, expected, "Got unwanted exception" + message if not shouldThrow and expectedException(actual, expected)
throw actual if (shouldThrow and actual and expected and not expectedException(actual, expected)) or (not shouldThrow and actual)
return
"use strict"
util = require("util")
pSlice = Array::slice
assert = module.exports = ok
assert.AssertionError = AssertionError = (options) ->
@name = "AssertionError"
@actual = options.actual
@expected = options.expected
@operator = options.operator
if options.message
@message = options.message
@generatedMessage = false
else
@message = getMessage(this)
@generatedMessage = true
stackStartFunction = options.stackStartFunction or fail
Error.captureStackTrace this, stackStartFunction
return
util.inherits assert.AssertionError, Error
assert.fail = fail
assert.ok = ok
assert.equal = equal = (actual, expected, message) ->
fail actual, expected, message, "==", assert.equal unless actual is expected
return
assert.notEqual = notEqual = (actual, expected, message) ->
fail actual, expected, message, "!=", assert.notEqual if actual is expected
return
assert.deepEqual = deepEqual = (actual, expected, message) ->
fail actual, expected, message, "deepEqual", assert.deepEqual unless _deepEqual(actual, expected)
return
assert.notDeepEqual = notDeepEqual = (actual, expected, message) ->
fail actual, expected, message, "notDeepEqual", assert.notDeepEqual if _deepEqual(actual, expected)
return
assert.strictEqual = strictEqual = (actual, expected, message) ->
fail actual, expected, message, "===", assert.strictEqual if actual isnt expected
return
assert.notStrictEqual = notStrictEqual = (actual, expected, message) ->
fail actual, expected, message, "!==", assert.notStrictEqual if actual is expected
return
# 11. Expected to throw an error:
# assert.throws(block, Error_opt, message_opt);
assert.throws = (block, error, message) -> #optional
#optional
_throws.apply this, [true].concat(pSlice.call(arguments))
return
# EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = (block, message) -> #optional
_throws.apply this, [false].concat(pSlice.call(arguments))
return
assert.ifError = (err) ->
throw err if err
return
| true | # http://wiki.commonjs.org/wiki/Unit_Testing/1.0
#
# THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
#
# Originally from narwhal.js (http://narwhaljs.org)
# Copyright (c) 2009 PI:NAME:<NAME>END_PI <2PI:EMAIL:<EMAIL>END_PI>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the 'Software'), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS 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.
# UTILITY
# 1. The assert module provides functions that throw
# AssertionError's when particular conditions are not met. The
# assert module must conform to the following interface.
# 2. The AssertionError is defined in assert.
# new assert.AssertionError({ message: message,
# actual: actual,
# expected: expected })
# assert.AssertionError instanceof Error
replacer = (key, value) ->
return "" + value if util.isUndefined(value)
return value.toString() if util.isNumber(value) and not isFinite(value)
return value.toString() if util.isFunction(value) or util.isRegExp(value)
value
truncate = (s, n) ->
if util.isString(s)
(if s.length < n then s else s.slice(0, n))
else
s
getMessage = (self) ->
truncate(JSON.stringify(self.actual, replacer), 128) + " " + self.operator + " " + truncate(JSON.stringify(self.expected, replacer), 128)
# At present only the three keys mentioned above are used and
# understood by the spec. Implementations or sub modules can pass
# other keys to the AssertionError's constructor - they will be
# ignored.
# 3. All of the following functions must throw an AssertionError
# when a corresponding condition is not met, with a message that
# may be undefined if not provided. All assertion methods provide
# both the actual and expected values to the assertion error for
# display purposes.
fail = (actual, expected, message, operator, stackStartFunction) ->
throw new assert.AssertionError(
message: message
actual: actual
expected: expected
operator: operator
stackStartFunction: stackStartFunction
)return
# EXTENSION! allows for well behaved errors defined elsewhere.
# 4. Pure assertion tests whether a value is truthy, as determined
# by !!guard.
# assert.ok(guard, message_opt);
# This statement is equivalent to assert.equal(true, !!guard,
# message_opt);. To test strictly for the value true, use
# assert.strictEqual(true, guard, message_opt);.
ok = (value, message) ->
fail value, true, message, "==", assert.ok unless value
return
# 5. The equality assertion tests shallow, coercive equality with
# ==.
# assert.equal(actual, expected, message_opt);
# 6. The non-equality assertion tests for whether two objects are not equal
# with != assert.notEqual(actual, expected, message_opt);
# 7. The equivalence assertion tests a deep equality relation.
# assert.deepEqual(actual, expected, message_opt);
_deepEqual = (actual, expected) ->
# 7.1. All identical values are equivalent, as determined by ===.
if actual is expected
true
else if util.isBuffer(actual) and util.isBuffer(expected)
return false unless actual.length is expected.length
i = 0
while i < actual.length
return false if actual[i] isnt expected[i]
i++
true
# 7.2. If the expected value is a Date object, the actual value is
# equivalent if it is also a Date object that refers to the same time.
else if util.isDate(actual) and util.isDate(expected)
actual.getTime() is expected.getTime()
# 7.3 If the expected value is a RegExp object, the actual value is
# equivalent if it is also a RegExp object with the same source and
# properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
else if util.isRegExp(actual) and util.isRegExp(expected)
actual.source is expected.source and actual.global is expected.global and actual.multiline is expected.multiline and actual.lastIndex is expected.lastIndex and actual.ignoreCase is expected.ignoreCase
# 7.4. Other pairs that do not both pass typeof value == 'object',
# equivalence is determined by ==.
else if not util.isObject(actual) and not util.isObject(expected)
actual is expected
# 7.5 For all other Object pairs, including Array objects, equivalence is
# determined by having the same number of owned properties (as verified
# with Object.prototype.hasOwnProperty.call), the same set of keys
# (although not necessarily the same order), equivalent values for every
# corresponding key, and an identical 'prototype' property. Note: this
# accounts for both named and indexed properties on Arrays.
else
objEquiv actual, expected
isArguments = (object) ->
Object::toString.call(object) is "[object Arguments]"
objEquiv = (a, b) ->
return false if util.isNullOrUndefined(a) or util.isNullOrUndefined(b)
# an identical 'prototype' property.
return false if a:: isnt b::
#~~~I've managed to break Object.keys through screwy arguments passing.
# Converting to array solves the problem.
aIsArgs = isArguments(a)
bIsArgs = isArguments(b)
return false if (aIsArgs and not bIsArgs) or (not aIsArgs and bIsArgs)
if aIsArgs
a = pSlice.call(a)
b = pSlice.call(b)
return _deepEqual(a, b)
try
ka = Object.keys(a)
kb = Object.keys(b)
key = undefined
i = undefined
catch e #happens when one is a string literal and the other isn't
return false
# having the same number of owned properties (keys incorporates
# hasOwnProperty)
return false unless ka.length is kb.length
#the same set of keys (although not necessarily the same order),
ka.sort()
kb.sort()
#~~~cheap key test
i = ka.length - 1
while i >= 0
return false unless ka[i] is kb[i]
i--
#equivalent values for every corresponding key, and
#~~~possibly expensive deep test
i = ka.length - 1
while i >= 0
key = ka[i]
return false unless _deepEqual(a[key], b[key])
i--
true
# 8. The non-equivalence assertion tests for any deep inequality.
# assert.notDeepEqual(actual, expected, message_opt);
# 9. The strict equality assertion tests strict equality, as determined by ===.
# assert.strictEqual(actual, expected, message_opt);
# 10. The strict non-equality assertion tests for strict inequality, as
# determined by !==. assert.notStrictEqual(actual, expected, message_opt);
expectedException = (actual, expected) ->
return false if not actual or not expected
if Object::toString.call(expected) is "[object RegExp]"
return expected.test(actual)
else if actual instanceof expected
return true
else return true if expected.call({}, actual) is true
false
_throws = (shouldThrow, block, expected, message) ->
actual = undefined
if util.isString(expected)
message = expected
expected = null
try
block()
catch e
actual = e
message = ((if expected and expected.name then " (" + expected.name + ")." else ".")) + ((if message then " " + message else "."))
fail actual, expected, "Missing expected exception" + message if shouldThrow and not actual
fail actual, expected, "Got unwanted exception" + message if not shouldThrow and expectedException(actual, expected)
throw actual if (shouldThrow and actual and expected and not expectedException(actual, expected)) or (not shouldThrow and actual)
return
"use strict"
util = require("util")
pSlice = Array::slice
assert = module.exports = ok
assert.AssertionError = AssertionError = (options) ->
@name = "AssertionError"
@actual = options.actual
@expected = options.expected
@operator = options.operator
if options.message
@message = options.message
@generatedMessage = false
else
@message = getMessage(this)
@generatedMessage = true
stackStartFunction = options.stackStartFunction or fail
Error.captureStackTrace this, stackStartFunction
return
util.inherits assert.AssertionError, Error
assert.fail = fail
assert.ok = ok
assert.equal = equal = (actual, expected, message) ->
fail actual, expected, message, "==", assert.equal unless actual is expected
return
assert.notEqual = notEqual = (actual, expected, message) ->
fail actual, expected, message, "!=", assert.notEqual if actual is expected
return
assert.deepEqual = deepEqual = (actual, expected, message) ->
fail actual, expected, message, "deepEqual", assert.deepEqual unless _deepEqual(actual, expected)
return
assert.notDeepEqual = notDeepEqual = (actual, expected, message) ->
fail actual, expected, message, "notDeepEqual", assert.notDeepEqual if _deepEqual(actual, expected)
return
assert.strictEqual = strictEqual = (actual, expected, message) ->
fail actual, expected, message, "===", assert.strictEqual if actual isnt expected
return
assert.notStrictEqual = notStrictEqual = (actual, expected, message) ->
fail actual, expected, message, "!==", assert.notStrictEqual if actual is expected
return
# 11. Expected to throw an error:
# assert.throws(block, Error_opt, message_opt);
assert.throws = (block, error, message) -> #optional
#optional
_throws.apply this, [true].concat(pSlice.call(arguments))
return
# EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = (block, message) -> #optional
_throws.apply this, [false].concat(pSlice.call(arguments))
return
assert.ifError = (err) ->
throw err if err
return
|
[
{
"context": "# Droplet controller.\n#\n# Copyright (c) 2014 Anthony Bau (dab1998@gmail.com)\n# MIT License.\n\nhelper = requ",
"end": 56,
"score": 0.9998631477355957,
"start": 45,
"tag": "NAME",
"value": "Anthony Bau"
},
{
"context": "t controller.\n#\n# Copyright (c) 2014 Anthony B... | src/controller.coffee | jmkulwik/droplet | 0 | # Droplet controller.
#
# Copyright (c) 2014 Anthony Bau (dab1998@gmail.com)
# MIT License.
helper = require './helper.coffee'
draw = require './draw.coffee'
model = require './model.coffee'
view = require './view.coffee'
QUAD = require '../vendor/quadtree.js'
modes = require './modes.coffee'
# ## Magic constants
PALETTE_TOP_MARGIN = 5
PALETTE_MARGIN = 5
MIN_DRAG_DISTANCE = 1
PALETTE_LEFT_MARGIN = 5
DEFAULT_INDENT_DEPTH = ' '
ANIMATION_FRAME_RATE = 60
DISCOURAGE_DROP_TIMEOUT = 1000
MAX_DROP_DISTANCE = 100
CURSOR_WIDTH_DECREASE = 3
CURSOR_HEIGHT_DECREASE = 2
CURSOR_UNFOCUSED_OPACITY = 0.5
DEBUG_FLAG = false
DROPDOWN_SCROLLBAR_PADDING = 17
BACKSPACE_KEY = 8
TAB_KEY = 9
ENTER_KEY = 13
LEFT_ARROW_KEY = 37
UP_ARROW_KEY = 38
RIGHT_ARROW_KEY = 39
DOWN_ARROW_KEY = 40
Z_KEY = 90
Y_KEY = 89
META_KEYS = [91, 92, 93, 223, 224]
CONTROL_KEYS = [17, 162, 163]
GRAY_BLOCK_MARGIN = 5
GRAY_BLOCK_HANDLE_WIDTH = 15
GRAY_BLOCK_HANDLE_HEIGHT = 30
GRAY_BLOCK_COLOR = 'rgba(256, 256, 256, 0.5)'
GRAY_BLOCK_BORDER = '#AAA'
userAgent = ''
if typeof(window) isnt 'undefined' and window.navigator?.userAgent
userAgent = window.navigator.userAgent
isOSX = /OS X/.test(userAgent)
command_modifiers = if isOSX then META_KEYS else CONTROL_KEYS
command_pressed = (e) -> if isOSX then e.metaKey else e.ctrlKey
# FOUNDATION
# ================================
# ## Editor event bindings
#
# These are different events associated with the Editor
# that features will want to bind to.
unsortedEditorBindings = {
'populate': [] # after an empty editor is created
'resize': [] # after the window is resized
'resize_palette': [] # after the palette is resized
'redraw_main': [] # whenever we need to redraw the main canvas
'redraw_palette': [] # repaint the graphics of the palette
'rebuild_palette': [] # redraw the paltte, both graphics and elements
'mousedown': []
'mousemove': []
'mouseup': []
'dblclick': []
'keydown': []
'keyup': []
}
editorBindings = {}
SVG_STANDARD = helper.SVG_STANDARD
EMBOSS_FILTER_SVG = """
<svg xlmns="#{SVG_STANDARD}">
<filter id="dropShadow" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceAlpha" dx="5" dy="5" />
<feGaussianBlur result="blurOut" in="offOut" stdDeviation="1" />
<feBlend in="SourceGraphic" in2="blurOut" out="blendOut" mode="normal" />
<feComposite in="blendOut" in2="SourceGraphic" k2="0.5" k3="0.5" operator="arithmetic" />
</filter>
</svg>
"""
# This hook function is for convenience,
# for features to add events that will occur at
# various times in the editor lifecycle.
hook = (event, priority, fn) ->
unsortedEditorBindings[event].push {
priority: priority
fn: fn
}
class Session
constructor: (_main, _palette, _drag, @options, standardViewSettings) -> # TODO rearchitecture so that a session is independent of elements again
# Option flags
@readOnly = false
@paletteGroups = @options.palette
@showPaletteInTextMode = @options.showPaletteInTextMode ? false
@paletteEnabled = @options.enablePaletteAtStart ? true
@dropIntoAceAtLineStart = @options.dropIntoAceAtLineStart ? false
@allowFloatingBlocks = @options.allowFloatingBlocks ? true
# By default, attempt to preserve empty sockets when round-tripping
@options.preserveEmpty ?= true
# Mode
@options.mode = @options.mode.replace /$\/ace\/mode\//, ''
if @options.mode of modes
@mode = new modes[@options.mode] @options.modeOptions
else
@mode = null
# Instantiate an Droplet editor view
@view = new view.View _main, helper.extend standardViewSettings, @options.viewSettings ? {}
@paletteView = new view.View _palette, helper.extend {}, standardViewSettings, @options.viewSettings ? {}, {
showDropdowns: @options.showDropdownInPalette ? false
}
@dragView = new view.View _drag, helper.extend {}, standardViewSettings, @options.viewSettings ? {}
# ## Document initialization
# We start off with an empty document
@tree = new model.Document(@rootContext)
# Line markings
@markedLines = {}
@markedBlocks = {}; @nextMarkedBlockId = 0
@extraMarks = {}
# Undo/redo stack
@undoStack = []
@redoStack = []
@changeEventVersion = 0
# Floating blocks
@floatingBlocks = []
# Cursor
@cursor = new CrossDocumentLocation(0, new model.Location(0, 'documentStart'))
# Scrolling
@viewports = {
main: new draw.Rectangle 0, 0, 0, 0
palette: new draw.Rectangle 0, 0, 0, 0
}
# Block toggle
@currentlyUsingBlocks = true
# Fonts
@fontSize = 15
@fontFamily = 'Courier New'
metrics = helper.fontMetrics(@fontFamily, @fontSize)
@fontAscent = metrics.prettytop
@fontDescent = metrics.descent
@fontWidth = @view.draw.measureCtx.measureText(' ').width
# Remembered sockets
@rememberedSockets = []
# ## The Editor Class
exports.Editor = class Editor
constructor: (@aceEditor, @options) ->
# ## DOM Population
# This stage of ICE Editor construction populates the given wrapper
# element with all the necessary ICE editor components.
@debugging = true
@options = helper.deepCopy @options
# ### Wrapper
# Create the div that will contain all the ICE Editor graphics
@dropletElement = document.createElement 'div'
@dropletElement.className = 'droplet-wrapper-div'
@dropletElement.innerHTML = EMBOSS_FILTER_SVG
# We give our element a tabIndex so that it can be focused and capture keypresses.
@dropletElement.tabIndex = 0
# ### Canvases
# Create the palette and main canvases
# A measuring canvas for measuring text
@measureCanvas = document.createElement 'canvas'
@measureCtx = @measureCanvas.getContext '2d'
# Main canvas first
@mainCanvas = document.createElementNS SVG_STANDARD, 'svg'
#@mainCanvasWrapper = document.createElementNS SVG_STANDARD, 'g'
#@mainCanvas = document.createElementNS SVG_STANDARD, 'g'
#@mainCanvas.appendChild @mainCanvasWrapper
#@mainCanvasWrapper.appendChild @mainCanvas
@mainCanvas.setAttribute 'class', 'droplet-main-canvas'
@mainCanvas.setAttribute 'shape-rendering', 'optimizeSpeed'
@paletteWrapper = document.createElement 'div'
@paletteWrapper.className = 'droplet-palette-wrapper'
@paletteElement = document.createElement 'div'
@paletteElement.className = 'droplet-palette-element'
@paletteWrapper.appendChild @paletteElement
# Then palette canvas
@paletteCanvas = @paletteCtx = document.createElementNS SVG_STANDARD, 'svg'
@paletteCanvas.setAttribute 'class', 'droplet-palette-canvas'
@paletteWrapper.style.position = 'absolute'
@paletteWrapper.style.left = '0px'
@paletteWrapper.style.top = '0px'
@paletteWrapper.style.bottom = '0px'
@paletteWrapper.style.width = '270px'
# We will also have to initialize the
# drag canvas.
@dragCanvas = @dragCtx = document.createElementNS SVG_STANDARD, 'svg'
@dragCanvas.setAttribute 'class', 'droplet-drag-canvas'
@dragCanvas.style.left = '0px'
@dragCanvas.style.top = '0px'
@dragCanvas.style.transform = 'translate(-9999px,-9999px)'
@draw = new draw.Draw(@mainCanvas)
@dropletElement.style.left = @paletteWrapper.clientWidth + 'px'
do @draw.refreshFontCapital
@standardViewSettings =
padding: 5
indentWidth: 20
textHeight: helper.getFontHeight 'Courier New', 15
indentTongueHeight: 20
tabOffset: 10
tabWidth: 15
tabHeight: 4
tabSideWidth: 1 / 4
dropAreaHeight: 20
indentDropAreaMinWidth: 50
emptySocketWidth: 20
emptyLineHeight: 25
highlightAreaHeight: 10
shadowBlur: 5
ctx: @measureCtx
draw: @draw
# We can be passed a div
if @aceEditor instanceof Node
@wrapperElement = @aceEditor
@wrapperElement.style.position = 'absolute'
@wrapperElement.style.right =
@wrapperElement.style.left =
@wrapperElement.style.top =
@wrapperElement.style.bottom = '0px'
@aceElement = document.createElement 'div'
@aceElement.className = 'droplet-ace'
@wrapperElement.appendChild @aceElement
@aceEditor = ace.edit @aceElement
@aceEditor.setTheme 'ace/theme/chrome'
@aceEditor.setFontSize 15
acemode = @options.mode
if acemode is 'coffeescript' then acemode = 'coffee'
@aceEditor.getSession().setMode 'ace/mode/' + acemode
@aceEditor.getSession().setTabSize 2
else
@wrapperElement = document.createElement 'div'
@wrapperElement.style.position = 'absolute'
@wrapperElement.style.right =
@wrapperElement.style.left =
@wrapperElement.style.top =
@wrapperElement.style.bottom = '0px'
@aceElement = @aceEditor.container
@aceElement.className += ' droplet-ace'
@aceEditor.container.parentElement.appendChild @wrapperElement
@wrapperElement.appendChild @aceEditor.container
# Append populated divs
@wrapperElement.appendChild @dropletElement
@wrapperElement.appendChild @paletteWrapper
@wrapperElement.style.backgroundColor = '#FFF'
@currentlyAnimating = false
@transitionContainer = document.createElement 'div'
@transitionContainer.className = 'droplet-transition-container'
@dropletElement.appendChild @transitionContainer
if @options?
@session = new Session @mainCanvas, @paletteCanvas, @dragCanvas, @options, @standardViewSettings
@sessions = new helper.PairDict([
[@aceEditor.getSession(), @session]
])
else
@session = null
@sessions = new helper.PairDict []
@options = {
extraBottomHeight: 10
}
# Sessions are bound to other ace sessions;
# on ace session change Droplet will also change sessions.
@aceEditor.on 'changeSession', (e) =>
if @sessions.contains(e.session)
@updateNewSession @sessions.get(e.session)
else if e.session._dropletSession?
@updateNewSession e.session._dropletSession
@sessions.set(e.session, e.session._dropletSession)
else
@updateNewSession null
@setEditorState false
# Set up event bindings before creating a view
@bindings = {}
boundListeners = []
# Call all the feature bindings that are supposed
# to happen now.
for binding in editorBindings.populate
binding.call this
# ## Resize
# This stage of ICE editor construction, which is repeated
# whenever the editor is resized, should adjust the sizes
# of all the ICE editor componenents to fit the wrapper.
window.addEventListener 'resize', => @resizeBlockMode()
# ## Tracker Events
# We allow binding to the tracker element.
dispatchMouseEvent = (event) =>
# Ignore mouse clicks that are not the left-button
if event.type isnt 'mousemove' and event.which isnt 1 then return
# Ignore mouse clicks whose target is the scrollbar
if event.target is @mainScroller then return
trackPoint = new @draw.Point(event.clientX, event.clientY)
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings[event.type]
handler.call this, trackPoint, event, state
# Stop mousedown event default behavior so that
# we don't get bad selections
if event.type is 'mousedown'
event.preventDefault?()
event.returnValue = false
return false
dispatchKeyEvent = (event) =>
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings[event.type]
handler.call this, event, state
for eventName, elements of {
keydown: [@dropletElement, @paletteElement]
keyup: [@dropletElement, @paletteElement]
mousedown: [@dropletElement, @paletteElement, @dragCover]
dblclick: [@dropletElement, @paletteElement, @dragCover]
mouseup: [window]
mousemove: [window] } then do (eventName, elements) =>
for element in elements
if /^key/.test eventName
element.addEventListener eventName, dispatchKeyEvent
else
element.addEventListener eventName, dispatchMouseEvent
@resizeBlockMode()
# Now that we've populated everything, immediately redraw.
@redrawMain()
@rebuildPalette()
# If we were given an unrecognized mode or asked to start in text mode,
# flip into text mode here
useBlockMode = @session?.mode? && !@options.textModeAtStart
# Always call @setEditorState to ensure palette is positioned properly
@setEditorState useBlockMode
return this
setMode: (mode, modeOptions) ->
modeClass = modes[mode]
if modeClass
@options.mode = mode
@session.mode = new modeClass modeOptions
else
@options.mode = null
@session.mode = null
@setValue @getValue()
getMode: ->
@options.mode
setReadOnly: (readOnly) ->
@session.readOnly = readOnly
@aceEditor.setReadOnly readOnly
getReadOnly: ->
@session.readOnly
# ## Foundational Resize
# At the editor core, we will need to resize
# all of the natively-added canvases, as well
# as the wrapper element, whenever a resize
# occurs.
resizeTextMode: ->
@resizeAceElement()
@aceEditor.resize true
if @session?
@resizePalette()
return
resizeBlockMode: ->
return unless @session?
@resizeTextMode()
@dropletElement.style.height = "#{@wrapperElement.clientHeight}px"
if @session.paletteEnabled
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
@dropletElement.style.width = "#{@wrapperElement.clientWidth - @paletteWrapper.clientWidth}px"
else
@dropletElement.style.left = "0px"
@dropletElement.style.width = "#{@wrapperElement.clientWidth}px"
#@resizeGutter()
@session.viewports.main.height = @dropletElement.clientHeight
@session.viewports.main.width = @dropletElement.clientWidth - @gutter.clientWidth
@mainCanvas.setAttribute 'width', @dropletElement.clientWidth - @gutter.clientWidth
@mainCanvas.style.left = "#{@gutter.clientWidth}px"
@transitionContainer.style.left = "#{@gutter.clientWidth}px"
@resizePalette()
@resizePaletteHighlight()
@resizeNubby()
@resizeMainScroller()
@resizeDragCanvas()
# Re-scroll and redraw main
@session.viewports.main.y = @mainScroller.scrollTop
@session.viewports.main.x = @mainScroller.scrollLeft
resizePalette: ->
for binding in editorBindings.resize_palette
binding.call this
@rebuildPalette()
resize: ->
if @session?.currentlyUsingBlocks #TODO session
@resizeBlockMode()
else
@resizeTextMode()
updateNewSession: (session) ->
@session.view.clearFromCanvas()
@session.paletteView.clearFromCanvas()
@session.dragView.clearFromCanvas()
@session = session
return unless session?
# Force scroll into our position
offsetY = @session.viewports.main.y
offsetX = @session.viewports.main.x
@setEditorState @session.currentlyUsingBlocks
@redrawMain()
@mainScroller.scrollTop = offsetY
@mainScroller.scrollLeft = offsetX
@setPalette @session.paletteGroups
hasSessionFor: (aceSession) -> @sessions.contains(aceSession)
bindNewSession: (opts) ->
if @sessions.contains(@aceEditor.getSession())
throw new ArgumentError 'Cannot bind a new session where one already exists.'
else
session = new Session @mainCanvas, @paletteCanvas, @dragCanvas, opts, @standardViewSettings
@sessions.set(@aceEditor.getSession(), session)
@session = session
@aceEditor.getSession()._dropletSession = @session
@session.currentlyUsingBlocks = false
@setValue_raw @getAceValue()
@setPalette @session.paletteGroups
return session
Editor::clearCanvas = (canvas) -> # TODO remove and remove all references to
# RENDERING CAPABILITIES
# ================================
# ## Redraw
# There are two different redraw events, redraw_main and rebuild_palette,
# for redrawing the main canvas and palette canvas, respectively.
#
# Redrawing simply involves issuing a call to the View.
Editor::clearMain = (opts) -> # TODO remove and remove all references to
Editor::setTopNubbyStyle = (height = 10, color = '#EBEBEB') ->
@nubbyHeight = Math.max(0, height); @nubbyColor = color
@topNubbyPath ?= new @draw.Path([], true)
@topNubbyPath.activate()
@topNubbyPath.setParent @mainCanvas
points = []
points.push new @draw.Point @mainCanvas.clientWidth, -5
points.push new @draw.Point @mainCanvas.clientWidth, height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth, height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth * (1 - @session.view.opts.tabSideWidth),
@session.view.opts.tabHeight + height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth * @session.view.opts.tabSideWidth,
@session.view.opts.tabHeight + height
points.push new @draw.Point @session.view.opts.tabOffset, height
points.push new @draw.Point @session.view.opts.bevelClip, height
points.push new @draw.Point 0, height + @session.view.opts.bevelClip
points.push new @draw.Point -5, height + @session.view.opts.bevelClip
points.push new @draw.Point -5, -5
@topNubbyPath.setPoints points
@topNubbyPath.style.fillColor = color
@redrawMain()
Editor::resizeNubby = ->
@setTopNubbyStyle @nubbyHeight, @nubbyColor
Editor::initializeFloatingBlock = (record, i) ->
record.renderGroup = new @session.view.draw.Group()
record.grayBox = new @session.view.draw.NoRectangle()
record.grayBoxPath = new @session.view.draw.Path(
[], false, {
fillColor: GRAY_BLOCK_COLOR
strokeColor: GRAY_BLOCK_BORDER
lineWidth: 4
dotted: '8 5'
cssClass: 'droplet-floating-container'
}
)
record.startText = new @session.view.draw.Text(
(new @session.view.draw.Point(0, 0)), @session.mode.startComment
)
record.endText = new @session.view.draw.Text(
(new @session.view.draw.Point(0, 0)), @session.mode.endComment
)
for element in [record.grayBoxPath, record.startText, record.endText]
element.setParent record.renderGroup
element.activate()
@session.view.getViewNodeFor(record.block).group.setParent record.renderGroup
record.renderGroup.activate()
# TODO maybe refactor into qualifiedFocus
if i < @session.floatingBlocks.length
@mainCanvas.insertBefore record.renderGroup.element, @session.floatingBlocks[i].renderGroup.element
else
@mainCanvas.appendChild record.renderGroup
Editor::drawFloatingBlock = (record, startWidth, endWidth, rect, opts) ->
blockView = @session.view.getViewNodeFor record.block
blockView.layout record.position.x, record.position.y
rectangle = new @session.view.draw.Rectangle(); rectangle.copy(blockView.totalBounds)
rectangle.x -= GRAY_BLOCK_MARGIN; rectangle.y -= GRAY_BLOCK_MARGIN
rectangle.width += 2 * GRAY_BLOCK_MARGIN; rectangle.height += 2 * GRAY_BLOCK_MARGIN
bottomTextPosition = blockView.totalBounds.bottom() - blockView.distanceToBase[blockView.lineLength - 1].below - @session.fontSize
if (blockView.totalBounds.width - blockView.bounds[blockView.bounds.length - 1].width) < endWidth
if blockView.lineLength > 1
rectangle.height += @session.fontSize
bottomTextPosition = rectangle.bottom() - @session.fontSize - 5
else
rectangle.width += endWidth
unless rectangle.equals(record.grayBox)
record.grayBox = rectangle
oldBounds = record.grayBoxPath?.bounds?() ? new @session.view.draw.NoRectangle()
startHeight = blockView.bounds[0].height + 10
points = []
# Make the path surrounding the gray box (with rounded corners)
points.push new @session.view.draw.Point rectangle.right() - 5, rectangle.y
points.push new @session.view.draw.Point rectangle.right(), rectangle.y + 5
points.push new @session.view.draw.Point rectangle.right(), rectangle.bottom() - 5
points.push new @session.view.draw.Point rectangle.right() - 5, rectangle.bottom()
if blockView.lineLength > 1
points.push new @session.view.draw.Point rectangle.x + 5, rectangle.bottom()
points.push new @session.view.draw.Point rectangle.x, rectangle.bottom() - 5
else
points.push new @session.view.draw.Point rectangle.x, rectangle.bottom()
# Handle
points.push new @session.view.draw.Point rectangle.x, rectangle.y + startHeight
points.push new @session.view.draw.Point rectangle.x - startWidth + 5, rectangle.y + startHeight
points.push new @session.view.draw.Point rectangle.x - startWidth, rectangle.y + startHeight - 5
points.push new @session.view.draw.Point rectangle.x - startWidth, rectangle.y + 5
points.push new @session.view.draw.Point rectangle.x - startWidth + 5, rectangle.y
points.push new @session.view.draw.Point rectangle.x, rectangle.y
record.grayBoxPath.setPoints points
if opts.boundingRectangle?
opts.boundingRectangle.unite path.bounds()
opts.boundingRectangle.unite(oldBounds)
return @redrawMain opts
record.grayBoxPath.update()
record.startText.point.x = blockView.totalBounds.x - startWidth
record.startText.point.y = blockView.totalBounds.y + blockView.distanceToBase[0].above - @session.fontSize
record.startText.update()
record.endText.point.x = record.grayBox.right() - endWidth - 5
record.endText.point.y = bottomTextPosition
record.endText.update()
blockView.draw rect, {
grayscale: false
selected: false
noText: false
}
hook 'populate', 0, ->
@currentlyDrawnFloatingBlocks = []
Editor::redrawMain = (opts = {}) ->
return unless @session?
unless @currentlyAnimating_suprressRedraw
@session.view.beginDraw()
# Clear the main canvas
@clearMain(opts)
@topNubbyPath.update()
rect = @session.viewports.main
options = {
grayscale: false
selected: false
noText: (opts.noText ? false)
}
# Draw the new tree on the main context
layoutResult = @session.view.getViewNodeFor(@session.tree).layout 0, @nubbyHeight
@session.view.getViewNodeFor(@session.tree).draw rect, options
@session.view.getViewNodeFor(@session.tree).root()
for el, i in @currentlyDrawnFloatingBlocks
unless el.record in @session.floatingBlocks
el.record.grayBoxPath.destroy()
el.record.startText.destroy()
el.record.endText.destroy()
@currentlyDrawnFloatingBlocks = []
# Draw floating blocks
startWidth = @session.mode.startComment.length * @session.fontWidth
endWidth = @session.mode.endComment.length * @session.fontWidth
for record in @session.floatingBlocks
element = @drawFloatingBlock(record, startWidth, endWidth, rect, opts)
@currentlyDrawnFloatingBlocks.push {
record: record
}
# Draw the cursor (if exists, and is inserted)
@redrawCursors(); @redrawHighlights()
@resizeGutter()
for binding in editorBindings.redraw_main
binding.call this, layoutResult
if @session.changeEventVersion isnt @session.tree.version
@session.changeEventVersion = @session.tree.version
@fireEvent 'change', []
@session.view.cleanupDraw()
unless @alreadyScheduledCleanup
@alreadyScheduledCleanup = true
setTimeout (=>
@alreadyScheduledCleanup = false
if @session?
@session.view.garbageCollect()
), 0
return null
Editor::redrawHighlights = ->
@redrawCursors()
@redrawLassoHighlight()
# If there is an block that is being dragged,
# draw it in gray
if @draggingBlock? and @inDisplay @draggingBlock
@session.view.getViewNodeFor(@draggingBlock).draw new @draw.Rectangle(
@session.viewports.main.x,
@session.viewports.main.y,
@session.viewports.main.width,
@session.viewports.main.height
), {grayscale: true}
Editor::clearCursorCanvas = ->
@textCursorPath.deactivate()
@cursorPath.deactivate()
Editor::redrawCursors = ->
return unless @session?
@clearCursorCanvas()
if @cursorAtSocket()
@redrawTextHighlights()
else unless @lassoSelection?
@drawCursor()
Editor::drawCursor = -> @strokeCursor @determineCursorPosition()
Editor::clearPalette = -> # TODO remove and remove all references to
Editor::clearPaletteHighlightCanvas = -> # TODO remove and remove all references to
Editor::redrawPalette = ->
return unless @session?.currentPaletteBlocks?
@clearPalette()
@session.paletteView.beginDraw()
# We will construct a vertical layout
# with padding for the palette blocks.
# To do this, we will need to keep track
# of the last bottom edge of a palette block.
lastBottomEdge = PALETTE_TOP_MARGIN
for entry in @session.currentPaletteBlocks
# Layout this block
paletteBlockView = @session.paletteView.getViewNodeFor entry.block
paletteBlockView.layout PALETTE_LEFT_MARGIN, lastBottomEdge
# Render the block
paletteBlockView.draw()
paletteBlockView.group.setParent @paletteCtx
element = document.createElementNS SVG_STANDARD, 'title'
element.innerHTML = entry.title ? entry.block.stringify()
paletteBlockView.group.element.appendChild element
paletteBlockView.group.element.setAttribute 'data-id', entry.id
# Update lastBottomEdge
lastBottomEdge = paletteBlockView.getBounds().bottom() + PALETTE_MARGIN
for binding in editorBindings.redraw_palette
binding.call this
@paletteCanvas.style.height = lastBottomEdge + 'px'
@session.paletteView.garbageCollect()
Editor::rebuildPalette = ->
return unless @session?.currentPaletteBlocks?
@redrawPalette()
for binding in editorBindings.rebuild_palette
binding.call this
# MOUSE INTERACTION WRAPPERS
# ================================
# These are some common operations we need to do with
# the mouse that will be convenient later.
Editor::absoluteOffset = (el) ->
point = new @draw.Point el.offsetLeft, el.offsetTop
el = el.offsetParent
until el is document.body or not el?
point.x += el.offsetLeft - el.scrollLeft
point.y += el.offsetTop - el.scrollTop
el = el.offsetParent
return point
# ### Conversion functions
# Convert a point relative to the page into
# a point relative to one of the two canvases.
Editor::trackerPointToMain = (point) ->
if not @mainCanvas.parentElement?
return new @draw.Point(NaN, NaN)
gbr = @mainCanvas.getBoundingClientRect()
new @draw.Point(point.x - gbr.left,
point.y - gbr.top)
Editor::trackerPointToPalette = (point) ->
if not @paletteCanvas.parentElement?
return new @draw.Point(NaN, NaN)
gbr = @paletteCanvas.getBoundingClientRect()
new @draw.Point(point.x - gbr.left,
point.y - gbr.top)
Editor::trackerPointIsInElement = (point, element) ->
if not @session? or @session.readOnly
return false
if not element.parentElement?
return false
gbr = element.getBoundingClientRect()
return point.x >= gbr.left and point.x < gbr.right and
point.y >= gbr.top and point.y < gbr.bottom
Editor::trackerPointIsInMain = (point) ->
return this.trackerPointIsInElement point, @mainCanvas
Editor::trackerPointIsInMainScroller = (point) ->
return this.trackerPointIsInElement point, @mainScroller
Editor::trackerPointIsInGutter = (point) ->
return this.trackerPointIsInElement point, @gutter
Editor::trackerPointIsInPalette = (point) ->
return this.trackerPointIsInElement point, @paletteCanvas
Editor::trackerPointIsInAce = (point) ->
return this.trackerPointIsInElement point, @aceElement
# ### hitTest
# Simple function for going through a linked-list block
# and seeing what the innermost child is that we hit.
Editor::hitTest = (point, block, view = @session.view) ->
if @session.readOnly
return null
head = block.start
seek = block.end
result = null
until head is seek
if head.type is 'blockStart' and view.getViewNodeFor(head.container).path.contains point
result = head.container
seek = head.container.end
head = head.next
# If we had a child hit, return it.
return result
hook 'mousedown', 10, ->
x = document.body.scrollLeft
y = document.body.scrollTop
@dropletElement.focus()
window.scrollTo(x, y)
Editor::removeBlankLines = ->
# If we have blank lines at the end,
# get rid of them
head = tail = @session.tree.end.prev
while head?.type is 'newline'
head = head.prev
if head.type is 'newline'
@spliceOut new model.List head, tail
# UNDO STACK SUPPORT
# ================================
# We must declare a few
# fields a populate time
# Now we hook to ctrl-z to undo.
hook 'keydown', 0, (event, state) ->
if event.which is Z_KEY and event.shiftKey and command_pressed(event)
@redo()
else if event.which is Z_KEY and command_pressed(event)
@undo()
else if event.which is Y_KEY and command_pressed(event)
@redo()
class EditorState
constructor: (@root, @floats) ->
equals: (other) ->
return false unless @root is other.root and @floats.length is other.floats.length
for el, i in @floats
return false unless el.position.equals(other.floats[i].position) and el.string is other.floats[i].string
return true
toString: -> JSON.stringify {
@root, @floats
}
Editor::getSerializedEditorState = ->
return new EditorState @session.tree.stringify(), @session.floatingBlocks.map (x) -> {
position: x.position
string: x.block.stringify()
}
Editor::clearUndoStack = ->
return unless @session?
@session.undoStack.length = 0
@session.redoStack.length = 0
Editor::undo = ->
return unless @session?
# Don't allow a socket to be highlighted during
# an undo operation
@setCursor @session.cursor, ((x) -> x.type isnt 'socketStart')
currentValue = @getSerializedEditorState()
until @session.undoStack.length is 0 or
(@session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint and
not @getSerializedEditorState().equals(currentValue))
operation = @popUndo()
if operation instanceof FloatingOperation
@performFloatingOperation(operation, 'backward')
else
@getDocument(operation.document).perform(
operation.operation, 'backward', @getPreserves(operation.document)
) unless operation instanceof CapturePoint
# Set the the remembered socket contents to the state it was in
# at this point in the undo stack.
if @session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint
@session.rememberedSockets = @session.undoStack[@session.undoStack.length - 1].rememberedSockets.map (x) -> x.clone()
@popUndo()
@correctCursor()
@redrawMain()
return
Editor::pushUndo = (operation) ->
@session.redoStack.length = 0
@session.undoStack.push operation
Editor::popUndo = ->
operation = @session.undoStack.pop()
@session.redoStack.push(operation) if operation?
return operation
Editor::popRedo = ->
operation = @session.redoStack.pop()
@session.undoStack.push(operation) if operation?
return operation
Editor::redo = ->
currentValue = @getSerializedEditorState()
until @session.redoStack.length is 0 or
(@session.redoStack[@session.redoStack.length - 1] instanceof CapturePoint and
not @getSerializedEditorState().equals(currentValue))
operation = @popRedo()
if operation instanceof FloatingOperation
@performFloatingOperation(operation, 'forward')
else
@getDocument(operation.document).perform(
operation.operation, 'forward', @getPreserves(operation.document)
) unless operation instanceof CapturePoint
# Set the the remembered socket contents to the state it was in
# at this point in the undo stack.
if @session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint
@session.rememberedSockets = @session.undoStack[@session.undoStack.length - 1].rememberedSockets.map (x) -> x.clone()
@popRedo()
@redrawMain()
return
# ## undoCapture and CapturePoint ##
# A CapturePoint is a sentinel indicating that the undo stack
# should stop when the user presses Ctrl+Z or Ctrl+Y. Each CapturePoint
# also remembers the @rememberedSocket state at the time it was placed,
# to preserved remembered socket contents across undo and redo.
Editor::undoCapture = ->
@pushUndo new CapturePoint(@session.rememberedSockets)
class CapturePoint
constructor: (rememberedSockets) ->
@rememberedSockets = rememberedSockets.map (x) -> x.clone()
# BASIC BLOCK MOVE SUPPORT
# ================================
Editor::getPreserves = (dropletDocument) ->
if dropletDocument instanceof model.Document
dropletDocument = @documentIndex dropletDocument
array = [@session.cursor]
array = array.concat @session.rememberedSockets.map(
(x) -> x.socket
)
return array.filter((location) ->
location.document is dropletDocument
).map((location) -> location.location)
Editor::spliceOut = (node, container = null) ->
# Make an empty list if we haven't been
# passed one
unless node instanceof model.List
node = new model.List node, node
operation = null
dropletDocument = node.getDocument()
parent = node.parent
if dropletDocument?
operation = node.getDocument().remove node, @getPreserves(dropletDocument)
@pushUndo {operation, document: @getDocuments().indexOf(dropletDocument)}
# If we are removing a block from a socket, and the socket is in our
# dictionary of remembered socket contents, repopulate the socket with
# its old contents.
if parent?.type is 'socket' and node.start.type is 'blockStart'
for socket, i in @session.rememberedSockets
if @fromCrossDocumentLocation(socket.socket) is parent
@session.rememberedSockets.splice i, 0
@populateSocket parent, socket.text
break
# Remove the floating dropletDocument if it is now
# empty
if dropletDocument.start.next is dropletDocument.end
for record, i in @session.floatingBlocks
if record.block is dropletDocument
@pushUndo new FloatingOperation i, record.block, record.position, 'delete'
# If the cursor's document is about to vanish,
# put it back in the main tree.
if @session.cursor.document is i + 1
@setCursor @session.tree.start
if @session.cursor.document > i + 1
@session.cursor.document -= 1
@session.floatingBlocks.splice i, 1
for socket in @session.rememberedSockets
if socket.socket.document > i
socket.socket.document -= 1
break
else if container?
# No document, so try to remove from container if it was supplied
container.remove node
@prepareNode node, null
@correctCursor()
return operation
Editor::spliceIn = (node, location) ->
# Track changes in the cursor by temporarily
# using a pointer to it
container = location.container ? location.parent
if container.type is 'block'
container = container.parent
else if container.type is 'socket' and
container.start.next isnt container.end
if @documentIndex(container) != -1
# If we're splicing into a socket found in a document and it already has
# something in it, remove it. Additionally, remember the old
# contents in @session.rememberedSockets for later repopulation if they take
# the block back out.
@session.rememberedSockets.push new RememberedSocketRecord(
@toCrossDocumentLocation(container),
container.textContent()
)
@spliceOut (new model.List container.start.next, container.end.prev), container
dropletDocument = location.getDocument()
@prepareNode node, container
if dropletDocument?
operation = dropletDocument.insert location, node, @getPreserves(dropletDocument)
@pushUndo {operation, document: @getDocuments().indexOf(dropletDocument)}
@correctCursor()
return operation
else
# No document, so just insert into container
container.insert location, node
return null
class RememberedSocketRecord
constructor: (@socket, @text) ->
clone: ->
new RememberedSocketRecord(
@socket.clone(),
@text
)
Editor::replace = (before, after, updates = []) ->
dropletDocument = before.start.getDocument()
if dropletDocument?
operation = dropletDocument.replace before, after, updates.concat(@getPreserves(dropletDocument))
@pushUndo {operation, document: @documentIndex(dropletDocument)}
@correctCursor()
return operation
else
return null
Editor::adjustPosToLineStart = (pos) ->
line = @aceEditor.session.getLine pos.row
if pos.row == @aceEditor.session.getLength() - 1
pos.column = if (pos.column >= line.length / 2) then line.length else 0
else
pos.column = 0
pos
Editor::correctCursor = ->
cursor = @fromCrossDocumentLocation @session.cursor
unless @validCursorPosition cursor
until not cursor? or (@validCursorPosition(cursor) and cursor.type isnt 'socketStart')
cursor = cursor.next
unless cursor? then cursor = @fromCrossDocumentLocation @session.cursor
until not cursor? or (@validCursorPosition(cursor) and cursor.type isnt 'socketStart')
cursor = cursor.prev
@session.cursor = @toCrossDocumentLocation cursor
Editor::prepareNode = (node, context) ->
if node instanceof model.Container
leading = node.getLeadingText()
if node.start.next is node.end.prev
trailing = null
else
trailing = node.getTrailingText()
[leading, trailing, classes] = @session.mode.parens leading, trailing, node.getReader(),
context?.getReader?() ? null
node.setLeadingText leading; node.setTrailingText trailing
# At population-time, we will
# want to set up a few fields.
hook 'populate', 0, ->
@clickedPoint = null
@clickedBlock = null
@clickedBlockPaletteEntry = null
@draggingBlock = null
@draggingOffset = null
@lastHighlight = @lastHighlightPath = null
# And the canvas for drawing highlights
@highlightCanvas = @highlightCtx = document.createElementNS SVG_STANDARD, 'g'
# We append it to the tracker element,
# so that it can appear in front of the scrollers.
#@dropletElement.appendChild @dragCanvas
#document.body.appendChild @dragCanvas
@wrapperElement.appendChild @dragCanvas
@mainCanvas.appendChild @highlightCanvas
Editor::clearHighlightCanvas = ->
for path in [@textCursorPath]
path.deactivate()
# Utility function for clearing the drag canvas,
# an operation we will be doing a lot.
Editor::clearDrag = ->
@clearHighlightCanvas()
# On resize, we will want to size the drag canvas correctly.
Editor::resizeDragCanvas = ->
@dragCanvas.style.width = "#{0}px"
@dragCanvas.style.height = "#{0}px"
@highlightCanvas.style.width = "#{@dropletElement.clientWidth - @gutter.clientWidth}px"
@highlightCanvas.style.height = "#{@dropletElement.clientHeight}px"
@highlightCanvas.style.left = "#{@mainCanvas.offsetLeft}px"
Editor::getDocuments = ->
documents = [@session.tree]
for el, i in @session.floatingBlocks
documents.push el.block
return documents
Editor::getDocument = (n) ->
if n is 0 then @session.tree
else @session.floatingBlocks[n - 1].block
Editor::documentIndex = (block) ->
@getDocuments().indexOf block.getDocument()
Editor::fromCrossDocumentLocation = (location) ->
@getDocument(location.document).getFromLocation location.location
Editor::toCrossDocumentLocation = (block) ->
new CrossDocumentLocation @documentIndex(block), block.getLocation()
# On mousedown, we will want to
# hit test blocks in the root tree to
# see if we want to move them.
#
# We do not do anything until the user
# drags their mouse five pixels
hook 'mousedown', 1, (point, event, state) ->
# If someone else has already taken this click, pass.
if state.consumedHitTest then return
# If it's not in the main pane, pass.
if not @trackerPointIsInMain(point) then return
# Hit test against the tree.
mainPoint = @trackerPointToMain(point)
for dropletDocument, i in @getDocuments() by -1
# First attempt handling text input
if @handleTextInputClick mainPoint, dropletDocument
state.consumedHitTest = true
return
else if @session.cursor.document is i and @cursorAtSocket()
@setCursor @session.cursor, ((token) -> token.type isnt 'socketStart')
hitTestResult = @hitTest mainPoint, dropletDocument
# Produce debugging output
if @debugging and event.shiftKey
line = null
node = @session.view.getViewNodeFor(hitTestResult)
for box, i in node.bounds
if box.contains(mainPoint)
line = i
break
@dumpNodeForDebug(hitTestResult, line)
# If it came back positive,
# deal with the click.
if hitTestResult?
# Record the hit test result (the block we want to pick up)
@clickedBlock = hitTestResult
@clickedBlockPaletteEntry = null
# Move the cursor somewhere nearby
@setCursor @clickedBlock.start.next
# Record the point at which is was clicked (for clickedBlock->draggingBlock)
@clickedPoint = point
# Signify to any other hit testing
# handlers that we have already consumed
# the hit test opportunity for this event.
state.consumedHitTest = true
return
else if i > 0
record = @session.floatingBlocks[i - 1]
if record.grayBoxPath? and record.grayBoxPath.contains @trackerPointToMain point
@clickedBlock = new model.List record.block.start.next, record.block.end.prev
@clickedPoint = point
@session.view.getViewNodeFor(@clickedBlock).absorbCache() # TODO MERGE inspection
state.consumedHitTest = true
@redrawMain()
return
# If the user clicks inside a block
# and the block contains a button
# which is either add or subtract button
# call the handleButton callback
hook 'mousedown', 4, (point, event, state) ->
if state.consumedHitTest then return
if not @trackerPointIsInMain(point) then return
mainPoint = @trackerPointToMain point
#Buttons aren't clickable in a selection
if @lassoSelection? and @hitTest(mainPoint, @lassoSelection)? then return
hitTestResult = @hitTest mainPoint, @session.tree
if hitTestResult?
hitTestBlock = @session.view.getViewNodeFor hitTestResult
str = hitTestResult.stringifyInPlace()
if hitTestBlock.addButtonRect? and hitTestBlock.addButtonRect.contains mainPoint
line = @session.mode.handleButton str, 'add-button', hitTestResult.getReader()
if line?.length >= 0
@populateBlock hitTestResult, line
@redrawMain()
state.consumedHitTest = true
### TODO
else if hitTestBlock.subtractButtonRect? and hitTestBlock.subtractButtonRect.contains mainPoint
line = @session.mode.handleButton str, 'subtract-button', hitTestResult.getReader()
if line?.length >= 0
@populateBlock hitTestResult, line
@redrawMain()
state.consumedHitTest = true
###
# If the user lifts the mouse
# before they have dragged five pixels,
# abort stuff.
hook 'mouseup', 0, (point, event, state) ->
# @clickedBlock and @clickedPoint should will exist iff
# we have dragged not yet more than 5 pixels.
#
# To abort, all we need to do is null.
if @clickedBlock?
@clickedBlock = null
@clickedPoint = null
Editor::drawDraggingBlock = ->
# Draw the new dragging block on the drag canvas.
#
# When we are dragging things, we draw the shadow.
# Also, we translate the block 1x1 to the right,
# so that we can see its borders.
@session.dragView.clearCache()
draggingBlockView = @session.dragView.getViewNodeFor @draggingBlock
draggingBlockView.layout 1, 1
@dragCanvas.width = Math.min draggingBlockView.totalBounds.width + 10, window.screen.width
@dragCanvas.height = Math.min draggingBlockView.totalBounds.height + 10, window.screen.height
draggingBlockView.draw new @draw.Rectangle 0, 0, @dragCanvas.width, @dragCanvas.height
Editor::wouldDelete = (position) ->
mainPoint = @trackerPointToMain position
palettePoint = @trackerPointToPalette position
return not @lastHighlight and not @session.viewports.main.contains(mainPoint)
# On mousemove, if there is a clicked block but no drag block,
# we might want to transition to a dragging the block if the user
# moved their mouse far enough.
hook 'mousemove', 1, (point, event, state) ->
return unless @session?
if not state.capturedPickup and @clickedBlock? and point.from(@clickedPoint).magnitude() > MIN_DRAG_DISTANCE
# Signify that we are now dragging a block.
@draggingBlock = @clickedBlock
@dragReplacing = false
# Our dragging offset must be computed using the canvas on which this block
# is rendered.
#
# NOTE: this really falls under "PALETTE SUPPORT", but must
# go here. Try to organise this better.
if @clickedBlockPaletteEntry
@draggingOffset = @session.paletteView.getViewNodeFor(@draggingBlock).bounds[0].upperLeftCorner().from(
@trackerPointToPalette(@clickedPoint))
# Substitute in expansion for this palette entry, if supplied.
expansion = @clickedBlockPaletteEntry.expansion
# Call expansion() function with no parameter to get the initial value.
if 'function' is typeof expansion then expansion = expansion()
if (expansion) then expansion = parseBlock(@session.mode, expansion, @clickedBlockPaletteEntry.context)
@draggingBlock = (expansion or @draggingBlock).clone()
# Special @draggingBlock setup for expansion function blocks.
if 'function' is typeof @clickedBlockPaletteEntry.expansion
# Any block generated from an expansion function should be treated as
# any-drop because it can change with subsequent expansion() calls.
if 'mostly-value' in @draggingBlock.classes
@draggingBlock.classes.push 'any-drop'
# Attach expansion() function and lastExpansionText to @draggingBlock.
@draggingBlock.lastExpansionText = expansion
@draggingBlock.expansion = @clickedBlockPaletteEntry.expansion
else
# Find the line on the block that we have
# actually clicked, and attempt to translate the block
# so that if it re-shapes, we're still touching it.
#
# To do this, we will assume that the left edge of a free
# block are all aligned.
mainPoint = @trackerPointToMain @clickedPoint
viewNode = @session.view.getViewNodeFor @draggingBlock
if @draggingBlock instanceof model.List and not
(@draggingBlock instanceof model.Container)
viewNode.absorbCache()
@draggingOffset = null
for bound, line in viewNode.bounds
if bound.contains mainPoint
@draggingOffset = bound.upperLeftCorner().from mainPoint
@draggingOffset.y += viewNode.bounds[0].y - bound.y
break
unless @draggingOffset?
@draggingOffset = viewNode.bounds[0].upperLeftCorner().from mainPoint
# TODO figure out what to do with lists here
# Draw the new dragging block on the drag canvas.
#
# When we are dragging things, we draw the shadow.
# Also, we translate the block 1x1 to the right,
# so that we can see its borders.
@session.dragView.beginDraw()
draggingBlockView = @session.dragView.getViewNodeFor @draggingBlock
draggingBlockView.layout 1, 1
draggingBlockView.root()
draggingBlockView.draw()
@session.dragView.garbageCollect()
@dragCanvas.style.width = "#{Math.min draggingBlockView.totalBounds.width + 10, window.screen.width}px"
@dragCanvas.style.height = "#{Math.min draggingBlockView.totalBounds.height + 10, window.screen.height}px"
# Translate it immediately into position
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
# Construct a quadtree of drop areas
# for faster dragging
@dropPointQuadTree = QUAD.init
x: @session.viewports.main.x
y: @session.viewports.main.y
w: @session.viewports.main.width
h: @session.viewports.main.height
for dropletDocument in @getDocuments()
head = dropletDocument.start
# Don't allow dropping at the start of the document
# if we are already dragging a block that is at
# the start of the document.
if @draggingBlock.start.prev is head
head = head.next
until head is dropletDocument.end
if head is @draggingBlock.start
head = @draggingBlock.end
if head instanceof model.StartToken
acceptLevel = @getAcceptLevel @draggingBlock, head.container
unless acceptLevel is helper.FORBID
dropPoint = @session.view.getViewNodeFor(head.container).dropPoint
if dropPoint?
allowed = true
for record, i in @session.floatingBlocks by -1
if record.block is dropletDocument
break
else if record.grayBoxPath.contains dropPoint
allowed = false
break
if allowed
@dropPointQuadTree.insert
x: dropPoint.x
y: dropPoint.y
w: 0
h: 0
acceptLevel: acceptLevel
_droplet_node: head.container
head = head.next
@dragCanvas.style.transform = "translate(#{position.x + getOffsetLeft(@dropletElement)}px,#{position.y + getOffsetTop(@dropletElement)}px)"
# Now we are done with the "clickedX" suite of stuff.
@clickedPoint = @clickedBlock = null
@clickedBlockPaletteEntry = null
@begunTrash = @wouldDelete position
# Redraw the main canvas
@redrawMain()
Editor::getClosestDroppableBlock = (mainPoint, isDebugMode) ->
best = null; min = Infinity
if not (@dropPointQuadTree)
return null
testPoints = @dropPointQuadTree.retrieve {
x: mainPoint.x - MAX_DROP_DISTANCE
y: mainPoint.y - MAX_DROP_DISTANCE
w: MAX_DROP_DISTANCE * 2
h: MAX_DROP_DISTANCE * 2
}, (point) =>
unless (point.acceptLevel is helper.DISCOURAGE) and not isDebugMode
# Find a modified "distance" to the point
# that weights horizontal distance more
distance = mainPoint.from(point)
distance.y *= 2; distance = distance.magnitude()
# Select the node that is closest by said "distance"
if distance < min and mainPoint.from(point).magnitude() < MAX_DROP_DISTANCE and
@session.view.getViewNodeFor(point._droplet_node).highlightArea?
best = point._droplet_node
min = distance
best
Editor::getClosestDroppableBlockFromPosition = (position, isDebugMode) ->
if not @session.currentlyUsingBlocks
return null
mainPoint = @trackerPointToMain(position)
@getClosestDroppableBlock(mainPoint, isDebugMode)
Editor::getAcceptLevel = (drag, drop) ->
if drop.type is 'socket'
if drag.type is 'list'
return helper.FORBID
else
return @session.mode.drop drag.getReader(), drop.getReader(), null, null
# If it's a list/selection, try all of its children
else if drag.type is 'list'
minimum = helper.ENCOURAGE
drag.traverseOneLevel (child) =>
if child instanceof model.Container
minimum = Math.min minimum, @getAcceptLevel child, drop
return minimum
else if drop.type is 'block'
if drop.parent.type is 'socket'
return helper.FORBID
else
next = drop.nextSibling()
return @session.mode.drop drag.getReader(), drop.parent.getReader(), drop.getReader(), next?.getReader?()
else
next = drop.firstChild()
return @session.mode.drop drag.getReader(), drop.getReader(), drop.getReader(), next?.getReader?()
# On mousemove, if there is a dragged block, we want to
# translate the drag canvas into place,
# as well as highlighting any focused drop areas.
hook 'mousemove', 0, (point, event, state) ->
if @draggingBlock?
# Translate the drag canvas into position.
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
# If there is an expansion function, call it again here.
if (@draggingBlock.expansion)
# Call expansion() with the closest droppable block for all drag moves.
expansionText = @draggingBlock.expansion(@getClosestDroppableBlockFromPosition(position, event.shiftKey))
# Create replacement @draggingBlock if the returned text is new.
if expansionText isnt @draggingBlock.lastExpansionText
newBlock = parseBlock(@session.mode, expansionText)
newBlock.lastExpansionText = expansionText
newBlock.expansion = @draggingBlock.expansion
if 'any-drop' in @draggingBlock.classes
newBlock.classes.push 'any-drop'
@draggingBlock = newBlock
@drawDraggingBlock()
if not @session.currentlyUsingBlocks
if @trackerPointIsInAce position
pos = @aceEditor.renderer.screenToTextCoordinates position.x, position.y
if @session.dropIntoAceAtLineStart
pos = @adjustPosToLineStart pos
@aceEditor.focus()
@aceEditor.session.selection.moveToPosition pos
else
@aceEditor.blur()
rect = @wrapperElement.getBoundingClientRect()
@dragCanvas.style.transform = "translate(#{position.x - rect.left}px,#{position.y - rect.top}px)"
mainPoint = @trackerPointToMain(position)
# Check to see if the tree is empty;
# if it is, drop on the tree always
head = @session.tree.start.next
while head.type in ['newline', 'cursor'] or head.type is 'text' and head.value is ''
head = head.next
if head is @session.tree.end and @session.floatingBlocks.length is 0 and
@session.viewports.main.right() > mainPoint.x > @session.viewports.main.x - @gutter.clientWidth and
@session.viewports.main.bottom() > mainPoint.y > @session.viewports.main.y and
@getAcceptLevel(@draggingBlock, @session.tree) is helper.ENCOURAGE
@session.view.getViewNodeFor(@session.tree).highlightArea.update()
@lastHighlight = @session.tree
else
# If the user is touching the original location,
# assume they want to replace the block where they found it.
if @hitTest mainPoint, @draggingBlock
@dragReplacing = true
dropBlock = null
# If the user's block is outside the main pane, delete it
else if not @trackerPointIsInMain position
@dragReplacing = false
dropBlock= null
# Otherwise, find the closest droppable block
else
@dragReplacing = false
dropBlock = @getClosestDroppableBlock(mainPoint, event.shiftKey)
# Update highlight if necessary.
if dropBlock isnt @lastHighlight
# TODO if this becomes a performance issue,
# pull the drop highlights out into a new canvas.
@redrawHighlights()
@lastHighlightPath?.deactivate?()
if dropBlock?
@lastHighlightPath = @session.view.getViewNodeFor(dropBlock).highlightArea
@lastHighlightPath.update()
@qualifiedFocus dropBlock, @lastHighlightPath
@lastHighlight = dropBlock
palettePoint = @trackerPointToPalette position
if @wouldDelete(position)
if @begunTrash
@dragCanvas.style.opacity = 0.85
else
@dragCanvas.style.opacity = 0.3
else
@dragCanvas.style.opacity = 0.85
@begunTrash = false
Editor::qualifiedFocus = (node, path) ->
documentIndex = @documentIndex node
if documentIndex < @session.floatingBlocks.length
path.activate()
@mainCanvas.insertBefore path.element, @session.floatingBlocks[documentIndex].renderGroup.element
else
path.activate()
@mainCanvas.appendChild path.element
hook 'mouseup', 0, ->
clearTimeout @discourageDropTimeout; @discourageDropTimeout = null
hook 'mouseup', 1, (point, event, state) ->
if @dragReplacing
@endDrag()
# We will consume this event iff we dropped it successfully
# in the root tree.
if @draggingBlock?
if not @session.currentlyUsingBlocks
# See if we can drop the block's text in ace mode.
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
if @trackerPointIsInAce position
leadingWhitespaceRegex = /^(\s*)/
# Get the line of text we're dropping into
pos = @aceEditor.renderer.screenToTextCoordinates position.x, position.y
line = @aceEditor.session.getLine pos.row
indentation = leadingWhitespaceRegex.exec(line)[0]
skipInitialIndent = true
prefix = ''
suffix = ''
if @session.dropIntoAceAtLineStart
# First, adjust indentation if we're dropping into the start of a
# line that ends an indentation block
firstNonWhitespaceRegex = /\S/
firstChar = firstNonWhitespaceRegex.exec(line)
if firstChar and firstChar[0] == '}'
# If this line starts with a closing bracket, use the previous line's indentation
# TODO: generalize for language indentation semantics besides C/JavaScript
prevLine = @aceEditor.session.getLine(pos.row - 1)
indentation = leadingWhitespaceRegex.exec(prevLine)[0]
# Adjust pos to start of the line (as we did during mousemove)
pos = @adjustPosToLineStart pos
skipInitialIndent = false
if pos.column == 0
suffix = '\n'
else
# Handle the case where we're dropping a block at the end of the last line
prefix = '\n'
else if indentation.length == line.length or indentation.length == pos.column
# line is whitespace only or we're inserting at the beginning of a line
# Append with a newline
suffix = '\n' + indentation
else if pos.column == line.length
# We're at the end of a non-empty line.
# Insert a new line, and base our indentation off of the next line
prefix = '\n'
skipInitialIndent = false
nextLine = @aceEditor.session.getLine(pos.row + 1)
indentation = leadingWhitespaceRegex.exec(nextLine)[0]
# Call prepareNode, which may append with a semicolon
@prepareNode @draggingBlock, null
text = @draggingBlock.stringify @session.mode
# Indent each line, unless it's the first line and wasn't placed on
# a newline
text = text.split('\n').map((line, index) =>
return (if index == 0 and skipInitialIndent then '' else indentation) + line
).join('\n')
text = prefix + text + suffix
@aceEditor.onTextInput text
else if @lastHighlight?
@undoCapture()
# Remove the block from the tree.
rememberedSocketOffsets = @spliceRememberedSocketOffsets(@draggingBlock)
# TODO this is a hacky way of preserving locations
# across parenthesis insertion
hadTextToken = @draggingBlock.start.next.type is 'text'
@spliceOut @draggingBlock
@clearHighlightCanvas()
# Fire an event for a sound
@fireEvent 'sound', [@lastHighlight.type]
# Depending on what the highlighted element is,
# we might want to drop the block at its
# beginning or at its end.
#
# We will need to log undo operations here too.
switch @lastHighlight.type
when 'indent', 'socket'
@spliceIn @draggingBlock, @lastHighlight.start
when 'block'
@spliceIn @draggingBlock, @lastHighlight.end
else
if @lastHighlight.type is 'document'
@spliceIn @draggingBlock, @lastHighlight.start
# TODO as above
hasTextToken = @draggingBlock.start.next.type is 'text'
if hadTextToken and not hasTextToken
rememberedSocketOffsets.forEach (x) ->
x.offset -= 1
else if hasTextToken and not hadTextToken
rememberedSocketOffsets.forEach (x) ->
x.offset += 1
futureCursorLocation = @toCrossDocumentLocation @draggingBlock.start
# Reparse the parent if we are
# in a socket
#
# TODO "reparseable" property (or absent contexts), bubble up
# TODO performance on large programs
if @lastHighlight.type is 'socket'
@reparse @draggingBlock.parent.parent
# Now that we've done that, we can annul stuff.
@endDrag()
@setCursor(futureCursorLocation) if futureCursorLocation?
newBeginning = futureCursorLocation.location.count
newIndex = futureCursorLocation.document
for el, i in rememberedSocketOffsets
@session.rememberedSockets.push new RememberedSocketRecord(
new CrossDocumentLocation(
newIndex
new model.Location(el.offset + newBeginning, 'socket')
),
el.text
)
# Fire the event for sound
@fireEvent 'block-click'
Editor::spliceRememberedSocketOffsets = (block) ->
if block.getDocument()?
blockBegin = block.start.getLocation().count
offsets = []
newRememberedSockets = []
for el, i in @session.rememberedSockets
if block.contains @fromCrossDocumentLocation(el.socket)
offsets.push {
offset: el.socket.location.count - blockBegin
text: el.text
}
else
newRememberedSockets.push el
@session.rememberedSockets = newRememberedSockets
return offsets
else
[]
# FLOATING BLOCK SUPPORT
# ================================
class FloatingBlockRecord
constructor: (@block, @position) ->
Editor::inTree = (block) -> (block.container ? block).getDocument() is @session.tree
Editor::inDisplay = (block) -> (block.container ? block).getDocument() in @getDocuments()
# We can create floating blocks by dropping
# blocks without a highlight.
hook 'mouseup', 0, (point, event, state) ->
if @draggingBlock? and not @lastHighlight? and not @dragReplacing
oldParent = @draggingBlock.parent
# Before we put this block into our list of floating blocks,
# we need to figure out where on the main canvas
# we are going to render it.
trackPoint = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
renderPoint = @trackerPointToMain trackPoint
palettePoint = @trackerPointToPalette trackPoint
removeBlock = true
addBlockAsFloatingBlock = true
# If we dropped it off in the palette, abort (so as to delete the block).
unless @session.viewports.main.right() > renderPoint.x > @session.viewports.main.x - @gutter.clientWidth and
@session.viewports.main.bottom() > renderPoint.y > @session.viewports.main.y
if @draggingBlock is @lassoSelection
@lassoSelection = null
addBlockAsFloatingBlock = false
else
if renderPoint.x - @session.viewports.main.x < 0
renderPoint.x = @session.viewports.main.x
# If @session.allowFloatingBlocks is false, we end the drag without deleting the block.
if not @session.allowFloatingBlocks
addBlockAsFloatingBlock = false
removeBlock = false
if removeBlock
# Remove the block from the tree.
@undoCapture()
rememberedSocketOffsets = @spliceRememberedSocketOffsets(@draggingBlock)
@spliceOut @draggingBlock
if not addBlockAsFloatingBlock
@endDrag()
return
else if renderPoint.x - @session.viewports.main.x < 0
renderPoint.x = @session.viewports.main.x
# Add the undo operation associated
# with creating this floating block
newDocument = new model.Document(oldParent?.parseContext ? @session.mode.rootContext, {roundedSingletons: true})
newDocument.insert newDocument.start, @draggingBlock
@pushUndo new FloatingOperation @session.floatingBlocks.length, newDocument, renderPoint, 'create'
# Add this block to our list of floating blocks
@session.floatingBlocks.push record = new FloatingBlockRecord(
newDocument
renderPoint
)
@initializeFloatingBlock record, @session.floatingBlocks.length - 1
@setCursor @draggingBlock.start
# TODO write a test for this logic
for el, i in rememberedSocketOffsets
@session.rememberedSockets.push new RememberedSocketRecord(
new CrossDocumentLocation(
@session.floatingBlocks.length,
new model.Location(el.offset + 1, 'socket')
),
el.text
)
# Now that we've done that, we can annul stuff.
@clearDrag()
@draggingBlock = null
@draggingOffset = null
@lastHighlightPath?.destroy?()
@lastHighlight = @lastHighlightPath = null
@redrawMain()
Editor::performFloatingOperation = (op, direction) ->
if (op.type is 'create') is (direction is 'forward')
if @session.cursor.document > op.index
@session.cursor.document += 1
for socket in @session.rememberedSockets
if socket.socket.document > op.index
socket.socket.document += 1
@session.floatingBlocks.splice op.index, 0, record = new FloatingBlockRecord(
op.block.clone()
op.position
)
@initializeFloatingBlock record, op.index
else
# If the cursor's document is about to vanish,
# put it back in the main tree.
if @session.cursor.document is op.index + 1
@setCursor @session.tree.start
for socket in @session.rememberedSockets
if socket.socket.document > op.index + 1
socket.socket.document -= 1
@session.floatingBlocks.splice op.index, 1
class FloatingOperation
constructor: (@index, @block, @position, @type) ->
@block = @block.clone()
toString: -> JSON.stringify({
index: @index
block: @block.stringify()
position: @position.toString()
type: @type
})
# PALETTE SUPPORT
# ================================
# The first thing we will have to do with
# the palette is install the hierarchical menu.
#
# This happens at population time.
hook 'populate', 0, ->
# Create the hierarchical menu element.
@paletteHeader = document.createElement 'div'
@paletteHeader.className = 'droplet-palette-header'
# Append the element.
@paletteElement.appendChild @paletteHeader
if @session?
@setPalette @session.paletteGroups
parseBlock = (mode, code, context = null) =>
block = mode.parse(code, {context}).start.next.container
block.start.prev = block.end.next = null
block.setParent null
return block
Editor::setPalette = (paletteGroups) ->
@paletteHeader.innerHTML = ''
@session.paletteGroups = paletteGroups
@session.currentPaletteBlocks = []
@session.currentPaletteMetadata = []
paletteHeaderRow = null
for paletteGroup, i in @session.paletteGroups then do (paletteGroup, i) =>
# Start a new row, if we're at that point
# in our appending cycle
if i % 2 is 0
paletteHeaderRow = document.createElement 'div'
paletteHeaderRow.className = 'droplet-palette-header-row'
@paletteHeader.appendChild paletteHeaderRow
# hide the header if there is only one group, and it has no name.
if @session.paletteGroups.length is 1 and !paletteGroup.name
paletteHeaderRow.style.height = 0
# Create the element itself
paletteGroupHeader = paletteGroup.header = document.createElement 'div'
paletteGroupHeader.className = 'droplet-palette-group-header'
if paletteGroup.id
paletteGroupHeader.id = 'droplet-palette-group-header-' + paletteGroup.id
paletteGroupHeader.innerText = paletteGroupHeader.textContent = paletteGroupHeader.textContent = paletteGroup.name # innerText and textContent for FF compatability
if paletteGroup.color
paletteGroupHeader.className += ' ' + paletteGroup.color
paletteHeaderRow.appendChild paletteGroupHeader
newPaletteBlocks = []
# Parse all the blocks in this palette and clone them
for data in paletteGroup.blocks
newBlock = parseBlock(@session.mode, data.block, data.context)
expansion = data.expansion or null
newPaletteBlocks.push
block: newBlock
expansion: expansion
context: data.context
title: data.title
id: data.id
paletteGroup.parsedBlocks = newPaletteBlocks
# When we click this element,
# we should switch to it in the palette.
updatePalette = =>
@changePaletteGroup paletteGroup
clickHandler = =>
do updatePalette
paletteGroupHeader.addEventListener 'click', clickHandler
paletteGroupHeader.addEventListener 'touchstart', clickHandler
# If we are the first element, make us the selected palette group.
if i is 0
do updatePalette
@resizePalette()
@resizePaletteHighlight()
# Change which palette group is selected.
# group argument can be object, id (string), or name (string)
#
Editor::changePaletteGroup = (group) ->
for curGroup, i in @session.paletteGroups
if group is curGroup or group is curGroup.id or group is curGroup.name
paletteGroup = curGroup
break
if not paletteGroup
return
# Record that we are the selected group now
@session.currentPaletteGroup = paletteGroup.name
@session.currentPaletteBlocks = paletteGroup.parsedBlocks
@session.currentPaletteMetadata = paletteGroup.parsedBlocks
# Unapply the "selected" style to the current palette group header
@session.currentPaletteGroupHeader?.className =
@session.currentPaletteGroupHeader.className.replace(
/\s[-\w]*-selected\b/, '')
# Now we are the current palette group header
@session.currentPaletteGroupHeader = paletteGroup.header
@currentPaletteIndex = i
# Apply the "selected" style to us
@session.currentPaletteGroupHeader.className +=
' droplet-palette-group-header-selected'
# Redraw the palette.
@rebuildPalette()
@fireEvent 'selectpalette', [paletteGroup.name]
# The next thing we need to do with the palette
# is let people pick things up from it.
hook 'mousedown', 6, (point, event, state) ->
# If someone else has already taken this click, pass.
if state.consumedHitTest then return
# If it's not in the palette pane, pass.
if not @trackerPointIsInPalette(point) then return
palettePoint = @trackerPointToPalette point
if @session.viewports.palette.contains(palettePoint)
if @handleTextInputClickInPalette palettePoint
state.consumedHitTest = true
return
for entry in @session.currentPaletteBlocks
hitTestResult = @hitTest palettePoint, entry.block, @session.paletteView
if hitTestResult?
@clickedBlock = entry.block
@clickedPoint = point
@clickedBlockPaletteEntry = entry
state.consumedHitTest = true
@fireEvent 'pickblock', [entry.id]
return
@clickedBlockPaletteEntry = null
# PALETTE HIGHLIGHT CODE
# ================================
hook 'populate', 1, ->
@paletteHighlightCanvas = @paletteHighlightCtx = document.createElementNS SVG_STANDARD, 'svg'
@paletteHighlightCanvas.setAttribute 'class', 'droplet-palette-highlight-canvas'
@paletteHighlightPath = null
@currentHighlightedPaletteBlock = null
@paletteElement.appendChild @paletteHighlightCanvas
Editor::resizePaletteHighlight = ->
@paletteHighlightCanvas.style.top = @paletteHeader.clientHeight + 'px'
@paletteHighlightCanvas.style.width = "#{@paletteCanvas.clientWidth}px"
@paletteHighlightCanvas.style.height = "#{@paletteCanvas.clientHeight}px"
hook 'redraw_palette', 0, ->
@clearPaletteHighlightCanvas()
if @currentHighlightedPaletteBlock?
@paletteHighlightPath.update()
# TEXT INPUT SUPPORT
# ================================
# At populate-time, we need
# to create and append the hidden input
# we will use for text input.
hook 'populate', 1, ->
@hiddenInput = document.createElement 'textarea'
@hiddenInput.className = 'droplet-hidden-input'
@hiddenInput.addEventListener 'focus', =>
if @cursorAtSocket()
# Must ensure that @hiddenInput is within the client area
# or else the other divs under @dropletElement will scroll out of
# position when @hiddenInput receives keystrokes with focus
# (left and top should not be closer than 10 pixels from the edge)
bounds = @session.view.getViewNodeFor(@getCursor()).bounds[0]
###
inputLeft = bounds.x + @mainCanvas.offsetLeft - @session.viewports.main.x
inputLeft = Math.min inputLeft, @dropletElement.clientWidth - 10
inputLeft = Math.max @mainCanvas.offsetLeft, inputLeft
@hiddenInput.style.left = inputLeft + 'px'
inputTop = bounds.y - @session.viewports.main.y
inputTop = Math.min inputTop, @dropletElement.clientHeight - 10
inputTop = Math.max 0, inputTop
@hiddenInput.style.top = inputTop + 'px'
###
@dropletElement.appendChild @hiddenInput
# We also need to initialise some fields
# for knowing what is focused
@textInputAnchor = null
@textInputSelecting = false
@oldFocusValue = null
# Prevent kids from deleting a necessary quote accidentally
@hiddenInput.addEventListener 'keydown', (event) =>
if event.keyCode is 8 and @hiddenInput.value.length > 1 and
@hiddenInput.value[0] is @hiddenInput.value[@hiddenInput.value.length - 1] and
@hiddenInput.value[0] in ['\'', '\"'] and @hiddenInput.selectionEnd is 1
event.preventDefault()
# The hidden input should be set up
# to mirror the text to which it is associated.
for event in ['input', 'keyup', 'keydown', 'select']
@hiddenInput.addEventListener event, =>
@highlightFlashShow()
if @cursorAtSocket()
@redrawTextInput()
# Update the dropdown size to match
# the new length, if it is visible.
if @dropdownVisible
@formatDropdown()
Editor::resizeAceElement = ->
width = @wrapperElement.clientWidth
if @session?.showPaletteInTextMode and @session?.paletteEnabled
width -= @paletteWrapper.clientWidth
@aceElement.style.width = "#{width}px"
@aceElement.style.height = "#{@wrapperElement.clientHeight}px"
last_ = (array) -> array[array.length - 1]
# Redraw function for text input
Editor::redrawTextInput = ->
return unless @session?
sameLength = @getCursor().stringify().split('\n').length is @hiddenInput.value.split('\n').length
dropletDocument = @getCursor().getDocument()
# Set the value in the model to fit
# the hidden input value.
@populateSocket @getCursor(), @hiddenInput.value
textFocusView = @session.view.getViewNodeFor @getCursor()
# Determine the coordinate positions
# of the typing cursor
startRow = @getCursor().stringify()[...@hiddenInput.selectionStart].split('\n').length - 1
endRow = @getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n').length - 1
# Redraw the main canvas, on top of
# which we will draw the cursor and
# highlights.
if sameLength and startRow is endRow
line = endRow
head = @getCursor().start
until head is dropletDocument.start
head = head.prev
if head.type is 'newline' then line++
treeView = @session.view.getViewNodeFor dropletDocument
oldp = helper.deepCopy [
treeView.glue[line - 1],
treeView.glue[line],
treeView.bounds[line].height
]
treeView.layout()
newp = helper.deepCopy [
treeView.glue[line - 1],
treeView.glue[line],
treeView.bounds[line].height
]
# If the layout has not changed enough to affect
# anything non-local, only redraw locally.
@redrawMain()
###
if helper.deepEquals newp, oldp
rect = new @draw.NoRectangle()
rect.unite treeView.bounds[line - 1] if line > 0
rect.unite treeView.bounds[line]
rect.unite treeView.bounds[line + 1] if line + 1 < treeView.bounds.length
rect.width = Math.max rect.width, @mainCanvas.clientWidth
@redrawMain
boundingRectangle: rect
else @redrawMain()
###
# Otherwise, redraw the whole thing
else
@redrawMain()
Editor::redrawTextHighlights = (scrollIntoView = false) ->
@clearHighlightCanvas()
return unless @session?
return unless @cursorAtSocket()
textFocusView = @session.view.getViewNodeFor @getCursor()
# Determine the coordinate positions
# of the typing cursor
startRow = @getCursor().stringify()[...@hiddenInput.selectionStart].split('\n').length - 1
endRow = @getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n').length - 1
lines = @getCursor().stringify().split '\n'
startPosition = textFocusView.bounds[startRow].x + @session.view.opts.textPadding +
@session.fontWidth * last_(@getCursor().stringify()[...@hiddenInput.selectionStart].split('\n')).length +
(if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)
endPosition = textFocusView.bounds[endRow].x + @session.view.opts.textPadding +
@session.fontWidth * last_(@getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n')).length +
(if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)
# Now draw the highlight/typing cursor
#
# Draw a line if it is just a cursor
if @hiddenInput.selectionStart is @hiddenInput.selectionEnd
@qualifiedFocus @getCursor(), @textCursorPath
points = [
new @session.view.draw.Point(startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding),
new @session.view.draw.Point(startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding + @session.view.opts.textHeight)
]
@textCursorPath.setPoints points
@textCursorPath.style.strokeColor = '#000'
@textCursorPath.update()
@qualifiedFocus @getCursor(), @textCursorPath
@textInputHighlighted = false
# Draw a translucent rectangle if there is a selection.
else
@textInputHighlighted = true
# TODO maybe put this in the view?
rectangles = []
if startRow is endRow
rectangles.push new @session.view.draw.Rectangle startPosition,
textFocusView.bounds[startRow].y + @session.view.opts.textPadding
endPosition - startPosition, @session.view.opts.textHeight
else
rectangles.push new @session.view.draw.Rectangle startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding,
textFocusView.bounds[startRow].right() - @session.view.opts.textPadding - startPosition, @session.view.opts.textHeight
for i in [startRow + 1...endRow]
rectangles.push new @session.view.draw.Rectangle textFocusView.bounds[i].x,
textFocusView.bounds[i].y + @session.view.opts.textPadding,
textFocusView.bounds[i].width,
@session.view.opts.textHeight
rectangles.push new @session.view.draw.Rectangle textFocusView.bounds[endRow].x,
textFocusView.bounds[endRow].y + @session.view.opts.textPadding,
endPosition - textFocusView.bounds[endRow].x,
@session.view.opts.textHeight
left = []; right = []
for el, i in rectangles
left.push new @session.view.draw.Point el.x, el.y
left.push new @session.view.draw.Point el.x, el.bottom()
right.push new @session.view.draw.Point el.right(), el.y
right.push new @session.view.draw.Point el.right(), el.bottom()
@textCursorPath.setPoints left.concat right.reverse()
@textCursorPath.style.strokeColor = 'none'
@textCursorPath.update()
@qualifiedFocus @getCursor(), @textCursorPath
if scrollIntoView and endPosition > @session.viewports.main.x + @mainCanvas.clientWidth
@mainScroller.scrollLeft = endPosition - @mainCanvas.clientWidth + @session.view.opts.padding
escapeString = (str) ->
str[0] + str[1...-1].replace(/(\'|\"|\n)/g, '\\$1') + str[str.length - 1]
hook 'mousedown', 7, ->
@hideDropdown()
# If we can, try to reparse the focus
# value.
#
# When reparsing occurs, we first try to treat the socket
# as a separate block (inserting parentheses, etc), then fall
# back on reparsing it with original text before giving up.
#
# For instance:
#
# (a * b)
# -> edits [b] to [b + c]
# -> reparse to b + c
# -> inserts with parens to (a * (b + c))
# -> finished.
#
# OR
#
# function (a) {}
# -> edits [a] to [a, b]
# -> reparse to a, b
# -> inserts with parens to function((a, b)) {}
# -> FAILS.
# -> Fall back to raw reparsing the parent with unparenthesized text
# -> Reparses function(a, b) {} with two paremeters.
# -> Finsihed.
Editor::reparse = (list, recovery, updates = [], originalTrigger = list) ->
# Don't reparse sockets. When we reparse sockets,
# reparse them first, then try reparsing their parent and
# make sure everything checks out.
if list.start.type is 'socketStart'
return if list.start.next is list.end
originalText = list.textContent()
originalUpdates = updates.map (location) ->
count: location.count, type: location.type
# If our language mode has a string-fixing feature (in most languages,
# this will simply autoescape quoted "strings"), apply it
if @session.mode.stringFixer?
@populateSocket list, @session.mode.stringFixer list.textContent()
# Try reparsing the parent after beforetextfocus. If it fails,
# repopulate with the original text and try again.
unless @reparse list.parent, recovery, updates, originalTrigger
@populateSocket list, originalText
originalUpdates.forEach (location, i) ->
updates[i].count = location.count
updates[i].type = location.type
@reparse list.parent, recovery, updates, originalTrigger
return
parent = list.start.parent
if parent?.type is 'indent' and not list.start.container?.parseContext?
context = parent.parseContext
else
context = (list.start.container ? list.start.parent).parseContext
try
newList = @session.mode.parse list.stringifyInPlace(),{
wrapAtRoot: parent.type isnt 'socket'
context: context
}
catch e
try
newList = @session.mode.parse recovery(list.stringifyInPlace()), {
wrapAtRoot: parent.type isnt 'socket'
context: context
}
catch e
# Seek a parent that is not a socket
# (since we should never reparse just a socket)
while parent? and parent.type is 'socket'
parent = parent.parent
# Attempt to bubble up to the parent
if parent?
return @reparse parent, recovery, updates, originalTrigger
else
@session.view.getViewNodeFor(originalTrigger).mark {color: '#F00'}
return false
return if newList.start.next is newList.end
# Exclude the document start and end tags
newList = new model.List newList.start.next, newList.end.prev
# Prepare the new node for insertion
newList.traverseOneLevel (head) =>
@prepareNode head, parent
@replace list, newList, updates
@redrawMain()
return true
Editor::setTextSelectionRange = (selectionStart, selectionEnd) ->
if selectionStart? and not selectionEnd?
selectionEnd = selectionStart
# Focus the hidden input.
if @cursorAtSocket()
@hiddenInput.focus()
if selectionStart? and selectionEnd?
@hiddenInput.setSelectionRange selectionStart, selectionEnd
else if @hiddenInput.value[0] is @hiddenInput.value[@hiddenInput.value.length - 1] and
@hiddenInput.value[0] in ['\'', '"']
@hiddenInput.setSelectionRange 1, @hiddenInput.value.length - 1
else
@hiddenInput.setSelectionRange 0, @hiddenInput.value.length
@redrawTextInput()
# Redraw.
@redrawMain(); @redrawTextInput()
Editor::cursorAtSocket = -> @getCursor().type is 'socket'
Editor::populateSocket = (socket, string) ->
unless socket.textContent() is string
lines = string.split '\n'
unless socket.start.next is socket.end
@spliceOut new model.List socket.start.next, socket.end.prev
first = last = new model.TextToken lines[0]
for line, i in lines when i > 0
last = helper.connect last, new model.NewlineToken()
last = helper.connect last, new model.TextToken line
@spliceIn (new model.List(first, last)), socket.start
Editor::populateBlock = (block, string) ->
newBlock = @session.mode.parse(string, wrapAtRoot: false).start.next.container
if newBlock
# Find the first token before the block
# that will still be around after the
# block has been removed
position = block.start.prev
while position?.type is 'newline' and not (
position.prev?.type is 'indentStart' and
position.prev.container.end is block.end.next)
position = position.prev
@spliceOut block
@spliceIn newBlock, position
return true
return false
# Convenience hit-testing function
Editor::hitTestTextInput = (point, block) ->
head = block.start
while head?
if head.type is 'socketStart' and head.container.isDroppable() and
@session.view.getViewNodeFor(head.container).path.contains point
return head.container
head = head.next
return null
# Convenience functions for setting
# the text input selection, given
# points on the main canvas.
Editor::getTextPosition = (point) ->
textFocusView = @session.view.getViewNodeFor @getCursor()
row = Math.floor((point.y - textFocusView.bounds[0].y) / (@session.fontSize + 2 * @session.view.opts.padding))
row = Math.max row, 0
row = Math.min row, textFocusView.lineLength - 1
column = Math.max 0, Math.round((point.x - textFocusView.bounds[row].x - @session.view.opts.textPadding - (if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)) / @session.fontWidth)
lines = @getCursor().stringify().split('\n')[..row]
lines[lines.length - 1] = lines[lines.length - 1][...column]
return lines.join('\n').length
Editor::setTextInputAnchor = (point) ->
@textInputAnchor = @textInputHead = @getTextPosition point
@hiddenInput.setSelectionRange @textInputAnchor, @textInputHead
Editor::selectDoubleClick = (point) ->
position = @getTextPosition point
before = @getCursor().stringify()[...position].match(/\w*$/)[0]?.length ? 0
after = @getCursor().stringify()[position..].match(/^\w*/)[0]?.length ? 0
@textInputAnchor = position - before
@textInputHead = position + after
@hiddenInput.setSelectionRange @textInputAnchor, @textInputHead
Editor::setTextInputHead = (point) ->
@textInputHead = @getTextPosition point
@hiddenInput.setSelectionRange Math.min(@textInputAnchor, @textInputHead), Math.max(@textInputAnchor, @textInputHead)
# On mousedown, we will want to start
# selections and focus text inputs
# if we apply.
Editor::handleTextInputClick = (mainPoint, dropletDocument) ->
hitTestResult = @hitTestTextInput mainPoint, dropletDocument
# If they have clicked a socket,
# focus it.
if hitTestResult?
unless hitTestResult is @getCursor()
if hitTestResult.editable()
@undoCapture()
@setCursor hitTestResult
@redrawMain()
if hitTestResult.hasDropdown() and ((not hitTestResult.editable()) or
mainPoint.x - @session.view.getViewNodeFor(hitTestResult).bounds[0].x < helper.DROPDOWN_ARROW_WIDTH)
@showDropdown hitTestResult
@textInputSelecting = false
else
if @getCursor().hasDropdown() and
mainPoint.x - @session.view.getViewNodeFor(hitTestResult).bounds[0].x < helper.DROPDOWN_ARROW_WIDTH
@showDropdown()
@setTextInputAnchor mainPoint
@redrawTextInput()
@textInputSelecting = true
# Now that we have focused the text element
# in the Droplet model, focus the hidden input.
#
# It is important that this be done after the Droplet model
# has focused its text element, because
# the hidden input moves on the focus() event to
# the currently-focused Droplet element to make
# mobile screen scroll properly.
@hiddenInput.focus()
return true
else
return false
# Convenience hit-testing function
Editor::hitTestTextInputInPalette = (point, block) ->
head = block.start
while head?
if head.type is 'socketStart' and head.container.isDroppable() and
@session.paletteView.getViewNodeFor(head.container).path.contains point
return head.container
head = head.next
return null
Editor::handleTextInputClickInPalette = (palettePoint) ->
for entry in @session.currentPaletteBlocks
hitTestResult = @hitTestTextInputInPalette palettePoint, entry.block
# If they have clicked a socket, check to see if it is a dropdown
if hitTestResult?
if hitTestResult.hasDropdown()
@showDropdown hitTestResult, true
return true
return false
# Create the dropdown DOM element at populate time.
hook 'populate', 0, ->
@dropdownElement = document.createElement 'div'
@dropdownElement.className = 'droplet-dropdown'
@wrapperElement.appendChild @dropdownElement
@dropdownElement.innerHTML = ''
@dropdownElement.style.display = 'inline-block'
@dropdownVisible = false
# Update the dropdown to match
# the current text focus font and size.
Editor::formatDropdown = (socket = @getCursor(), view = @session.view) ->
@dropdownElement.style.fontFamily = @session.fontFamily
@dropdownElement.style.fontSize = @session.fontSize
@dropdownElement.style.minWidth = view.getViewNodeFor(socket).bounds[0].width
Editor::getDropdownList = (socket) ->
result = socket.dropdown
if result.generate
result = result.generate
if 'function' is typeof result
result = socket.dropdown()
else
result = socket.dropdown
if result.options
result = result.options
newresult = []
for key, val of result
newresult.push if 'string' is typeof val then { text: val, display: val } else val
return newresult
Editor::showDropdown = (socket = @getCursor(), inPalette = false) ->
@dropdownVisible = true
dropdownItems = []
@dropdownElement.innerHTML = ''
@dropdownElement.style.display = 'inline-block'
@formatDropdown socket, if inPalette then @session.paletteView else @session.view
for el, i in @getDropdownList(socket) then do (el) =>
div = document.createElement 'div'
div.innerHTML = el.display
div.className = 'droplet-dropdown-item'
dropdownItems.push div
div.style.paddingLeft = helper.DROPDOWN_ARROW_WIDTH
setText = (text) =>
@undoCapture()
# Attempting to populate the socket after the dropdown has closed should no-op
if @dropdownElement.style.display == 'none'
return
if inPalette
@populateSocket socket, text
@redrawPalette()
else if not socket.editable()
@populateSocket socket, text
@redrawMain()
else
if not @cursorAtSocket()
return
@populateSocket @getCursor(), text
@hiddenInput.value = text
@redrawMain()
@hideDropdown()
div.addEventListener 'mouseup', ->
if el.click
el.click(setText)
else
setText(el.text)
@dropdownElement.appendChild div
@dropdownElement.style.top = '-9999px'
@dropdownElement.style.left = '-9999px'
# Wait for a render. Then,
# if the div is scrolled vertically, add
# some padding on the right. After checking for this,
# move the dropdown element into position
setTimeout (=>
if @dropdownElement.clientHeight < @dropdownElement.scrollHeight
for el in dropdownItems
el.style.paddingRight = DROPDOWN_SCROLLBAR_PADDING
if inPalette
location = @session.paletteView.getViewNodeFor(socket).bounds[0]
@dropdownElement.style.left = location.x - @session.viewports.palette.x + @paletteCanvas.clientLeft + 'px'
@dropdownElement.style.minWidth = location.width + 'px'
dropdownTop = location.y + @session.fontSize - @session.viewports.palette.y + @paletteCanvas.clientTop
if dropdownTop + @dropdownElement.clientHeight > @paletteElement.clientHeight
dropdownTop -= (@session.fontSize + @dropdownElement.clientHeight)
@dropdownElement.style.top = dropdownTop + 'px'
else
location = @session.view.getViewNodeFor(socket).bounds[0]
@dropdownElement.style.left = location.x - @session.viewports.main.x + @dropletElement.offsetLeft + @gutter.clientWidth + 'px'
@dropdownElement.style.minWidth = location.width + 'px'
dropdownTop = location.y + @session.fontSize - @session.viewports.main.y
if dropdownTop + @dropdownElement.clientHeight > @dropletElement.clientHeight
dropdownTop -= (@session.fontSize + @dropdownElement.clientHeight)
@dropdownElement.style.top = dropdownTop + 'px'
), 0
Editor::hideDropdown = ->
@dropdownVisible = false
@dropdownElement.style.display = 'none'
@dropletElement.focus()
hook 'dblclick', 0, (point, event, state) ->
# If someone else already took this click, return.
if state.consumedHitTest then return
for dropletDocument in @getDocuments()
# Otherwise, look for a socket that
# the user has clicked
mainPoint = @trackerPointToMain point
hitTestResult = @hitTestTextInput mainPoint, @session.tree
# If they have clicked a socket,
# focus it, and
unless hitTestResult is @getCursor()
if hitTestResult? and hitTestResult.editable()
@redrawMain()
hitTestResult = @hitTestTextInput mainPoint, @session.tree
if hitTestResult? and hitTestResult.editable()
@setCursor hitTestResult
@redrawMain()
setTimeout (=>
@selectDoubleClick mainPoint
@redrawTextInput()
@textInputSelecting = false
), 0
state.consumedHitTest = true
return
# On mousemove, if we are selecting,
# we want to update the selection
# to match the mouse.
hook 'mousemove', 0, (point, event, state) ->
if @textInputSelecting
unless @cursorAtSocket()
@textInputSelecting = false; return
mainPoint = @trackerPointToMain point
@setTextInputHead mainPoint
@redrawTextInput()
# On mouseup, we want to stop selecting.
hook 'mouseup', 0, (point, event, state) ->
if @textInputSelecting
mainPoint = @trackerPointToMain point
@setTextInputHead mainPoint
@redrawTextInput()
@textInputSelecting = false
# LASSO SELECT SUPPORT
# ===============================
# The lasso select
# will have its own canvas
# for drawing the lasso. This needs
# to be added at populate-time, along
# with some fields.
hook 'populate', 0, ->
@lassoSelectRect = document.createElementNS SVG_STANDARD, 'rect'
@lassoSelectRect.setAttribute 'stroke', '#00f'
@lassoSelectRect.setAttribute 'fill', 'none'
@lassoSelectAnchor = null
@lassoSelection = null
@mainCanvas.appendChild @lassoSelectRect
Editor::clearLassoSelection = ->
@lassoSelection = null
@redrawHighlights()
# On mousedown, if nobody has taken
# a hit test yet, start a lasso select.
hook 'mousedown', 0, (point, event, state) ->
# Even if someone has taken it, we
# should remove the lasso segment that is
# already there.
unless state.clickedLassoSelection then @clearLassoSelection()
if state.consumedHitTest or state.suppressLassoSelect then return
# If it's not in the main pane, pass.
if not @trackerPointIsInMain(point) then return
if @trackerPointIsInPalette(point) then return
# If the point was actually in the main canvas,
# start a lasso select.
mainPoint = @trackerPointToMain(point).from @session.viewports.main
palettePoint = @trackerPointToPalette(point).from @session.viewports.palette
@lassoSelectAnchor = @trackerPointToMain point
# On mousemove, if we are in the middle of a
# lasso select, continue with it.
hook 'mousemove', 0, (point, event, state) ->
if @lassoSelectAnchor?
mainPoint = @trackerPointToMain point
lassoRectangle = new @draw.Rectangle(
Math.min(@lassoSelectAnchor.x, mainPoint.x),
Math.min(@lassoSelectAnchor.y, mainPoint.y),
Math.abs(@lassoSelectAnchor.x - mainPoint.x),
Math.abs(@lassoSelectAnchor.y - mainPoint.y)
)
findLassoSelect = (dropletDocument) =>
first = dropletDocument.start
until (not first?) or first.type is 'blockStart' and @session.view.getViewNodeFor(first.container).path.intersects lassoRectangle
first = first.next
last = dropletDocument.end
until (not last?) or last.type is 'blockEnd' and @session.view.getViewNodeFor(last.container).path.intersects lassoRectangle
last = last.prev
@clearHighlightCanvas()
@mainCanvas.appendChild @lassoSelectRect
@lassoSelectRect.style.display = 'block'
@lassoSelectRect.setAttribute 'x', lassoRectangle.x
@lassoSelectRect.setAttribute 'y', lassoRectangle.y
@lassoSelectRect.setAttribute 'width', lassoRectangle.width
@lassoSelectRect.setAttribute 'height', lassoRectangle.height
if first and last?
[first, last] = validateLassoSelection dropletDocument, first, last
@lassoSelection = new model.List first, last
@redrawLassoHighlight()
return true
else
@lassoSelection = null
@redrawLassoHighlight()
return false
unless @lassoSelectionDocument? and findLassoSelect @lassoSelectionDocument
for dropletDocument in @getDocuments()
if findLassoSelect dropletDocument
@lassoSelectionDocument = dropletDocument
break
Editor::redrawLassoHighlight = ->
return unless @session?
# Remove any existing selections
for dropletDocument in @getDocuments()
dropletDocumentView = @session.view.getViewNodeFor dropletDocument
dropletDocumentView.draw @session.viewports.main, {
selected: false
noText: @currentlyAnimating # TODO add some modularized way of having global view options
}
if @lassoSelection?
# Add any new selections
lassoView = @session.view.getViewNodeFor(@lassoSelection)
lassoView.absorbCache()
lassoView.draw @session.viewports.main, {selected: true}
# Convnience function for validating
# a lasso selection. A lasso selection
# cannot contain start tokens without
# their corresponding end tokens, or vice
# versa, and also must start and end
# with blocks (not Indents).
validateLassoSelection = (tree, first, last) ->
tokensToInclude = []
head = first
until head is last.next
if head instanceof model.StartToken or
head instanceof model.EndToken
tokensToInclude.push head.container.start
tokensToInclude.push head.container.end
head = head.next
first = tree.start
until first in tokensToInclude then first = first.next
last = tree.end
until last in tokensToInclude then last = last.prev
until first.type is 'blockStart'
first = first.prev
if first.type is 'blockEnd' then first = first.container.start.prev
until last.type is 'blockEnd'
last = last.next
if last.type is 'blockStart' then last = last.container.end.next
return [first, last]
# On mouseup, if we were
# doing a lasso select, insert a lasso
# select segment.
hook 'mouseup', 0, (point, event, state) ->
if @lassoSelectAnchor?
if @lassoSelection?
# Move the cursor to the selection
@setCursor @lassoSelection.end
@lassoSelectAnchor = null
@lassoSelectRect.style.display = 'none'
@redrawHighlights()
@lassoSelectionDocument = null
# On mousedown, we might want to
# pick a selected segment up; check.
hook 'mousedown', 3, (point, event, state) ->
if state.consumedHitTest then return
if @lassoSelection? and @hitTest(@trackerPointToMain(point), @lassoSelection)?
@clickedBlock = @lassoSelection
@clickedBlockPaletteEntry = null
@clickedPoint = point
state.consumedHitTest = true
state.clickedLassoSelection = true
# CURSOR OPERATION SUPPORT
# ================================
class CrossDocumentLocation
constructor: (@document, @location) ->
is: (other) -> @location.is(other.location) and @document is other.document
clone: ->
new CrossDocumentLocation(
@document,
@location.clone()
)
Editor::validCursorPosition = (destination) ->
return destination.type in ['documentStart', 'indentStart'] or
destination.type is 'blockEnd' and destination.parent.type in ['document', 'indent'] or
destination.type is 'socketStart' and destination.container.editable()
# A cursor is only allowed to be on a line.
Editor::setCursor = (destination, validate = (-> true), direction = 'after') ->
if destination? and destination instanceof CrossDocumentLocation
destination = @fromCrossDocumentLocation(destination)
# Abort if there is no destination (usually means
# someone wants to travel outside the document)
return unless destination? and @inDisplay destination
# Now set the new cursor
if destination instanceof model.Container
destination = destination.start
until @validCursorPosition(destination) and validate(destination)
destination = (if direction is 'after' then destination.next else destination.prev)
return unless destination?
destination = @toCrossDocumentLocation destination
# If the cursor was at a text input, reparse the old one
if @cursorAtSocket() and not @session.cursor.is(destination)
socket = @getCursor()
if '__comment__' not in socket.classes
@reparse socket, null, (if destination.document is @session.cursor.document then [destination.location] else [])
@hiddenInput.blur()
@dropletElement.focus()
@session.cursor = destination
# If we have messed up (usually because
# of a reparse), scramble to find a nearby
# okay place for the cursor
@correctCursor()
@redrawMain()
@highlightFlashShow()
# If we are now at a text input, populate the hidden input
if @cursorAtSocket()
if @getCursor()?.id of @session.extraMarks
delete @session.extraMarks[focus?.id]
@undoCapture()
@hiddenInput.value = @getCursor().textContent()
@hiddenInput.focus()
{start, end} = @session.mode.getDefaultSelectionRange @hiddenInput.value
@setTextSelectionRange start, end
Editor::determineCursorPosition = ->
# Do enough of the redraw to get the bounds
@session.view.getViewNodeFor(@session.tree).layout 0, @nubbyHeight
# Get a cursor that is in the model
cursor = @getCursor()
if cursor.type is 'documentStart'
bound = @session.view.getViewNodeFor(cursor.container).bounds[0]
return new @draw.Point bound.x, bound.y
else if cursor.type is 'indentStart'
line = if cursor.next.type is 'newline' then 1 else 0
bound = @session.view.getViewNodeFor(cursor.container).bounds[line]
return new @draw.Point bound.x, bound.y
else
line = @getCursor().getTextLocation().row - cursor.parent.getTextLocation().row
bound = @session.view.getViewNodeFor(cursor.parent).bounds[line]
return new @draw.Point bound.x, bound.bottom()
Editor::getCursor = ->
cursor = @fromCrossDocumentLocation @session.cursor
if cursor.type is 'socketStart'
return cursor.container
else
return cursor
Editor::scrollCursorIntoPosition = ->
axis = @determineCursorPosition().y
if axis < @session.viewports.main.y
@mainScroller.scrollTop = axis
else if axis > @session.viewports.main.bottom()
@mainScroller.scrollTop = axis - @session.viewports.main.height
@mainScroller.scrollLeft = 0
# Moves the cursor to the end of the document and scrolls it into position
# (in block and text mode)
Editor::scrollCursorToEndOfDocument = ->
if @session.currentlyUsingBlocks
pos = @session.tree.end
while pos && !@validCursorPosition(pos)
pos = pos.prev
@setCursor(pos)
@scrollCursorIntoPosition()
else
@aceEditor.scrollToLine @aceEditor.session.getLength()
# Pressing the up-arrow moves the cursor up.
hook 'keydown', 0, (event, state) ->
if event.which is UP_ARROW_KEY
@clearLassoSelection()
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, ((token) -> token.type isnt 'socketStart'), 'before'
@scrollCursorIntoPosition()
else if event.which is DOWN_ARROW_KEY
@clearLassoSelection()
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, ((token) -> token.type isnt 'socketStart'), 'after'
@scrollCursorIntoPosition()
else if event.which is RIGHT_ARROW_KEY and
(not @cursorAtSocket() or
@hiddenInput.selectionStart is @hiddenInput.value.length)
@clearLassoSelection()
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, null, 'after'
@scrollCursorIntoPosition()
event.preventDefault()
else if event.which is LEFT_ARROW_KEY and
(not @cursorAtSocket() or
@hiddenInput.selectionEnd is 0)
@clearLassoSelection()
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, null, 'before'
@scrollCursorIntoPosition()
event.preventDefault()
hook 'keydown', 0, (event, state) ->
if event.which isnt TAB_KEY then return
if event.shiftKey
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, ((token) -> token.type is 'socketStart'), 'before'
else
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, ((token) -> token.type is 'socketStart'), 'after'
event.preventDefault()
Editor::deleteAtCursor = ->
if @getCursor().type is 'blockEnd'
block = @getCursor().container
else if @getCursor().type is 'indentStart'
block = @getCursor().parent
else
return
@setCursor block.start, null, 'before'
@undoCapture()
@spliceOut block
@redrawMain()
hook 'keydown', 0, (event, state) ->
if not @session? or @session.readOnly
return
if event.which isnt BACKSPACE_KEY
return
if state.capturedBackspace
return
# We don't want to interrupt any text input editing
# sessions. We will, however, delete a handwritten
# block if it is currently empty.
if @lassoSelection?
@deleteLassoSelection()
event.preventDefault()
return false
else if not @cursorAtSocket() or
(@hiddenInput.value.length is 0 and @getCursor().handwritten)
@deleteAtCursor()
state.capturedBackspace = true
event.preventDefault()
return false
return true
Editor::deleteLassoSelection = ->
unless @lassoSelection?
if DEBUG_FLAG
throw new Error 'Cannot delete nonexistent lasso segment'
return null
cursorTarget = @lassoSelection.start.prev
@spliceOut @lassoSelection
@lassoSelection = null
@setCursor cursorTarget
@redrawMain()
# HANDWRITTEN BLOCK SUPPORT
# ================================
hook 'keydown', 0, (event, state) ->
if not @session? or @session.readOnly
return
if event.which is ENTER_KEY
if not @cursorAtSocket() and not event.shiftKey and not event.ctrlKey and not event.metaKey
# Construct the block; flag the socket as handwritten
newBlock = new model.Block(); newSocket = new model.Socket '', Infinity, true
newSocket.setParent newBlock
helper.connect newBlock.start, newSocket.start
helper.connect newSocket.end, newBlock.end
# Seek a place near the cursor we can actually
# put a block.
head = @getCursor()
while head.type is 'newline'
head = head.prev
newSocket.parseContext = head.parent.parseContext
@spliceIn newBlock, head #MUTATION
@redrawMain()
@newHandwrittenSocket = newSocket
else if @cursorAtSocket() and not event.shiftKey
socket = @getCursor()
@hiddenInput.blur()
@dropletElement.focus()
@setCursor @session.cursor, (token) -> token.type isnt 'socketStart'
@redrawMain()
if '__comment__' in socket.classes and @session.mode.startSingleLineComment
# Create another single line comment block just below
newBlock = new model.Block 0, 'blank', helper.ANY_DROP
newBlock.classes = ['__comment__', 'block-only']
newBlock.socketLevel = helper.BLOCK_ONLY
newTextMarker = new model.TextToken @session.mode.startSingleLineComment
newTextMarker.setParent newBlock
newSocket = new model.Socket '', 0, true
newSocket.classes = ['__comment__']
newSocket.setParent newBlock
helper.connect newBlock.start, newTextMarker
helper.connect newTextMarker, newSocket.start
helper.connect newSocket.end, newBlock.end
# Seek a place near the cursor we can actually
# put a block.
head = @getCursor()
while head.type is 'newline'
head = head.prev
@spliceIn newBlock, head #MUTATION
@redrawMain()
@newHandwrittenSocket = newSocket
hook 'keyup', 0, (event, state) ->
if not @session? or @session.readOnly
return
# prevents routing the initial enter keypress to a new handwritten
# block by focusing the block only after the enter key is released.
if event.which is ENTER_KEY
if @newHandwrittenSocket?
@setCursor @newHandwrittenSocket
@newHandwrittenSocket = null
containsCursor = (block) ->
head = block.start
until head is block.end
if head.type is 'cursor' then return true
head = head.next
return false
# ANIMATION AND ACE EDITOR SUPPORT
# ================================
Editor::copyAceEditor = ->
@gutter.style.width = @aceEditor.renderer.$gutterLayer.gutterWidth + 'px'
@resizeBlockMode()
return @setValue_raw @getAceValue()
# For animation and ace editor,
# we will need a couple convenience functions
# for getting the "absolute"-esque position
# of layouted elements (a la jQuery, without jQuery).
getOffsetTop = (element) ->
top = element.offsetTop
while (element = element.offsetParent)?
top += element.offsetTop
return top
getOffsetLeft = (element) ->
left = element.offsetLeft
while (element = element.offsetParent)?
left += element.offsetLeft
return left
Editor::computePlaintextTranslationVectors = ->
# Now we need to figure out where all the text elements are going
# to end up.
textElements = []; translationVectors = []
head = @session.tree.start
aceSession = @aceEditor.session
state = {
# Initial cursor positions are
# determined by ACE editor configuration.
x: (@aceEditor.container.getBoundingClientRect().left -
@aceElement.getBoundingClientRect().left +
@aceEditor.renderer.$gutterLayer.gutterWidth) -
@gutter.clientWidth + 5 # TODO find out where this 5 comes from
y: (@aceEditor.container.getBoundingClientRect().top -
@aceElement.getBoundingClientRect().top) -
aceSession.getScrollTop()
# Initial indent depth is 0
indent: 0
# Line height and left edge are
# determined by ACE editor configuration.
lineHeight: @aceEditor.renderer.layerConfig.lineHeight
leftEdge: (@aceEditor.container.getBoundingClientRect().left -
getOffsetLeft(@aceElement) +
@aceEditor.renderer.$gutterLayer.gutterWidth) -
@gutter.clientWidth + 5 # TODO see above
}
@measureCtx.font = @aceFontSize() + ' ' + @session.fontFamily
fontWidth = @measureCtx.measureText(' ').width
rownum = 0
until head is @session.tree.end
switch head.type
when 'text'
corner = @session.view.getViewNodeFor(head).bounds[0].upperLeftCorner()
corner.x -= @session.viewports.main.x
corner.y -= @session.viewports.main.y
translationVectors.push (new @draw.Point(state.x, state.y)).from(corner)
textElements.push @session.view.getViewNodeFor head
state.x += fontWidth * head.value.length
when 'socketStart'
if head.next is head.container.end or
head.next.type is 'text' and head.next.value is ''
state.x += fontWidth * head.container.emptyString.length
# Newline moves the cursor to the next line,
# plus some indent.
when 'newline'
# Be aware of wrapped ace editor lines.
wrappedlines = Math.max(1,
aceSession.documentToScreenRow(rownum + 1, 0) -
aceSession.documentToScreenRow(rownum, 0))
rownum += 1
state.y += state.lineHeight * wrappedlines
if head.specialIndent?
state.x = state.leftEdge + fontWidth * head.specialIndent.length
else
state.x = state.leftEdge + state.indent * fontWidth
when 'indentStart'
state.indent += head.container.depth
when 'indentEnd'
state.indent -= head.container.depth
head = head.next
return {
textElements: textElements
translationVectors: translationVectors
}
Editor::checkAndHighlightEmptySockets = ->
head = @session.tree.start
ok = true
until head is @session.tree.end
if (head.type is 'socketStart' and head.next is head.container.end or
head.type is 'socketStart' and head.next.type is 'text' and head.next.value is '') and
head.container.emptyString isnt ''
@markBlock head.container, {color: '#F00'}
ok = false
head = head.next
return ok
Editor::performMeltAnimation = (fadeTime = 500, translateTime = 1000, cb = ->) ->
if @session.currentlyUsingBlocks and not @currentlyAnimating
# If the preserveEmpty option is turned off, we will not round-trip empty sockets.
#
# Therefore, forbid melting if there is an empty socket. If there is,
# highlight it in red.
if not @session.options.preserveEmpty and not @checkAndHighlightEmptySockets()
@redrawMain()
return
@hideDropdown()
@fireEvent 'statechange', [false]
@setAceValue @getValue()
top = @findLineNumberAtCoordinate @session.viewports.main.y
@aceEditor.scrollToLine top
@aceEditor.resize true
@redrawMain noText: true
# Hide scrollbars and increase width
if @mainScroller.scrollWidth > @mainScroller.clientWidth
@mainScroller.style.overflowX = 'scroll'
else
@mainScroller.style.overflowX = 'hidden'
@mainScroller.style.overflowY = 'hidden'
@dropletElement.style.width = @wrapperElement.clientWidth + 'px'
@session.currentlyUsingBlocks = false; @currentlyAnimating = @currentlyAnimating_suppressRedraw = true
# Compute where the text will end up
# in the ace editor
{textElements, translationVectors} = @computePlaintextTranslationVectors()
translatingElements = []
for textElement, i in textElements
# Skip anything that's
# off the screen the whole time.
unless 0 < textElement.bounds[0].bottom() - @session.viewports.main.y + translationVectors[i].y and
textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y < @session.viewports.main.height
continue
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = textElement.model.value
div.style.font = @session.fontSize + 'px ' + @session.fontFamily
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y - @session.fontAscent}px"
div.className = 'droplet-transitioning-element'
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@transitionContainer.appendChild div
do (div, textElement, translationVectors, i) =>
setTimeout (=>
div.style.left = (textElement.bounds[0].x - @session.viewports.main.x + translationVectors[i].x) + 'px'
div.style.top = (textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y) + 'px'
div.style.fontSize = @aceFontSize()
), fadeTime
top = Math.max @aceEditor.getFirstVisibleRow(), 0
bottom = Math.min @aceEditor.getLastVisibleRow(), @session.view.getViewNodeFor(@session.tree).lineLength - 1
aceScrollTop = @aceEditor.session.getScrollTop()
treeView = @session.view.getViewNodeFor @session.tree
lineHeight = @aceEditor.renderer.layerConfig.lineHeight
for line in [top..bottom]
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = line + 1
div.style.left = 0
div.style.top = "#{treeView.bounds[line].y + treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent - @session.viewports.main.y}px"
div.style.font = @session.fontSize + 'px ' + @session.fontFamily
div.style.width = "#{@gutter.clientWidth}px"
translatingElements.push div
div.className = 'droplet-transitioning-element droplet-transitioning-gutter droplet-gutter-line'
# Add annotation
if @annotations[line]?
div.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
@dropletElement.appendChild div
do (div, line) =>
# Set off the css transition
setTimeout (=>
div.style.left = '0px'
div.style.top = (@aceEditor.session.documentToScreenRow(line, 0) *
lineHeight - aceScrollTop) + 'px'
div.style.fontSize = @aceFontSize()
), fadeTime
@lineNumberWrapper.style.display = 'none'
# Kick off fade-out transition
@mainCanvas.style.transition =
@highlightCanvas.style.transition = "opacity #{fadeTime}ms linear"
@mainCanvas.style.opacity = 0
paletteDisappearingWithMelt = @session.paletteEnabled and not @session.showPaletteInTextMode
if paletteDisappearingWithMelt
# Move the palette header into the background
@paletteHeader.style.zIndex = 0
setTimeout (=>
@dropletElement.style.transition = "left #{translateTime}ms"
@dropletElement.style.left = '0px'
), fadeTime
setTimeout (=>
# Translate the ICE editor div out of frame.
@dropletElement.style.transition = ''
# Translate the ACE editor div into frame.
@aceElement.style.top = '0px'
if @session.showPaletteInTextMode and @session.paletteEnabled
@aceElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@aceElement.style.left = '0px'
#if paletteDisappearingWithMelt
# @paletteWrapper.style.top = '-9999px'
# @paletteWrapper.style.left = '-9999px'
@dropletElement.style.top = '-9999px'
@dropletElement.style.left = '-9999px'
# Finalize a bunch of animations
# that should be complete by now,
# but might not actually be due to
# floating point stuff.
@currentlyAnimating = false
# Show scrollbars again
@mainScroller.style.overflow = 'auto'
for div in translatingElements
div.parentNode.removeChild div
@fireEvent 'toggledone', [@session.currentlyUsingBlocks]
if cb? then do cb
), fadeTime + translateTime
return success: true
Editor::aceFontSize = ->
parseFloat(@aceEditor.getFontSize()) + 'px'
Editor::performFreezeAnimation = (fadeTime = 500, translateTime = 500, cb = ->)->
return unless @session?
if not @session.currentlyUsingBlocks and not @currentlyAnimating
beforeTime = +(new Date())
setValueResult = @copyAceEditor()
afterTime = +(new Date())
unless setValueResult.success
if setValueResult.error
@fireEvent 'parseerror', [setValueResult.error]
return setValueResult
if @aceEditor.getFirstVisibleRow() is 0
@mainScroller.scrollTop = 0
else
@mainScroller.scrollTop = @session.view.getViewNodeFor(@session.tree).bounds[@aceEditor.getFirstVisibleRow()].y
@session.currentlyUsingBlocks = true
@currentlyAnimating = true
@fireEvent 'statechange', [true]
setTimeout (=>
# Hide scrollbars and increase width
@mainScroller.style.overflow = 'hidden'
@dropletElement.style.width = @wrapperElement.clientWidth + 'px'
@redrawMain noText: true
@currentlyAnimating_suppressRedraw = true
@aceElement.style.top = "-9999px"
@aceElement.style.left = "-9999px"
paletteAppearingWithFreeze = @session.paletteEnabled and not @session.showPaletteInTextMode
if paletteAppearingWithFreeze
@paletteWrapper.style.top = '0px'
@paletteHeader.style.zIndex = 0
@dropletElement.style.top = "0px"
if @session.paletteEnabled and not paletteAppearingWithFreeze
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@dropletElement.style.left = "0px"
{textElements, translationVectors} = @computePlaintextTranslationVectors()
translatingElements = []
for textElement, i in textElements
# Skip anything that's
# off the screen the whole time.
unless 0 < textElement.bounds[0].bottom() - @session.viewports.main.y + translationVectors[i].y and
textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y < @session.viewports.main.height
continue
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = textElement.model.value
div.style.font = @aceFontSize() + ' ' + @session.fontFamily
div.style.position = 'absolute'
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x + translationVectors[i].x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y}px"
div.className = 'droplet-transitioning-element'
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@transitionContainer.appendChild div
do (div, textElement) =>
setTimeout (=>
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y - @session.fontAscent}px"
div.style.fontSize = @session.fontSize + 'px'
), 0
top = Math.max @aceEditor.getFirstVisibleRow(), 0
bottom = Math.min @aceEditor.getLastVisibleRow(), @session.view.getViewNodeFor(@session.tree).lineLength - 1
treeView = @session.view.getViewNodeFor @session.tree
lineHeight = @aceEditor.renderer.layerConfig.lineHeight
aceScrollTop = @aceEditor.session.getScrollTop()
for line in [top..bottom]
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = line + 1
div.style.font = @aceFontSize() + ' ' + @session.fontFamily
div.style.width = "#{@aceEditor.renderer.$gutter.clientWidth}px"
div.style.left = 0
div.style.top = "#{@aceEditor.session.documentToScreenRow(line, 0) *
lineHeight - aceScrollTop}px"
div.className = 'droplet-transitioning-element droplet-transitioning-gutter droplet-gutter-line'
# Add annotation
if @annotations[line]?
div.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@dropletElement.appendChild div
do (div, line) =>
setTimeout (=>
div.style.left = 0
div.style.top = "#{treeView.bounds[line].y + treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent - @session.viewports.main.y}px"
div.style.fontSize = @session.fontSize + 'px'
), 0
@mainCanvas.style.opacity = 0
setTimeout (=>
@mainCanvas.style.transition = "opacity #{fadeTime}ms linear"
@mainCanvas.style.opacity = 1
), translateTime
@dropletElement.style.transition = "left #{fadeTime}ms"
if paletteAppearingWithFreeze
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
@paletteWrapper.style.left = '0px'
setTimeout (=>
@dropletElement.style.transition = ''
# Show scrollbars again
@mainScroller.style.overflow = 'auto'
@currentlyAnimating = false
@lineNumberWrapper.style.display = 'block'
@redrawMain()
@paletteHeader.style.zIndex = 257
for div in translatingElements
div.parentNode.removeChild div
@resizeBlockMode()
@fireEvent 'toggledone', [@session.currentlyUsingBlocks]
if cb? then do cb
), translateTime + fadeTime
), 0
return success: true
Editor::enablePalette = (enabled) ->
if not @currentlyAnimating and @session.paletteEnabled != enabled
@session.paletteEnabled = enabled
@currentlyAnimating = true
if @session.currentlyUsingBlocks
activeElement = @dropletElement
else
activeElement = @aceElement
if not @session.paletteEnabled
activeElement.style.transition = "left 500ms"
activeElement.style.left = '0px'
@paletteHeader.style.zIndex = 0
@resize()
setTimeout (=>
activeElement.style.transition = ''
#@paletteWrapper.style.top = '-9999px'
#@paletteWrapper.style.left = '-9999px'
@currentlyAnimating = false
@fireEvent 'palettetoggledone', [@session.paletteEnabled]
), 500
else
@paletteWrapper.style.top = '0px'
@paletteHeader.style.zIndex = 257
setTimeout (=>
activeElement.style.transition = "left 500ms"
activeElement.style.left = "#{@paletteWrapper.clientWidth}px"
@paletteWrapper.style.left = '0px'
setTimeout (=>
activeElement.style.transition = ''
@resize()
@currentlyAnimating = false
@fireEvent 'palettetoggledone', [@session.paletteEnabled]
), 500
), 0
Editor::toggleBlocks = (cb) ->
if @session.currentlyUsingBlocks
return @performMeltAnimation 500, 1000, cb
else
return @performFreezeAnimation 500, 500, cb
# SCROLLING SUPPORT
# ================================
hook 'populate', 2, ->
@mainScroller = document.createElement 'div'
@mainScroller.className = 'droplet-main-scroller'
# @mainScrollerIntermediary -- this is so that we can be certain that
# any event directly on @mainScroller is in fact on the @mainScroller scrollbar,
# so should not be captured by editor mouse event handlers.
@mainScrollerIntermediary = document.createElement 'div'
@mainScrollerIntermediary.className = 'droplet-main-scroller-intermediary'
@mainScrollerStuffing = document.createElement 'div'
@mainScrollerStuffing.className = 'droplet-main-scroller-stuffing'
@mainScroller.appendChild @mainCanvas
@dropletElement.appendChild @mainScroller
# Prevent scrolling on wrapper element
@wrapperElement.addEventListener 'scroll', =>
@wrapperElement.scrollTop = @wrapperElement.scrollLeft = 0
@mainScroller.addEventListener 'scroll', =>
@session.viewports.main.y = @mainScroller.scrollTop
@session.viewports.main.x = @mainScroller.scrollLeft
@redrawMain()
@paletteScroller = document.createElement 'div'
@paletteScroller.className = 'droplet-palette-scroller'
@paletteScroller.appendChild @paletteCanvas
@paletteScrollerStuffing = document.createElement 'div'
@paletteScrollerStuffing.className = 'droplet-palette-scroller-stuffing'
@paletteScroller.appendChild @paletteScrollerStuffing
@paletteElement.appendChild @paletteScroller
@paletteScroller.addEventListener 'scroll', =>
@session.viewports.palette.y = @paletteScroller.scrollTop
@session.viewports.palette.x = @paletteScroller.scrollLeft
Editor::resizeMainScroller = ->
@mainScroller.style.width = "#{@dropletElement.clientWidth}px"
@mainScroller.style.height = "#{@dropletElement.clientHeight}px"
hook 'resize_palette', 0, ->
@paletteScroller.style.top = "#{@paletteHeader.clientHeight}px"
@session.viewports.palette.height = @paletteScroller.clientHeight
@session.viewports.palette.width = @paletteScroller.clientWidth
hook 'redraw_main', 1, ->
bounds = @session.view.getViewNodeFor(@session.tree).getBounds()
for record in @session.floatingBlocks
bounds.unite @session.view.getViewNodeFor(record.block).getBounds()
# We add some extra height to the bottom
# of the document so that the last block isn't
# jammed up against the edge of the screen.
#
# Default this extra space to fontSize (approx. 1 line).
height = Math.max(
bounds.bottom() + (@options.extraBottomHeight ? @session.fontSize),
@dropletElement.clientHeight
)
if height isnt @lastHeight
@lastHeight = height
@mainCanvas.setAttribute 'height', height
@mainCanvas.style.height = "#{height}px"
hook 'redraw_palette', 0, ->
bounds = new @draw.NoRectangle()
for entry in @session.currentPaletteBlocks
bounds.unite @session.paletteView.getViewNodeFor(entry.block).getBounds()
# For now, we will comment out this line
# due to bugs
#@paletteScrollerStuffing.style.width = "#{bounds.right()}px"
@paletteScrollerStuffing.style.height = "#{bounds.bottom()}px"
# MULTIPLE FONT SIZE SUPPORT
# ================================
hook 'populate', 0, ->
@session.fontSize = 15
@session.fontFamily = 'Courier New'
@measureCtx.font = '15px Courier New'
@session.fontWidth = @measureCtx.measureText(' ').width
metrics = helper.fontMetrics(@session.fontFamily, @session.fontSize)
@session.fontAscent = metrics.prettytop
@session.fontDescent = metrics.descent
Editor::setFontSize_raw = (fontSize) ->
unless @session.fontSize is fontSize
@measureCtx.font = fontSize + ' px ' + @session.fontFamily
@session.fontWidth = @measureCtx.measureText(' ').width
@session.fontSize = fontSize
@paletteHeader.style.fontSize = "#{fontSize}px"
@gutter.style.fontSize = "#{fontSize}px"
@tooltipElement.style.fontSize = "#{fontSize}px"
@session.view.opts.textHeight =
@session.paletteView.opts.textHeight =
@session.dragView.opts.textHeight = helper.getFontHeight @session.fontFamily, @session.fontSize
metrics = helper.fontMetrics(@session.fontFamily, @session.fontSize)
@session.fontAscent = metrics.prettytop
@session.fontDescent = metrics.descent
@session.view.clearCache()
@session.paletteView.clearCache()
@session.dragView.clearCache()
@session.view.draw.setGlobalFontSize @session.fontSize
@session.paletteView.draw.setGlobalFontSize @session.fontSize
@session.dragView.draw.setGlobalFontSize @session.fontSize
@gutter.style.width = @aceEditor.renderer.$gutterLayer.gutterWidth + 'px'
@redrawMain()
@rebuildPalette()
Editor::setFontFamily = (fontFamily) ->
@measureCtx.font = @session.fontSize + 'px ' + fontFamily
@draw.setGlobalFontFamily fontFamily
@session.fontFamily = fontFamily
@session.view.opts.textHeight = helper.getFontHeight @session.fontFamily, @session.fontSize
@session.fontAscent = helper.fontMetrics(@session.fontFamily, @session.fontSize).prettytop
@session.view.clearCache(); @session.dragView.clearCache()
@gutter.style.fontFamily = fontFamily
@tooltipElement.style.fontFamily = fontFamily
@redrawMain()
@rebuildPalette()
Editor::setFontSize = (fontSize) ->
@setFontSize_raw fontSize
@resizeBlockMode()
# LINE MARKING SUPPORT
# ================================
Editor::getHighlightPath = (model, style, view = @session.view) ->
path = view.getViewNodeFor(model).path.clone()
path.style.fillColor = null
path.style.strokeColor = style.color
path.style.lineWidth = 3
path.noclip = true; path.bevel = false
return path
Editor::markLine = (line, style) ->
return unless @session?
block = @session.tree.getBlockOnLine line
@session.view.getViewNodeFor(block).mark style
Editor::markBlock = (block, style) ->
return unless @session?
@session.view.getViewNodeFor(block).mark style
# ## Mark
# `mark(line, col, style)` will mark the first block after the given (line, col) coordinate
# with the given style.
Editor::mark = (location, style) ->
return unless @session?
block = @session.tree.getFromTextLocation location
block = block.container ? block
@session.view.getViewNodeFor(block).mark style
@redrawHighlights() # TODO MERGE investigate
Editor::clearLineMarks = ->
@session.view.clearMarks()
@redrawHighlights()
# LINE HOVER SUPPORT
# ================================
hook 'populate', 0, ->
@lastHoveredLine = null
hook 'mousemove', 0, (point, event, state) ->
# Do not attempt to detect this if we are currently dragging something,
# or no event handlers are bound.
if not @draggingBlock? and not @clickedBlock? and @hasEvent 'linehover'
if not @trackerPointIsInMainScroller point then return
mainPoint = @trackerPointToMain point
treeView = @session.view.getViewNodeFor @session.tree
if @lastHoveredLine? and treeView.bounds[@lastHoveredLine]? and
treeView.bounds[@lastHoveredLine].contains mainPoint
return
hoveredLine = @findLineNumberAtCoordinate mainPoint.y
unless treeView.bounds[hoveredLine].contains mainPoint
hoveredLine = null
if hoveredLine isnt @lastHoveredLine
@fireEvent 'linehover', [line: @lastHoveredLine = hoveredLine]
# GET/SET VALUE SUPPORT
# ================================
# Whitespace trimming hack enable/disable
# setter
hook 'populate', 0, ->
@trimWhitespace = false
Editor::setTrimWhitespace = (trimWhitespace) ->
@trimWhitespace = trimWhitespace
Editor::setValue_raw = (value) ->
try
if @trimWhitespace then value = value.trim()
newParse = @session.mode.parse value, {
wrapAtRoot: true
preserveEmpty: @session.options.preserveEmpty
}
unless @session.tree.start.next is @session.tree.end
removal = new model.List @session.tree.start.next, @session.tree.end.prev
@spliceOut removal
unless newParse.start.next is newParse.end
@spliceIn new model.List(newParse.start.next, newParse.end.prev), @session.tree.start
@removeBlankLines()
@redrawMain()
return success: true
catch e
return success: false, error: e
Editor::setValue = (value) ->
if not @session?
return @aceEditor.setValue value
oldScrollTop = @aceEditor.session.getScrollTop()
@setAceValue value
@resizeTextMode()
@aceEditor.session.setScrollTop oldScrollTop
if @session.currentlyUsingBlocks
result = @setValue_raw value
if result.success is false
@setEditorState false
@aceEditor.setValue value
if result.error
@fireEvent 'parseerror', [result.error]
Editor::addEmptyLine = (str) ->
if str.length is 0 or str[str.length - 1] is '\n'
return str
else
return str + '\n'
Editor::getValue = ->
if @session?.currentlyUsingBlocks
return @addEmptyLine @session.tree.stringify({
preserveEmpty: @session.options.preserveEmpty
})
else
@getAceValue()
Editor::getAceValue = ->
value = @aceEditor.getValue()
@lastAceSeenValue = value
Editor::setAceValue = (value) ->
if value isnt @lastAceSeenValue
@aceEditor.setValue value, 1
# TODO: move ace cursor to location matching droplet cursor.
@lastAceSeenValue = value
# PUBLIC EVENT BINDING HOOKS
# ===============================
Editor::on = (event, handler) ->
@bindings[event] = handler
Editor::once = (event, handler) ->
@bindings[event] = ->
handler.apply this, arguments
@bindings[event] = null
Editor::fireEvent = (event, args) ->
if event of @bindings
@bindings[event].apply this, args
Editor::hasEvent = (event) -> event of @bindings and @bindings[event]?
# SYNCHRONOUS TOGGLE SUPPORT
# ================================
Editor::setEditorState = (useBlocks) ->
@mainCanvas.style.transition = @highlightCanvas.style.transition = ''
if useBlocks
if not @session?
throw new ArgumentError 'cannot switch to blocks if a session has not been set up.'
unless @session.currentlyUsingBlocks
@setValue_raw @getAceValue()
@dropletElement.style.top = '0px'
if @session.paletteEnabled
@paletteWrapper.style.top = @paletteWrapper.style.left = '0px'
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@paletteWrapper.style.top = '0px'
@dropletElement.style.left = '0px'
@aceElement.style.top = @aceElement.style.left = '-9999px'
@session.currentlyUsingBlocks = true
@lineNumberWrapper.style.display = 'block'
@mainCanvas.style.opacity =
@highlightCanvas.style.opacity = 1
@resizeBlockMode(); @redrawMain()
else
# Forbid melting if there is an empty socket. If there is,
# highlight it in red.
if @session? and not @session.options.preserveEmpty and not @checkAndHighlightEmptySockets()
@redrawMain()
return
@hideDropdown()
paletteVisibleInNewState = @session?.paletteEnabled and @session.showPaletteInTextMode
oldScrollTop = @aceEditor.session.getScrollTop()
if @session?.currentlyUsingBlocks
@setAceValue @getValue()
@aceEditor.resize true
@aceEditor.session.setScrollTop oldScrollTop
@dropletElement.style.top = @dropletElement.style.left = '-9999px'
@paletteWrapper.style.top = @paletteWrapper.style.left = '0px'
@aceElement.style.top = '0px'
if paletteVisibleInNewState
@aceElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@aceElement.style.left = '0px'
@session?.currentlyUsingBlocks = false
@lineNumberWrapper.style.display = 'none'
@mainCanvas.style.opacity =
@highlightCanvas.style.opacity = 0
@resizeBlockMode()
# DRAG CANVAS SHOW/HIDE HACK
# ================================
hook 'populate', 0, ->
@dragCover = document.createElement 'div'
@dragCover.className = 'droplet-drag-cover'
@dragCover.style.display = 'none'
document.body.appendChild @dragCover
# On mousedown, bring the drag
# canvas to the front so that it
# appears to "float" over all other elements
hook 'mousedown', -1, ->
if @clickedBlock?
@dragCover.style.display = 'block'
# On mouseup, throw the drag canvas away completely.
hook 'mouseup', 0, ->
@dragCanvas.style.transform = "translate(-9999px, -9999px)"
@dragCover.style.display = 'none'
# FAILSAFE END DRAG HACK
# ================================
hook 'mousedown', 10, ->
if @draggingBlock?
@endDrag()
Editor::endDrag = ->
# Ensure that the cursor is not in a socket.
if @cursorAtSocket()
@setCursor @session.cursor, (x) -> x.type isnt 'socketStart'
@clearDrag()
@draggingBlock = null
@draggingOffset = null
@lastHighlightPath?.deactivate?()
@lastHighlight = @lastHighlightPath = null
@redrawMain()
return
# PALETTE EVENT
# =================================
hook 'rebuild_palette', 0, ->
@fireEvent 'changepalette', []
# TOUCHSCREEN SUPPORT
# =================================
# We will attempt to emulate
# mouse events using touchstart/end
# data.
touchEvents =
'touchstart': 'mousedown'
'touchmove': 'mousemove'
'touchend': 'mouseup'
# A timeout for selection
TOUCH_SELECTION_TIMEOUT = 1000
Editor::touchEventToPoint = (event, index) ->
absolutePoint = new @draw.Point(
event.changedTouches[index].clientX,
event.changedTouches[index].clientY
)
return absolutePoint
Editor::queueLassoMousedown = (trackPoint, event) ->
@lassoSelectStartTimeout = setTimeout (=>
state = {}
for handler in editorBindings.mousedown
handler.call this, trackPoint, event, state), TOUCH_SELECTION_TIMEOUT
# We will bind the same way as mouse events do,
# wrapping to be compatible with a mouse event interface.
#
# When users drag with multiple fingers, we emulate scrolling.
# Otherwise, we emulate mousedown/mouseup
hook 'populate', 0, ->
@touchScrollAnchor = new @draw.Point 0, 0
@lassoSelectStartTimeout = null
@wrapperElement.addEventListener 'touchstart', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
# We keep a state object so that handlers
# can know about each other.
#
# We will suppress lasso select to
# allow scrolling.
state = {
suppressLassoSelect: true
}
# Call all the handlers.
for handler in editorBindings.mousedown
handler.call this, trackPoint, event, state
# If we did not hit anything,
# we may want to start a lasso select
# in a little bit.
if state.consumedHitTest
event.preventDefault()
else
@queueLassoMousedown trackPoint, event
@wrapperElement.addEventListener 'touchmove', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
unless @clickedBlock? or @draggingBlock?
@queueLassoMousedown trackPoint, event
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings.mousemove
handler.call this, trackPoint, event, state
# If we are in the middle of some action,
# prevent scrolling.
if @clickedBlock? or @draggingBlock? or @lassoSelectAnchor? or @textInputSelecting
event.preventDefault()
@wrapperElement.addEventListener 'touchend', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings.mouseup
handler.call this, trackPoint, event, state
event.preventDefault()
# CURSOR DRAW SUPPORRT
# ================================
hook 'populate', 0, ->
@cursorCtx = document.createElementNS SVG_STANDARD, 'g'
@textCursorPath = new @session.view.draw.Path([], false, {
'strokeColor': '#000'
'lineWidth': '2'
'fillColor': 'rgba(0, 0, 256, 0.3)'
'cssClass': 'droplet-cursor-path'
})
@textCursorPath.setParent @mainCanvas
cursorElement = document.createElementNS SVG_STANDARD, 'path'
cursorElement.setAttribute 'fill', 'none'
cursorElement.setAttribute 'stroke', '#000'
cursorElement.setAttribute 'stroke-width', '3'
cursorElement.setAttribute 'stroke-linecap', 'round'
cursorElement.setAttribute 'd', "M#{@session.view.opts.tabOffset + CURSOR_WIDTH_DECREASE / 2} 0 " +
"Q#{@session.view.opts.tabOffset + @session.view.opts.tabWidth / 2} #{@session.view.opts.tabHeight}" +
" #{@session.view.opts.tabOffset + @session.view.opts.tabWidth - CURSOR_WIDTH_DECREASE / 2} 0"
@cursorPath = new @session.view.draw.ElementWrapper(cursorElement)
@cursorPath.setParent @mainCanvas
@mainCanvas.appendChild @cursorCtx
Editor::strokeCursor = (point) ->
return unless point?
@cursorPath.element.setAttribute 'transform', "translate(#{point.x}, #{point.y})"
@qualifiedFocus @getCursor(), @cursorPath
Editor::highlightFlashShow = ->
return unless @session?
if @flashTimeout? then clearTimeout @flashTimeout
if @cursorAtSocket()
@textCursorPath.activate()
else
@cursorPath.activate()
@highlightsCurrentlyShown = true
@flashTimeout = setTimeout (=> @flash()), 500
Editor::highlightFlashHide = ->
return unless @session?
if @flashTimeout? then clearTimeout @flashTimeout
if @cursorAtSocket()
@textCursorPath.deactivate()
else
@cursorPath.deactivate()
@highlightsCurrentlyShown = false
@flashTimeout = setTimeout (=> @flash()), 500
Editor::editorHasFocus = ->
document.activeElement in [@dropletElement, @hiddenInput, @copyPasteInput] and
document.hasFocus()
Editor::flash = ->
return unless @session?
if @lassoSelection? or @draggingBlock? or
(@cursorAtSocket() and @textInputHighlighted) or
not @highlightsCurrentlyShown or
not @editorHasFocus()
@highlightFlashShow()
else
@highlightFlashHide()
hook 'populate', 0, ->
@highlightsCurrentlyShown = false
blurCursors = =>
@highlightFlashShow()
@cursorCtx.style.opacity = CURSOR_UNFOCUSED_OPACITY
@dropletElement.addEventListener 'blur', blurCursors
@hiddenInput.addEventListener 'blur', blurCursors
@copyPasteInput.addEventListener 'blur', blurCursors
focusCursors = =>
@highlightFlashShow()
@cursorCtx.style.transition = ''
@cursorCtx.style.opacity = 1
@dropletElement.addEventListener 'focus', focusCursors
@hiddenInput.addEventListener 'focus', focusCursors
@copyPasteInput.addEventListener 'focus', focusCursors
@flashTimeout = setTimeout (=> @flash()), 0
# ONE MORE DROP CASE
# ================================
# TODO possibly move this next utility function to view?
Editor::viewOrChildrenContains = (model, point, view = @session.view) ->
modelView = view.getViewNodeFor model
if modelView.path.contains point
return true
for childObj in modelView.children
if @session.viewOrChildrenContains childObj.child, point, view
return true
return false
# LINE NUMBER GUTTER CODE
# ================================
hook 'populate', 0, ->
@gutter = document.createElement 'div'
@gutter.className = 'droplet-gutter'
@lineNumberWrapper = document.createElement 'div'
@gutter.appendChild @lineNumberWrapper
@gutterVersion = -1
@lastGutterWidth = null
@lineNumberTags = {}
@mainScroller.appendChild @gutter
# Record of embedder-set annotations
# and breakpoints used in rendering.
# Should mirror ace all the time.
@annotations = {}
@breakpoints = {}
@tooltipElement = document.createElement 'div'
@tooltipElement.className = 'droplet-tooltip'
@dropletElement.appendChild @tooltipElement
@aceEditor.on 'guttermousedown', (e) =>
# Ensure that the click actually happened
# on a line and not just in gutter space.
target = e.domEvent.target
if target.className.indexOf('ace_gutter-cell') is -1
return
# Otherwise, get the row and fire a Droplet gutter
# mousedown event.
row = e.getDocumentPosition().row
e.stop()
@fireEvent 'guttermousedown', [{line: row, event: e.domEvent}]
hook 'mousedown', 11, (point, event, state) ->
# Check if mousedown within the gutter
if not @trackerPointIsInGutter(point) then return
# Find the line that was clicked
mainPoint = @trackerPointToMain point
treeView = @session.view.getViewNodeFor @session.tree
clickedLine = @findLineNumberAtCoordinate mainPoint.y
@fireEvent 'guttermousedown', [{line: clickedLine, event: event}]
# Prevent other hooks from taking this event
return true
Editor::setBreakpoint = (row) ->
# Delegate
@aceEditor.session.setBreakpoint(row)
# Add to our own records
@breakpoints[row] = true
# Redraw gutter.
# TODO: if this ends up being a performance issue,
# selectively apply classes
@redrawGutter false
Editor::clearBreakpoint = (row) ->
@aceEditor.session.clearBreakpoint(row)
@breakpoints[row] = false
@redrawGutter false
Editor::clearBreakpoints = (row) ->
@aceEditor.session.clearBreakpoints()
@breakpoints = {}
@redrawGutter false
Editor::getBreakpoints = (row) ->
@aceEditor.session.getBreakpoints()
Editor::setAnnotations = (annotations) ->
@aceEditor.session.setAnnotations annotations
@annotations = {}
for el, i in annotations
@annotations[el.row] ?= []
@annotations[el.row].push el
@redrawGutter false
Editor::resizeGutter = ->
unless @lastGutterWidth is @aceEditor.renderer.$gutterLayer.gutterWidth
@lastGutterWidth = @aceEditor.renderer.$gutterLayer.gutterWidth
@gutter.style.width = @lastGutterWidth + 'px'
return @resize()
unless @lastGutterHeight is Math.max(@dropletElement.clientHeight, @mainCanvas.clientHeight)
@lastGutterHeight = Math.max(@dropletElement.clientHeight, @mainCanvas.clientHeight)
@gutter.style.height = @lastGutterHeight + 'px'
Editor::addLineNumberForLine = (line) ->
treeView = @session.view.getViewNodeFor @session.tree
if line of @lineNumberTags
lineDiv = @lineNumberTags[line].tag
else
lineDiv = document.createElement 'div'
lineDiv.innerText = lineDiv.textContent = line + 1
@lineNumberTags[line] = {
tag: lineDiv
lastPosition: null
}
if treeView.bounds[line].y isnt @lineNumberTags[line].lastPosition
lineDiv.className = 'droplet-gutter-line'
# Add annotation mouseover text
# and graphics
if @annotations[line]?
lineDiv.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
title = @annotations[line].map((x) -> x.text).join('\n')
lineDiv.addEventListener 'mouseover', =>
@tooltipElement.innerText =
@tooltipElement.textContent = title
@tooltipElement.style.display = 'block'
lineDiv.addEventListener 'mousemove', (event) =>
@tooltipElement.style.left = event.pageX + 'px'
@tooltipElement.style.top = event.pageY + 'px'
lineDiv.addEventListener 'mouseout', =>
@tooltipElement.style.display = 'none'
# Add breakpoint graphics
if @breakpoints[line]
lineDiv.className += ' droplet_breakpoint'
lineDiv.style.top = "#{treeView.bounds[line].y}px"
lineDiv.style.paddingTop = "#{treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent}px"
lineDiv.style.paddingBottom = "#{treeView.distanceToBase[line].below - @session.fontDescent}"
lineDiv.style.height = treeView.bounds[line].height + 'px'
lineDiv.style.fontSize = @session.fontSize + 'px'
@lineNumberWrapper.appendChild lineDiv
@lineNumberTags[line].lastPosition = treeView.bounds[line].y
TYPE_SEVERITY = {
'error': 2
'warning': 1
'info': 0
}
TYPE_FROM_SEVERITY = ['info', 'warning', 'error']
getMostSevereAnnotationType = (arr) ->
TYPE_FROM_SEVERITY[Math.max.apply(this, arr.map((x) -> TYPE_SEVERITY[x.type]))]
Editor::findLineNumberAtCoordinate = (coord) ->
treeView = @session.view.getViewNodeFor @session.tree
start = 0; end = treeView.bounds.length
pivot = Math.floor (start + end) / 2
while treeView.bounds[pivot].y isnt coord and start < end
if start is pivot or end is pivot
return pivot
if treeView.bounds[pivot].y > coord
end = pivot
else
start = pivot
if end < 0 then return 0
if start >= treeView.bounds.length then return treeView.bounds.length - 1
pivot = Math.floor (start + end) / 2
return pivot
hook 'redraw_main', 0, (changedBox) ->
@redrawGutter(changedBox)
Editor::redrawGutter = (changedBox = true) ->
return unless @session?
treeView = @session.view.getViewNodeFor @session.tree
top = @findLineNumberAtCoordinate @session.viewports.main.y
bottom = @findLineNumberAtCoordinate @session.viewports.main.bottom()
for line in [top..bottom]
@addLineNumberForLine line
for line, tag of @lineNumberTags
if line < top or line > bottom
@lineNumberTags[line].tag.parentNode.removeChild @lineNumberTags[line].tag
delete @lineNumberTags[line]
if changedBox
@resizeGutter()
Editor::setPaletteWidth = (width) ->
@paletteWrapper.style.width = width + 'px'
@resizeBlockMode()
# COPY AND PASTE
# ================================
hook 'populate', 1, ->
@copyPasteInput = document.createElement 'textarea'
@copyPasteInput.style.position = 'absolute'
@copyPasteInput.style.left = @copyPasteInput.style.top = '-9999px'
@dropletElement.appendChild @copyPasteInput
pressedVKey = false
pressedXKey = false
@copyPasteInput.addEventListener 'keydown', (event) ->
pressedVKey = pressedXKey = false
if event.keyCode is 86
pressedVKey = true
else if event.keyCode is 88
pressedXKey = true
@copyPasteInput.addEventListener 'input', =>
if not @session? or @session.readOnly
return
if pressedVKey and not @cursorAtSocket()
str = @copyPasteInput.value; lines = str.split '\n'
# Strip any common leading indent
# from all the lines of the pasted tet
minIndent = lines.map((line) -> line.length - line.trimLeft().length).reduce((a, b) -> Math.min(a, b))
str = lines.map((line) -> line[minIndent...]).join('\n')
str = str.replace /^\n*|\n*$/g, ''
try
blocks = @session.mode.parse str, {context: @getCursor().parent.parseContext}
blocks = new model.List blocks.start.next, blocks.end.prev
catch e
blocks = null
return unless blocks?
@undoCapture()
@spliceIn blocks, @getCursor()
@setCursor blocks.end
@redrawMain()
@copyPasteInput.setSelectionRange 0, @copyPasteInput.value.length
else if pressedXKey and @lassoSelection?
@spliceOut @lassoSelection; @lassoSelection = null
@redrawMain()
hook 'keydown', 0, (event, state) ->
if event.which in command_modifiers
unless @cursorAtSocket()
x = document.body.scrollLeft
y = document.body.scrollTop
@copyPasteInput.focus()
window.scrollTo(x, y)
if @lassoSelection?
@copyPasteInput.value = @lassoSelection.stringifyInPlace()
@copyPasteInput.setSelectionRange 0, @copyPasteInput.value.length
hook 'keyup', 0, (point, event, state) ->
if event.which in command_modifiers
if @cursorAtSocket()
@hiddenInput.focus()
else
@dropletElement.focus()
# OVRFLOW BIT
# ================================
Editor::overflowsX = ->
@documentDimensions().width > @session.viewportDimensions().width
Editor::overflowsY = ->
@documentDimensions().height > @session.viewportDimensions().height
Editor::documentDimensions = ->
bounds = @session.view.getViewNodeFor(@session.tree).totalBounds
return {
width: bounds.width
height: bounds.height
}
Editor::viewportDimensions = ->
return @session.viewports.main
# LINE LOCATION API
# =================
Editor::getLineMetrics = (row) ->
viewNode = @session.view.getViewNodeFor @session.tree
bounds = (new @session.view.draw.Rectangle()).copy(viewNode.bounds[row])
bounds.x += @mainCanvas.offsetLeft + @mainCanvas.offsetParent.offsetLeft
return {
bounds: bounds
distanceToBase: {
above: viewNode.distanceToBase[row].above
below: viewNode.distanceToBase[row].below
}
}
# DEBUG CODE
# ================================
Editor::dumpNodeForDebug = (hitTestResult, line) ->
console.log('Model node:')
console.log(hitTestResult.serialize())
console.log('View node:')
console.log(@session.view.getViewNodeFor(hitTestResult).serialize(line))
# CLOSING FOUNDATIONAL STUFF
# ================================
# Order the arrays correctly.
for key of unsortedEditorBindings
unsortedEditorBindings[key].sort (a, b) -> if a.priority > b.priority then -1 else 1
editorBindings[key] = []
for binding in unsortedEditorBindings[key]
editorBindings[key].push binding.fn
| 134419 | # Droplet controller.
#
# Copyright (c) 2014 <NAME> (<EMAIL>)
# MIT License.
helper = require './helper.coffee'
draw = require './draw.coffee'
model = require './model.coffee'
view = require './view.coffee'
QUAD = require '../vendor/quadtree.js'
modes = require './modes.coffee'
# ## Magic constants
PALETTE_TOP_MARGIN = 5
PALETTE_MARGIN = 5
MIN_DRAG_DISTANCE = 1
PALETTE_LEFT_MARGIN = 5
DEFAULT_INDENT_DEPTH = ' '
ANIMATION_FRAME_RATE = 60
DISCOURAGE_DROP_TIMEOUT = 1000
MAX_DROP_DISTANCE = 100
CURSOR_WIDTH_DECREASE = 3
CURSOR_HEIGHT_DECREASE = 2
CURSOR_UNFOCUSED_OPACITY = 0.5
DEBUG_FLAG = false
DROPDOWN_SCROLLBAR_PADDING = 17
BACKSPACE_KEY = 8
TAB_KEY = 9
ENTER_KEY = 13
LEFT_ARROW_KEY = 37
UP_ARROW_KEY = 38
RIGHT_ARROW_KEY = 39
DOWN_ARROW_KEY = 40
Z_KEY = 90
Y_KEY = 89
META_KEYS = [91, 92, 93, 223, 224]
CONTROL_KEYS = [17, 162, 163]
GRAY_BLOCK_MARGIN = 5
GRAY_BLOCK_HANDLE_WIDTH = 15
GRAY_BLOCK_HANDLE_HEIGHT = 30
GRAY_BLOCK_COLOR = 'rgba(256, 256, 256, 0.5)'
GRAY_BLOCK_BORDER = '#AAA'
userAgent = ''
if typeof(window) isnt 'undefined' and window.navigator?.userAgent
userAgent = window.navigator.userAgent
isOSX = /OS X/.test(userAgent)
command_modifiers = if isOSX then META_KEYS else CONTROL_KEYS
command_pressed = (e) -> if isOSX then e.metaKey else e.ctrlKey
# FOUNDATION
# ================================
# ## Editor event bindings
#
# These are different events associated with the Editor
# that features will want to bind to.
unsortedEditorBindings = {
'populate': [] # after an empty editor is created
'resize': [] # after the window is resized
'resize_palette': [] # after the palette is resized
'redraw_main': [] # whenever we need to redraw the main canvas
'redraw_palette': [] # repaint the graphics of the palette
'rebuild_palette': [] # redraw the paltte, both graphics and elements
'mousedown': []
'mousemove': []
'mouseup': []
'dblclick': []
'keydown': []
'keyup': []
}
editorBindings = {}
SVG_STANDARD = helper.SVG_STANDARD
EMBOSS_FILTER_SVG = """
<svg xlmns="#{SVG_STANDARD}">
<filter id="dropShadow" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceAlpha" dx="5" dy="5" />
<feGaussianBlur result="blurOut" in="offOut" stdDeviation="1" />
<feBlend in="SourceGraphic" in2="blurOut" out="blendOut" mode="normal" />
<feComposite in="blendOut" in2="SourceGraphic" k2="0.5" k3="0.5" operator="arithmetic" />
</filter>
</svg>
"""
# This hook function is for convenience,
# for features to add events that will occur at
# various times in the editor lifecycle.
hook = (event, priority, fn) ->
unsortedEditorBindings[event].push {
priority: priority
fn: fn
}
class Session
constructor: (_main, _palette, _drag, @options, standardViewSettings) -> # TODO rearchitecture so that a session is independent of elements again
# Option flags
@readOnly = false
@paletteGroups = @options.palette
@showPaletteInTextMode = @options.showPaletteInTextMode ? false
@paletteEnabled = @options.enablePaletteAtStart ? true
@dropIntoAceAtLineStart = @options.dropIntoAceAtLineStart ? false
@allowFloatingBlocks = @options.allowFloatingBlocks ? true
# By default, attempt to preserve empty sockets when round-tripping
@options.preserveEmpty ?= true
# Mode
@options.mode = @options.mode.replace /$\/ace\/mode\//, ''
if @options.mode of modes
@mode = new modes[@options.mode] @options.modeOptions
else
@mode = null
# Instantiate an Droplet editor view
@view = new view.View _main, helper.extend standardViewSettings, @options.viewSettings ? {}
@paletteView = new view.View _palette, helper.extend {}, standardViewSettings, @options.viewSettings ? {}, {
showDropdowns: @options.showDropdownInPalette ? false
}
@dragView = new view.View _drag, helper.extend {}, standardViewSettings, @options.viewSettings ? {}
# ## Document initialization
# We start off with an empty document
@tree = new model.Document(@rootContext)
# Line markings
@markedLines = {}
@markedBlocks = {}; @nextMarkedBlockId = 0
@extraMarks = {}
# Undo/redo stack
@undoStack = []
@redoStack = []
@changeEventVersion = 0
# Floating blocks
@floatingBlocks = []
# Cursor
@cursor = new CrossDocumentLocation(0, new model.Location(0, 'documentStart'))
# Scrolling
@viewports = {
main: new draw.Rectangle 0, 0, 0, 0
palette: new draw.Rectangle 0, 0, 0, 0
}
# Block toggle
@currentlyUsingBlocks = true
# Fonts
@fontSize = 15
@fontFamily = 'Courier New'
metrics = helper.fontMetrics(@fontFamily, @fontSize)
@fontAscent = metrics.prettytop
@fontDescent = metrics.descent
@fontWidth = @view.draw.measureCtx.measureText(' ').width
# Remembered sockets
@rememberedSockets = []
# ## The Editor Class
exports.Editor = class Editor
constructor: (@aceEditor, @options) ->
# ## DOM Population
# This stage of ICE Editor construction populates the given wrapper
# element with all the necessary ICE editor components.
@debugging = true
@options = helper.deepCopy @options
# ### Wrapper
# Create the div that will contain all the ICE Editor graphics
@dropletElement = document.createElement 'div'
@dropletElement.className = 'droplet-wrapper-div'
@dropletElement.innerHTML = EMBOSS_FILTER_SVG
# We give our element a tabIndex so that it can be focused and capture keypresses.
@dropletElement.tabIndex = 0
# ### Canvases
# Create the palette and main canvases
# A measuring canvas for measuring text
@measureCanvas = document.createElement 'canvas'
@measureCtx = @measureCanvas.getContext '2d'
# Main canvas first
@mainCanvas = document.createElementNS SVG_STANDARD, 'svg'
#@mainCanvasWrapper = document.createElementNS SVG_STANDARD, 'g'
#@mainCanvas = document.createElementNS SVG_STANDARD, 'g'
#@mainCanvas.appendChild @mainCanvasWrapper
#@mainCanvasWrapper.appendChild @mainCanvas
@mainCanvas.setAttribute 'class', 'droplet-main-canvas'
@mainCanvas.setAttribute 'shape-rendering', 'optimizeSpeed'
@paletteWrapper = document.createElement 'div'
@paletteWrapper.className = 'droplet-palette-wrapper'
@paletteElement = document.createElement 'div'
@paletteElement.className = 'droplet-palette-element'
@paletteWrapper.appendChild @paletteElement
# Then palette canvas
@paletteCanvas = @paletteCtx = document.createElementNS SVG_STANDARD, 'svg'
@paletteCanvas.setAttribute 'class', 'droplet-palette-canvas'
@paletteWrapper.style.position = 'absolute'
@paletteWrapper.style.left = '0px'
@paletteWrapper.style.top = '0px'
@paletteWrapper.style.bottom = '0px'
@paletteWrapper.style.width = '270px'
# We will also have to initialize the
# drag canvas.
@dragCanvas = @dragCtx = document.createElementNS SVG_STANDARD, 'svg'
@dragCanvas.setAttribute 'class', 'droplet-drag-canvas'
@dragCanvas.style.left = '0px'
@dragCanvas.style.top = '0px'
@dragCanvas.style.transform = 'translate(-9999px,-9999px)'
@draw = new draw.Draw(@mainCanvas)
@dropletElement.style.left = @paletteWrapper.clientWidth + 'px'
do @draw.refreshFontCapital
@standardViewSettings =
padding: 5
indentWidth: 20
textHeight: helper.getFontHeight 'Courier New', 15
indentTongueHeight: 20
tabOffset: 10
tabWidth: 15
tabHeight: 4
tabSideWidth: 1 / 4
dropAreaHeight: 20
indentDropAreaMinWidth: 50
emptySocketWidth: 20
emptyLineHeight: 25
highlightAreaHeight: 10
shadowBlur: 5
ctx: @measureCtx
draw: @draw
# We can be passed a div
if @aceEditor instanceof Node
@wrapperElement = @aceEditor
@wrapperElement.style.position = 'absolute'
@wrapperElement.style.right =
@wrapperElement.style.left =
@wrapperElement.style.top =
@wrapperElement.style.bottom = '0px'
@aceElement = document.createElement 'div'
@aceElement.className = 'droplet-ace'
@wrapperElement.appendChild @aceElement
@aceEditor = ace.edit @aceElement
@aceEditor.setTheme 'ace/theme/chrome'
@aceEditor.setFontSize 15
acemode = @options.mode
if acemode is 'coffeescript' then acemode = 'coffee'
@aceEditor.getSession().setMode 'ace/mode/' + acemode
@aceEditor.getSession().setTabSize 2
else
@wrapperElement = document.createElement 'div'
@wrapperElement.style.position = 'absolute'
@wrapperElement.style.right =
@wrapperElement.style.left =
@wrapperElement.style.top =
@wrapperElement.style.bottom = '0px'
@aceElement = @aceEditor.container
@aceElement.className += ' droplet-ace'
@aceEditor.container.parentElement.appendChild @wrapperElement
@wrapperElement.appendChild @aceEditor.container
# Append populated divs
@wrapperElement.appendChild @dropletElement
@wrapperElement.appendChild @paletteWrapper
@wrapperElement.style.backgroundColor = '#FFF'
@currentlyAnimating = false
@transitionContainer = document.createElement 'div'
@transitionContainer.className = 'droplet-transition-container'
@dropletElement.appendChild @transitionContainer
if @options?
@session = new Session @mainCanvas, @paletteCanvas, @dragCanvas, @options, @standardViewSettings
@sessions = new helper.PairDict([
[@aceEditor.getSession(), @session]
])
else
@session = null
@sessions = new helper.PairDict []
@options = {
extraBottomHeight: 10
}
# Sessions are bound to other ace sessions;
# on ace session change Droplet will also change sessions.
@aceEditor.on 'changeSession', (e) =>
if @sessions.contains(e.session)
@updateNewSession @sessions.get(e.session)
else if e.session._dropletSession?
@updateNewSession e.session._dropletSession
@sessions.set(e.session, e.session._dropletSession)
else
@updateNewSession null
@setEditorState false
# Set up event bindings before creating a view
@bindings = {}
boundListeners = []
# Call all the feature bindings that are supposed
# to happen now.
for binding in editorBindings.populate
binding.call this
# ## Resize
# This stage of ICE editor construction, which is repeated
# whenever the editor is resized, should adjust the sizes
# of all the ICE editor componenents to fit the wrapper.
window.addEventListener 'resize', => @resizeBlockMode()
# ## Tracker Events
# We allow binding to the tracker element.
dispatchMouseEvent = (event) =>
# Ignore mouse clicks that are not the left-button
if event.type isnt 'mousemove' and event.which isnt 1 then return
# Ignore mouse clicks whose target is the scrollbar
if event.target is @mainScroller then return
trackPoint = new @draw.Point(event.clientX, event.clientY)
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings[event.type]
handler.call this, trackPoint, event, state
# Stop mousedown event default behavior so that
# we don't get bad selections
if event.type is 'mousedown'
event.preventDefault?()
event.returnValue = false
return false
dispatchKeyEvent = (event) =>
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings[event.type]
handler.call this, event, state
for eventName, elements of {
keydown: [@dropletElement, @paletteElement]
keyup: [@dropletElement, @paletteElement]
mousedown: [@dropletElement, @paletteElement, @dragCover]
dblclick: [@dropletElement, @paletteElement, @dragCover]
mouseup: [window]
mousemove: [window] } then do (eventName, elements) =>
for element in elements
if /^key/.test eventName
element.addEventListener eventName, dispatchKeyEvent
else
element.addEventListener eventName, dispatchMouseEvent
@resizeBlockMode()
# Now that we've populated everything, immediately redraw.
@redrawMain()
@rebuildPalette()
# If we were given an unrecognized mode or asked to start in text mode,
# flip into text mode here
useBlockMode = @session?.mode? && !@options.textModeAtStart
# Always call @setEditorState to ensure palette is positioned properly
@setEditorState useBlockMode
return this
setMode: (mode, modeOptions) ->
modeClass = modes[mode]
if modeClass
@options.mode = mode
@session.mode = new modeClass modeOptions
else
@options.mode = null
@session.mode = null
@setValue @getValue()
getMode: ->
@options.mode
setReadOnly: (readOnly) ->
@session.readOnly = readOnly
@aceEditor.setReadOnly readOnly
getReadOnly: ->
@session.readOnly
# ## Foundational Resize
# At the editor core, we will need to resize
# all of the natively-added canvases, as well
# as the wrapper element, whenever a resize
# occurs.
resizeTextMode: ->
@resizeAceElement()
@aceEditor.resize true
if @session?
@resizePalette()
return
resizeBlockMode: ->
return unless @session?
@resizeTextMode()
@dropletElement.style.height = "#{@wrapperElement.clientHeight}px"
if @session.paletteEnabled
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
@dropletElement.style.width = "#{@wrapperElement.clientWidth - @paletteWrapper.clientWidth}px"
else
@dropletElement.style.left = "0px"
@dropletElement.style.width = "#{@wrapperElement.clientWidth}px"
#@resizeGutter()
@session.viewports.main.height = @dropletElement.clientHeight
@session.viewports.main.width = @dropletElement.clientWidth - @gutter.clientWidth
@mainCanvas.setAttribute 'width', @dropletElement.clientWidth - @gutter.clientWidth
@mainCanvas.style.left = "#{@gutter.clientWidth}px"
@transitionContainer.style.left = "#{@gutter.clientWidth}px"
@resizePalette()
@resizePaletteHighlight()
@resizeNubby()
@resizeMainScroller()
@resizeDragCanvas()
# Re-scroll and redraw main
@session.viewports.main.y = @mainScroller.scrollTop
@session.viewports.main.x = @mainScroller.scrollLeft
resizePalette: ->
for binding in editorBindings.resize_palette
binding.call this
@rebuildPalette()
resize: ->
if @session?.currentlyUsingBlocks #TODO session
@resizeBlockMode()
else
@resizeTextMode()
updateNewSession: (session) ->
@session.view.clearFromCanvas()
@session.paletteView.clearFromCanvas()
@session.dragView.clearFromCanvas()
@session = session
return unless session?
# Force scroll into our position
offsetY = @session.viewports.main.y
offsetX = @session.viewports.main.x
@setEditorState @session.currentlyUsingBlocks
@redrawMain()
@mainScroller.scrollTop = offsetY
@mainScroller.scrollLeft = offsetX
@setPalette @session.paletteGroups
hasSessionFor: (aceSession) -> @sessions.contains(aceSession)
bindNewSession: (opts) ->
if @sessions.contains(@aceEditor.getSession())
throw new ArgumentError 'Cannot bind a new session where one already exists.'
else
session = new Session @mainCanvas, @paletteCanvas, @dragCanvas, opts, @standardViewSettings
@sessions.set(@aceEditor.getSession(), session)
@session = session
@aceEditor.getSession()._dropletSession = @session
@session.currentlyUsingBlocks = false
@setValue_raw @getAceValue()
@setPalette @session.paletteGroups
return session
Editor::clearCanvas = (canvas) -> # TODO remove and remove all references to
# RENDERING CAPABILITIES
# ================================
# ## Redraw
# There are two different redraw events, redraw_main and rebuild_palette,
# for redrawing the main canvas and palette canvas, respectively.
#
# Redrawing simply involves issuing a call to the View.
Editor::clearMain = (opts) -> # TODO remove and remove all references to
Editor::setTopNubbyStyle = (height = 10, color = '#EBEBEB') ->
@nubbyHeight = Math.max(0, height); @nubbyColor = color
@topNubbyPath ?= new @draw.Path([], true)
@topNubbyPath.activate()
@topNubbyPath.setParent @mainCanvas
points = []
points.push new @draw.Point @mainCanvas.clientWidth, -5
points.push new @draw.Point @mainCanvas.clientWidth, height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth, height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth * (1 - @session.view.opts.tabSideWidth),
@session.view.opts.tabHeight + height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth * @session.view.opts.tabSideWidth,
@session.view.opts.tabHeight + height
points.push new @draw.Point @session.view.opts.tabOffset, height
points.push new @draw.Point @session.view.opts.bevelClip, height
points.push new @draw.Point 0, height + @session.view.opts.bevelClip
points.push new @draw.Point -5, height + @session.view.opts.bevelClip
points.push new @draw.Point -5, -5
@topNubbyPath.setPoints points
@topNubbyPath.style.fillColor = color
@redrawMain()
Editor::resizeNubby = ->
@setTopNubbyStyle @nubbyHeight, @nubbyColor
Editor::initializeFloatingBlock = (record, i) ->
record.renderGroup = new @session.view.draw.Group()
record.grayBox = new @session.view.draw.NoRectangle()
record.grayBoxPath = new @session.view.draw.Path(
[], false, {
fillColor: GRAY_BLOCK_COLOR
strokeColor: GRAY_BLOCK_BORDER
lineWidth: 4
dotted: '8 5'
cssClass: 'droplet-floating-container'
}
)
record.startText = new @session.view.draw.Text(
(new @session.view.draw.Point(0, 0)), @session.mode.startComment
)
record.endText = new @session.view.draw.Text(
(new @session.view.draw.Point(0, 0)), @session.mode.endComment
)
for element in [record.grayBoxPath, record.startText, record.endText]
element.setParent record.renderGroup
element.activate()
@session.view.getViewNodeFor(record.block).group.setParent record.renderGroup
record.renderGroup.activate()
# TODO maybe refactor into qualifiedFocus
if i < @session.floatingBlocks.length
@mainCanvas.insertBefore record.renderGroup.element, @session.floatingBlocks[i].renderGroup.element
else
@mainCanvas.appendChild record.renderGroup
Editor::drawFloatingBlock = (record, startWidth, endWidth, rect, opts) ->
blockView = @session.view.getViewNodeFor record.block
blockView.layout record.position.x, record.position.y
rectangle = new @session.view.draw.Rectangle(); rectangle.copy(blockView.totalBounds)
rectangle.x -= GRAY_BLOCK_MARGIN; rectangle.y -= GRAY_BLOCK_MARGIN
rectangle.width += 2 * GRAY_BLOCK_MARGIN; rectangle.height += 2 * GRAY_BLOCK_MARGIN
bottomTextPosition = blockView.totalBounds.bottom() - blockView.distanceToBase[blockView.lineLength - 1].below - @session.fontSize
if (blockView.totalBounds.width - blockView.bounds[blockView.bounds.length - 1].width) < endWidth
if blockView.lineLength > 1
rectangle.height += @session.fontSize
bottomTextPosition = rectangle.bottom() - @session.fontSize - 5
else
rectangle.width += endWidth
unless rectangle.equals(record.grayBox)
record.grayBox = rectangle
oldBounds = record.grayBoxPath?.bounds?() ? new @session.view.draw.NoRectangle()
startHeight = blockView.bounds[0].height + 10
points = []
# Make the path surrounding the gray box (with rounded corners)
points.push new @session.view.draw.Point rectangle.right() - 5, rectangle.y
points.push new @session.view.draw.Point rectangle.right(), rectangle.y + 5
points.push new @session.view.draw.Point rectangle.right(), rectangle.bottom() - 5
points.push new @session.view.draw.Point rectangle.right() - 5, rectangle.bottom()
if blockView.lineLength > 1
points.push new @session.view.draw.Point rectangle.x + 5, rectangle.bottom()
points.push new @session.view.draw.Point rectangle.x, rectangle.bottom() - 5
else
points.push new @session.view.draw.Point rectangle.x, rectangle.bottom()
# Handle
points.push new @session.view.draw.Point rectangle.x, rectangle.y + startHeight
points.push new @session.view.draw.Point rectangle.x - startWidth + 5, rectangle.y + startHeight
points.push new @session.view.draw.Point rectangle.x - startWidth, rectangle.y + startHeight - 5
points.push new @session.view.draw.Point rectangle.x - startWidth, rectangle.y + 5
points.push new @session.view.draw.Point rectangle.x - startWidth + 5, rectangle.y
points.push new @session.view.draw.Point rectangle.x, rectangle.y
record.grayBoxPath.setPoints points
if opts.boundingRectangle?
opts.boundingRectangle.unite path.bounds()
opts.boundingRectangle.unite(oldBounds)
return @redrawMain opts
record.grayBoxPath.update()
record.startText.point.x = blockView.totalBounds.x - startWidth
record.startText.point.y = blockView.totalBounds.y + blockView.distanceToBase[0].above - @session.fontSize
record.startText.update()
record.endText.point.x = record.grayBox.right() - endWidth - 5
record.endText.point.y = bottomTextPosition
record.endText.update()
blockView.draw rect, {
grayscale: false
selected: false
noText: false
}
hook 'populate', 0, ->
@currentlyDrawnFloatingBlocks = []
Editor::redrawMain = (opts = {}) ->
return unless @session?
unless @currentlyAnimating_suprressRedraw
@session.view.beginDraw()
# Clear the main canvas
@clearMain(opts)
@topNubbyPath.update()
rect = @session.viewports.main
options = {
grayscale: false
selected: false
noText: (opts.noText ? false)
}
# Draw the new tree on the main context
layoutResult = @session.view.getViewNodeFor(@session.tree).layout 0, @nubbyHeight
@session.view.getViewNodeFor(@session.tree).draw rect, options
@session.view.getViewNodeFor(@session.tree).root()
for el, i in @currentlyDrawnFloatingBlocks
unless el.record in @session.floatingBlocks
el.record.grayBoxPath.destroy()
el.record.startText.destroy()
el.record.endText.destroy()
@currentlyDrawnFloatingBlocks = []
# Draw floating blocks
startWidth = @session.mode.startComment.length * @session.fontWidth
endWidth = @session.mode.endComment.length * @session.fontWidth
for record in @session.floatingBlocks
element = @drawFloatingBlock(record, startWidth, endWidth, rect, opts)
@currentlyDrawnFloatingBlocks.push {
record: record
}
# Draw the cursor (if exists, and is inserted)
@redrawCursors(); @redrawHighlights()
@resizeGutter()
for binding in editorBindings.redraw_main
binding.call this, layoutResult
if @session.changeEventVersion isnt @session.tree.version
@session.changeEventVersion = @session.tree.version
@fireEvent 'change', []
@session.view.cleanupDraw()
unless @alreadyScheduledCleanup
@alreadyScheduledCleanup = true
setTimeout (=>
@alreadyScheduledCleanup = false
if @session?
@session.view.garbageCollect()
), 0
return null
Editor::redrawHighlights = ->
@redrawCursors()
@redrawLassoHighlight()
# If there is an block that is being dragged,
# draw it in gray
if @draggingBlock? and @inDisplay @draggingBlock
@session.view.getViewNodeFor(@draggingBlock).draw new @draw.Rectangle(
@session.viewports.main.x,
@session.viewports.main.y,
@session.viewports.main.width,
@session.viewports.main.height
), {grayscale: true}
Editor::clearCursorCanvas = ->
@textCursorPath.deactivate()
@cursorPath.deactivate()
Editor::redrawCursors = ->
return unless @session?
@clearCursorCanvas()
if @cursorAtSocket()
@redrawTextHighlights()
else unless @lassoSelection?
@drawCursor()
Editor::drawCursor = -> @strokeCursor @determineCursorPosition()
Editor::clearPalette = -> # TODO remove and remove all references to
Editor::clearPaletteHighlightCanvas = -> # TODO remove and remove all references to
Editor::redrawPalette = ->
return unless @session?.currentPaletteBlocks?
@clearPalette()
@session.paletteView.beginDraw()
# We will construct a vertical layout
# with padding for the palette blocks.
# To do this, we will need to keep track
# of the last bottom edge of a palette block.
lastBottomEdge = PALETTE_TOP_MARGIN
for entry in @session.currentPaletteBlocks
# Layout this block
paletteBlockView = @session.paletteView.getViewNodeFor entry.block
paletteBlockView.layout PALETTE_LEFT_MARGIN, lastBottomEdge
# Render the block
paletteBlockView.draw()
paletteBlockView.group.setParent @paletteCtx
element = document.createElementNS SVG_STANDARD, 'title'
element.innerHTML = entry.title ? entry.block.stringify()
paletteBlockView.group.element.appendChild element
paletteBlockView.group.element.setAttribute 'data-id', entry.id
# Update lastBottomEdge
lastBottomEdge = paletteBlockView.getBounds().bottom() + PALETTE_MARGIN
for binding in editorBindings.redraw_palette
binding.call this
@paletteCanvas.style.height = lastBottomEdge + 'px'
@session.paletteView.garbageCollect()
Editor::rebuildPalette = ->
return unless @session?.currentPaletteBlocks?
@redrawPalette()
for binding in editorBindings.rebuild_palette
binding.call this
# MOUSE INTERACTION WRAPPERS
# ================================
# These are some common operations we need to do with
# the mouse that will be convenient later.
Editor::absoluteOffset = (el) ->
point = new @draw.Point el.offsetLeft, el.offsetTop
el = el.offsetParent
until el is document.body or not el?
point.x += el.offsetLeft - el.scrollLeft
point.y += el.offsetTop - el.scrollTop
el = el.offsetParent
return point
# ### Conversion functions
# Convert a point relative to the page into
# a point relative to one of the two canvases.
Editor::trackerPointToMain = (point) ->
if not @mainCanvas.parentElement?
return new @draw.Point(NaN, NaN)
gbr = @mainCanvas.getBoundingClientRect()
new @draw.Point(point.x - gbr.left,
point.y - gbr.top)
Editor::trackerPointToPalette = (point) ->
if not @paletteCanvas.parentElement?
return new @draw.Point(NaN, NaN)
gbr = @paletteCanvas.getBoundingClientRect()
new @draw.Point(point.x - gbr.left,
point.y - gbr.top)
Editor::trackerPointIsInElement = (point, element) ->
if not @session? or @session.readOnly
return false
if not element.parentElement?
return false
gbr = element.getBoundingClientRect()
return point.x >= gbr.left and point.x < gbr.right and
point.y >= gbr.top and point.y < gbr.bottom
Editor::trackerPointIsInMain = (point) ->
return this.trackerPointIsInElement point, @mainCanvas
Editor::trackerPointIsInMainScroller = (point) ->
return this.trackerPointIsInElement point, @mainScroller
Editor::trackerPointIsInGutter = (point) ->
return this.trackerPointIsInElement point, @gutter
Editor::trackerPointIsInPalette = (point) ->
return this.trackerPointIsInElement point, @paletteCanvas
Editor::trackerPointIsInAce = (point) ->
return this.trackerPointIsInElement point, @aceElement
# ### hitTest
# Simple function for going through a linked-list block
# and seeing what the innermost child is that we hit.
Editor::hitTest = (point, block, view = @session.view) ->
if @session.readOnly
return null
head = block.start
seek = block.end
result = null
until head is seek
if head.type is 'blockStart' and view.getViewNodeFor(head.container).path.contains point
result = head.container
seek = head.container.end
head = head.next
# If we had a child hit, return it.
return result
hook 'mousedown', 10, ->
x = document.body.scrollLeft
y = document.body.scrollTop
@dropletElement.focus()
window.scrollTo(x, y)
Editor::removeBlankLines = ->
# If we have blank lines at the end,
# get rid of them
head = tail = @session.tree.end.prev
while head?.type is 'newline'
head = head.prev
if head.type is 'newline'
@spliceOut new model.List head, tail
# UNDO STACK SUPPORT
# ================================
# We must declare a few
# fields a populate time
# Now we hook to ctrl-z to undo.
hook 'keydown', 0, (event, state) ->
if event.which is Z_KEY and event.shiftKey and command_pressed(event)
@redo()
else if event.which is Z_KEY and command_pressed(event)
@undo()
else if event.which is Y_KEY and command_pressed(event)
@redo()
class EditorState
constructor: (@root, @floats) ->
equals: (other) ->
return false unless @root is other.root and @floats.length is other.floats.length
for el, i in @floats
return false unless el.position.equals(other.floats[i].position) and el.string is other.floats[i].string
return true
toString: -> JSON.stringify {
@root, @floats
}
Editor::getSerializedEditorState = ->
return new EditorState @session.tree.stringify(), @session.floatingBlocks.map (x) -> {
position: x.position
string: x.block.stringify()
}
Editor::clearUndoStack = ->
return unless @session?
@session.undoStack.length = 0
@session.redoStack.length = 0
Editor::undo = ->
return unless @session?
# Don't allow a socket to be highlighted during
# an undo operation
@setCursor @session.cursor, ((x) -> x.type isnt 'socketStart')
currentValue = @getSerializedEditorState()
until @session.undoStack.length is 0 or
(@session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint and
not @getSerializedEditorState().equals(currentValue))
operation = @popUndo()
if operation instanceof FloatingOperation
@performFloatingOperation(operation, 'backward')
else
@getDocument(operation.document).perform(
operation.operation, 'backward', @getPreserves(operation.document)
) unless operation instanceof CapturePoint
# Set the the remembered socket contents to the state it was in
# at this point in the undo stack.
if @session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint
@session.rememberedSockets = @session.undoStack[@session.undoStack.length - 1].rememberedSockets.map (x) -> x.clone()
@popUndo()
@correctCursor()
@redrawMain()
return
Editor::pushUndo = (operation) ->
@session.redoStack.length = 0
@session.undoStack.push operation
Editor::popUndo = ->
operation = @session.undoStack.pop()
@session.redoStack.push(operation) if operation?
return operation
Editor::popRedo = ->
operation = @session.redoStack.pop()
@session.undoStack.push(operation) if operation?
return operation
Editor::redo = ->
currentValue = @getSerializedEditorState()
until @session.redoStack.length is 0 or
(@session.redoStack[@session.redoStack.length - 1] instanceof CapturePoint and
not @getSerializedEditorState().equals(currentValue))
operation = @popRedo()
if operation instanceof FloatingOperation
@performFloatingOperation(operation, 'forward')
else
@getDocument(operation.document).perform(
operation.operation, 'forward', @getPreserves(operation.document)
) unless operation instanceof CapturePoint
# Set the the remembered socket contents to the state it was in
# at this point in the undo stack.
if @session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint
@session.rememberedSockets = @session.undoStack[@session.undoStack.length - 1].rememberedSockets.map (x) -> x.clone()
@popRedo()
@redrawMain()
return
# ## undoCapture and CapturePoint ##
# A CapturePoint is a sentinel indicating that the undo stack
# should stop when the user presses Ctrl+Z or Ctrl+Y. Each CapturePoint
# also remembers the @rememberedSocket state at the time it was placed,
# to preserved remembered socket contents across undo and redo.
Editor::undoCapture = ->
@pushUndo new CapturePoint(@session.rememberedSockets)
class CapturePoint
constructor: (rememberedSockets) ->
@rememberedSockets = rememberedSockets.map (x) -> x.clone()
# BASIC BLOCK MOVE SUPPORT
# ================================
Editor::getPreserves = (dropletDocument) ->
if dropletDocument instanceof model.Document
dropletDocument = @documentIndex dropletDocument
array = [@session.cursor]
array = array.concat @session.rememberedSockets.map(
(x) -> x.socket
)
return array.filter((location) ->
location.document is dropletDocument
).map((location) -> location.location)
Editor::spliceOut = (node, container = null) ->
# Make an empty list if we haven't been
# passed one
unless node instanceof model.List
node = new model.List node, node
operation = null
dropletDocument = node.getDocument()
parent = node.parent
if dropletDocument?
operation = node.getDocument().remove node, @getPreserves(dropletDocument)
@pushUndo {operation, document: @getDocuments().indexOf(dropletDocument)}
# If we are removing a block from a socket, and the socket is in our
# dictionary of remembered socket contents, repopulate the socket with
# its old contents.
if parent?.type is 'socket' and node.start.type is 'blockStart'
for socket, i in @session.rememberedSockets
if @fromCrossDocumentLocation(socket.socket) is parent
@session.rememberedSockets.splice i, 0
@populateSocket parent, socket.text
break
# Remove the floating dropletDocument if it is now
# empty
if dropletDocument.start.next is dropletDocument.end
for record, i in @session.floatingBlocks
if record.block is dropletDocument
@pushUndo new FloatingOperation i, record.block, record.position, 'delete'
# If the cursor's document is about to vanish,
# put it back in the main tree.
if @session.cursor.document is i + 1
@setCursor @session.tree.start
if @session.cursor.document > i + 1
@session.cursor.document -= 1
@session.floatingBlocks.splice i, 1
for socket in @session.rememberedSockets
if socket.socket.document > i
socket.socket.document -= 1
break
else if container?
# No document, so try to remove from container if it was supplied
container.remove node
@prepareNode node, null
@correctCursor()
return operation
Editor::spliceIn = (node, location) ->
# Track changes in the cursor by temporarily
# using a pointer to it
container = location.container ? location.parent
if container.type is 'block'
container = container.parent
else if container.type is 'socket' and
container.start.next isnt container.end
if @documentIndex(container) != -1
# If we're splicing into a socket found in a document and it already has
# something in it, remove it. Additionally, remember the old
# contents in @session.rememberedSockets for later repopulation if they take
# the block back out.
@session.rememberedSockets.push new RememberedSocketRecord(
@toCrossDocumentLocation(container),
container.textContent()
)
@spliceOut (new model.List container.start.next, container.end.prev), container
dropletDocument = location.getDocument()
@prepareNode node, container
if dropletDocument?
operation = dropletDocument.insert location, node, @getPreserves(dropletDocument)
@pushUndo {operation, document: @getDocuments().indexOf(dropletDocument)}
@correctCursor()
return operation
else
# No document, so just insert into container
container.insert location, node
return null
class RememberedSocketRecord
constructor: (@socket, @text) ->
clone: ->
new RememberedSocketRecord(
@socket.clone(),
@text
)
Editor::replace = (before, after, updates = []) ->
dropletDocument = before.start.getDocument()
if dropletDocument?
operation = dropletDocument.replace before, after, updates.concat(@getPreserves(dropletDocument))
@pushUndo {operation, document: @documentIndex(dropletDocument)}
@correctCursor()
return operation
else
return null
Editor::adjustPosToLineStart = (pos) ->
line = @aceEditor.session.getLine pos.row
if pos.row == @aceEditor.session.getLength() - 1
pos.column = if (pos.column >= line.length / 2) then line.length else 0
else
pos.column = 0
pos
Editor::correctCursor = ->
cursor = @fromCrossDocumentLocation @session.cursor
unless @validCursorPosition cursor
until not cursor? or (@validCursorPosition(cursor) and cursor.type isnt 'socketStart')
cursor = cursor.next
unless cursor? then cursor = @fromCrossDocumentLocation @session.cursor
until not cursor? or (@validCursorPosition(cursor) and cursor.type isnt 'socketStart')
cursor = cursor.prev
@session.cursor = @toCrossDocumentLocation cursor
Editor::prepareNode = (node, context) ->
if node instanceof model.Container
leading = node.getLeadingText()
if node.start.next is node.end.prev
trailing = null
else
trailing = node.getTrailingText()
[leading, trailing, classes] = @session.mode.parens leading, trailing, node.getReader(),
context?.getReader?() ? null
node.setLeadingText leading; node.setTrailingText trailing
# At population-time, we will
# want to set up a few fields.
hook 'populate', 0, ->
@clickedPoint = null
@clickedBlock = null
@clickedBlockPaletteEntry = null
@draggingBlock = null
@draggingOffset = null
@lastHighlight = @lastHighlightPath = null
# And the canvas for drawing highlights
@highlightCanvas = @highlightCtx = document.createElementNS SVG_STANDARD, 'g'
# We append it to the tracker element,
# so that it can appear in front of the scrollers.
#@dropletElement.appendChild @dragCanvas
#document.body.appendChild @dragCanvas
@wrapperElement.appendChild @dragCanvas
@mainCanvas.appendChild @highlightCanvas
Editor::clearHighlightCanvas = ->
for path in [@textCursorPath]
path.deactivate()
# Utility function for clearing the drag canvas,
# an operation we will be doing a lot.
Editor::clearDrag = ->
@clearHighlightCanvas()
# On resize, we will want to size the drag canvas correctly.
Editor::resizeDragCanvas = ->
@dragCanvas.style.width = "#{0}px"
@dragCanvas.style.height = "#{0}px"
@highlightCanvas.style.width = "#{@dropletElement.clientWidth - @gutter.clientWidth}px"
@highlightCanvas.style.height = "#{@dropletElement.clientHeight}px"
@highlightCanvas.style.left = "#{@mainCanvas.offsetLeft}px"
Editor::getDocuments = ->
documents = [@session.tree]
for el, i in @session.floatingBlocks
documents.push el.block
return documents
Editor::getDocument = (n) ->
if n is 0 then @session.tree
else @session.floatingBlocks[n - 1].block
Editor::documentIndex = (block) ->
@getDocuments().indexOf block.getDocument()
Editor::fromCrossDocumentLocation = (location) ->
@getDocument(location.document).getFromLocation location.location
Editor::toCrossDocumentLocation = (block) ->
new CrossDocumentLocation @documentIndex(block), block.getLocation()
# On mousedown, we will want to
# hit test blocks in the root tree to
# see if we want to move them.
#
# We do not do anything until the user
# drags their mouse five pixels
hook 'mousedown', 1, (point, event, state) ->
# If someone else has already taken this click, pass.
if state.consumedHitTest then return
# If it's not in the main pane, pass.
if not @trackerPointIsInMain(point) then return
# Hit test against the tree.
mainPoint = @trackerPointToMain(point)
for dropletDocument, i in @getDocuments() by -1
# First attempt handling text input
if @handleTextInputClick mainPoint, dropletDocument
state.consumedHitTest = true
return
else if @session.cursor.document is i and @cursorAtSocket()
@setCursor @session.cursor, ((token) -> token.type isnt 'socketStart')
hitTestResult = @hitTest mainPoint, dropletDocument
# Produce debugging output
if @debugging and event.shiftKey
line = null
node = @session.view.getViewNodeFor(hitTestResult)
for box, i in node.bounds
if box.contains(mainPoint)
line = i
break
@dumpNodeForDebug(hitTestResult, line)
# If it came back positive,
# deal with the click.
if hitTestResult?
# Record the hit test result (the block we want to pick up)
@clickedBlock = hitTestResult
@clickedBlockPaletteEntry = null
# Move the cursor somewhere nearby
@setCursor @clickedBlock.start.next
# Record the point at which is was clicked (for clickedBlock->draggingBlock)
@clickedPoint = point
# Signify to any other hit testing
# handlers that we have already consumed
# the hit test opportunity for this event.
state.consumedHitTest = true
return
else if i > 0
record = @session.floatingBlocks[i - 1]
if record.grayBoxPath? and record.grayBoxPath.contains @trackerPointToMain point
@clickedBlock = new model.List record.block.start.next, record.block.end.prev
@clickedPoint = point
@session.view.getViewNodeFor(@clickedBlock).absorbCache() # TODO MERGE inspection
state.consumedHitTest = true
@redrawMain()
return
# If the user clicks inside a block
# and the block contains a button
# which is either add or subtract button
# call the handleButton callback
hook 'mousedown', 4, (point, event, state) ->
if state.consumedHitTest then return
if not @trackerPointIsInMain(point) then return
mainPoint = @trackerPointToMain point
#Buttons aren't clickable in a selection
if @lassoSelection? and @hitTest(mainPoint, @lassoSelection)? then return
hitTestResult = @hitTest mainPoint, @session.tree
if hitTestResult?
hitTestBlock = @session.view.getViewNodeFor hitTestResult
str = hitTestResult.stringifyInPlace()
if hitTestBlock.addButtonRect? and hitTestBlock.addButtonRect.contains mainPoint
line = @session.mode.handleButton str, 'add-button', hitTestResult.getReader()
if line?.length >= 0
@populateBlock hitTestResult, line
@redrawMain()
state.consumedHitTest = true
### TODO
else if hitTestBlock.subtractButtonRect? and hitTestBlock.subtractButtonRect.contains mainPoint
line = @session.mode.handleButton str, 'subtract-button', hitTestResult.getReader()
if line?.length >= 0
@populateBlock hitTestResult, line
@redrawMain()
state.consumedHitTest = true
###
# If the user lifts the mouse
# before they have dragged five pixels,
# abort stuff.
hook 'mouseup', 0, (point, event, state) ->
# @clickedBlock and @clickedPoint should will exist iff
# we have dragged not yet more than 5 pixels.
#
# To abort, all we need to do is null.
if @clickedBlock?
@clickedBlock = null
@clickedPoint = null
Editor::drawDraggingBlock = ->
# Draw the new dragging block on the drag canvas.
#
# When we are dragging things, we draw the shadow.
# Also, we translate the block 1x1 to the right,
# so that we can see its borders.
@session.dragView.clearCache()
draggingBlockView = @session.dragView.getViewNodeFor @draggingBlock
draggingBlockView.layout 1, 1
@dragCanvas.width = Math.min draggingBlockView.totalBounds.width + 10, window.screen.width
@dragCanvas.height = Math.min draggingBlockView.totalBounds.height + 10, window.screen.height
draggingBlockView.draw new @draw.Rectangle 0, 0, @dragCanvas.width, @dragCanvas.height
Editor::wouldDelete = (position) ->
mainPoint = @trackerPointToMain position
palettePoint = @trackerPointToPalette position
return not @lastHighlight and not @session.viewports.main.contains(mainPoint)
# On mousemove, if there is a clicked block but no drag block,
# we might want to transition to a dragging the block if the user
# moved their mouse far enough.
hook 'mousemove', 1, (point, event, state) ->
return unless @session?
if not state.capturedPickup and @clickedBlock? and point.from(@clickedPoint).magnitude() > MIN_DRAG_DISTANCE
# Signify that we are now dragging a block.
@draggingBlock = @clickedBlock
@dragReplacing = false
# Our dragging offset must be computed using the canvas on which this block
# is rendered.
#
# NOTE: this really falls under "PALETTE SUPPORT", but must
# go here. Try to organise this better.
if @clickedBlockPaletteEntry
@draggingOffset = @session.paletteView.getViewNodeFor(@draggingBlock).bounds[0].upperLeftCorner().from(
@trackerPointToPalette(@clickedPoint))
# Substitute in expansion for this palette entry, if supplied.
expansion = @clickedBlockPaletteEntry.expansion
# Call expansion() function with no parameter to get the initial value.
if 'function' is typeof expansion then expansion = expansion()
if (expansion) then expansion = parseBlock(@session.mode, expansion, @clickedBlockPaletteEntry.context)
@draggingBlock = (expansion or @draggingBlock).clone()
# Special @draggingBlock setup for expansion function blocks.
if 'function' is typeof @clickedBlockPaletteEntry.expansion
# Any block generated from an expansion function should be treated as
# any-drop because it can change with subsequent expansion() calls.
if 'mostly-value' in @draggingBlock.classes
@draggingBlock.classes.push 'any-drop'
# Attach expansion() function and lastExpansionText to @draggingBlock.
@draggingBlock.lastExpansionText = expansion
@draggingBlock.expansion = @clickedBlockPaletteEntry.expansion
else
# Find the line on the block that we have
# actually clicked, and attempt to translate the block
# so that if it re-shapes, we're still touching it.
#
# To do this, we will assume that the left edge of a free
# block are all aligned.
mainPoint = @trackerPointToMain @clickedPoint
viewNode = @session.view.getViewNodeFor @draggingBlock
if @draggingBlock instanceof model.List and not
(@draggingBlock instanceof model.Container)
viewNode.absorbCache()
@draggingOffset = null
for bound, line in viewNode.bounds
if bound.contains mainPoint
@draggingOffset = bound.upperLeftCorner().from mainPoint
@draggingOffset.y += viewNode.bounds[0].y - bound.y
break
unless @draggingOffset?
@draggingOffset = viewNode.bounds[0].upperLeftCorner().from mainPoint
# TODO figure out what to do with lists here
# Draw the new dragging block on the drag canvas.
#
# When we are dragging things, we draw the shadow.
# Also, we translate the block 1x1 to the right,
# so that we can see its borders.
@session.dragView.beginDraw()
draggingBlockView = @session.dragView.getViewNodeFor @draggingBlock
draggingBlockView.layout 1, 1
draggingBlockView.root()
draggingBlockView.draw()
@session.dragView.garbageCollect()
@dragCanvas.style.width = "#{Math.min draggingBlockView.totalBounds.width + 10, window.screen.width}px"
@dragCanvas.style.height = "#{Math.min draggingBlockView.totalBounds.height + 10, window.screen.height}px"
# Translate it immediately into position
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
# Construct a quadtree of drop areas
# for faster dragging
@dropPointQuadTree = QUAD.init
x: @session.viewports.main.x
y: @session.viewports.main.y
w: @session.viewports.main.width
h: @session.viewports.main.height
for dropletDocument in @getDocuments()
head = dropletDocument.start
# Don't allow dropping at the start of the document
# if we are already dragging a block that is at
# the start of the document.
if @draggingBlock.start.prev is head
head = head.next
until head is dropletDocument.end
if head is @draggingBlock.start
head = @draggingBlock.end
if head instanceof model.StartToken
acceptLevel = @getAcceptLevel @draggingBlock, head.container
unless acceptLevel is helper.FORBID
dropPoint = @session.view.getViewNodeFor(head.container).dropPoint
if dropPoint?
allowed = true
for record, i in @session.floatingBlocks by -1
if record.block is dropletDocument
break
else if record.grayBoxPath.contains dropPoint
allowed = false
break
if allowed
@dropPointQuadTree.insert
x: dropPoint.x
y: dropPoint.y
w: 0
h: 0
acceptLevel: acceptLevel
_droplet_node: head.container
head = head.next
@dragCanvas.style.transform = "translate(#{position.x + getOffsetLeft(@dropletElement)}px,#{position.y + getOffsetTop(@dropletElement)}px)"
# Now we are done with the "clickedX" suite of stuff.
@clickedPoint = @clickedBlock = null
@clickedBlockPaletteEntry = null
@begunTrash = @wouldDelete position
# Redraw the main canvas
@redrawMain()
Editor::getClosestDroppableBlock = (mainPoint, isDebugMode) ->
best = null; min = Infinity
if not (@dropPointQuadTree)
return null
testPoints = @dropPointQuadTree.retrieve {
x: mainPoint.x - MAX_DROP_DISTANCE
y: mainPoint.y - MAX_DROP_DISTANCE
w: MAX_DROP_DISTANCE * 2
h: MAX_DROP_DISTANCE * 2
}, (point) =>
unless (point.acceptLevel is helper.DISCOURAGE) and not isDebugMode
# Find a modified "distance" to the point
# that weights horizontal distance more
distance = mainPoint.from(point)
distance.y *= 2; distance = distance.magnitude()
# Select the node that is closest by said "distance"
if distance < min and mainPoint.from(point).magnitude() < MAX_DROP_DISTANCE and
@session.view.getViewNodeFor(point._droplet_node).highlightArea?
best = point._droplet_node
min = distance
best
Editor::getClosestDroppableBlockFromPosition = (position, isDebugMode) ->
if not @session.currentlyUsingBlocks
return null
mainPoint = @trackerPointToMain(position)
@getClosestDroppableBlock(mainPoint, isDebugMode)
Editor::getAcceptLevel = (drag, drop) ->
if drop.type is 'socket'
if drag.type is 'list'
return helper.FORBID
else
return @session.mode.drop drag.getReader(), drop.getReader(), null, null
# If it's a list/selection, try all of its children
else if drag.type is 'list'
minimum = helper.ENCOURAGE
drag.traverseOneLevel (child) =>
if child instanceof model.Container
minimum = Math.min minimum, @getAcceptLevel child, drop
return minimum
else if drop.type is 'block'
if drop.parent.type is 'socket'
return helper.FORBID
else
next = drop.nextSibling()
return @session.mode.drop drag.getReader(), drop.parent.getReader(), drop.getReader(), next?.getReader?()
else
next = drop.firstChild()
return @session.mode.drop drag.getReader(), drop.getReader(), drop.getReader(), next?.getReader?()
# On mousemove, if there is a dragged block, we want to
# translate the drag canvas into place,
# as well as highlighting any focused drop areas.
hook 'mousemove', 0, (point, event, state) ->
if @draggingBlock?
# Translate the drag canvas into position.
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
# If there is an expansion function, call it again here.
if (@draggingBlock.expansion)
# Call expansion() with the closest droppable block for all drag moves.
expansionText = @draggingBlock.expansion(@getClosestDroppableBlockFromPosition(position, event.shiftKey))
# Create replacement @draggingBlock if the returned text is new.
if expansionText isnt @draggingBlock.lastExpansionText
newBlock = parseBlock(@session.mode, expansionText)
newBlock.lastExpansionText = expansionText
newBlock.expansion = @draggingBlock.expansion
if 'any-drop' in @draggingBlock.classes
newBlock.classes.push 'any-drop'
@draggingBlock = newBlock
@drawDraggingBlock()
if not @session.currentlyUsingBlocks
if @trackerPointIsInAce position
pos = @aceEditor.renderer.screenToTextCoordinates position.x, position.y
if @session.dropIntoAceAtLineStart
pos = @adjustPosToLineStart pos
@aceEditor.focus()
@aceEditor.session.selection.moveToPosition pos
else
@aceEditor.blur()
rect = @wrapperElement.getBoundingClientRect()
@dragCanvas.style.transform = "translate(#{position.x - rect.left}px,#{position.y - rect.top}px)"
mainPoint = @trackerPointToMain(position)
# Check to see if the tree is empty;
# if it is, drop on the tree always
head = @session.tree.start.next
while head.type in ['newline', 'cursor'] or head.type is 'text' and head.value is ''
head = head.next
if head is @session.tree.end and @session.floatingBlocks.length is 0 and
@session.viewports.main.right() > mainPoint.x > @session.viewports.main.x - @gutter.clientWidth and
@session.viewports.main.bottom() > mainPoint.y > @session.viewports.main.y and
@getAcceptLevel(@draggingBlock, @session.tree) is helper.ENCOURAGE
@session.view.getViewNodeFor(@session.tree).highlightArea.update()
@lastHighlight = @session.tree
else
# If the user is touching the original location,
# assume they want to replace the block where they found it.
if @hitTest mainPoint, @draggingBlock
@dragReplacing = true
dropBlock = null
# If the user's block is outside the main pane, delete it
else if not @trackerPointIsInMain position
@dragReplacing = false
dropBlock= null
# Otherwise, find the closest droppable block
else
@dragReplacing = false
dropBlock = @getClosestDroppableBlock(mainPoint, event.shiftKey)
# Update highlight if necessary.
if dropBlock isnt @lastHighlight
# TODO if this becomes a performance issue,
# pull the drop highlights out into a new canvas.
@redrawHighlights()
@lastHighlightPath?.deactivate?()
if dropBlock?
@lastHighlightPath = @session.view.getViewNodeFor(dropBlock).highlightArea
@lastHighlightPath.update()
@qualifiedFocus dropBlock, @lastHighlightPath
@lastHighlight = dropBlock
palettePoint = @trackerPointToPalette position
if @wouldDelete(position)
if @begunTrash
@dragCanvas.style.opacity = 0.85
else
@dragCanvas.style.opacity = 0.3
else
@dragCanvas.style.opacity = 0.85
@begunTrash = false
Editor::qualifiedFocus = (node, path) ->
documentIndex = @documentIndex node
if documentIndex < @session.floatingBlocks.length
path.activate()
@mainCanvas.insertBefore path.element, @session.floatingBlocks[documentIndex].renderGroup.element
else
path.activate()
@mainCanvas.appendChild path.element
hook 'mouseup', 0, ->
clearTimeout @discourageDropTimeout; @discourageDropTimeout = null
hook 'mouseup', 1, (point, event, state) ->
if @dragReplacing
@endDrag()
# We will consume this event iff we dropped it successfully
# in the root tree.
if @draggingBlock?
if not @session.currentlyUsingBlocks
# See if we can drop the block's text in ace mode.
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
if @trackerPointIsInAce position
leadingWhitespaceRegex = /^(\s*)/
# Get the line of text we're dropping into
pos = @aceEditor.renderer.screenToTextCoordinates position.x, position.y
line = @aceEditor.session.getLine pos.row
indentation = leadingWhitespaceRegex.exec(line)[0]
skipInitialIndent = true
prefix = ''
suffix = ''
if @session.dropIntoAceAtLineStart
# First, adjust indentation if we're dropping into the start of a
# line that ends an indentation block
firstNonWhitespaceRegex = /\S/
firstChar = firstNonWhitespaceRegex.exec(line)
if firstChar and firstChar[0] == '}'
# If this line starts with a closing bracket, use the previous line's indentation
# TODO: generalize for language indentation semantics besides C/JavaScript
prevLine = @aceEditor.session.getLine(pos.row - 1)
indentation = leadingWhitespaceRegex.exec(prevLine)[0]
# Adjust pos to start of the line (as we did during mousemove)
pos = @adjustPosToLineStart pos
skipInitialIndent = false
if pos.column == 0
suffix = '\n'
else
# Handle the case where we're dropping a block at the end of the last line
prefix = '\n'
else if indentation.length == line.length or indentation.length == pos.column
# line is whitespace only or we're inserting at the beginning of a line
# Append with a newline
suffix = '\n' + indentation
else if pos.column == line.length
# We're at the end of a non-empty line.
# Insert a new line, and base our indentation off of the next line
prefix = '\n'
skipInitialIndent = false
nextLine = @aceEditor.session.getLine(pos.row + 1)
indentation = leadingWhitespaceRegex.exec(nextLine)[0]
# Call prepareNode, which may append with a semicolon
@prepareNode @draggingBlock, null
text = @draggingBlock.stringify @session.mode
# Indent each line, unless it's the first line and wasn't placed on
# a newline
text = text.split('\n').map((line, index) =>
return (if index == 0 and skipInitialIndent then '' else indentation) + line
).join('\n')
text = prefix + text + suffix
@aceEditor.onTextInput text
else if @lastHighlight?
@undoCapture()
# Remove the block from the tree.
rememberedSocketOffsets = @spliceRememberedSocketOffsets(@draggingBlock)
# TODO this is a hacky way of preserving locations
# across parenthesis insertion
hadTextToken = @draggingBlock.start.next.type is 'text'
@spliceOut @draggingBlock
@clearHighlightCanvas()
# Fire an event for a sound
@fireEvent 'sound', [@lastHighlight.type]
# Depending on what the highlighted element is,
# we might want to drop the block at its
# beginning or at its end.
#
# We will need to log undo operations here too.
switch @lastHighlight.type
when 'indent', 'socket'
@spliceIn @draggingBlock, @lastHighlight.start
when 'block'
@spliceIn @draggingBlock, @lastHighlight.end
else
if @lastHighlight.type is 'document'
@spliceIn @draggingBlock, @lastHighlight.start
# TODO as above
hasTextToken = @draggingBlock.start.next.type is 'text'
if hadTextToken and not hasTextToken
rememberedSocketOffsets.forEach (x) ->
x.offset -= 1
else if hasTextToken and not hadTextToken
rememberedSocketOffsets.forEach (x) ->
x.offset += 1
futureCursorLocation = @toCrossDocumentLocation @draggingBlock.start
# Reparse the parent if we are
# in a socket
#
# TODO "reparseable" property (or absent contexts), bubble up
# TODO performance on large programs
if @lastHighlight.type is 'socket'
@reparse @draggingBlock.parent.parent
# Now that we've done that, we can annul stuff.
@endDrag()
@setCursor(futureCursorLocation) if futureCursorLocation?
newBeginning = futureCursorLocation.location.count
newIndex = futureCursorLocation.document
for el, i in rememberedSocketOffsets
@session.rememberedSockets.push new RememberedSocketRecord(
new CrossDocumentLocation(
newIndex
new model.Location(el.offset + newBeginning, 'socket')
),
el.text
)
# Fire the event for sound
@fireEvent 'block-click'
Editor::spliceRememberedSocketOffsets = (block) ->
if block.getDocument()?
blockBegin = block.start.getLocation().count
offsets = []
newRememberedSockets = []
for el, i in @session.rememberedSockets
if block.contains @fromCrossDocumentLocation(el.socket)
offsets.push {
offset: el.socket.location.count - blockBegin
text: el.text
}
else
newRememberedSockets.push el
@session.rememberedSockets = newRememberedSockets
return offsets
else
[]
# FLOATING BLOCK SUPPORT
# ================================
class FloatingBlockRecord
constructor: (@block, @position) ->
Editor::inTree = (block) -> (block.container ? block).getDocument() is @session.tree
Editor::inDisplay = (block) -> (block.container ? block).getDocument() in @getDocuments()
# We can create floating blocks by dropping
# blocks without a highlight.
hook 'mouseup', 0, (point, event, state) ->
if @draggingBlock? and not @lastHighlight? and not @dragReplacing
oldParent = @draggingBlock.parent
# Before we put this block into our list of floating blocks,
# we need to figure out where on the main canvas
# we are going to render it.
trackPoint = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
renderPoint = @trackerPointToMain trackPoint
palettePoint = @trackerPointToPalette trackPoint
removeBlock = true
addBlockAsFloatingBlock = true
# If we dropped it off in the palette, abort (so as to delete the block).
unless @session.viewports.main.right() > renderPoint.x > @session.viewports.main.x - @gutter.clientWidth and
@session.viewports.main.bottom() > renderPoint.y > @session.viewports.main.y
if @draggingBlock is @lassoSelection
@lassoSelection = null
addBlockAsFloatingBlock = false
else
if renderPoint.x - @session.viewports.main.x < 0
renderPoint.x = @session.viewports.main.x
# If @session.allowFloatingBlocks is false, we end the drag without deleting the block.
if not @session.allowFloatingBlocks
addBlockAsFloatingBlock = false
removeBlock = false
if removeBlock
# Remove the block from the tree.
@undoCapture()
rememberedSocketOffsets = @spliceRememberedSocketOffsets(@draggingBlock)
@spliceOut @draggingBlock
if not addBlockAsFloatingBlock
@endDrag()
return
else if renderPoint.x - @session.viewports.main.x < 0
renderPoint.x = @session.viewports.main.x
# Add the undo operation associated
# with creating this floating block
newDocument = new model.Document(oldParent?.parseContext ? @session.mode.rootContext, {roundedSingletons: true})
newDocument.insert newDocument.start, @draggingBlock
@pushUndo new FloatingOperation @session.floatingBlocks.length, newDocument, renderPoint, 'create'
# Add this block to our list of floating blocks
@session.floatingBlocks.push record = new FloatingBlockRecord(
newDocument
renderPoint
)
@initializeFloatingBlock record, @session.floatingBlocks.length - 1
@setCursor @draggingBlock.start
# TODO write a test for this logic
for el, i in rememberedSocketOffsets
@session.rememberedSockets.push new RememberedSocketRecord(
new CrossDocumentLocation(
@session.floatingBlocks.length,
new model.Location(el.offset + 1, 'socket')
),
el.text
)
# Now that we've done that, we can annul stuff.
@clearDrag()
@draggingBlock = null
@draggingOffset = null
@lastHighlightPath?.destroy?()
@lastHighlight = @lastHighlightPath = null
@redrawMain()
Editor::performFloatingOperation = (op, direction) ->
if (op.type is 'create') is (direction is 'forward')
if @session.cursor.document > op.index
@session.cursor.document += 1
for socket in @session.rememberedSockets
if socket.socket.document > op.index
socket.socket.document += 1
@session.floatingBlocks.splice op.index, 0, record = new FloatingBlockRecord(
op.block.clone()
op.position
)
@initializeFloatingBlock record, op.index
else
# If the cursor's document is about to vanish,
# put it back in the main tree.
if @session.cursor.document is op.index + 1
@setCursor @session.tree.start
for socket in @session.rememberedSockets
if socket.socket.document > op.index + 1
socket.socket.document -= 1
@session.floatingBlocks.splice op.index, 1
class FloatingOperation
constructor: (@index, @block, @position, @type) ->
@block = @block.clone()
toString: -> JSON.stringify({
index: @index
block: @block.stringify()
position: @position.toString()
type: @type
})
# PALETTE SUPPORT
# ================================
# The first thing we will have to do with
# the palette is install the hierarchical menu.
#
# This happens at population time.
hook 'populate', 0, ->
# Create the hierarchical menu element.
@paletteHeader = document.createElement 'div'
@paletteHeader.className = 'droplet-palette-header'
# Append the element.
@paletteElement.appendChild @paletteHeader
if @session?
@setPalette @session.paletteGroups
parseBlock = (mode, code, context = null) =>
block = mode.parse(code, {context}).start.next.container
block.start.prev = block.end.next = null
block.setParent null
return block
Editor::setPalette = (paletteGroups) ->
@paletteHeader.innerHTML = ''
@session.paletteGroups = paletteGroups
@session.currentPaletteBlocks = []
@session.currentPaletteMetadata = []
paletteHeaderRow = null
for paletteGroup, i in @session.paletteGroups then do (paletteGroup, i) =>
# Start a new row, if we're at that point
# in our appending cycle
if i % 2 is 0
paletteHeaderRow = document.createElement 'div'
paletteHeaderRow.className = 'droplet-palette-header-row'
@paletteHeader.appendChild paletteHeaderRow
# hide the header if there is only one group, and it has no name.
if @session.paletteGroups.length is 1 and !paletteGroup.name
paletteHeaderRow.style.height = 0
# Create the element itself
paletteGroupHeader = paletteGroup.header = document.createElement 'div'
paletteGroupHeader.className = 'droplet-palette-group-header'
if paletteGroup.id
paletteGroupHeader.id = 'droplet-palette-group-header-' + paletteGroup.id
paletteGroupHeader.innerText = paletteGroupHeader.textContent = paletteGroupHeader.textContent = paletteGroup.name # innerText and textContent for FF compatability
if paletteGroup.color
paletteGroupHeader.className += ' ' + paletteGroup.color
paletteHeaderRow.appendChild paletteGroupHeader
newPaletteBlocks = []
# Parse all the blocks in this palette and clone them
for data in paletteGroup.blocks
newBlock = parseBlock(@session.mode, data.block, data.context)
expansion = data.expansion or null
newPaletteBlocks.push
block: newBlock
expansion: expansion
context: data.context
title: data.title
id: data.id
paletteGroup.parsedBlocks = newPaletteBlocks
# When we click this element,
# we should switch to it in the palette.
updatePalette = =>
@changePaletteGroup paletteGroup
clickHandler = =>
do updatePalette
paletteGroupHeader.addEventListener 'click', clickHandler
paletteGroupHeader.addEventListener 'touchstart', clickHandler
# If we are the first element, make us the selected palette group.
if i is 0
do updatePalette
@resizePalette()
@resizePaletteHighlight()
# Change which palette group is selected.
# group argument can be object, id (string), or name (string)
#
Editor::changePaletteGroup = (group) ->
for curGroup, i in @session.paletteGroups
if group is curGroup or group is curGroup.id or group is curGroup.name
paletteGroup = curGroup
break
if not paletteGroup
return
# Record that we are the selected group now
@session.currentPaletteGroup = paletteGroup.name
@session.currentPaletteBlocks = paletteGroup.parsedBlocks
@session.currentPaletteMetadata = paletteGroup.parsedBlocks
# Unapply the "selected" style to the current palette group header
@session.currentPaletteGroupHeader?.className =
@session.currentPaletteGroupHeader.className.replace(
/\s[-\w]*-selected\b/, '')
# Now we are the current palette group header
@session.currentPaletteGroupHeader = paletteGroup.header
@currentPaletteIndex = i
# Apply the "selected" style to us
@session.currentPaletteGroupHeader.className +=
' droplet-palette-group-header-selected'
# Redraw the palette.
@rebuildPalette()
@fireEvent 'selectpalette', [paletteGroup.name]
# The next thing we need to do with the palette
# is let people pick things up from it.
hook 'mousedown', 6, (point, event, state) ->
# If someone else has already taken this click, pass.
if state.consumedHitTest then return
# If it's not in the palette pane, pass.
if not @trackerPointIsInPalette(point) then return
palettePoint = @trackerPointToPalette point
if @session.viewports.palette.contains(palettePoint)
if @handleTextInputClickInPalette palettePoint
state.consumedHitTest = true
return
for entry in @session.currentPaletteBlocks
hitTestResult = @hitTest palettePoint, entry.block, @session.paletteView
if hitTestResult?
@clickedBlock = entry.block
@clickedPoint = point
@clickedBlockPaletteEntry = entry
state.consumedHitTest = true
@fireEvent 'pickblock', [entry.id]
return
@clickedBlockPaletteEntry = null
# PALETTE HIGHLIGHT CODE
# ================================
hook 'populate', 1, ->
@paletteHighlightCanvas = @paletteHighlightCtx = document.createElementNS SVG_STANDARD, 'svg'
@paletteHighlightCanvas.setAttribute 'class', 'droplet-palette-highlight-canvas'
@paletteHighlightPath = null
@currentHighlightedPaletteBlock = null
@paletteElement.appendChild @paletteHighlightCanvas
Editor::resizePaletteHighlight = ->
@paletteHighlightCanvas.style.top = @paletteHeader.clientHeight + 'px'
@paletteHighlightCanvas.style.width = "#{@paletteCanvas.clientWidth}px"
@paletteHighlightCanvas.style.height = "#{@paletteCanvas.clientHeight}px"
hook 'redraw_palette', 0, ->
@clearPaletteHighlightCanvas()
if @currentHighlightedPaletteBlock?
@paletteHighlightPath.update()
# TEXT INPUT SUPPORT
# ================================
# At populate-time, we need
# to create and append the hidden input
# we will use for text input.
hook 'populate', 1, ->
@hiddenInput = document.createElement 'textarea'
@hiddenInput.className = 'droplet-hidden-input'
@hiddenInput.addEventListener 'focus', =>
if @cursorAtSocket()
# Must ensure that @hiddenInput is within the client area
# or else the other divs under @dropletElement will scroll out of
# position when @hiddenInput receives keystrokes with focus
# (left and top should not be closer than 10 pixels from the edge)
bounds = @session.view.getViewNodeFor(@getCursor()).bounds[0]
###
inputLeft = bounds.x + @mainCanvas.offsetLeft - @session.viewports.main.x
inputLeft = Math.min inputLeft, @dropletElement.clientWidth - 10
inputLeft = Math.max @mainCanvas.offsetLeft, inputLeft
@hiddenInput.style.left = inputLeft + 'px'
inputTop = bounds.y - @session.viewports.main.y
inputTop = Math.min inputTop, @dropletElement.clientHeight - 10
inputTop = Math.max 0, inputTop
@hiddenInput.style.top = inputTop + 'px'
###
@dropletElement.appendChild @hiddenInput
# We also need to initialise some fields
# for knowing what is focused
@textInputAnchor = null
@textInputSelecting = false
@oldFocusValue = null
# Prevent kids from deleting a necessary quote accidentally
@hiddenInput.addEventListener 'keydown', (event) =>
if event.keyCode is 8 and @hiddenInput.value.length > 1 and
@hiddenInput.value[0] is @hiddenInput.value[@hiddenInput.value.length - 1] and
@hiddenInput.value[0] in ['\'', '\"'] and @hiddenInput.selectionEnd is 1
event.preventDefault()
# The hidden input should be set up
# to mirror the text to which it is associated.
for event in ['input', 'keyup', 'keydown', 'select']
@hiddenInput.addEventListener event, =>
@highlightFlashShow()
if @cursorAtSocket()
@redrawTextInput()
# Update the dropdown size to match
# the new length, if it is visible.
if @dropdownVisible
@formatDropdown()
Editor::resizeAceElement = ->
width = @wrapperElement.clientWidth
if @session?.showPaletteInTextMode and @session?.paletteEnabled
width -= @paletteWrapper.clientWidth
@aceElement.style.width = "#{width}px"
@aceElement.style.height = "#{@wrapperElement.clientHeight}px"
last_ = (array) -> array[array.length - 1]
# Redraw function for text input
Editor::redrawTextInput = ->
return unless @session?
sameLength = @getCursor().stringify().split('\n').length is @hiddenInput.value.split('\n').length
dropletDocument = @getCursor().getDocument()
# Set the value in the model to fit
# the hidden input value.
@populateSocket @getCursor(), @hiddenInput.value
textFocusView = @session.view.getViewNodeFor @getCursor()
# Determine the coordinate positions
# of the typing cursor
startRow = @getCursor().stringify()[...@hiddenInput.selectionStart].split('\n').length - 1
endRow = @getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n').length - 1
# Redraw the main canvas, on top of
# which we will draw the cursor and
# highlights.
if sameLength and startRow is endRow
line = endRow
head = @getCursor().start
until head is dropletDocument.start
head = head.prev
if head.type is 'newline' then line++
treeView = @session.view.getViewNodeFor dropletDocument
oldp = helper.deepCopy [
treeView.glue[line - 1],
treeView.glue[line],
treeView.bounds[line].height
]
treeView.layout()
newp = helper.deepCopy [
treeView.glue[line - 1],
treeView.glue[line],
treeView.bounds[line].height
]
# If the layout has not changed enough to affect
# anything non-local, only redraw locally.
@redrawMain()
###
if helper.deepEquals newp, oldp
rect = new @draw.NoRectangle()
rect.unite treeView.bounds[line - 1] if line > 0
rect.unite treeView.bounds[line]
rect.unite treeView.bounds[line + 1] if line + 1 < treeView.bounds.length
rect.width = Math.max rect.width, @mainCanvas.clientWidth
@redrawMain
boundingRectangle: rect
else @redrawMain()
###
# Otherwise, redraw the whole thing
else
@redrawMain()
Editor::redrawTextHighlights = (scrollIntoView = false) ->
@clearHighlightCanvas()
return unless @session?
return unless @cursorAtSocket()
textFocusView = @session.view.getViewNodeFor @getCursor()
# Determine the coordinate positions
# of the typing cursor
startRow = @getCursor().stringify()[...@hiddenInput.selectionStart].split('\n').length - 1
endRow = @getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n').length - 1
lines = @getCursor().stringify().split '\n'
startPosition = textFocusView.bounds[startRow].x + @session.view.opts.textPadding +
@session.fontWidth * last_(@getCursor().stringify()[...@hiddenInput.selectionStart].split('\n')).length +
(if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)
endPosition = textFocusView.bounds[endRow].x + @session.view.opts.textPadding +
@session.fontWidth * last_(@getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n')).length +
(if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)
# Now draw the highlight/typing cursor
#
# Draw a line if it is just a cursor
if @hiddenInput.selectionStart is @hiddenInput.selectionEnd
@qualifiedFocus @getCursor(), @textCursorPath
points = [
new @session.view.draw.Point(startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding),
new @session.view.draw.Point(startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding + @session.view.opts.textHeight)
]
@textCursorPath.setPoints points
@textCursorPath.style.strokeColor = '#000'
@textCursorPath.update()
@qualifiedFocus @getCursor(), @textCursorPath
@textInputHighlighted = false
# Draw a translucent rectangle if there is a selection.
else
@textInputHighlighted = true
# TODO maybe put this in the view?
rectangles = []
if startRow is endRow
rectangles.push new @session.view.draw.Rectangle startPosition,
textFocusView.bounds[startRow].y + @session.view.opts.textPadding
endPosition - startPosition, @session.view.opts.textHeight
else
rectangles.push new @session.view.draw.Rectangle startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding,
textFocusView.bounds[startRow].right() - @session.view.opts.textPadding - startPosition, @session.view.opts.textHeight
for i in [startRow + 1...endRow]
rectangles.push new @session.view.draw.Rectangle textFocusView.bounds[i].x,
textFocusView.bounds[i].y + @session.view.opts.textPadding,
textFocusView.bounds[i].width,
@session.view.opts.textHeight
rectangles.push new @session.view.draw.Rectangle textFocusView.bounds[endRow].x,
textFocusView.bounds[endRow].y + @session.view.opts.textPadding,
endPosition - textFocusView.bounds[endRow].x,
@session.view.opts.textHeight
left = []; right = []
for el, i in rectangles
left.push new @session.view.draw.Point el.x, el.y
left.push new @session.view.draw.Point el.x, el.bottom()
right.push new @session.view.draw.Point el.right(), el.y
right.push new @session.view.draw.Point el.right(), el.bottom()
@textCursorPath.setPoints left.concat right.reverse()
@textCursorPath.style.strokeColor = 'none'
@textCursorPath.update()
@qualifiedFocus @getCursor(), @textCursorPath
if scrollIntoView and endPosition > @session.viewports.main.x + @mainCanvas.clientWidth
@mainScroller.scrollLeft = endPosition - @mainCanvas.clientWidth + @session.view.opts.padding
escapeString = (str) ->
str[0] + str[1...-1].replace(/(\'|\"|\n)/g, '\\$1') + str[str.length - 1]
hook 'mousedown', 7, ->
@hideDropdown()
# If we can, try to reparse the focus
# value.
#
# When reparsing occurs, we first try to treat the socket
# as a separate block (inserting parentheses, etc), then fall
# back on reparsing it with original text before giving up.
#
# For instance:
#
# (a * b)
# -> edits [b] to [b + c]
# -> reparse to b + c
# -> inserts with parens to (a * (b + c))
# -> finished.
#
# OR
#
# function (a) {}
# -> edits [a] to [a, b]
# -> reparse to a, b
# -> inserts with parens to function((a, b)) {}
# -> FAILS.
# -> Fall back to raw reparsing the parent with unparenthesized text
# -> Reparses function(a, b) {} with two paremeters.
# -> Finsihed.
Editor::reparse = (list, recovery, updates = [], originalTrigger = list) ->
# Don't reparse sockets. When we reparse sockets,
# reparse them first, then try reparsing their parent and
# make sure everything checks out.
if list.start.type is 'socketStart'
return if list.start.next is list.end
originalText = list.textContent()
originalUpdates = updates.map (location) ->
count: location.count, type: location.type
# If our language mode has a string-fixing feature (in most languages,
# this will simply autoescape quoted "strings"), apply it
if @session.mode.stringFixer?
@populateSocket list, @session.mode.stringFixer list.textContent()
# Try reparsing the parent after beforetextfocus. If it fails,
# repopulate with the original text and try again.
unless @reparse list.parent, recovery, updates, originalTrigger
@populateSocket list, originalText
originalUpdates.forEach (location, i) ->
updates[i].count = location.count
updates[i].type = location.type
@reparse list.parent, recovery, updates, originalTrigger
return
parent = list.start.parent
if parent?.type is 'indent' and not list.start.container?.parseContext?
context = parent.parseContext
else
context = (list.start.container ? list.start.parent).parseContext
try
newList = @session.mode.parse list.stringifyInPlace(),{
wrapAtRoot: parent.type isnt 'socket'
context: context
}
catch e
try
newList = @session.mode.parse recovery(list.stringifyInPlace()), {
wrapAtRoot: parent.type isnt 'socket'
context: context
}
catch e
# Seek a parent that is not a socket
# (since we should never reparse just a socket)
while parent? and parent.type is 'socket'
parent = parent.parent
# Attempt to bubble up to the parent
if parent?
return @reparse parent, recovery, updates, originalTrigger
else
@session.view.getViewNodeFor(originalTrigger).mark {color: '#F00'}
return false
return if newList.start.next is newList.end
# Exclude the document start and end tags
newList = new model.List newList.start.next, newList.end.prev
# Prepare the new node for insertion
newList.traverseOneLevel (head) =>
@prepareNode head, parent
@replace list, newList, updates
@redrawMain()
return true
Editor::setTextSelectionRange = (selectionStart, selectionEnd) ->
if selectionStart? and not selectionEnd?
selectionEnd = selectionStart
# Focus the hidden input.
if @cursorAtSocket()
@hiddenInput.focus()
if selectionStart? and selectionEnd?
@hiddenInput.setSelectionRange selectionStart, selectionEnd
else if @hiddenInput.value[0] is @hiddenInput.value[@hiddenInput.value.length - 1] and
@hiddenInput.value[0] in ['\'', '"']
@hiddenInput.setSelectionRange 1, @hiddenInput.value.length - 1
else
@hiddenInput.setSelectionRange 0, @hiddenInput.value.length
@redrawTextInput()
# Redraw.
@redrawMain(); @redrawTextInput()
Editor::cursorAtSocket = -> @getCursor().type is 'socket'
Editor::populateSocket = (socket, string) ->
unless socket.textContent() is string
lines = string.split '\n'
unless socket.start.next is socket.end
@spliceOut new model.List socket.start.next, socket.end.prev
first = last = new model.TextToken lines[0]
for line, i in lines when i > 0
last = helper.connect last, new model.NewlineToken()
last = helper.connect last, new model.TextToken line
@spliceIn (new model.List(first, last)), socket.start
Editor::populateBlock = (block, string) ->
newBlock = @session.mode.parse(string, wrapAtRoot: false).start.next.container
if newBlock
# Find the first token before the block
# that will still be around after the
# block has been removed
position = block.start.prev
while position?.type is 'newline' and not (
position.prev?.type is 'indentStart' and
position.prev.container.end is block.end.next)
position = position.prev
@spliceOut block
@spliceIn newBlock, position
return true
return false
# Convenience hit-testing function
Editor::hitTestTextInput = (point, block) ->
head = block.start
while head?
if head.type is 'socketStart' and head.container.isDroppable() and
@session.view.getViewNodeFor(head.container).path.contains point
return head.container
head = head.next
return null
# Convenience functions for setting
# the text input selection, given
# points on the main canvas.
Editor::getTextPosition = (point) ->
textFocusView = @session.view.getViewNodeFor @getCursor()
row = Math.floor((point.y - textFocusView.bounds[0].y) / (@session.fontSize + 2 * @session.view.opts.padding))
row = Math.max row, 0
row = Math.min row, textFocusView.lineLength - 1
column = Math.max 0, Math.round((point.x - textFocusView.bounds[row].x - @session.view.opts.textPadding - (if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)) / @session.fontWidth)
lines = @getCursor().stringify().split('\n')[..row]
lines[lines.length - 1] = lines[lines.length - 1][...column]
return lines.join('\n').length
Editor::setTextInputAnchor = (point) ->
@textInputAnchor = @textInputHead = @getTextPosition point
@hiddenInput.setSelectionRange @textInputAnchor, @textInputHead
Editor::selectDoubleClick = (point) ->
position = @getTextPosition point
before = @getCursor().stringify()[...position].match(/\w*$/)[0]?.length ? 0
after = @getCursor().stringify()[position..].match(/^\w*/)[0]?.length ? 0
@textInputAnchor = position - before
@textInputHead = position + after
@hiddenInput.setSelectionRange @textInputAnchor, @textInputHead
Editor::setTextInputHead = (point) ->
@textInputHead = @getTextPosition point
@hiddenInput.setSelectionRange Math.min(@textInputAnchor, @textInputHead), Math.max(@textInputAnchor, @textInputHead)
# On mousedown, we will want to start
# selections and focus text inputs
# if we apply.
Editor::handleTextInputClick = (mainPoint, dropletDocument) ->
hitTestResult = @hitTestTextInput mainPoint, dropletDocument
# If they have clicked a socket,
# focus it.
if hitTestResult?
unless hitTestResult is @getCursor()
if hitTestResult.editable()
@undoCapture()
@setCursor hitTestResult
@redrawMain()
if hitTestResult.hasDropdown() and ((not hitTestResult.editable()) or
mainPoint.x - @session.view.getViewNodeFor(hitTestResult).bounds[0].x < helper.DROPDOWN_ARROW_WIDTH)
@showDropdown hitTestResult
@textInputSelecting = false
else
if @getCursor().hasDropdown() and
mainPoint.x - @session.view.getViewNodeFor(hitTestResult).bounds[0].x < helper.DROPDOWN_ARROW_WIDTH
@showDropdown()
@setTextInputAnchor mainPoint
@redrawTextInput()
@textInputSelecting = true
# Now that we have focused the text element
# in the Droplet model, focus the hidden input.
#
# It is important that this be done after the Droplet model
# has focused its text element, because
# the hidden input moves on the focus() event to
# the currently-focused Droplet element to make
# mobile screen scroll properly.
@hiddenInput.focus()
return true
else
return false
# Convenience hit-testing function
Editor::hitTestTextInputInPalette = (point, block) ->
head = block.start
while head?
if head.type is 'socketStart' and head.container.isDroppable() and
@session.paletteView.getViewNodeFor(head.container).path.contains point
return head.container
head = head.next
return null
Editor::handleTextInputClickInPalette = (palettePoint) ->
for entry in @session.currentPaletteBlocks
hitTestResult = @hitTestTextInputInPalette palettePoint, entry.block
# If they have clicked a socket, check to see if it is a dropdown
if hitTestResult?
if hitTestResult.hasDropdown()
@showDropdown hitTestResult, true
return true
return false
# Create the dropdown DOM element at populate time.
hook 'populate', 0, ->
@dropdownElement = document.createElement 'div'
@dropdownElement.className = 'droplet-dropdown'
@wrapperElement.appendChild @dropdownElement
@dropdownElement.innerHTML = ''
@dropdownElement.style.display = 'inline-block'
@dropdownVisible = false
# Update the dropdown to match
# the current text focus font and size.
Editor::formatDropdown = (socket = @getCursor(), view = @session.view) ->
@dropdownElement.style.fontFamily = @session.fontFamily
@dropdownElement.style.fontSize = @session.fontSize
@dropdownElement.style.minWidth = view.getViewNodeFor(socket).bounds[0].width
Editor::getDropdownList = (socket) ->
result = socket.dropdown
if result.generate
result = result.generate
if 'function' is typeof result
result = socket.dropdown()
else
result = socket.dropdown
if result.options
result = result.options
newresult = []
for key, val of result
newresult.push if 'string' is typeof val then { text: val, display: val } else val
return newresult
Editor::showDropdown = (socket = @getCursor(), inPalette = false) ->
@dropdownVisible = true
dropdownItems = []
@dropdownElement.innerHTML = ''
@dropdownElement.style.display = 'inline-block'
@formatDropdown socket, if inPalette then @session.paletteView else @session.view
for el, i in @getDropdownList(socket) then do (el) =>
div = document.createElement 'div'
div.innerHTML = el.display
div.className = 'droplet-dropdown-item'
dropdownItems.push div
div.style.paddingLeft = helper.DROPDOWN_ARROW_WIDTH
setText = (text) =>
@undoCapture()
# Attempting to populate the socket after the dropdown has closed should no-op
if @dropdownElement.style.display == 'none'
return
if inPalette
@populateSocket socket, text
@redrawPalette()
else if not socket.editable()
@populateSocket socket, text
@redrawMain()
else
if not @cursorAtSocket()
return
@populateSocket @getCursor(), text
@hiddenInput.value = text
@redrawMain()
@hideDropdown()
div.addEventListener 'mouseup', ->
if el.click
el.click(setText)
else
setText(el.text)
@dropdownElement.appendChild div
@dropdownElement.style.top = '-9999px'
@dropdownElement.style.left = '-9999px'
# Wait for a render. Then,
# if the div is scrolled vertically, add
# some padding on the right. After checking for this,
# move the dropdown element into position
setTimeout (=>
if @dropdownElement.clientHeight < @dropdownElement.scrollHeight
for el in dropdownItems
el.style.paddingRight = DROPDOWN_SCROLLBAR_PADDING
if inPalette
location = @session.paletteView.getViewNodeFor(socket).bounds[0]
@dropdownElement.style.left = location.x - @session.viewports.palette.x + @paletteCanvas.clientLeft + 'px'
@dropdownElement.style.minWidth = location.width + 'px'
dropdownTop = location.y + @session.fontSize - @session.viewports.palette.y + @paletteCanvas.clientTop
if dropdownTop + @dropdownElement.clientHeight > @paletteElement.clientHeight
dropdownTop -= (@session.fontSize + @dropdownElement.clientHeight)
@dropdownElement.style.top = dropdownTop + 'px'
else
location = @session.view.getViewNodeFor(socket).bounds[0]
@dropdownElement.style.left = location.x - @session.viewports.main.x + @dropletElement.offsetLeft + @gutter.clientWidth + 'px'
@dropdownElement.style.minWidth = location.width + 'px'
dropdownTop = location.y + @session.fontSize - @session.viewports.main.y
if dropdownTop + @dropdownElement.clientHeight > @dropletElement.clientHeight
dropdownTop -= (@session.fontSize + @dropdownElement.clientHeight)
@dropdownElement.style.top = dropdownTop + 'px'
), 0
Editor::hideDropdown = ->
@dropdownVisible = false
@dropdownElement.style.display = 'none'
@dropletElement.focus()
hook 'dblclick', 0, (point, event, state) ->
# If someone else already took this click, return.
if state.consumedHitTest then return
for dropletDocument in @getDocuments()
# Otherwise, look for a socket that
# the user has clicked
mainPoint = @trackerPointToMain point
hitTestResult = @hitTestTextInput mainPoint, @session.tree
# If they have clicked a socket,
# focus it, and
unless hitTestResult is @getCursor()
if hitTestResult? and hitTestResult.editable()
@redrawMain()
hitTestResult = @hitTestTextInput mainPoint, @session.tree
if hitTestResult? and hitTestResult.editable()
@setCursor hitTestResult
@redrawMain()
setTimeout (=>
@selectDoubleClick mainPoint
@redrawTextInput()
@textInputSelecting = false
), 0
state.consumedHitTest = true
return
# On mousemove, if we are selecting,
# we want to update the selection
# to match the mouse.
hook 'mousemove', 0, (point, event, state) ->
if @textInputSelecting
unless @cursorAtSocket()
@textInputSelecting = false; return
mainPoint = @trackerPointToMain point
@setTextInputHead mainPoint
@redrawTextInput()
# On mouseup, we want to stop selecting.
hook 'mouseup', 0, (point, event, state) ->
if @textInputSelecting
mainPoint = @trackerPointToMain point
@setTextInputHead mainPoint
@redrawTextInput()
@textInputSelecting = false
# LASSO SELECT SUPPORT
# ===============================
# The lasso select
# will have its own canvas
# for drawing the lasso. This needs
# to be added at populate-time, along
# with some fields.
hook 'populate', 0, ->
@lassoSelectRect = document.createElementNS SVG_STANDARD, 'rect'
@lassoSelectRect.setAttribute 'stroke', '#00f'
@lassoSelectRect.setAttribute 'fill', 'none'
@lassoSelectAnchor = null
@lassoSelection = null
@mainCanvas.appendChild @lassoSelectRect
Editor::clearLassoSelection = ->
@lassoSelection = null
@redrawHighlights()
# On mousedown, if nobody has taken
# a hit test yet, start a lasso select.
hook 'mousedown', 0, (point, event, state) ->
# Even if someone has taken it, we
# should remove the lasso segment that is
# already there.
unless state.clickedLassoSelection then @clearLassoSelection()
if state.consumedHitTest or state.suppressLassoSelect then return
# If it's not in the main pane, pass.
if not @trackerPointIsInMain(point) then return
if @trackerPointIsInPalette(point) then return
# If the point was actually in the main canvas,
# start a lasso select.
mainPoint = @trackerPointToMain(point).from @session.viewports.main
palettePoint = @trackerPointToPalette(point).from @session.viewports.palette
@lassoSelectAnchor = @trackerPointToMain point
# On mousemove, if we are in the middle of a
# lasso select, continue with it.
hook 'mousemove', 0, (point, event, state) ->
if @lassoSelectAnchor?
mainPoint = @trackerPointToMain point
lassoRectangle = new @draw.Rectangle(
Math.min(@lassoSelectAnchor.x, mainPoint.x),
Math.min(@lassoSelectAnchor.y, mainPoint.y),
Math.abs(@lassoSelectAnchor.x - mainPoint.x),
Math.abs(@lassoSelectAnchor.y - mainPoint.y)
)
findLassoSelect = (dropletDocument) =>
first = dropletDocument.start
until (not first?) or first.type is 'blockStart' and @session.view.getViewNodeFor(first.container).path.intersects lassoRectangle
first = first.next
last = dropletDocument.end
until (not last?) or last.type is 'blockEnd' and @session.view.getViewNodeFor(last.container).path.intersects lassoRectangle
last = last.prev
@clearHighlightCanvas()
@mainCanvas.appendChild @lassoSelectRect
@lassoSelectRect.style.display = 'block'
@lassoSelectRect.setAttribute 'x', lassoRectangle.x
@lassoSelectRect.setAttribute 'y', lassoRectangle.y
@lassoSelectRect.setAttribute 'width', lassoRectangle.width
@lassoSelectRect.setAttribute 'height', lassoRectangle.height
if first and last?
[first, last] = validateLassoSelection dropletDocument, first, last
@lassoSelection = new model.List first, last
@redrawLassoHighlight()
return true
else
@lassoSelection = null
@redrawLassoHighlight()
return false
unless @lassoSelectionDocument? and findLassoSelect @lassoSelectionDocument
for dropletDocument in @getDocuments()
if findLassoSelect dropletDocument
@lassoSelectionDocument = dropletDocument
break
Editor::redrawLassoHighlight = ->
return unless @session?
# Remove any existing selections
for dropletDocument in @getDocuments()
dropletDocumentView = @session.view.getViewNodeFor dropletDocument
dropletDocumentView.draw @session.viewports.main, {
selected: false
noText: @currentlyAnimating # TODO add some modularized way of having global view options
}
if @lassoSelection?
# Add any new selections
lassoView = @session.view.getViewNodeFor(@lassoSelection)
lassoView.absorbCache()
lassoView.draw @session.viewports.main, {selected: true}
# Convnience function for validating
# a lasso selection. A lasso selection
# cannot contain start tokens without
# their corresponding end tokens, or vice
# versa, and also must start and end
# with blocks (not Indents).
validateLassoSelection = (tree, first, last) ->
tokensToInclude = []
head = first
until head is last.next
if head instanceof model.StartToken or
head instanceof model.EndToken
tokensToInclude.push head.container.start
tokensToInclude.push head.container.end
head = head.next
first = tree.start
until first in tokensToInclude then first = first.next
last = tree.end
until last in tokensToInclude then last = last.prev
until first.type is 'blockStart'
first = first.prev
if first.type is 'blockEnd' then first = first.container.start.prev
until last.type is 'blockEnd'
last = last.next
if last.type is 'blockStart' then last = last.container.end.next
return [first, last]
# On mouseup, if we were
# doing a lasso select, insert a lasso
# select segment.
hook 'mouseup', 0, (point, event, state) ->
if @lassoSelectAnchor?
if @lassoSelection?
# Move the cursor to the selection
@setCursor @lassoSelection.end
@lassoSelectAnchor = null
@lassoSelectRect.style.display = 'none'
@redrawHighlights()
@lassoSelectionDocument = null
# On mousedown, we might want to
# pick a selected segment up; check.
hook 'mousedown', 3, (point, event, state) ->
if state.consumedHitTest then return
if @lassoSelection? and @hitTest(@trackerPointToMain(point), @lassoSelection)?
@clickedBlock = @lassoSelection
@clickedBlockPaletteEntry = null
@clickedPoint = point
state.consumedHitTest = true
state.clickedLassoSelection = true
# CURSOR OPERATION SUPPORT
# ================================
class CrossDocumentLocation
constructor: (@document, @location) ->
is: (other) -> @location.is(other.location) and @document is other.document
clone: ->
new CrossDocumentLocation(
@document,
@location.clone()
)
Editor::validCursorPosition = (destination) ->
return destination.type in ['documentStart', 'indentStart'] or
destination.type is 'blockEnd' and destination.parent.type in ['document', 'indent'] or
destination.type is 'socketStart' and destination.container.editable()
# A cursor is only allowed to be on a line.
Editor::setCursor = (destination, validate = (-> true), direction = 'after') ->
if destination? and destination instanceof CrossDocumentLocation
destination = @fromCrossDocumentLocation(destination)
# Abort if there is no destination (usually means
# someone wants to travel outside the document)
return unless destination? and @inDisplay destination
# Now set the new cursor
if destination instanceof model.Container
destination = destination.start
until @validCursorPosition(destination) and validate(destination)
destination = (if direction is 'after' then destination.next else destination.prev)
return unless destination?
destination = @toCrossDocumentLocation destination
# If the cursor was at a text input, reparse the old one
if @cursorAtSocket() and not @session.cursor.is(destination)
socket = @getCursor()
if '__comment__' not in socket.classes
@reparse socket, null, (if destination.document is @session.cursor.document then [destination.location] else [])
@hiddenInput.blur()
@dropletElement.focus()
@session.cursor = destination
# If we have messed up (usually because
# of a reparse), scramble to find a nearby
# okay place for the cursor
@correctCursor()
@redrawMain()
@highlightFlashShow()
# If we are now at a text input, populate the hidden input
if @cursorAtSocket()
if @getCursor()?.id of @session.extraMarks
delete @session.extraMarks[focus?.id]
@undoCapture()
@hiddenInput.value = @getCursor().textContent()
@hiddenInput.focus()
{start, end} = @session.mode.getDefaultSelectionRange @hiddenInput.value
@setTextSelectionRange start, end
Editor::determineCursorPosition = ->
# Do enough of the redraw to get the bounds
@session.view.getViewNodeFor(@session.tree).layout 0, @nubbyHeight
# Get a cursor that is in the model
cursor = @getCursor()
if cursor.type is 'documentStart'
bound = @session.view.getViewNodeFor(cursor.container).bounds[0]
return new @draw.Point bound.x, bound.y
else if cursor.type is 'indentStart'
line = if cursor.next.type is 'newline' then 1 else 0
bound = @session.view.getViewNodeFor(cursor.container).bounds[line]
return new @draw.Point bound.x, bound.y
else
line = @getCursor().getTextLocation().row - cursor.parent.getTextLocation().row
bound = @session.view.getViewNodeFor(cursor.parent).bounds[line]
return new @draw.Point bound.x, bound.bottom()
Editor::getCursor = ->
cursor = @fromCrossDocumentLocation @session.cursor
if cursor.type is 'socketStart'
return cursor.container
else
return cursor
Editor::scrollCursorIntoPosition = ->
axis = @determineCursorPosition().y
if axis < @session.viewports.main.y
@mainScroller.scrollTop = axis
else if axis > @session.viewports.main.bottom()
@mainScroller.scrollTop = axis - @session.viewports.main.height
@mainScroller.scrollLeft = 0
# Moves the cursor to the end of the document and scrolls it into position
# (in block and text mode)
Editor::scrollCursorToEndOfDocument = ->
if @session.currentlyUsingBlocks
pos = @session.tree.end
while pos && !@validCursorPosition(pos)
pos = pos.prev
@setCursor(pos)
@scrollCursorIntoPosition()
else
@aceEditor.scrollToLine @aceEditor.session.getLength()
# Pressing the up-arrow moves the cursor up.
hook 'keydown', 0, (event, state) ->
if event.which is UP_ARROW_KEY
@clearLassoSelection()
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, ((token) -> token.type isnt 'socketStart'), 'before'
@scrollCursorIntoPosition()
else if event.which is DOWN_ARROW_KEY
@clearLassoSelection()
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, ((token) -> token.type isnt 'socketStart'), 'after'
@scrollCursorIntoPosition()
else if event.which is RIGHT_ARROW_KEY and
(not @cursorAtSocket() or
@hiddenInput.selectionStart is @hiddenInput.value.length)
@clearLassoSelection()
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, null, 'after'
@scrollCursorIntoPosition()
event.preventDefault()
else if event.which is LEFT_ARROW_KEY and
(not @cursorAtSocket() or
@hiddenInput.selectionEnd is 0)
@clearLassoSelection()
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, null, 'before'
@scrollCursorIntoPosition()
event.preventDefault()
hook 'keydown', 0, (event, state) ->
if event.which isnt TAB_KEY then return
if event.shiftKey
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, ((token) -> token.type is 'socketStart'), 'before'
else
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, ((token) -> token.type is 'socketStart'), 'after'
event.preventDefault()
Editor::deleteAtCursor = ->
if @getCursor().type is 'blockEnd'
block = @getCursor().container
else if @getCursor().type is 'indentStart'
block = @getCursor().parent
else
return
@setCursor block.start, null, 'before'
@undoCapture()
@spliceOut block
@redrawMain()
hook 'keydown', 0, (event, state) ->
if not @session? or @session.readOnly
return
if event.which isnt BACKSPACE_KEY
return
if state.capturedBackspace
return
# We don't want to interrupt any text input editing
# sessions. We will, however, delete a handwritten
# block if it is currently empty.
if @lassoSelection?
@deleteLassoSelection()
event.preventDefault()
return false
else if not @cursorAtSocket() or
(@hiddenInput.value.length is 0 and @getCursor().handwritten)
@deleteAtCursor()
state.capturedBackspace = true
event.preventDefault()
return false
return true
Editor::deleteLassoSelection = ->
unless @lassoSelection?
if DEBUG_FLAG
throw new Error 'Cannot delete nonexistent lasso segment'
return null
cursorTarget = @lassoSelection.start.prev
@spliceOut @lassoSelection
@lassoSelection = null
@setCursor cursorTarget
@redrawMain()
# HANDWRITTEN BLOCK SUPPORT
# ================================
hook 'keydown', 0, (event, state) ->
if not @session? or @session.readOnly
return
if event.which is ENTER_KEY
if not @cursorAtSocket() and not event.shiftKey and not event.ctrlKey and not event.metaKey
# Construct the block; flag the socket as handwritten
newBlock = new model.Block(); newSocket = new model.Socket '', Infinity, true
newSocket.setParent newBlock
helper.connect newBlock.start, newSocket.start
helper.connect newSocket.end, newBlock.end
# Seek a place near the cursor we can actually
# put a block.
head = @getCursor()
while head.type is 'newline'
head = head.prev
newSocket.parseContext = head.parent.parseContext
@spliceIn newBlock, head #MUTATION
@redrawMain()
@newHandwrittenSocket = newSocket
else if @cursorAtSocket() and not event.shiftKey
socket = @getCursor()
@hiddenInput.blur()
@dropletElement.focus()
@setCursor @session.cursor, (token) -> token.type isnt 'socketStart'
@redrawMain()
if '__comment__' in socket.classes and @session.mode.startSingleLineComment
# Create another single line comment block just below
newBlock = new model.Block 0, 'blank', helper.ANY_DROP
newBlock.classes = ['__comment__', 'block-only']
newBlock.socketLevel = helper.BLOCK_ONLY
newTextMarker = new model.TextToken @session.mode.startSingleLineComment
newTextMarker.setParent newBlock
newSocket = new model.Socket '', 0, true
newSocket.classes = ['__comment__']
newSocket.setParent newBlock
helper.connect newBlock.start, newTextMarker
helper.connect newTextMarker, newSocket.start
helper.connect newSocket.end, newBlock.end
# Seek a place near the cursor we can actually
# put a block.
head = @getCursor()
while head.type is 'newline'
head = head.prev
@spliceIn newBlock, head #MUTATION
@redrawMain()
@newHandwrittenSocket = newSocket
hook 'keyup', 0, (event, state) ->
if not @session? or @session.readOnly
return
# prevents routing the initial enter keypress to a new handwritten
# block by focusing the block only after the enter key is released.
if event.which is ENTER_KEY
if @newHandwrittenSocket?
@setCursor @newHandwrittenSocket
@newHandwrittenSocket = null
containsCursor = (block) ->
head = block.start
until head is block.end
if head.type is 'cursor' then return true
head = head.next
return false
# ANIMATION AND ACE EDITOR SUPPORT
# ================================
Editor::copyAceEditor = ->
@gutter.style.width = @aceEditor.renderer.$gutterLayer.gutterWidth + 'px'
@resizeBlockMode()
return @setValue_raw @getAceValue()
# For animation and ace editor,
# we will need a couple convenience functions
# for getting the "absolute"-esque position
# of layouted elements (a la jQuery, without jQuery).
getOffsetTop = (element) ->
top = element.offsetTop
while (element = element.offsetParent)?
top += element.offsetTop
return top
getOffsetLeft = (element) ->
left = element.offsetLeft
while (element = element.offsetParent)?
left += element.offsetLeft
return left
Editor::computePlaintextTranslationVectors = ->
# Now we need to figure out where all the text elements are going
# to end up.
textElements = []; translationVectors = []
head = @session.tree.start
aceSession = @aceEditor.session
state = {
# Initial cursor positions are
# determined by ACE editor configuration.
x: (@aceEditor.container.getBoundingClientRect().left -
@aceElement.getBoundingClientRect().left +
@aceEditor.renderer.$gutterLayer.gutterWidth) -
@gutter.clientWidth + 5 # TODO find out where this 5 comes from
y: (@aceEditor.container.getBoundingClientRect().top -
@aceElement.getBoundingClientRect().top) -
aceSession.getScrollTop()
# Initial indent depth is 0
indent: 0
# Line height and left edge are
# determined by ACE editor configuration.
lineHeight: @aceEditor.renderer.layerConfig.lineHeight
leftEdge: (@aceEditor.container.getBoundingClientRect().left -
getOffsetLeft(@aceElement) +
@aceEditor.renderer.$gutterLayer.gutterWidth) -
@gutter.clientWidth + 5 # TODO see above
}
@measureCtx.font = @aceFontSize() + ' ' + @session.fontFamily
fontWidth = @measureCtx.measureText(' ').width
rownum = 0
until head is @session.tree.end
switch head.type
when 'text'
corner = @session.view.getViewNodeFor(head).bounds[0].upperLeftCorner()
corner.x -= @session.viewports.main.x
corner.y -= @session.viewports.main.y
translationVectors.push (new @draw.Point(state.x, state.y)).from(corner)
textElements.push @session.view.getViewNodeFor head
state.x += fontWidth * head.value.length
when 'socketStart'
if head.next is head.container.end or
head.next.type is 'text' and head.next.value is ''
state.x += fontWidth * head.container.emptyString.length
# Newline moves the cursor to the next line,
# plus some indent.
when 'newline'
# Be aware of wrapped ace editor lines.
wrappedlines = Math.max(1,
aceSession.documentToScreenRow(rownum + 1, 0) -
aceSession.documentToScreenRow(rownum, 0))
rownum += 1
state.y += state.lineHeight * wrappedlines
if head.specialIndent?
state.x = state.leftEdge + fontWidth * head.specialIndent.length
else
state.x = state.leftEdge + state.indent * fontWidth
when 'indentStart'
state.indent += head.container.depth
when 'indentEnd'
state.indent -= head.container.depth
head = head.next
return {
textElements: textElements
translationVectors: translationVectors
}
Editor::checkAndHighlightEmptySockets = ->
head = @session.tree.start
ok = true
until head is @session.tree.end
if (head.type is 'socketStart' and head.next is head.container.end or
head.type is 'socketStart' and head.next.type is 'text' and head.next.value is '') and
head.container.emptyString isnt ''
@markBlock head.container, {color: '#F00'}
ok = false
head = head.next
return ok
Editor::performMeltAnimation = (fadeTime = 500, translateTime = 1000, cb = ->) ->
if @session.currentlyUsingBlocks and not @currentlyAnimating
# If the preserveEmpty option is turned off, we will not round-trip empty sockets.
#
# Therefore, forbid melting if there is an empty socket. If there is,
# highlight it in red.
if not @session.options.preserveEmpty and not @checkAndHighlightEmptySockets()
@redrawMain()
return
@hideDropdown()
@fireEvent 'statechange', [false]
@setAceValue @getValue()
top = @findLineNumberAtCoordinate @session.viewports.main.y
@aceEditor.scrollToLine top
@aceEditor.resize true
@redrawMain noText: true
# Hide scrollbars and increase width
if @mainScroller.scrollWidth > @mainScroller.clientWidth
@mainScroller.style.overflowX = 'scroll'
else
@mainScroller.style.overflowX = 'hidden'
@mainScroller.style.overflowY = 'hidden'
@dropletElement.style.width = @wrapperElement.clientWidth + 'px'
@session.currentlyUsingBlocks = false; @currentlyAnimating = @currentlyAnimating_suppressRedraw = true
# Compute where the text will end up
# in the ace editor
{textElements, translationVectors} = @computePlaintextTranslationVectors()
translatingElements = []
for textElement, i in textElements
# Skip anything that's
# off the screen the whole time.
unless 0 < textElement.bounds[0].bottom() - @session.viewports.main.y + translationVectors[i].y and
textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y < @session.viewports.main.height
continue
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = textElement.model.value
div.style.font = @session.fontSize + 'px ' + @session.fontFamily
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y - @session.fontAscent}px"
div.className = 'droplet-transitioning-element'
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@transitionContainer.appendChild div
do (div, textElement, translationVectors, i) =>
setTimeout (=>
div.style.left = (textElement.bounds[0].x - @session.viewports.main.x + translationVectors[i].x) + 'px'
div.style.top = (textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y) + 'px'
div.style.fontSize = @aceFontSize()
), fadeTime
top = Math.max @aceEditor.getFirstVisibleRow(), 0
bottom = Math.min @aceEditor.getLastVisibleRow(), @session.view.getViewNodeFor(@session.tree).lineLength - 1
aceScrollTop = @aceEditor.session.getScrollTop()
treeView = @session.view.getViewNodeFor @session.tree
lineHeight = @aceEditor.renderer.layerConfig.lineHeight
for line in [top..bottom]
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = line + 1
div.style.left = 0
div.style.top = "#{treeView.bounds[line].y + treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent - @session.viewports.main.y}px"
div.style.font = @session.fontSize + 'px ' + @session.fontFamily
div.style.width = "#{@gutter.clientWidth}px"
translatingElements.push div
div.className = 'droplet-transitioning-element droplet-transitioning-gutter droplet-gutter-line'
# Add annotation
if @annotations[line]?
div.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
@dropletElement.appendChild div
do (div, line) =>
# Set off the css transition
setTimeout (=>
div.style.left = '0px'
div.style.top = (@aceEditor.session.documentToScreenRow(line, 0) *
lineHeight - aceScrollTop) + 'px'
div.style.fontSize = @aceFontSize()
), fadeTime
@lineNumberWrapper.style.display = 'none'
# Kick off fade-out transition
@mainCanvas.style.transition =
@highlightCanvas.style.transition = "opacity #{fadeTime}ms linear"
@mainCanvas.style.opacity = 0
paletteDisappearingWithMelt = @session.paletteEnabled and not @session.showPaletteInTextMode
if paletteDisappearingWithMelt
# Move the palette header into the background
@paletteHeader.style.zIndex = 0
setTimeout (=>
@dropletElement.style.transition = "left #{translateTime}ms"
@dropletElement.style.left = '0px'
), fadeTime
setTimeout (=>
# Translate the ICE editor div out of frame.
@dropletElement.style.transition = ''
# Translate the ACE editor div into frame.
@aceElement.style.top = '0px'
if @session.showPaletteInTextMode and @session.paletteEnabled
@aceElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@aceElement.style.left = '0px'
#if paletteDisappearingWithMelt
# @paletteWrapper.style.top = '-9999px'
# @paletteWrapper.style.left = '-9999px'
@dropletElement.style.top = '-9999px'
@dropletElement.style.left = '-9999px'
# Finalize a bunch of animations
# that should be complete by now,
# but might not actually be due to
# floating point stuff.
@currentlyAnimating = false
# Show scrollbars again
@mainScroller.style.overflow = 'auto'
for div in translatingElements
div.parentNode.removeChild div
@fireEvent 'toggledone', [@session.currentlyUsingBlocks]
if cb? then do cb
), fadeTime + translateTime
return success: true
Editor::aceFontSize = ->
parseFloat(@aceEditor.getFontSize()) + 'px'
Editor::performFreezeAnimation = (fadeTime = 500, translateTime = 500, cb = ->)->
return unless @session?
if not @session.currentlyUsingBlocks and not @currentlyAnimating
beforeTime = +(new Date())
setValueResult = @copyAceEditor()
afterTime = +(new Date())
unless setValueResult.success
if setValueResult.error
@fireEvent 'parseerror', [setValueResult.error]
return setValueResult
if @aceEditor.getFirstVisibleRow() is 0
@mainScroller.scrollTop = 0
else
@mainScroller.scrollTop = @session.view.getViewNodeFor(@session.tree).bounds[@aceEditor.getFirstVisibleRow()].y
@session.currentlyUsingBlocks = true
@currentlyAnimating = true
@fireEvent 'statechange', [true]
setTimeout (=>
# Hide scrollbars and increase width
@mainScroller.style.overflow = 'hidden'
@dropletElement.style.width = @wrapperElement.clientWidth + 'px'
@redrawMain noText: true
@currentlyAnimating_suppressRedraw = true
@aceElement.style.top = "-9999px"
@aceElement.style.left = "-9999px"
paletteAppearingWithFreeze = @session.paletteEnabled and not @session.showPaletteInTextMode
if paletteAppearingWithFreeze
@paletteWrapper.style.top = '0px'
@paletteHeader.style.zIndex = 0
@dropletElement.style.top = "0px"
if @session.paletteEnabled and not paletteAppearingWithFreeze
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@dropletElement.style.left = "0px"
{textElements, translationVectors} = @computePlaintextTranslationVectors()
translatingElements = []
for textElement, i in textElements
# Skip anything that's
# off the screen the whole time.
unless 0 < textElement.bounds[0].bottom() - @session.viewports.main.y + translationVectors[i].y and
textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y < @session.viewports.main.height
continue
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = textElement.model.value
div.style.font = @aceFontSize() + ' ' + @session.fontFamily
div.style.position = 'absolute'
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x + translationVectors[i].x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y}px"
div.className = 'droplet-transitioning-element'
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@transitionContainer.appendChild div
do (div, textElement) =>
setTimeout (=>
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y - @session.fontAscent}px"
div.style.fontSize = @session.fontSize + 'px'
), 0
top = Math.max @aceEditor.getFirstVisibleRow(), 0
bottom = Math.min @aceEditor.getLastVisibleRow(), @session.view.getViewNodeFor(@session.tree).lineLength - 1
treeView = @session.view.getViewNodeFor @session.tree
lineHeight = @aceEditor.renderer.layerConfig.lineHeight
aceScrollTop = @aceEditor.session.getScrollTop()
for line in [top..bottom]
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = line + 1
div.style.font = @aceFontSize() + ' ' + @session.fontFamily
div.style.width = "#{@aceEditor.renderer.$gutter.clientWidth}px"
div.style.left = 0
div.style.top = "#{@aceEditor.session.documentToScreenRow(line, 0) *
lineHeight - aceScrollTop}px"
div.className = 'droplet-transitioning-element droplet-transitioning-gutter droplet-gutter-line'
# Add annotation
if @annotations[line]?
div.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@dropletElement.appendChild div
do (div, line) =>
setTimeout (=>
div.style.left = 0
div.style.top = "#{treeView.bounds[line].y + treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent - @session.viewports.main.y}px"
div.style.fontSize = @session.fontSize + 'px'
), 0
@mainCanvas.style.opacity = 0
setTimeout (=>
@mainCanvas.style.transition = "opacity #{fadeTime}ms linear"
@mainCanvas.style.opacity = 1
), translateTime
@dropletElement.style.transition = "left #{fadeTime}ms"
if paletteAppearingWithFreeze
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
@paletteWrapper.style.left = '0px'
setTimeout (=>
@dropletElement.style.transition = ''
# Show scrollbars again
@mainScroller.style.overflow = 'auto'
@currentlyAnimating = false
@lineNumberWrapper.style.display = 'block'
@redrawMain()
@paletteHeader.style.zIndex = 257
for div in translatingElements
div.parentNode.removeChild div
@resizeBlockMode()
@fireEvent 'toggledone', [@session.currentlyUsingBlocks]
if cb? then do cb
), translateTime + fadeTime
), 0
return success: true
Editor::enablePalette = (enabled) ->
if not @currentlyAnimating and @session.paletteEnabled != enabled
@session.paletteEnabled = enabled
@currentlyAnimating = true
if @session.currentlyUsingBlocks
activeElement = @dropletElement
else
activeElement = @aceElement
if not @session.paletteEnabled
activeElement.style.transition = "left 500ms"
activeElement.style.left = '0px'
@paletteHeader.style.zIndex = 0
@resize()
setTimeout (=>
activeElement.style.transition = ''
#@paletteWrapper.style.top = '-9999px'
#@paletteWrapper.style.left = '-9999px'
@currentlyAnimating = false
@fireEvent 'palettetoggledone', [@session.paletteEnabled]
), 500
else
@paletteWrapper.style.top = '0px'
@paletteHeader.style.zIndex = 257
setTimeout (=>
activeElement.style.transition = "left 500ms"
activeElement.style.left = "#{@paletteWrapper.clientWidth}px"
@paletteWrapper.style.left = '0px'
setTimeout (=>
activeElement.style.transition = ''
@resize()
@currentlyAnimating = false
@fireEvent 'palettetoggledone', [@session.paletteEnabled]
), 500
), 0
Editor::toggleBlocks = (cb) ->
if @session.currentlyUsingBlocks
return @performMeltAnimation 500, 1000, cb
else
return @performFreezeAnimation 500, 500, cb
# SCROLLING SUPPORT
# ================================
hook 'populate', 2, ->
@mainScroller = document.createElement 'div'
@mainScroller.className = 'droplet-main-scroller'
# @mainScrollerIntermediary -- this is so that we can be certain that
# any event directly on @mainScroller is in fact on the @mainScroller scrollbar,
# so should not be captured by editor mouse event handlers.
@mainScrollerIntermediary = document.createElement 'div'
@mainScrollerIntermediary.className = 'droplet-main-scroller-intermediary'
@mainScrollerStuffing = document.createElement 'div'
@mainScrollerStuffing.className = 'droplet-main-scroller-stuffing'
@mainScroller.appendChild @mainCanvas
@dropletElement.appendChild @mainScroller
# Prevent scrolling on wrapper element
@wrapperElement.addEventListener 'scroll', =>
@wrapperElement.scrollTop = @wrapperElement.scrollLeft = 0
@mainScroller.addEventListener 'scroll', =>
@session.viewports.main.y = @mainScroller.scrollTop
@session.viewports.main.x = @mainScroller.scrollLeft
@redrawMain()
@paletteScroller = document.createElement 'div'
@paletteScroller.className = 'droplet-palette-scroller'
@paletteScroller.appendChild @paletteCanvas
@paletteScrollerStuffing = document.createElement 'div'
@paletteScrollerStuffing.className = 'droplet-palette-scroller-stuffing'
@paletteScroller.appendChild @paletteScrollerStuffing
@paletteElement.appendChild @paletteScroller
@paletteScroller.addEventListener 'scroll', =>
@session.viewports.palette.y = @paletteScroller.scrollTop
@session.viewports.palette.x = @paletteScroller.scrollLeft
Editor::resizeMainScroller = ->
@mainScroller.style.width = "#{@dropletElement.clientWidth}px"
@mainScroller.style.height = "#{@dropletElement.clientHeight}px"
hook 'resize_palette', 0, ->
@paletteScroller.style.top = "#{@paletteHeader.clientHeight}px"
@session.viewports.palette.height = @paletteScroller.clientHeight
@session.viewports.palette.width = @paletteScroller.clientWidth
hook 'redraw_main', 1, ->
bounds = @session.view.getViewNodeFor(@session.tree).getBounds()
for record in @session.floatingBlocks
bounds.unite @session.view.getViewNodeFor(record.block).getBounds()
# We add some extra height to the bottom
# of the document so that the last block isn't
# jammed up against the edge of the screen.
#
# Default this extra space to fontSize (approx. 1 line).
height = Math.max(
bounds.bottom() + (@options.extraBottomHeight ? @session.fontSize),
@dropletElement.clientHeight
)
if height isnt @lastHeight
@lastHeight = height
@mainCanvas.setAttribute 'height', height
@mainCanvas.style.height = "#{height}px"
hook 'redraw_palette', 0, ->
bounds = new @draw.NoRectangle()
for entry in @session.currentPaletteBlocks
bounds.unite @session.paletteView.getViewNodeFor(entry.block).getBounds()
# For now, we will comment out this line
# due to bugs
#@paletteScrollerStuffing.style.width = "#{bounds.right()}px"
@paletteScrollerStuffing.style.height = "#{bounds.bottom()}px"
# MULTIPLE FONT SIZE SUPPORT
# ================================
hook 'populate', 0, ->
@session.fontSize = 15
@session.fontFamily = 'Courier New'
@measureCtx.font = '15px Courier New'
@session.fontWidth = @measureCtx.measureText(' ').width
metrics = helper.fontMetrics(@session.fontFamily, @session.fontSize)
@session.fontAscent = metrics.prettytop
@session.fontDescent = metrics.descent
Editor::setFontSize_raw = (fontSize) ->
unless @session.fontSize is fontSize
@measureCtx.font = fontSize + ' px ' + @session.fontFamily
@session.fontWidth = @measureCtx.measureText(' ').width
@session.fontSize = fontSize
@paletteHeader.style.fontSize = "#{fontSize}px"
@gutter.style.fontSize = "#{fontSize}px"
@tooltipElement.style.fontSize = "#{fontSize}px"
@session.view.opts.textHeight =
@session.paletteView.opts.textHeight =
@session.dragView.opts.textHeight = helper.getFontHeight @session.fontFamily, @session.fontSize
metrics = helper.fontMetrics(@session.fontFamily, @session.fontSize)
@session.fontAscent = metrics.prettytop
@session.fontDescent = metrics.descent
@session.view.clearCache()
@session.paletteView.clearCache()
@session.dragView.clearCache()
@session.view.draw.setGlobalFontSize @session.fontSize
@session.paletteView.draw.setGlobalFontSize @session.fontSize
@session.dragView.draw.setGlobalFontSize @session.fontSize
@gutter.style.width = @aceEditor.renderer.$gutterLayer.gutterWidth + 'px'
@redrawMain()
@rebuildPalette()
Editor::setFontFamily = (fontFamily) ->
@measureCtx.font = @session.fontSize + 'px ' + fontFamily
@draw.setGlobalFontFamily fontFamily
@session.fontFamily = fontFamily
@session.view.opts.textHeight = helper.getFontHeight @session.fontFamily, @session.fontSize
@session.fontAscent = helper.fontMetrics(@session.fontFamily, @session.fontSize).prettytop
@session.view.clearCache(); @session.dragView.clearCache()
@gutter.style.fontFamily = fontFamily
@tooltipElement.style.fontFamily = fontFamily
@redrawMain()
@rebuildPalette()
Editor::setFontSize = (fontSize) ->
@setFontSize_raw fontSize
@resizeBlockMode()
# LINE MARKING SUPPORT
# ================================
Editor::getHighlightPath = (model, style, view = @session.view) ->
path = view.getViewNodeFor(model).path.clone()
path.style.fillColor = null
path.style.strokeColor = style.color
path.style.lineWidth = 3
path.noclip = true; path.bevel = false
return path
Editor::markLine = (line, style) ->
return unless @session?
block = @session.tree.getBlockOnLine line
@session.view.getViewNodeFor(block).mark style
Editor::markBlock = (block, style) ->
return unless @session?
@session.view.getViewNodeFor(block).mark style
# ## Mark
# `mark(line, col, style)` will mark the first block after the given (line, col) coordinate
# with the given style.
Editor::mark = (location, style) ->
return unless @session?
block = @session.tree.getFromTextLocation location
block = block.container ? block
@session.view.getViewNodeFor(block).mark style
@redrawHighlights() # TODO MERGE investigate
Editor::clearLineMarks = ->
@session.view.clearMarks()
@redrawHighlights()
# LINE HOVER SUPPORT
# ================================
hook 'populate', 0, ->
@lastHoveredLine = null
hook 'mousemove', 0, (point, event, state) ->
# Do not attempt to detect this if we are currently dragging something,
# or no event handlers are bound.
if not @draggingBlock? and not @clickedBlock? and @hasEvent 'linehover'
if not @trackerPointIsInMainScroller point then return
mainPoint = @trackerPointToMain point
treeView = @session.view.getViewNodeFor @session.tree
if @lastHoveredLine? and treeView.bounds[@lastHoveredLine]? and
treeView.bounds[@lastHoveredLine].contains mainPoint
return
hoveredLine = @findLineNumberAtCoordinate mainPoint.y
unless treeView.bounds[hoveredLine].contains mainPoint
hoveredLine = null
if hoveredLine isnt @lastHoveredLine
@fireEvent 'linehover', [line: @lastHoveredLine = hoveredLine]
# GET/SET VALUE SUPPORT
# ================================
# Whitespace trimming hack enable/disable
# setter
hook 'populate', 0, ->
@trimWhitespace = false
Editor::setTrimWhitespace = (trimWhitespace) ->
@trimWhitespace = trimWhitespace
Editor::setValue_raw = (value) ->
try
if @trimWhitespace then value = value.trim()
newParse = @session.mode.parse value, {
wrapAtRoot: true
preserveEmpty: @session.options.preserveEmpty
}
unless @session.tree.start.next is @session.tree.end
removal = new model.List @session.tree.start.next, @session.tree.end.prev
@spliceOut removal
unless newParse.start.next is newParse.end
@spliceIn new model.List(newParse.start.next, newParse.end.prev), @session.tree.start
@removeBlankLines()
@redrawMain()
return success: true
catch e
return success: false, error: e
Editor::setValue = (value) ->
if not @session?
return @aceEditor.setValue value
oldScrollTop = @aceEditor.session.getScrollTop()
@setAceValue value
@resizeTextMode()
@aceEditor.session.setScrollTop oldScrollTop
if @session.currentlyUsingBlocks
result = @setValue_raw value
if result.success is false
@setEditorState false
@aceEditor.setValue value
if result.error
@fireEvent 'parseerror', [result.error]
Editor::addEmptyLine = (str) ->
if str.length is 0 or str[str.length - 1] is '\n'
return str
else
return str + '\n'
Editor::getValue = ->
if @session?.currentlyUsingBlocks
return @addEmptyLine @session.tree.stringify({
preserveEmpty: @session.options.preserveEmpty
})
else
@getAceValue()
Editor::getAceValue = ->
value = @aceEditor.getValue()
@lastAceSeenValue = value
Editor::setAceValue = (value) ->
if value isnt @lastAceSeenValue
@aceEditor.setValue value, 1
# TODO: move ace cursor to location matching droplet cursor.
@lastAceSeenValue = value
# PUBLIC EVENT BINDING HOOKS
# ===============================
Editor::on = (event, handler) ->
@bindings[event] = handler
Editor::once = (event, handler) ->
@bindings[event] = ->
handler.apply this, arguments
@bindings[event] = null
Editor::fireEvent = (event, args) ->
if event of @bindings
@bindings[event].apply this, args
Editor::hasEvent = (event) -> event of @bindings and @bindings[event]?
# SYNCHRONOUS TOGGLE SUPPORT
# ================================
Editor::setEditorState = (useBlocks) ->
@mainCanvas.style.transition = @highlightCanvas.style.transition = ''
if useBlocks
if not @session?
throw new ArgumentError 'cannot switch to blocks if a session has not been set up.'
unless @session.currentlyUsingBlocks
@setValue_raw @getAceValue()
@dropletElement.style.top = '0px'
if @session.paletteEnabled
@paletteWrapper.style.top = @paletteWrapper.style.left = '0px'
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@paletteWrapper.style.top = '0px'
@dropletElement.style.left = '0px'
@aceElement.style.top = @aceElement.style.left = '-9999px'
@session.currentlyUsingBlocks = true
@lineNumberWrapper.style.display = 'block'
@mainCanvas.style.opacity =
@highlightCanvas.style.opacity = 1
@resizeBlockMode(); @redrawMain()
else
# Forbid melting if there is an empty socket. If there is,
# highlight it in red.
if @session? and not @session.options.preserveEmpty and not @checkAndHighlightEmptySockets()
@redrawMain()
return
@hideDropdown()
paletteVisibleInNewState = @session?.paletteEnabled and @session.showPaletteInTextMode
oldScrollTop = @aceEditor.session.getScrollTop()
if @session?.currentlyUsingBlocks
@setAceValue @getValue()
@aceEditor.resize true
@aceEditor.session.setScrollTop oldScrollTop
@dropletElement.style.top = @dropletElement.style.left = '-9999px'
@paletteWrapper.style.top = @paletteWrapper.style.left = '0px'
@aceElement.style.top = '0px'
if paletteVisibleInNewState
@aceElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@aceElement.style.left = '0px'
@session?.currentlyUsingBlocks = false
@lineNumberWrapper.style.display = 'none'
@mainCanvas.style.opacity =
@highlightCanvas.style.opacity = 0
@resizeBlockMode()
# DRAG CANVAS SHOW/HIDE HACK
# ================================
hook 'populate', 0, ->
@dragCover = document.createElement 'div'
@dragCover.className = 'droplet-drag-cover'
@dragCover.style.display = 'none'
document.body.appendChild @dragCover
# On mousedown, bring the drag
# canvas to the front so that it
# appears to "float" over all other elements
hook 'mousedown', -1, ->
if @clickedBlock?
@dragCover.style.display = 'block'
# On mouseup, throw the drag canvas away completely.
hook 'mouseup', 0, ->
@dragCanvas.style.transform = "translate(-9999px, -9999px)"
@dragCover.style.display = 'none'
# FAILSAFE END DRAG HACK
# ================================
hook 'mousedown', 10, ->
if @draggingBlock?
@endDrag()
Editor::endDrag = ->
# Ensure that the cursor is not in a socket.
if @cursorAtSocket()
@setCursor @session.cursor, (x) -> x.type isnt 'socketStart'
@clearDrag()
@draggingBlock = null
@draggingOffset = null
@lastHighlightPath?.deactivate?()
@lastHighlight = @lastHighlightPath = null
@redrawMain()
return
# PALETTE EVENT
# =================================
hook 'rebuild_palette', 0, ->
@fireEvent 'changepalette', []
# TOUCHSCREEN SUPPORT
# =================================
# We will attempt to emulate
# mouse events using touchstart/end
# data.
touchEvents =
'touchstart': 'mousedown'
'touchmove': 'mousemove'
'touchend': 'mouseup'
# A timeout for selection
TOUCH_SELECTION_TIMEOUT = 1000
Editor::touchEventToPoint = (event, index) ->
absolutePoint = new @draw.Point(
event.changedTouches[index].clientX,
event.changedTouches[index].clientY
)
return absolutePoint
Editor::queueLassoMousedown = (trackPoint, event) ->
@lassoSelectStartTimeout = setTimeout (=>
state = {}
for handler in editorBindings.mousedown
handler.call this, trackPoint, event, state), TOUCH_SELECTION_TIMEOUT
# We will bind the same way as mouse events do,
# wrapping to be compatible with a mouse event interface.
#
# When users drag with multiple fingers, we emulate scrolling.
# Otherwise, we emulate mousedown/mouseup
hook 'populate', 0, ->
@touchScrollAnchor = new @draw.Point 0, 0
@lassoSelectStartTimeout = null
@wrapperElement.addEventListener 'touchstart', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
# We keep a state object so that handlers
# can know about each other.
#
# We will suppress lasso select to
# allow scrolling.
state = {
suppressLassoSelect: true
}
# Call all the handlers.
for handler in editorBindings.mousedown
handler.call this, trackPoint, event, state
# If we did not hit anything,
# we may want to start a lasso select
# in a little bit.
if state.consumedHitTest
event.preventDefault()
else
@queueLassoMousedown trackPoint, event
@wrapperElement.addEventListener 'touchmove', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
unless @clickedBlock? or @draggingBlock?
@queueLassoMousedown trackPoint, event
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings.mousemove
handler.call this, trackPoint, event, state
# If we are in the middle of some action,
# prevent scrolling.
if @clickedBlock? or @draggingBlock? or @lassoSelectAnchor? or @textInputSelecting
event.preventDefault()
@wrapperElement.addEventListener 'touchend', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings.mouseup
handler.call this, trackPoint, event, state
event.preventDefault()
# CURSOR DRAW SUPPORRT
# ================================
hook 'populate', 0, ->
@cursorCtx = document.createElementNS SVG_STANDARD, 'g'
@textCursorPath = new @session.view.draw.Path([], false, {
'strokeColor': '#000'
'lineWidth': '2'
'fillColor': 'rgba(0, 0, 256, 0.3)'
'cssClass': 'droplet-cursor-path'
})
@textCursorPath.setParent @mainCanvas
cursorElement = document.createElementNS SVG_STANDARD, 'path'
cursorElement.setAttribute 'fill', 'none'
cursorElement.setAttribute 'stroke', '#000'
cursorElement.setAttribute 'stroke-width', '3'
cursorElement.setAttribute 'stroke-linecap', 'round'
cursorElement.setAttribute 'd', "M#{@session.view.opts.tabOffset + CURSOR_WIDTH_DECREASE / 2} 0 " +
"Q#{@session.view.opts.tabOffset + @session.view.opts.tabWidth / 2} #{@session.view.opts.tabHeight}" +
" #{@session.view.opts.tabOffset + @session.view.opts.tabWidth - CURSOR_WIDTH_DECREASE / 2} 0"
@cursorPath = new @session.view.draw.ElementWrapper(cursorElement)
@cursorPath.setParent @mainCanvas
@mainCanvas.appendChild @cursorCtx
Editor::strokeCursor = (point) ->
return unless point?
@cursorPath.element.setAttribute 'transform', "translate(#{point.x}, #{point.y})"
@qualifiedFocus @getCursor(), @cursorPath
Editor::highlightFlashShow = ->
return unless @session?
if @flashTimeout? then clearTimeout @flashTimeout
if @cursorAtSocket()
@textCursorPath.activate()
else
@cursorPath.activate()
@highlightsCurrentlyShown = true
@flashTimeout = setTimeout (=> @flash()), 500
Editor::highlightFlashHide = ->
return unless @session?
if @flashTimeout? then clearTimeout @flashTimeout
if @cursorAtSocket()
@textCursorPath.deactivate()
else
@cursorPath.deactivate()
@highlightsCurrentlyShown = false
@flashTimeout = setTimeout (=> @flash()), 500
Editor::editorHasFocus = ->
document.activeElement in [@dropletElement, @hiddenInput, @copyPasteInput] and
document.hasFocus()
Editor::flash = ->
return unless @session?
if @lassoSelection? or @draggingBlock? or
(@cursorAtSocket() and @textInputHighlighted) or
not @highlightsCurrentlyShown or
not @editorHasFocus()
@highlightFlashShow()
else
@highlightFlashHide()
hook 'populate', 0, ->
@highlightsCurrentlyShown = false
blurCursors = =>
@highlightFlashShow()
@cursorCtx.style.opacity = CURSOR_UNFOCUSED_OPACITY
@dropletElement.addEventListener 'blur', blurCursors
@hiddenInput.addEventListener 'blur', blurCursors
@copyPasteInput.addEventListener 'blur', blurCursors
focusCursors = =>
@highlightFlashShow()
@cursorCtx.style.transition = ''
@cursorCtx.style.opacity = 1
@dropletElement.addEventListener 'focus', focusCursors
@hiddenInput.addEventListener 'focus', focusCursors
@copyPasteInput.addEventListener 'focus', focusCursors
@flashTimeout = setTimeout (=> @flash()), 0
# ONE MORE DROP CASE
# ================================
# TODO possibly move this next utility function to view?
Editor::viewOrChildrenContains = (model, point, view = @session.view) ->
modelView = view.getViewNodeFor model
if modelView.path.contains point
return true
for childObj in modelView.children
if @session.viewOrChildrenContains childObj.child, point, view
return true
return false
# LINE NUMBER GUTTER CODE
# ================================
hook 'populate', 0, ->
@gutter = document.createElement 'div'
@gutter.className = 'droplet-gutter'
@lineNumberWrapper = document.createElement 'div'
@gutter.appendChild @lineNumberWrapper
@gutterVersion = -1
@lastGutterWidth = null
@lineNumberTags = {}
@mainScroller.appendChild @gutter
# Record of embedder-set annotations
# and breakpoints used in rendering.
# Should mirror ace all the time.
@annotations = {}
@breakpoints = {}
@tooltipElement = document.createElement 'div'
@tooltipElement.className = 'droplet-tooltip'
@dropletElement.appendChild @tooltipElement
@aceEditor.on 'guttermousedown', (e) =>
# Ensure that the click actually happened
# on a line and not just in gutter space.
target = e.domEvent.target
if target.className.indexOf('ace_gutter-cell') is -1
return
# Otherwise, get the row and fire a Droplet gutter
# mousedown event.
row = e.getDocumentPosition().row
e.stop()
@fireEvent 'guttermousedown', [{line: row, event: e.domEvent}]
hook 'mousedown', 11, (point, event, state) ->
# Check if mousedown within the gutter
if not @trackerPointIsInGutter(point) then return
# Find the line that was clicked
mainPoint = @trackerPointToMain point
treeView = @session.view.getViewNodeFor @session.tree
clickedLine = @findLineNumberAtCoordinate mainPoint.y
@fireEvent 'guttermousedown', [{line: clickedLine, event: event}]
# Prevent other hooks from taking this event
return true
Editor::setBreakpoint = (row) ->
# Delegate
@aceEditor.session.setBreakpoint(row)
# Add to our own records
@breakpoints[row] = true
# Redraw gutter.
# TODO: if this ends up being a performance issue,
# selectively apply classes
@redrawGutter false
Editor::clearBreakpoint = (row) ->
@aceEditor.session.clearBreakpoint(row)
@breakpoints[row] = false
@redrawGutter false
Editor::clearBreakpoints = (row) ->
@aceEditor.session.clearBreakpoints()
@breakpoints = {}
@redrawGutter false
Editor::getBreakpoints = (row) ->
@aceEditor.session.getBreakpoints()
Editor::setAnnotations = (annotations) ->
@aceEditor.session.setAnnotations annotations
@annotations = {}
for el, i in annotations
@annotations[el.row] ?= []
@annotations[el.row].push el
@redrawGutter false
Editor::resizeGutter = ->
unless @lastGutterWidth is @aceEditor.renderer.$gutterLayer.gutterWidth
@lastGutterWidth = @aceEditor.renderer.$gutterLayer.gutterWidth
@gutter.style.width = @lastGutterWidth + 'px'
return @resize()
unless @lastGutterHeight is Math.max(@dropletElement.clientHeight, @mainCanvas.clientHeight)
@lastGutterHeight = Math.max(@dropletElement.clientHeight, @mainCanvas.clientHeight)
@gutter.style.height = @lastGutterHeight + 'px'
Editor::addLineNumberForLine = (line) ->
treeView = @session.view.getViewNodeFor @session.tree
if line of @lineNumberTags
lineDiv = @lineNumberTags[line].tag
else
lineDiv = document.createElement 'div'
lineDiv.innerText = lineDiv.textContent = line + 1
@lineNumberTags[line] = {
tag: lineDiv
lastPosition: null
}
if treeView.bounds[line].y isnt @lineNumberTags[line].lastPosition
lineDiv.className = 'droplet-gutter-line'
# Add annotation mouseover text
# and graphics
if @annotations[line]?
lineDiv.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
title = @annotations[line].map((x) -> x.text).join('\n')
lineDiv.addEventListener 'mouseover', =>
@tooltipElement.innerText =
@tooltipElement.textContent = title
@tooltipElement.style.display = 'block'
lineDiv.addEventListener 'mousemove', (event) =>
@tooltipElement.style.left = event.pageX + 'px'
@tooltipElement.style.top = event.pageY + 'px'
lineDiv.addEventListener 'mouseout', =>
@tooltipElement.style.display = 'none'
# Add breakpoint graphics
if @breakpoints[line]
lineDiv.className += ' droplet_breakpoint'
lineDiv.style.top = "#{treeView.bounds[line].y}px"
lineDiv.style.paddingTop = "#{treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent}px"
lineDiv.style.paddingBottom = "#{treeView.distanceToBase[line].below - @session.fontDescent}"
lineDiv.style.height = treeView.bounds[line].height + 'px'
lineDiv.style.fontSize = @session.fontSize + 'px'
@lineNumberWrapper.appendChild lineDiv
@lineNumberTags[line].lastPosition = treeView.bounds[line].y
TYPE_SEVERITY = {
'error': 2
'warning': 1
'info': 0
}
TYPE_FROM_SEVERITY = ['info', 'warning', 'error']
getMostSevereAnnotationType = (arr) ->
TYPE_FROM_SEVERITY[Math.max.apply(this, arr.map((x) -> TYPE_SEVERITY[x.type]))]
Editor::findLineNumberAtCoordinate = (coord) ->
treeView = @session.view.getViewNodeFor @session.tree
start = 0; end = treeView.bounds.length
pivot = Math.floor (start + end) / 2
while treeView.bounds[pivot].y isnt coord and start < end
if start is pivot or end is pivot
return pivot
if treeView.bounds[pivot].y > coord
end = pivot
else
start = pivot
if end < 0 then return 0
if start >= treeView.bounds.length then return treeView.bounds.length - 1
pivot = Math.floor (start + end) / 2
return pivot
hook 'redraw_main', 0, (changedBox) ->
@redrawGutter(changedBox)
Editor::redrawGutter = (changedBox = true) ->
return unless @session?
treeView = @session.view.getViewNodeFor @session.tree
top = @findLineNumberAtCoordinate @session.viewports.main.y
bottom = @findLineNumberAtCoordinate @session.viewports.main.bottom()
for line in [top..bottom]
@addLineNumberForLine line
for line, tag of @lineNumberTags
if line < top or line > bottom
@lineNumberTags[line].tag.parentNode.removeChild @lineNumberTags[line].tag
delete @lineNumberTags[line]
if changedBox
@resizeGutter()
Editor::setPaletteWidth = (width) ->
@paletteWrapper.style.width = width + 'px'
@resizeBlockMode()
# COPY AND PASTE
# ================================
hook 'populate', 1, ->
@copyPasteInput = document.createElement 'textarea'
@copyPasteInput.style.position = 'absolute'
@copyPasteInput.style.left = @copyPasteInput.style.top = '-9999px'
@dropletElement.appendChild @copyPasteInput
pressedVKey = false
pressedXKey = false
@copyPasteInput.addEventListener 'keydown', (event) ->
pressedVKey = pressedXKey = false
if event.keyCode is 86
pressedVKey = true
else if event.keyCode is 88
pressedXKey = true
@copyPasteInput.addEventListener 'input', =>
if not @session? or @session.readOnly
return
if pressedVKey and not @cursorAtSocket()
str = @copyPasteInput.value; lines = str.split '\n'
# Strip any common leading indent
# from all the lines of the pasted tet
minIndent = lines.map((line) -> line.length - line.trimLeft().length).reduce((a, b) -> Math.min(a, b))
str = lines.map((line) -> line[minIndent...]).join('\n')
str = str.replace /^\n*|\n*$/g, ''
try
blocks = @session.mode.parse str, {context: @getCursor().parent.parseContext}
blocks = new model.List blocks.start.next, blocks.end.prev
catch e
blocks = null
return unless blocks?
@undoCapture()
@spliceIn blocks, @getCursor()
@setCursor blocks.end
@redrawMain()
@copyPasteInput.setSelectionRange 0, @copyPasteInput.value.length
else if pressedXKey and @lassoSelection?
@spliceOut @lassoSelection; @lassoSelection = null
@redrawMain()
hook 'keydown', 0, (event, state) ->
if event.which in command_modifiers
unless @cursorAtSocket()
x = document.body.scrollLeft
y = document.body.scrollTop
@copyPasteInput.focus()
window.scrollTo(x, y)
if @lassoSelection?
@copyPasteInput.value = @lassoSelection.stringifyInPlace()
@copyPasteInput.setSelectionRange 0, @copyPasteInput.value.length
hook 'keyup', 0, (point, event, state) ->
if event.which in command_modifiers
if @cursorAtSocket()
@hiddenInput.focus()
else
@dropletElement.focus()
# OVRFLOW BIT
# ================================
Editor::overflowsX = ->
@documentDimensions().width > @session.viewportDimensions().width
Editor::overflowsY = ->
@documentDimensions().height > @session.viewportDimensions().height
Editor::documentDimensions = ->
bounds = @session.view.getViewNodeFor(@session.tree).totalBounds
return {
width: bounds.width
height: bounds.height
}
Editor::viewportDimensions = ->
return @session.viewports.main
# LINE LOCATION API
# =================
Editor::getLineMetrics = (row) ->
viewNode = @session.view.getViewNodeFor @session.tree
bounds = (new @session.view.draw.Rectangle()).copy(viewNode.bounds[row])
bounds.x += @mainCanvas.offsetLeft + @mainCanvas.offsetParent.offsetLeft
return {
bounds: bounds
distanceToBase: {
above: viewNode.distanceToBase[row].above
below: viewNode.distanceToBase[row].below
}
}
# DEBUG CODE
# ================================
Editor::dumpNodeForDebug = (hitTestResult, line) ->
console.log('Model node:')
console.log(hitTestResult.serialize())
console.log('View node:')
console.log(@session.view.getViewNodeFor(hitTestResult).serialize(line))
# CLOSING FOUNDATIONAL STUFF
# ================================
# Order the arrays correctly.
for key of unsortedEditorBindings
unsortedEditorBindings[key].sort (a, b) -> if a.priority > b.priority then -1 else 1
editorBindings[key] = []
for binding in unsortedEditorBindings[key]
editorBindings[key].push binding.fn
| true | # Droplet controller.
#
# Copyright (c) 2014 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# MIT License.
helper = require './helper.coffee'
draw = require './draw.coffee'
model = require './model.coffee'
view = require './view.coffee'
QUAD = require '../vendor/quadtree.js'
modes = require './modes.coffee'
# ## Magic constants
PALETTE_TOP_MARGIN = 5
PALETTE_MARGIN = 5
MIN_DRAG_DISTANCE = 1
PALETTE_LEFT_MARGIN = 5
DEFAULT_INDENT_DEPTH = ' '
ANIMATION_FRAME_RATE = 60
DISCOURAGE_DROP_TIMEOUT = 1000
MAX_DROP_DISTANCE = 100
CURSOR_WIDTH_DECREASE = 3
CURSOR_HEIGHT_DECREASE = 2
CURSOR_UNFOCUSED_OPACITY = 0.5
DEBUG_FLAG = false
DROPDOWN_SCROLLBAR_PADDING = 17
BACKSPACE_KEY = 8
TAB_KEY = 9
ENTER_KEY = 13
LEFT_ARROW_KEY = 37
UP_ARROW_KEY = 38
RIGHT_ARROW_KEY = 39
DOWN_ARROW_KEY = 40
Z_KEY = 90
Y_KEY = 89
META_KEYS = [91, 92, 93, 223, 224]
CONTROL_KEYS = [17, 162, 163]
GRAY_BLOCK_MARGIN = 5
GRAY_BLOCK_HANDLE_WIDTH = 15
GRAY_BLOCK_HANDLE_HEIGHT = 30
GRAY_BLOCK_COLOR = 'rgba(256, 256, 256, 0.5)'
GRAY_BLOCK_BORDER = '#AAA'
userAgent = ''
if typeof(window) isnt 'undefined' and window.navigator?.userAgent
userAgent = window.navigator.userAgent
isOSX = /OS X/.test(userAgent)
command_modifiers = if isOSX then META_KEYS else CONTROL_KEYS
command_pressed = (e) -> if isOSX then e.metaKey else e.ctrlKey
# FOUNDATION
# ================================
# ## Editor event bindings
#
# These are different events associated with the Editor
# that features will want to bind to.
unsortedEditorBindings = {
'populate': [] # after an empty editor is created
'resize': [] # after the window is resized
'resize_palette': [] # after the palette is resized
'redraw_main': [] # whenever we need to redraw the main canvas
'redraw_palette': [] # repaint the graphics of the palette
'rebuild_palette': [] # redraw the paltte, both graphics and elements
'mousedown': []
'mousemove': []
'mouseup': []
'dblclick': []
'keydown': []
'keyup': []
}
editorBindings = {}
SVG_STANDARD = helper.SVG_STANDARD
EMBOSS_FILTER_SVG = """
<svg xlmns="#{SVG_STANDARD}">
<filter id="dropShadow" x="0" y="0" width="200%" height="200%">
<feOffset result="offOut" in="SourceAlpha" dx="5" dy="5" />
<feGaussianBlur result="blurOut" in="offOut" stdDeviation="1" />
<feBlend in="SourceGraphic" in2="blurOut" out="blendOut" mode="normal" />
<feComposite in="blendOut" in2="SourceGraphic" k2="0.5" k3="0.5" operator="arithmetic" />
</filter>
</svg>
"""
# This hook function is for convenience,
# for features to add events that will occur at
# various times in the editor lifecycle.
hook = (event, priority, fn) ->
unsortedEditorBindings[event].push {
priority: priority
fn: fn
}
class Session
constructor: (_main, _palette, _drag, @options, standardViewSettings) -> # TODO rearchitecture so that a session is independent of elements again
# Option flags
@readOnly = false
@paletteGroups = @options.palette
@showPaletteInTextMode = @options.showPaletteInTextMode ? false
@paletteEnabled = @options.enablePaletteAtStart ? true
@dropIntoAceAtLineStart = @options.dropIntoAceAtLineStart ? false
@allowFloatingBlocks = @options.allowFloatingBlocks ? true
# By default, attempt to preserve empty sockets when round-tripping
@options.preserveEmpty ?= true
# Mode
@options.mode = @options.mode.replace /$\/ace\/mode\//, ''
if @options.mode of modes
@mode = new modes[@options.mode] @options.modeOptions
else
@mode = null
# Instantiate an Droplet editor view
@view = new view.View _main, helper.extend standardViewSettings, @options.viewSettings ? {}
@paletteView = new view.View _palette, helper.extend {}, standardViewSettings, @options.viewSettings ? {}, {
showDropdowns: @options.showDropdownInPalette ? false
}
@dragView = new view.View _drag, helper.extend {}, standardViewSettings, @options.viewSettings ? {}
# ## Document initialization
# We start off with an empty document
@tree = new model.Document(@rootContext)
# Line markings
@markedLines = {}
@markedBlocks = {}; @nextMarkedBlockId = 0
@extraMarks = {}
# Undo/redo stack
@undoStack = []
@redoStack = []
@changeEventVersion = 0
# Floating blocks
@floatingBlocks = []
# Cursor
@cursor = new CrossDocumentLocation(0, new model.Location(0, 'documentStart'))
# Scrolling
@viewports = {
main: new draw.Rectangle 0, 0, 0, 0
palette: new draw.Rectangle 0, 0, 0, 0
}
# Block toggle
@currentlyUsingBlocks = true
# Fonts
@fontSize = 15
@fontFamily = 'Courier New'
metrics = helper.fontMetrics(@fontFamily, @fontSize)
@fontAscent = metrics.prettytop
@fontDescent = metrics.descent
@fontWidth = @view.draw.measureCtx.measureText(' ').width
# Remembered sockets
@rememberedSockets = []
# ## The Editor Class
exports.Editor = class Editor
constructor: (@aceEditor, @options) ->
# ## DOM Population
# This stage of ICE Editor construction populates the given wrapper
# element with all the necessary ICE editor components.
@debugging = true
@options = helper.deepCopy @options
# ### Wrapper
# Create the div that will contain all the ICE Editor graphics
@dropletElement = document.createElement 'div'
@dropletElement.className = 'droplet-wrapper-div'
@dropletElement.innerHTML = EMBOSS_FILTER_SVG
# We give our element a tabIndex so that it can be focused and capture keypresses.
@dropletElement.tabIndex = 0
# ### Canvases
# Create the palette and main canvases
# A measuring canvas for measuring text
@measureCanvas = document.createElement 'canvas'
@measureCtx = @measureCanvas.getContext '2d'
# Main canvas first
@mainCanvas = document.createElementNS SVG_STANDARD, 'svg'
#@mainCanvasWrapper = document.createElementNS SVG_STANDARD, 'g'
#@mainCanvas = document.createElementNS SVG_STANDARD, 'g'
#@mainCanvas.appendChild @mainCanvasWrapper
#@mainCanvasWrapper.appendChild @mainCanvas
@mainCanvas.setAttribute 'class', 'droplet-main-canvas'
@mainCanvas.setAttribute 'shape-rendering', 'optimizeSpeed'
@paletteWrapper = document.createElement 'div'
@paletteWrapper.className = 'droplet-palette-wrapper'
@paletteElement = document.createElement 'div'
@paletteElement.className = 'droplet-palette-element'
@paletteWrapper.appendChild @paletteElement
# Then palette canvas
@paletteCanvas = @paletteCtx = document.createElementNS SVG_STANDARD, 'svg'
@paletteCanvas.setAttribute 'class', 'droplet-palette-canvas'
@paletteWrapper.style.position = 'absolute'
@paletteWrapper.style.left = '0px'
@paletteWrapper.style.top = '0px'
@paletteWrapper.style.bottom = '0px'
@paletteWrapper.style.width = '270px'
# We will also have to initialize the
# drag canvas.
@dragCanvas = @dragCtx = document.createElementNS SVG_STANDARD, 'svg'
@dragCanvas.setAttribute 'class', 'droplet-drag-canvas'
@dragCanvas.style.left = '0px'
@dragCanvas.style.top = '0px'
@dragCanvas.style.transform = 'translate(-9999px,-9999px)'
@draw = new draw.Draw(@mainCanvas)
@dropletElement.style.left = @paletteWrapper.clientWidth + 'px'
do @draw.refreshFontCapital
@standardViewSettings =
padding: 5
indentWidth: 20
textHeight: helper.getFontHeight 'Courier New', 15
indentTongueHeight: 20
tabOffset: 10
tabWidth: 15
tabHeight: 4
tabSideWidth: 1 / 4
dropAreaHeight: 20
indentDropAreaMinWidth: 50
emptySocketWidth: 20
emptyLineHeight: 25
highlightAreaHeight: 10
shadowBlur: 5
ctx: @measureCtx
draw: @draw
# We can be passed a div
if @aceEditor instanceof Node
@wrapperElement = @aceEditor
@wrapperElement.style.position = 'absolute'
@wrapperElement.style.right =
@wrapperElement.style.left =
@wrapperElement.style.top =
@wrapperElement.style.bottom = '0px'
@aceElement = document.createElement 'div'
@aceElement.className = 'droplet-ace'
@wrapperElement.appendChild @aceElement
@aceEditor = ace.edit @aceElement
@aceEditor.setTheme 'ace/theme/chrome'
@aceEditor.setFontSize 15
acemode = @options.mode
if acemode is 'coffeescript' then acemode = 'coffee'
@aceEditor.getSession().setMode 'ace/mode/' + acemode
@aceEditor.getSession().setTabSize 2
else
@wrapperElement = document.createElement 'div'
@wrapperElement.style.position = 'absolute'
@wrapperElement.style.right =
@wrapperElement.style.left =
@wrapperElement.style.top =
@wrapperElement.style.bottom = '0px'
@aceElement = @aceEditor.container
@aceElement.className += ' droplet-ace'
@aceEditor.container.parentElement.appendChild @wrapperElement
@wrapperElement.appendChild @aceEditor.container
# Append populated divs
@wrapperElement.appendChild @dropletElement
@wrapperElement.appendChild @paletteWrapper
@wrapperElement.style.backgroundColor = '#FFF'
@currentlyAnimating = false
@transitionContainer = document.createElement 'div'
@transitionContainer.className = 'droplet-transition-container'
@dropletElement.appendChild @transitionContainer
if @options?
@session = new Session @mainCanvas, @paletteCanvas, @dragCanvas, @options, @standardViewSettings
@sessions = new helper.PairDict([
[@aceEditor.getSession(), @session]
])
else
@session = null
@sessions = new helper.PairDict []
@options = {
extraBottomHeight: 10
}
# Sessions are bound to other ace sessions;
# on ace session change Droplet will also change sessions.
@aceEditor.on 'changeSession', (e) =>
if @sessions.contains(e.session)
@updateNewSession @sessions.get(e.session)
else if e.session._dropletSession?
@updateNewSession e.session._dropletSession
@sessions.set(e.session, e.session._dropletSession)
else
@updateNewSession null
@setEditorState false
# Set up event bindings before creating a view
@bindings = {}
boundListeners = []
# Call all the feature bindings that are supposed
# to happen now.
for binding in editorBindings.populate
binding.call this
# ## Resize
# This stage of ICE editor construction, which is repeated
# whenever the editor is resized, should adjust the sizes
# of all the ICE editor componenents to fit the wrapper.
window.addEventListener 'resize', => @resizeBlockMode()
# ## Tracker Events
# We allow binding to the tracker element.
dispatchMouseEvent = (event) =>
# Ignore mouse clicks that are not the left-button
if event.type isnt 'mousemove' and event.which isnt 1 then return
# Ignore mouse clicks whose target is the scrollbar
if event.target is @mainScroller then return
trackPoint = new @draw.Point(event.clientX, event.clientY)
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings[event.type]
handler.call this, trackPoint, event, state
# Stop mousedown event default behavior so that
# we don't get bad selections
if event.type is 'mousedown'
event.preventDefault?()
event.returnValue = false
return false
dispatchKeyEvent = (event) =>
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings[event.type]
handler.call this, event, state
for eventName, elements of {
keydown: [@dropletElement, @paletteElement]
keyup: [@dropletElement, @paletteElement]
mousedown: [@dropletElement, @paletteElement, @dragCover]
dblclick: [@dropletElement, @paletteElement, @dragCover]
mouseup: [window]
mousemove: [window] } then do (eventName, elements) =>
for element in elements
if /^key/.test eventName
element.addEventListener eventName, dispatchKeyEvent
else
element.addEventListener eventName, dispatchMouseEvent
@resizeBlockMode()
# Now that we've populated everything, immediately redraw.
@redrawMain()
@rebuildPalette()
# If we were given an unrecognized mode or asked to start in text mode,
# flip into text mode here
useBlockMode = @session?.mode? && !@options.textModeAtStart
# Always call @setEditorState to ensure palette is positioned properly
@setEditorState useBlockMode
return this
setMode: (mode, modeOptions) ->
modeClass = modes[mode]
if modeClass
@options.mode = mode
@session.mode = new modeClass modeOptions
else
@options.mode = null
@session.mode = null
@setValue @getValue()
getMode: ->
@options.mode
setReadOnly: (readOnly) ->
@session.readOnly = readOnly
@aceEditor.setReadOnly readOnly
getReadOnly: ->
@session.readOnly
# ## Foundational Resize
# At the editor core, we will need to resize
# all of the natively-added canvases, as well
# as the wrapper element, whenever a resize
# occurs.
resizeTextMode: ->
@resizeAceElement()
@aceEditor.resize true
if @session?
@resizePalette()
return
resizeBlockMode: ->
return unless @session?
@resizeTextMode()
@dropletElement.style.height = "#{@wrapperElement.clientHeight}px"
if @session.paletteEnabled
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
@dropletElement.style.width = "#{@wrapperElement.clientWidth - @paletteWrapper.clientWidth}px"
else
@dropletElement.style.left = "0px"
@dropletElement.style.width = "#{@wrapperElement.clientWidth}px"
#@resizeGutter()
@session.viewports.main.height = @dropletElement.clientHeight
@session.viewports.main.width = @dropletElement.clientWidth - @gutter.clientWidth
@mainCanvas.setAttribute 'width', @dropletElement.clientWidth - @gutter.clientWidth
@mainCanvas.style.left = "#{@gutter.clientWidth}px"
@transitionContainer.style.left = "#{@gutter.clientWidth}px"
@resizePalette()
@resizePaletteHighlight()
@resizeNubby()
@resizeMainScroller()
@resizeDragCanvas()
# Re-scroll and redraw main
@session.viewports.main.y = @mainScroller.scrollTop
@session.viewports.main.x = @mainScroller.scrollLeft
resizePalette: ->
for binding in editorBindings.resize_palette
binding.call this
@rebuildPalette()
resize: ->
if @session?.currentlyUsingBlocks #TODO session
@resizeBlockMode()
else
@resizeTextMode()
updateNewSession: (session) ->
@session.view.clearFromCanvas()
@session.paletteView.clearFromCanvas()
@session.dragView.clearFromCanvas()
@session = session
return unless session?
# Force scroll into our position
offsetY = @session.viewports.main.y
offsetX = @session.viewports.main.x
@setEditorState @session.currentlyUsingBlocks
@redrawMain()
@mainScroller.scrollTop = offsetY
@mainScroller.scrollLeft = offsetX
@setPalette @session.paletteGroups
hasSessionFor: (aceSession) -> @sessions.contains(aceSession)
bindNewSession: (opts) ->
if @sessions.contains(@aceEditor.getSession())
throw new ArgumentError 'Cannot bind a new session where one already exists.'
else
session = new Session @mainCanvas, @paletteCanvas, @dragCanvas, opts, @standardViewSettings
@sessions.set(@aceEditor.getSession(), session)
@session = session
@aceEditor.getSession()._dropletSession = @session
@session.currentlyUsingBlocks = false
@setValue_raw @getAceValue()
@setPalette @session.paletteGroups
return session
Editor::clearCanvas = (canvas) -> # TODO remove and remove all references to
# RENDERING CAPABILITIES
# ================================
# ## Redraw
# There are two different redraw events, redraw_main and rebuild_palette,
# for redrawing the main canvas and palette canvas, respectively.
#
# Redrawing simply involves issuing a call to the View.
Editor::clearMain = (opts) -> # TODO remove and remove all references to
Editor::setTopNubbyStyle = (height = 10, color = '#EBEBEB') ->
@nubbyHeight = Math.max(0, height); @nubbyColor = color
@topNubbyPath ?= new @draw.Path([], true)
@topNubbyPath.activate()
@topNubbyPath.setParent @mainCanvas
points = []
points.push new @draw.Point @mainCanvas.clientWidth, -5
points.push new @draw.Point @mainCanvas.clientWidth, height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth, height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth * (1 - @session.view.opts.tabSideWidth),
@session.view.opts.tabHeight + height
points.push new @draw.Point @session.view.opts.tabOffset + @session.view.opts.tabWidth * @session.view.opts.tabSideWidth,
@session.view.opts.tabHeight + height
points.push new @draw.Point @session.view.opts.tabOffset, height
points.push new @draw.Point @session.view.opts.bevelClip, height
points.push new @draw.Point 0, height + @session.view.opts.bevelClip
points.push new @draw.Point -5, height + @session.view.opts.bevelClip
points.push new @draw.Point -5, -5
@topNubbyPath.setPoints points
@topNubbyPath.style.fillColor = color
@redrawMain()
Editor::resizeNubby = ->
@setTopNubbyStyle @nubbyHeight, @nubbyColor
Editor::initializeFloatingBlock = (record, i) ->
record.renderGroup = new @session.view.draw.Group()
record.grayBox = new @session.view.draw.NoRectangle()
record.grayBoxPath = new @session.view.draw.Path(
[], false, {
fillColor: GRAY_BLOCK_COLOR
strokeColor: GRAY_BLOCK_BORDER
lineWidth: 4
dotted: '8 5'
cssClass: 'droplet-floating-container'
}
)
record.startText = new @session.view.draw.Text(
(new @session.view.draw.Point(0, 0)), @session.mode.startComment
)
record.endText = new @session.view.draw.Text(
(new @session.view.draw.Point(0, 0)), @session.mode.endComment
)
for element in [record.grayBoxPath, record.startText, record.endText]
element.setParent record.renderGroup
element.activate()
@session.view.getViewNodeFor(record.block).group.setParent record.renderGroup
record.renderGroup.activate()
# TODO maybe refactor into qualifiedFocus
if i < @session.floatingBlocks.length
@mainCanvas.insertBefore record.renderGroup.element, @session.floatingBlocks[i].renderGroup.element
else
@mainCanvas.appendChild record.renderGroup
Editor::drawFloatingBlock = (record, startWidth, endWidth, rect, opts) ->
blockView = @session.view.getViewNodeFor record.block
blockView.layout record.position.x, record.position.y
rectangle = new @session.view.draw.Rectangle(); rectangle.copy(blockView.totalBounds)
rectangle.x -= GRAY_BLOCK_MARGIN; rectangle.y -= GRAY_BLOCK_MARGIN
rectangle.width += 2 * GRAY_BLOCK_MARGIN; rectangle.height += 2 * GRAY_BLOCK_MARGIN
bottomTextPosition = blockView.totalBounds.bottom() - blockView.distanceToBase[blockView.lineLength - 1].below - @session.fontSize
if (blockView.totalBounds.width - blockView.bounds[blockView.bounds.length - 1].width) < endWidth
if blockView.lineLength > 1
rectangle.height += @session.fontSize
bottomTextPosition = rectangle.bottom() - @session.fontSize - 5
else
rectangle.width += endWidth
unless rectangle.equals(record.grayBox)
record.grayBox = rectangle
oldBounds = record.grayBoxPath?.bounds?() ? new @session.view.draw.NoRectangle()
startHeight = blockView.bounds[0].height + 10
points = []
# Make the path surrounding the gray box (with rounded corners)
points.push new @session.view.draw.Point rectangle.right() - 5, rectangle.y
points.push new @session.view.draw.Point rectangle.right(), rectangle.y + 5
points.push new @session.view.draw.Point rectangle.right(), rectangle.bottom() - 5
points.push new @session.view.draw.Point rectangle.right() - 5, rectangle.bottom()
if blockView.lineLength > 1
points.push new @session.view.draw.Point rectangle.x + 5, rectangle.bottom()
points.push new @session.view.draw.Point rectangle.x, rectangle.bottom() - 5
else
points.push new @session.view.draw.Point rectangle.x, rectangle.bottom()
# Handle
points.push new @session.view.draw.Point rectangle.x, rectangle.y + startHeight
points.push new @session.view.draw.Point rectangle.x - startWidth + 5, rectangle.y + startHeight
points.push new @session.view.draw.Point rectangle.x - startWidth, rectangle.y + startHeight - 5
points.push new @session.view.draw.Point rectangle.x - startWidth, rectangle.y + 5
points.push new @session.view.draw.Point rectangle.x - startWidth + 5, rectangle.y
points.push new @session.view.draw.Point rectangle.x, rectangle.y
record.grayBoxPath.setPoints points
if opts.boundingRectangle?
opts.boundingRectangle.unite path.bounds()
opts.boundingRectangle.unite(oldBounds)
return @redrawMain opts
record.grayBoxPath.update()
record.startText.point.x = blockView.totalBounds.x - startWidth
record.startText.point.y = blockView.totalBounds.y + blockView.distanceToBase[0].above - @session.fontSize
record.startText.update()
record.endText.point.x = record.grayBox.right() - endWidth - 5
record.endText.point.y = bottomTextPosition
record.endText.update()
blockView.draw rect, {
grayscale: false
selected: false
noText: false
}
hook 'populate', 0, ->
@currentlyDrawnFloatingBlocks = []
Editor::redrawMain = (opts = {}) ->
return unless @session?
unless @currentlyAnimating_suprressRedraw
@session.view.beginDraw()
# Clear the main canvas
@clearMain(opts)
@topNubbyPath.update()
rect = @session.viewports.main
options = {
grayscale: false
selected: false
noText: (opts.noText ? false)
}
# Draw the new tree on the main context
layoutResult = @session.view.getViewNodeFor(@session.tree).layout 0, @nubbyHeight
@session.view.getViewNodeFor(@session.tree).draw rect, options
@session.view.getViewNodeFor(@session.tree).root()
for el, i in @currentlyDrawnFloatingBlocks
unless el.record in @session.floatingBlocks
el.record.grayBoxPath.destroy()
el.record.startText.destroy()
el.record.endText.destroy()
@currentlyDrawnFloatingBlocks = []
# Draw floating blocks
startWidth = @session.mode.startComment.length * @session.fontWidth
endWidth = @session.mode.endComment.length * @session.fontWidth
for record in @session.floatingBlocks
element = @drawFloatingBlock(record, startWidth, endWidth, rect, opts)
@currentlyDrawnFloatingBlocks.push {
record: record
}
# Draw the cursor (if exists, and is inserted)
@redrawCursors(); @redrawHighlights()
@resizeGutter()
for binding in editorBindings.redraw_main
binding.call this, layoutResult
if @session.changeEventVersion isnt @session.tree.version
@session.changeEventVersion = @session.tree.version
@fireEvent 'change', []
@session.view.cleanupDraw()
unless @alreadyScheduledCleanup
@alreadyScheduledCleanup = true
setTimeout (=>
@alreadyScheduledCleanup = false
if @session?
@session.view.garbageCollect()
), 0
return null
Editor::redrawHighlights = ->
@redrawCursors()
@redrawLassoHighlight()
# If there is an block that is being dragged,
# draw it in gray
if @draggingBlock? and @inDisplay @draggingBlock
@session.view.getViewNodeFor(@draggingBlock).draw new @draw.Rectangle(
@session.viewports.main.x,
@session.viewports.main.y,
@session.viewports.main.width,
@session.viewports.main.height
), {grayscale: true}
Editor::clearCursorCanvas = ->
@textCursorPath.deactivate()
@cursorPath.deactivate()
Editor::redrawCursors = ->
return unless @session?
@clearCursorCanvas()
if @cursorAtSocket()
@redrawTextHighlights()
else unless @lassoSelection?
@drawCursor()
Editor::drawCursor = -> @strokeCursor @determineCursorPosition()
Editor::clearPalette = -> # TODO remove and remove all references to
Editor::clearPaletteHighlightCanvas = -> # TODO remove and remove all references to
Editor::redrawPalette = ->
return unless @session?.currentPaletteBlocks?
@clearPalette()
@session.paletteView.beginDraw()
# We will construct a vertical layout
# with padding for the palette blocks.
# To do this, we will need to keep track
# of the last bottom edge of a palette block.
lastBottomEdge = PALETTE_TOP_MARGIN
for entry in @session.currentPaletteBlocks
# Layout this block
paletteBlockView = @session.paletteView.getViewNodeFor entry.block
paletteBlockView.layout PALETTE_LEFT_MARGIN, lastBottomEdge
# Render the block
paletteBlockView.draw()
paletteBlockView.group.setParent @paletteCtx
element = document.createElementNS SVG_STANDARD, 'title'
element.innerHTML = entry.title ? entry.block.stringify()
paletteBlockView.group.element.appendChild element
paletteBlockView.group.element.setAttribute 'data-id', entry.id
# Update lastBottomEdge
lastBottomEdge = paletteBlockView.getBounds().bottom() + PALETTE_MARGIN
for binding in editorBindings.redraw_palette
binding.call this
@paletteCanvas.style.height = lastBottomEdge + 'px'
@session.paletteView.garbageCollect()
Editor::rebuildPalette = ->
return unless @session?.currentPaletteBlocks?
@redrawPalette()
for binding in editorBindings.rebuild_palette
binding.call this
# MOUSE INTERACTION WRAPPERS
# ================================
# These are some common operations we need to do with
# the mouse that will be convenient later.
Editor::absoluteOffset = (el) ->
point = new @draw.Point el.offsetLeft, el.offsetTop
el = el.offsetParent
until el is document.body or not el?
point.x += el.offsetLeft - el.scrollLeft
point.y += el.offsetTop - el.scrollTop
el = el.offsetParent
return point
# ### Conversion functions
# Convert a point relative to the page into
# a point relative to one of the two canvases.
Editor::trackerPointToMain = (point) ->
if not @mainCanvas.parentElement?
return new @draw.Point(NaN, NaN)
gbr = @mainCanvas.getBoundingClientRect()
new @draw.Point(point.x - gbr.left,
point.y - gbr.top)
Editor::trackerPointToPalette = (point) ->
if not @paletteCanvas.parentElement?
return new @draw.Point(NaN, NaN)
gbr = @paletteCanvas.getBoundingClientRect()
new @draw.Point(point.x - gbr.left,
point.y - gbr.top)
Editor::trackerPointIsInElement = (point, element) ->
if not @session? or @session.readOnly
return false
if not element.parentElement?
return false
gbr = element.getBoundingClientRect()
return point.x >= gbr.left and point.x < gbr.right and
point.y >= gbr.top and point.y < gbr.bottom
Editor::trackerPointIsInMain = (point) ->
return this.trackerPointIsInElement point, @mainCanvas
Editor::trackerPointIsInMainScroller = (point) ->
return this.trackerPointIsInElement point, @mainScroller
Editor::trackerPointIsInGutter = (point) ->
return this.trackerPointIsInElement point, @gutter
Editor::trackerPointIsInPalette = (point) ->
return this.trackerPointIsInElement point, @paletteCanvas
Editor::trackerPointIsInAce = (point) ->
return this.trackerPointIsInElement point, @aceElement
# ### hitTest
# Simple function for going through a linked-list block
# and seeing what the innermost child is that we hit.
Editor::hitTest = (point, block, view = @session.view) ->
if @session.readOnly
return null
head = block.start
seek = block.end
result = null
until head is seek
if head.type is 'blockStart' and view.getViewNodeFor(head.container).path.contains point
result = head.container
seek = head.container.end
head = head.next
# If we had a child hit, return it.
return result
hook 'mousedown', 10, ->
x = document.body.scrollLeft
y = document.body.scrollTop
@dropletElement.focus()
window.scrollTo(x, y)
Editor::removeBlankLines = ->
# If we have blank lines at the end,
# get rid of them
head = tail = @session.tree.end.prev
while head?.type is 'newline'
head = head.prev
if head.type is 'newline'
@spliceOut new model.List head, tail
# UNDO STACK SUPPORT
# ================================
# We must declare a few
# fields a populate time
# Now we hook to ctrl-z to undo.
hook 'keydown', 0, (event, state) ->
if event.which is Z_KEY and event.shiftKey and command_pressed(event)
@redo()
else if event.which is Z_KEY and command_pressed(event)
@undo()
else if event.which is Y_KEY and command_pressed(event)
@redo()
class EditorState
constructor: (@root, @floats) ->
equals: (other) ->
return false unless @root is other.root and @floats.length is other.floats.length
for el, i in @floats
return false unless el.position.equals(other.floats[i].position) and el.string is other.floats[i].string
return true
toString: -> JSON.stringify {
@root, @floats
}
Editor::getSerializedEditorState = ->
return new EditorState @session.tree.stringify(), @session.floatingBlocks.map (x) -> {
position: x.position
string: x.block.stringify()
}
Editor::clearUndoStack = ->
return unless @session?
@session.undoStack.length = 0
@session.redoStack.length = 0
Editor::undo = ->
return unless @session?
# Don't allow a socket to be highlighted during
# an undo operation
@setCursor @session.cursor, ((x) -> x.type isnt 'socketStart')
currentValue = @getSerializedEditorState()
until @session.undoStack.length is 0 or
(@session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint and
not @getSerializedEditorState().equals(currentValue))
operation = @popUndo()
if operation instanceof FloatingOperation
@performFloatingOperation(operation, 'backward')
else
@getDocument(operation.document).perform(
operation.operation, 'backward', @getPreserves(operation.document)
) unless operation instanceof CapturePoint
# Set the the remembered socket contents to the state it was in
# at this point in the undo stack.
if @session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint
@session.rememberedSockets = @session.undoStack[@session.undoStack.length - 1].rememberedSockets.map (x) -> x.clone()
@popUndo()
@correctCursor()
@redrawMain()
return
Editor::pushUndo = (operation) ->
@session.redoStack.length = 0
@session.undoStack.push operation
Editor::popUndo = ->
operation = @session.undoStack.pop()
@session.redoStack.push(operation) if operation?
return operation
Editor::popRedo = ->
operation = @session.redoStack.pop()
@session.undoStack.push(operation) if operation?
return operation
Editor::redo = ->
currentValue = @getSerializedEditorState()
until @session.redoStack.length is 0 or
(@session.redoStack[@session.redoStack.length - 1] instanceof CapturePoint and
not @getSerializedEditorState().equals(currentValue))
operation = @popRedo()
if operation instanceof FloatingOperation
@performFloatingOperation(operation, 'forward')
else
@getDocument(operation.document).perform(
operation.operation, 'forward', @getPreserves(operation.document)
) unless operation instanceof CapturePoint
# Set the the remembered socket contents to the state it was in
# at this point in the undo stack.
if @session.undoStack[@session.undoStack.length - 1] instanceof CapturePoint
@session.rememberedSockets = @session.undoStack[@session.undoStack.length - 1].rememberedSockets.map (x) -> x.clone()
@popRedo()
@redrawMain()
return
# ## undoCapture and CapturePoint ##
# A CapturePoint is a sentinel indicating that the undo stack
# should stop when the user presses Ctrl+Z or Ctrl+Y. Each CapturePoint
# also remembers the @rememberedSocket state at the time it was placed,
# to preserved remembered socket contents across undo and redo.
Editor::undoCapture = ->
@pushUndo new CapturePoint(@session.rememberedSockets)
class CapturePoint
constructor: (rememberedSockets) ->
@rememberedSockets = rememberedSockets.map (x) -> x.clone()
# BASIC BLOCK MOVE SUPPORT
# ================================
Editor::getPreserves = (dropletDocument) ->
if dropletDocument instanceof model.Document
dropletDocument = @documentIndex dropletDocument
array = [@session.cursor]
array = array.concat @session.rememberedSockets.map(
(x) -> x.socket
)
return array.filter((location) ->
location.document is dropletDocument
).map((location) -> location.location)
Editor::spliceOut = (node, container = null) ->
# Make an empty list if we haven't been
# passed one
unless node instanceof model.List
node = new model.List node, node
operation = null
dropletDocument = node.getDocument()
parent = node.parent
if dropletDocument?
operation = node.getDocument().remove node, @getPreserves(dropletDocument)
@pushUndo {operation, document: @getDocuments().indexOf(dropletDocument)}
# If we are removing a block from a socket, and the socket is in our
# dictionary of remembered socket contents, repopulate the socket with
# its old contents.
if parent?.type is 'socket' and node.start.type is 'blockStart'
for socket, i in @session.rememberedSockets
if @fromCrossDocumentLocation(socket.socket) is parent
@session.rememberedSockets.splice i, 0
@populateSocket parent, socket.text
break
# Remove the floating dropletDocument if it is now
# empty
if dropletDocument.start.next is dropletDocument.end
for record, i in @session.floatingBlocks
if record.block is dropletDocument
@pushUndo new FloatingOperation i, record.block, record.position, 'delete'
# If the cursor's document is about to vanish,
# put it back in the main tree.
if @session.cursor.document is i + 1
@setCursor @session.tree.start
if @session.cursor.document > i + 1
@session.cursor.document -= 1
@session.floatingBlocks.splice i, 1
for socket in @session.rememberedSockets
if socket.socket.document > i
socket.socket.document -= 1
break
else if container?
# No document, so try to remove from container if it was supplied
container.remove node
@prepareNode node, null
@correctCursor()
return operation
Editor::spliceIn = (node, location) ->
# Track changes in the cursor by temporarily
# using a pointer to it
container = location.container ? location.parent
if container.type is 'block'
container = container.parent
else if container.type is 'socket' and
container.start.next isnt container.end
if @documentIndex(container) != -1
# If we're splicing into a socket found in a document and it already has
# something in it, remove it. Additionally, remember the old
# contents in @session.rememberedSockets for later repopulation if they take
# the block back out.
@session.rememberedSockets.push new RememberedSocketRecord(
@toCrossDocumentLocation(container),
container.textContent()
)
@spliceOut (new model.List container.start.next, container.end.prev), container
dropletDocument = location.getDocument()
@prepareNode node, container
if dropletDocument?
operation = dropletDocument.insert location, node, @getPreserves(dropletDocument)
@pushUndo {operation, document: @getDocuments().indexOf(dropletDocument)}
@correctCursor()
return operation
else
# No document, so just insert into container
container.insert location, node
return null
class RememberedSocketRecord
constructor: (@socket, @text) ->
clone: ->
new RememberedSocketRecord(
@socket.clone(),
@text
)
Editor::replace = (before, after, updates = []) ->
dropletDocument = before.start.getDocument()
if dropletDocument?
operation = dropletDocument.replace before, after, updates.concat(@getPreserves(dropletDocument))
@pushUndo {operation, document: @documentIndex(dropletDocument)}
@correctCursor()
return operation
else
return null
Editor::adjustPosToLineStart = (pos) ->
line = @aceEditor.session.getLine pos.row
if pos.row == @aceEditor.session.getLength() - 1
pos.column = if (pos.column >= line.length / 2) then line.length else 0
else
pos.column = 0
pos
Editor::correctCursor = ->
cursor = @fromCrossDocumentLocation @session.cursor
unless @validCursorPosition cursor
until not cursor? or (@validCursorPosition(cursor) and cursor.type isnt 'socketStart')
cursor = cursor.next
unless cursor? then cursor = @fromCrossDocumentLocation @session.cursor
until not cursor? or (@validCursorPosition(cursor) and cursor.type isnt 'socketStart')
cursor = cursor.prev
@session.cursor = @toCrossDocumentLocation cursor
Editor::prepareNode = (node, context) ->
if node instanceof model.Container
leading = node.getLeadingText()
if node.start.next is node.end.prev
trailing = null
else
trailing = node.getTrailingText()
[leading, trailing, classes] = @session.mode.parens leading, trailing, node.getReader(),
context?.getReader?() ? null
node.setLeadingText leading; node.setTrailingText trailing
# At population-time, we will
# want to set up a few fields.
hook 'populate', 0, ->
@clickedPoint = null
@clickedBlock = null
@clickedBlockPaletteEntry = null
@draggingBlock = null
@draggingOffset = null
@lastHighlight = @lastHighlightPath = null
# And the canvas for drawing highlights
@highlightCanvas = @highlightCtx = document.createElementNS SVG_STANDARD, 'g'
# We append it to the tracker element,
# so that it can appear in front of the scrollers.
#@dropletElement.appendChild @dragCanvas
#document.body.appendChild @dragCanvas
@wrapperElement.appendChild @dragCanvas
@mainCanvas.appendChild @highlightCanvas
Editor::clearHighlightCanvas = ->
for path in [@textCursorPath]
path.deactivate()
# Utility function for clearing the drag canvas,
# an operation we will be doing a lot.
Editor::clearDrag = ->
@clearHighlightCanvas()
# On resize, we will want to size the drag canvas correctly.
Editor::resizeDragCanvas = ->
@dragCanvas.style.width = "#{0}px"
@dragCanvas.style.height = "#{0}px"
@highlightCanvas.style.width = "#{@dropletElement.clientWidth - @gutter.clientWidth}px"
@highlightCanvas.style.height = "#{@dropletElement.clientHeight}px"
@highlightCanvas.style.left = "#{@mainCanvas.offsetLeft}px"
Editor::getDocuments = ->
documents = [@session.tree]
for el, i in @session.floatingBlocks
documents.push el.block
return documents
Editor::getDocument = (n) ->
if n is 0 then @session.tree
else @session.floatingBlocks[n - 1].block
Editor::documentIndex = (block) ->
@getDocuments().indexOf block.getDocument()
Editor::fromCrossDocumentLocation = (location) ->
@getDocument(location.document).getFromLocation location.location
Editor::toCrossDocumentLocation = (block) ->
new CrossDocumentLocation @documentIndex(block), block.getLocation()
# On mousedown, we will want to
# hit test blocks in the root tree to
# see if we want to move them.
#
# We do not do anything until the user
# drags their mouse five pixels
hook 'mousedown', 1, (point, event, state) ->
# If someone else has already taken this click, pass.
if state.consumedHitTest then return
# If it's not in the main pane, pass.
if not @trackerPointIsInMain(point) then return
# Hit test against the tree.
mainPoint = @trackerPointToMain(point)
for dropletDocument, i in @getDocuments() by -1
# First attempt handling text input
if @handleTextInputClick mainPoint, dropletDocument
state.consumedHitTest = true
return
else if @session.cursor.document is i and @cursorAtSocket()
@setCursor @session.cursor, ((token) -> token.type isnt 'socketStart')
hitTestResult = @hitTest mainPoint, dropletDocument
# Produce debugging output
if @debugging and event.shiftKey
line = null
node = @session.view.getViewNodeFor(hitTestResult)
for box, i in node.bounds
if box.contains(mainPoint)
line = i
break
@dumpNodeForDebug(hitTestResult, line)
# If it came back positive,
# deal with the click.
if hitTestResult?
# Record the hit test result (the block we want to pick up)
@clickedBlock = hitTestResult
@clickedBlockPaletteEntry = null
# Move the cursor somewhere nearby
@setCursor @clickedBlock.start.next
# Record the point at which is was clicked (for clickedBlock->draggingBlock)
@clickedPoint = point
# Signify to any other hit testing
# handlers that we have already consumed
# the hit test opportunity for this event.
state.consumedHitTest = true
return
else if i > 0
record = @session.floatingBlocks[i - 1]
if record.grayBoxPath? and record.grayBoxPath.contains @trackerPointToMain point
@clickedBlock = new model.List record.block.start.next, record.block.end.prev
@clickedPoint = point
@session.view.getViewNodeFor(@clickedBlock).absorbCache() # TODO MERGE inspection
state.consumedHitTest = true
@redrawMain()
return
# If the user clicks inside a block
# and the block contains a button
# which is either add or subtract button
# call the handleButton callback
hook 'mousedown', 4, (point, event, state) ->
if state.consumedHitTest then return
if not @trackerPointIsInMain(point) then return
mainPoint = @trackerPointToMain point
#Buttons aren't clickable in a selection
if @lassoSelection? and @hitTest(mainPoint, @lassoSelection)? then return
hitTestResult = @hitTest mainPoint, @session.tree
if hitTestResult?
hitTestBlock = @session.view.getViewNodeFor hitTestResult
str = hitTestResult.stringifyInPlace()
if hitTestBlock.addButtonRect? and hitTestBlock.addButtonRect.contains mainPoint
line = @session.mode.handleButton str, 'add-button', hitTestResult.getReader()
if line?.length >= 0
@populateBlock hitTestResult, line
@redrawMain()
state.consumedHitTest = true
### TODO
else if hitTestBlock.subtractButtonRect? and hitTestBlock.subtractButtonRect.contains mainPoint
line = @session.mode.handleButton str, 'subtract-button', hitTestResult.getReader()
if line?.length >= 0
@populateBlock hitTestResult, line
@redrawMain()
state.consumedHitTest = true
###
# If the user lifts the mouse
# before they have dragged five pixels,
# abort stuff.
hook 'mouseup', 0, (point, event, state) ->
# @clickedBlock and @clickedPoint should will exist iff
# we have dragged not yet more than 5 pixels.
#
# To abort, all we need to do is null.
if @clickedBlock?
@clickedBlock = null
@clickedPoint = null
Editor::drawDraggingBlock = ->
# Draw the new dragging block on the drag canvas.
#
# When we are dragging things, we draw the shadow.
# Also, we translate the block 1x1 to the right,
# so that we can see its borders.
@session.dragView.clearCache()
draggingBlockView = @session.dragView.getViewNodeFor @draggingBlock
draggingBlockView.layout 1, 1
@dragCanvas.width = Math.min draggingBlockView.totalBounds.width + 10, window.screen.width
@dragCanvas.height = Math.min draggingBlockView.totalBounds.height + 10, window.screen.height
draggingBlockView.draw new @draw.Rectangle 0, 0, @dragCanvas.width, @dragCanvas.height
Editor::wouldDelete = (position) ->
mainPoint = @trackerPointToMain position
palettePoint = @trackerPointToPalette position
return not @lastHighlight and not @session.viewports.main.contains(mainPoint)
# On mousemove, if there is a clicked block but no drag block,
# we might want to transition to a dragging the block if the user
# moved their mouse far enough.
hook 'mousemove', 1, (point, event, state) ->
return unless @session?
if not state.capturedPickup and @clickedBlock? and point.from(@clickedPoint).magnitude() > MIN_DRAG_DISTANCE
# Signify that we are now dragging a block.
@draggingBlock = @clickedBlock
@dragReplacing = false
# Our dragging offset must be computed using the canvas on which this block
# is rendered.
#
# NOTE: this really falls under "PALETTE SUPPORT", but must
# go here. Try to organise this better.
if @clickedBlockPaletteEntry
@draggingOffset = @session.paletteView.getViewNodeFor(@draggingBlock).bounds[0].upperLeftCorner().from(
@trackerPointToPalette(@clickedPoint))
# Substitute in expansion for this palette entry, if supplied.
expansion = @clickedBlockPaletteEntry.expansion
# Call expansion() function with no parameter to get the initial value.
if 'function' is typeof expansion then expansion = expansion()
if (expansion) then expansion = parseBlock(@session.mode, expansion, @clickedBlockPaletteEntry.context)
@draggingBlock = (expansion or @draggingBlock).clone()
# Special @draggingBlock setup for expansion function blocks.
if 'function' is typeof @clickedBlockPaletteEntry.expansion
# Any block generated from an expansion function should be treated as
# any-drop because it can change with subsequent expansion() calls.
if 'mostly-value' in @draggingBlock.classes
@draggingBlock.classes.push 'any-drop'
# Attach expansion() function and lastExpansionText to @draggingBlock.
@draggingBlock.lastExpansionText = expansion
@draggingBlock.expansion = @clickedBlockPaletteEntry.expansion
else
# Find the line on the block that we have
# actually clicked, and attempt to translate the block
# so that if it re-shapes, we're still touching it.
#
# To do this, we will assume that the left edge of a free
# block are all aligned.
mainPoint = @trackerPointToMain @clickedPoint
viewNode = @session.view.getViewNodeFor @draggingBlock
if @draggingBlock instanceof model.List and not
(@draggingBlock instanceof model.Container)
viewNode.absorbCache()
@draggingOffset = null
for bound, line in viewNode.bounds
if bound.contains mainPoint
@draggingOffset = bound.upperLeftCorner().from mainPoint
@draggingOffset.y += viewNode.bounds[0].y - bound.y
break
unless @draggingOffset?
@draggingOffset = viewNode.bounds[0].upperLeftCorner().from mainPoint
# TODO figure out what to do with lists here
# Draw the new dragging block on the drag canvas.
#
# When we are dragging things, we draw the shadow.
# Also, we translate the block 1x1 to the right,
# so that we can see its borders.
@session.dragView.beginDraw()
draggingBlockView = @session.dragView.getViewNodeFor @draggingBlock
draggingBlockView.layout 1, 1
draggingBlockView.root()
draggingBlockView.draw()
@session.dragView.garbageCollect()
@dragCanvas.style.width = "#{Math.min draggingBlockView.totalBounds.width + 10, window.screen.width}px"
@dragCanvas.style.height = "#{Math.min draggingBlockView.totalBounds.height + 10, window.screen.height}px"
# Translate it immediately into position
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
# Construct a quadtree of drop areas
# for faster dragging
@dropPointQuadTree = QUAD.init
x: @session.viewports.main.x
y: @session.viewports.main.y
w: @session.viewports.main.width
h: @session.viewports.main.height
for dropletDocument in @getDocuments()
head = dropletDocument.start
# Don't allow dropping at the start of the document
# if we are already dragging a block that is at
# the start of the document.
if @draggingBlock.start.prev is head
head = head.next
until head is dropletDocument.end
if head is @draggingBlock.start
head = @draggingBlock.end
if head instanceof model.StartToken
acceptLevel = @getAcceptLevel @draggingBlock, head.container
unless acceptLevel is helper.FORBID
dropPoint = @session.view.getViewNodeFor(head.container).dropPoint
if dropPoint?
allowed = true
for record, i in @session.floatingBlocks by -1
if record.block is dropletDocument
break
else if record.grayBoxPath.contains dropPoint
allowed = false
break
if allowed
@dropPointQuadTree.insert
x: dropPoint.x
y: dropPoint.y
w: 0
h: 0
acceptLevel: acceptLevel
_droplet_node: head.container
head = head.next
@dragCanvas.style.transform = "translate(#{position.x + getOffsetLeft(@dropletElement)}px,#{position.y + getOffsetTop(@dropletElement)}px)"
# Now we are done with the "clickedX" suite of stuff.
@clickedPoint = @clickedBlock = null
@clickedBlockPaletteEntry = null
@begunTrash = @wouldDelete position
# Redraw the main canvas
@redrawMain()
Editor::getClosestDroppableBlock = (mainPoint, isDebugMode) ->
best = null; min = Infinity
if not (@dropPointQuadTree)
return null
testPoints = @dropPointQuadTree.retrieve {
x: mainPoint.x - MAX_DROP_DISTANCE
y: mainPoint.y - MAX_DROP_DISTANCE
w: MAX_DROP_DISTANCE * 2
h: MAX_DROP_DISTANCE * 2
}, (point) =>
unless (point.acceptLevel is helper.DISCOURAGE) and not isDebugMode
# Find a modified "distance" to the point
# that weights horizontal distance more
distance = mainPoint.from(point)
distance.y *= 2; distance = distance.magnitude()
# Select the node that is closest by said "distance"
if distance < min and mainPoint.from(point).magnitude() < MAX_DROP_DISTANCE and
@session.view.getViewNodeFor(point._droplet_node).highlightArea?
best = point._droplet_node
min = distance
best
Editor::getClosestDroppableBlockFromPosition = (position, isDebugMode) ->
if not @session.currentlyUsingBlocks
return null
mainPoint = @trackerPointToMain(position)
@getClosestDroppableBlock(mainPoint, isDebugMode)
Editor::getAcceptLevel = (drag, drop) ->
if drop.type is 'socket'
if drag.type is 'list'
return helper.FORBID
else
return @session.mode.drop drag.getReader(), drop.getReader(), null, null
# If it's a list/selection, try all of its children
else if drag.type is 'list'
minimum = helper.ENCOURAGE
drag.traverseOneLevel (child) =>
if child instanceof model.Container
minimum = Math.min minimum, @getAcceptLevel child, drop
return minimum
else if drop.type is 'block'
if drop.parent.type is 'socket'
return helper.FORBID
else
next = drop.nextSibling()
return @session.mode.drop drag.getReader(), drop.parent.getReader(), drop.getReader(), next?.getReader?()
else
next = drop.firstChild()
return @session.mode.drop drag.getReader(), drop.getReader(), drop.getReader(), next?.getReader?()
# On mousemove, if there is a dragged block, we want to
# translate the drag canvas into place,
# as well as highlighting any focused drop areas.
hook 'mousemove', 0, (point, event, state) ->
if @draggingBlock?
# Translate the drag canvas into position.
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
# If there is an expansion function, call it again here.
if (@draggingBlock.expansion)
# Call expansion() with the closest droppable block for all drag moves.
expansionText = @draggingBlock.expansion(@getClosestDroppableBlockFromPosition(position, event.shiftKey))
# Create replacement @draggingBlock if the returned text is new.
if expansionText isnt @draggingBlock.lastExpansionText
newBlock = parseBlock(@session.mode, expansionText)
newBlock.lastExpansionText = expansionText
newBlock.expansion = @draggingBlock.expansion
if 'any-drop' in @draggingBlock.classes
newBlock.classes.push 'any-drop'
@draggingBlock = newBlock
@drawDraggingBlock()
if not @session.currentlyUsingBlocks
if @trackerPointIsInAce position
pos = @aceEditor.renderer.screenToTextCoordinates position.x, position.y
if @session.dropIntoAceAtLineStart
pos = @adjustPosToLineStart pos
@aceEditor.focus()
@aceEditor.session.selection.moveToPosition pos
else
@aceEditor.blur()
rect = @wrapperElement.getBoundingClientRect()
@dragCanvas.style.transform = "translate(#{position.x - rect.left}px,#{position.y - rect.top}px)"
mainPoint = @trackerPointToMain(position)
# Check to see if the tree is empty;
# if it is, drop on the tree always
head = @session.tree.start.next
while head.type in ['newline', 'cursor'] or head.type is 'text' and head.value is ''
head = head.next
if head is @session.tree.end and @session.floatingBlocks.length is 0 and
@session.viewports.main.right() > mainPoint.x > @session.viewports.main.x - @gutter.clientWidth and
@session.viewports.main.bottom() > mainPoint.y > @session.viewports.main.y and
@getAcceptLevel(@draggingBlock, @session.tree) is helper.ENCOURAGE
@session.view.getViewNodeFor(@session.tree).highlightArea.update()
@lastHighlight = @session.tree
else
# If the user is touching the original location,
# assume they want to replace the block where they found it.
if @hitTest mainPoint, @draggingBlock
@dragReplacing = true
dropBlock = null
# If the user's block is outside the main pane, delete it
else if not @trackerPointIsInMain position
@dragReplacing = false
dropBlock= null
# Otherwise, find the closest droppable block
else
@dragReplacing = false
dropBlock = @getClosestDroppableBlock(mainPoint, event.shiftKey)
# Update highlight if necessary.
if dropBlock isnt @lastHighlight
# TODO if this becomes a performance issue,
# pull the drop highlights out into a new canvas.
@redrawHighlights()
@lastHighlightPath?.deactivate?()
if dropBlock?
@lastHighlightPath = @session.view.getViewNodeFor(dropBlock).highlightArea
@lastHighlightPath.update()
@qualifiedFocus dropBlock, @lastHighlightPath
@lastHighlight = dropBlock
palettePoint = @trackerPointToPalette position
if @wouldDelete(position)
if @begunTrash
@dragCanvas.style.opacity = 0.85
else
@dragCanvas.style.opacity = 0.3
else
@dragCanvas.style.opacity = 0.85
@begunTrash = false
Editor::qualifiedFocus = (node, path) ->
documentIndex = @documentIndex node
if documentIndex < @session.floatingBlocks.length
path.activate()
@mainCanvas.insertBefore path.element, @session.floatingBlocks[documentIndex].renderGroup.element
else
path.activate()
@mainCanvas.appendChild path.element
hook 'mouseup', 0, ->
clearTimeout @discourageDropTimeout; @discourageDropTimeout = null
hook 'mouseup', 1, (point, event, state) ->
if @dragReplacing
@endDrag()
# We will consume this event iff we dropped it successfully
# in the root tree.
if @draggingBlock?
if not @session.currentlyUsingBlocks
# See if we can drop the block's text in ace mode.
position = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
if @trackerPointIsInAce position
leadingWhitespaceRegex = /^(\s*)/
# Get the line of text we're dropping into
pos = @aceEditor.renderer.screenToTextCoordinates position.x, position.y
line = @aceEditor.session.getLine pos.row
indentation = leadingWhitespaceRegex.exec(line)[0]
skipInitialIndent = true
prefix = ''
suffix = ''
if @session.dropIntoAceAtLineStart
# First, adjust indentation if we're dropping into the start of a
# line that ends an indentation block
firstNonWhitespaceRegex = /\S/
firstChar = firstNonWhitespaceRegex.exec(line)
if firstChar and firstChar[0] == '}'
# If this line starts with a closing bracket, use the previous line's indentation
# TODO: generalize for language indentation semantics besides C/JavaScript
prevLine = @aceEditor.session.getLine(pos.row - 1)
indentation = leadingWhitespaceRegex.exec(prevLine)[0]
# Adjust pos to start of the line (as we did during mousemove)
pos = @adjustPosToLineStart pos
skipInitialIndent = false
if pos.column == 0
suffix = '\n'
else
# Handle the case where we're dropping a block at the end of the last line
prefix = '\n'
else if indentation.length == line.length or indentation.length == pos.column
# line is whitespace only or we're inserting at the beginning of a line
# Append with a newline
suffix = '\n' + indentation
else if pos.column == line.length
# We're at the end of a non-empty line.
# Insert a new line, and base our indentation off of the next line
prefix = '\n'
skipInitialIndent = false
nextLine = @aceEditor.session.getLine(pos.row + 1)
indentation = leadingWhitespaceRegex.exec(nextLine)[0]
# Call prepareNode, which may append with a semicolon
@prepareNode @draggingBlock, null
text = @draggingBlock.stringify @session.mode
# Indent each line, unless it's the first line and wasn't placed on
# a newline
text = text.split('\n').map((line, index) =>
return (if index == 0 and skipInitialIndent then '' else indentation) + line
).join('\n')
text = prefix + text + suffix
@aceEditor.onTextInput text
else if @lastHighlight?
@undoCapture()
# Remove the block from the tree.
rememberedSocketOffsets = @spliceRememberedSocketOffsets(@draggingBlock)
# TODO this is a hacky way of preserving locations
# across parenthesis insertion
hadTextToken = @draggingBlock.start.next.type is 'text'
@spliceOut @draggingBlock
@clearHighlightCanvas()
# Fire an event for a sound
@fireEvent 'sound', [@lastHighlight.type]
# Depending on what the highlighted element is,
# we might want to drop the block at its
# beginning or at its end.
#
# We will need to log undo operations here too.
switch @lastHighlight.type
when 'indent', 'socket'
@spliceIn @draggingBlock, @lastHighlight.start
when 'block'
@spliceIn @draggingBlock, @lastHighlight.end
else
if @lastHighlight.type is 'document'
@spliceIn @draggingBlock, @lastHighlight.start
# TODO as above
hasTextToken = @draggingBlock.start.next.type is 'text'
if hadTextToken and not hasTextToken
rememberedSocketOffsets.forEach (x) ->
x.offset -= 1
else if hasTextToken and not hadTextToken
rememberedSocketOffsets.forEach (x) ->
x.offset += 1
futureCursorLocation = @toCrossDocumentLocation @draggingBlock.start
# Reparse the parent if we are
# in a socket
#
# TODO "reparseable" property (or absent contexts), bubble up
# TODO performance on large programs
if @lastHighlight.type is 'socket'
@reparse @draggingBlock.parent.parent
# Now that we've done that, we can annul stuff.
@endDrag()
@setCursor(futureCursorLocation) if futureCursorLocation?
newBeginning = futureCursorLocation.location.count
newIndex = futureCursorLocation.document
for el, i in rememberedSocketOffsets
@session.rememberedSockets.push new RememberedSocketRecord(
new CrossDocumentLocation(
newIndex
new model.Location(el.offset + newBeginning, 'socket')
),
el.text
)
# Fire the event for sound
@fireEvent 'block-click'
Editor::spliceRememberedSocketOffsets = (block) ->
if block.getDocument()?
blockBegin = block.start.getLocation().count
offsets = []
newRememberedSockets = []
for el, i in @session.rememberedSockets
if block.contains @fromCrossDocumentLocation(el.socket)
offsets.push {
offset: el.socket.location.count - blockBegin
text: el.text
}
else
newRememberedSockets.push el
@session.rememberedSockets = newRememberedSockets
return offsets
else
[]
# FLOATING BLOCK SUPPORT
# ================================
class FloatingBlockRecord
constructor: (@block, @position) ->
Editor::inTree = (block) -> (block.container ? block).getDocument() is @session.tree
Editor::inDisplay = (block) -> (block.container ? block).getDocument() in @getDocuments()
# We can create floating blocks by dropping
# blocks without a highlight.
hook 'mouseup', 0, (point, event, state) ->
if @draggingBlock? and not @lastHighlight? and not @dragReplacing
oldParent = @draggingBlock.parent
# Before we put this block into our list of floating blocks,
# we need to figure out where on the main canvas
# we are going to render it.
trackPoint = new @draw.Point(
point.x + @draggingOffset.x,
point.y + @draggingOffset.y
)
renderPoint = @trackerPointToMain trackPoint
palettePoint = @trackerPointToPalette trackPoint
removeBlock = true
addBlockAsFloatingBlock = true
# If we dropped it off in the palette, abort (so as to delete the block).
unless @session.viewports.main.right() > renderPoint.x > @session.viewports.main.x - @gutter.clientWidth and
@session.viewports.main.bottom() > renderPoint.y > @session.viewports.main.y
if @draggingBlock is @lassoSelection
@lassoSelection = null
addBlockAsFloatingBlock = false
else
if renderPoint.x - @session.viewports.main.x < 0
renderPoint.x = @session.viewports.main.x
# If @session.allowFloatingBlocks is false, we end the drag without deleting the block.
if not @session.allowFloatingBlocks
addBlockAsFloatingBlock = false
removeBlock = false
if removeBlock
# Remove the block from the tree.
@undoCapture()
rememberedSocketOffsets = @spliceRememberedSocketOffsets(@draggingBlock)
@spliceOut @draggingBlock
if not addBlockAsFloatingBlock
@endDrag()
return
else if renderPoint.x - @session.viewports.main.x < 0
renderPoint.x = @session.viewports.main.x
# Add the undo operation associated
# with creating this floating block
newDocument = new model.Document(oldParent?.parseContext ? @session.mode.rootContext, {roundedSingletons: true})
newDocument.insert newDocument.start, @draggingBlock
@pushUndo new FloatingOperation @session.floatingBlocks.length, newDocument, renderPoint, 'create'
# Add this block to our list of floating blocks
@session.floatingBlocks.push record = new FloatingBlockRecord(
newDocument
renderPoint
)
@initializeFloatingBlock record, @session.floatingBlocks.length - 1
@setCursor @draggingBlock.start
# TODO write a test for this logic
for el, i in rememberedSocketOffsets
@session.rememberedSockets.push new RememberedSocketRecord(
new CrossDocumentLocation(
@session.floatingBlocks.length,
new model.Location(el.offset + 1, 'socket')
),
el.text
)
# Now that we've done that, we can annul stuff.
@clearDrag()
@draggingBlock = null
@draggingOffset = null
@lastHighlightPath?.destroy?()
@lastHighlight = @lastHighlightPath = null
@redrawMain()
Editor::performFloatingOperation = (op, direction) ->
if (op.type is 'create') is (direction is 'forward')
if @session.cursor.document > op.index
@session.cursor.document += 1
for socket in @session.rememberedSockets
if socket.socket.document > op.index
socket.socket.document += 1
@session.floatingBlocks.splice op.index, 0, record = new FloatingBlockRecord(
op.block.clone()
op.position
)
@initializeFloatingBlock record, op.index
else
# If the cursor's document is about to vanish,
# put it back in the main tree.
if @session.cursor.document is op.index + 1
@setCursor @session.tree.start
for socket in @session.rememberedSockets
if socket.socket.document > op.index + 1
socket.socket.document -= 1
@session.floatingBlocks.splice op.index, 1
class FloatingOperation
constructor: (@index, @block, @position, @type) ->
@block = @block.clone()
toString: -> JSON.stringify({
index: @index
block: @block.stringify()
position: @position.toString()
type: @type
})
# PALETTE SUPPORT
# ================================
# The first thing we will have to do with
# the palette is install the hierarchical menu.
#
# This happens at population time.
hook 'populate', 0, ->
# Create the hierarchical menu element.
@paletteHeader = document.createElement 'div'
@paletteHeader.className = 'droplet-palette-header'
# Append the element.
@paletteElement.appendChild @paletteHeader
if @session?
@setPalette @session.paletteGroups
parseBlock = (mode, code, context = null) =>
block = mode.parse(code, {context}).start.next.container
block.start.prev = block.end.next = null
block.setParent null
return block
Editor::setPalette = (paletteGroups) ->
@paletteHeader.innerHTML = ''
@session.paletteGroups = paletteGroups
@session.currentPaletteBlocks = []
@session.currentPaletteMetadata = []
paletteHeaderRow = null
for paletteGroup, i in @session.paletteGroups then do (paletteGroup, i) =>
# Start a new row, if we're at that point
# in our appending cycle
if i % 2 is 0
paletteHeaderRow = document.createElement 'div'
paletteHeaderRow.className = 'droplet-palette-header-row'
@paletteHeader.appendChild paletteHeaderRow
# hide the header if there is only one group, and it has no name.
if @session.paletteGroups.length is 1 and !paletteGroup.name
paletteHeaderRow.style.height = 0
# Create the element itself
paletteGroupHeader = paletteGroup.header = document.createElement 'div'
paletteGroupHeader.className = 'droplet-palette-group-header'
if paletteGroup.id
paletteGroupHeader.id = 'droplet-palette-group-header-' + paletteGroup.id
paletteGroupHeader.innerText = paletteGroupHeader.textContent = paletteGroupHeader.textContent = paletteGroup.name # innerText and textContent for FF compatability
if paletteGroup.color
paletteGroupHeader.className += ' ' + paletteGroup.color
paletteHeaderRow.appendChild paletteGroupHeader
newPaletteBlocks = []
# Parse all the blocks in this palette and clone them
for data in paletteGroup.blocks
newBlock = parseBlock(@session.mode, data.block, data.context)
expansion = data.expansion or null
newPaletteBlocks.push
block: newBlock
expansion: expansion
context: data.context
title: data.title
id: data.id
paletteGroup.parsedBlocks = newPaletteBlocks
# When we click this element,
# we should switch to it in the palette.
updatePalette = =>
@changePaletteGroup paletteGroup
clickHandler = =>
do updatePalette
paletteGroupHeader.addEventListener 'click', clickHandler
paletteGroupHeader.addEventListener 'touchstart', clickHandler
# If we are the first element, make us the selected palette group.
if i is 0
do updatePalette
@resizePalette()
@resizePaletteHighlight()
# Change which palette group is selected.
# group argument can be object, id (string), or name (string)
#
Editor::changePaletteGroup = (group) ->
for curGroup, i in @session.paletteGroups
if group is curGroup or group is curGroup.id or group is curGroup.name
paletteGroup = curGroup
break
if not paletteGroup
return
# Record that we are the selected group now
@session.currentPaletteGroup = paletteGroup.name
@session.currentPaletteBlocks = paletteGroup.parsedBlocks
@session.currentPaletteMetadata = paletteGroup.parsedBlocks
# Unapply the "selected" style to the current palette group header
@session.currentPaletteGroupHeader?.className =
@session.currentPaletteGroupHeader.className.replace(
/\s[-\w]*-selected\b/, '')
# Now we are the current palette group header
@session.currentPaletteGroupHeader = paletteGroup.header
@currentPaletteIndex = i
# Apply the "selected" style to us
@session.currentPaletteGroupHeader.className +=
' droplet-palette-group-header-selected'
# Redraw the palette.
@rebuildPalette()
@fireEvent 'selectpalette', [paletteGroup.name]
# The next thing we need to do with the palette
# is let people pick things up from it.
hook 'mousedown', 6, (point, event, state) ->
# If someone else has already taken this click, pass.
if state.consumedHitTest then return
# If it's not in the palette pane, pass.
if not @trackerPointIsInPalette(point) then return
palettePoint = @trackerPointToPalette point
if @session.viewports.palette.contains(palettePoint)
if @handleTextInputClickInPalette palettePoint
state.consumedHitTest = true
return
for entry in @session.currentPaletteBlocks
hitTestResult = @hitTest palettePoint, entry.block, @session.paletteView
if hitTestResult?
@clickedBlock = entry.block
@clickedPoint = point
@clickedBlockPaletteEntry = entry
state.consumedHitTest = true
@fireEvent 'pickblock', [entry.id]
return
@clickedBlockPaletteEntry = null
# PALETTE HIGHLIGHT CODE
# ================================
hook 'populate', 1, ->
@paletteHighlightCanvas = @paletteHighlightCtx = document.createElementNS SVG_STANDARD, 'svg'
@paletteHighlightCanvas.setAttribute 'class', 'droplet-palette-highlight-canvas'
@paletteHighlightPath = null
@currentHighlightedPaletteBlock = null
@paletteElement.appendChild @paletteHighlightCanvas
Editor::resizePaletteHighlight = ->
@paletteHighlightCanvas.style.top = @paletteHeader.clientHeight + 'px'
@paletteHighlightCanvas.style.width = "#{@paletteCanvas.clientWidth}px"
@paletteHighlightCanvas.style.height = "#{@paletteCanvas.clientHeight}px"
hook 'redraw_palette', 0, ->
@clearPaletteHighlightCanvas()
if @currentHighlightedPaletteBlock?
@paletteHighlightPath.update()
# TEXT INPUT SUPPORT
# ================================
# At populate-time, we need
# to create and append the hidden input
# we will use for text input.
hook 'populate', 1, ->
@hiddenInput = document.createElement 'textarea'
@hiddenInput.className = 'droplet-hidden-input'
@hiddenInput.addEventListener 'focus', =>
if @cursorAtSocket()
# Must ensure that @hiddenInput is within the client area
# or else the other divs under @dropletElement will scroll out of
# position when @hiddenInput receives keystrokes with focus
# (left and top should not be closer than 10 pixels from the edge)
bounds = @session.view.getViewNodeFor(@getCursor()).bounds[0]
###
inputLeft = bounds.x + @mainCanvas.offsetLeft - @session.viewports.main.x
inputLeft = Math.min inputLeft, @dropletElement.clientWidth - 10
inputLeft = Math.max @mainCanvas.offsetLeft, inputLeft
@hiddenInput.style.left = inputLeft + 'px'
inputTop = bounds.y - @session.viewports.main.y
inputTop = Math.min inputTop, @dropletElement.clientHeight - 10
inputTop = Math.max 0, inputTop
@hiddenInput.style.top = inputTop + 'px'
###
@dropletElement.appendChild @hiddenInput
# We also need to initialise some fields
# for knowing what is focused
@textInputAnchor = null
@textInputSelecting = false
@oldFocusValue = null
# Prevent kids from deleting a necessary quote accidentally
@hiddenInput.addEventListener 'keydown', (event) =>
if event.keyCode is 8 and @hiddenInput.value.length > 1 and
@hiddenInput.value[0] is @hiddenInput.value[@hiddenInput.value.length - 1] and
@hiddenInput.value[0] in ['\'', '\"'] and @hiddenInput.selectionEnd is 1
event.preventDefault()
# The hidden input should be set up
# to mirror the text to which it is associated.
for event in ['input', 'keyup', 'keydown', 'select']
@hiddenInput.addEventListener event, =>
@highlightFlashShow()
if @cursorAtSocket()
@redrawTextInput()
# Update the dropdown size to match
# the new length, if it is visible.
if @dropdownVisible
@formatDropdown()
Editor::resizeAceElement = ->
width = @wrapperElement.clientWidth
if @session?.showPaletteInTextMode and @session?.paletteEnabled
width -= @paletteWrapper.clientWidth
@aceElement.style.width = "#{width}px"
@aceElement.style.height = "#{@wrapperElement.clientHeight}px"
last_ = (array) -> array[array.length - 1]
# Redraw function for text input
Editor::redrawTextInput = ->
return unless @session?
sameLength = @getCursor().stringify().split('\n').length is @hiddenInput.value.split('\n').length
dropletDocument = @getCursor().getDocument()
# Set the value in the model to fit
# the hidden input value.
@populateSocket @getCursor(), @hiddenInput.value
textFocusView = @session.view.getViewNodeFor @getCursor()
# Determine the coordinate positions
# of the typing cursor
startRow = @getCursor().stringify()[...@hiddenInput.selectionStart].split('\n').length - 1
endRow = @getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n').length - 1
# Redraw the main canvas, on top of
# which we will draw the cursor and
# highlights.
if sameLength and startRow is endRow
line = endRow
head = @getCursor().start
until head is dropletDocument.start
head = head.prev
if head.type is 'newline' then line++
treeView = @session.view.getViewNodeFor dropletDocument
oldp = helper.deepCopy [
treeView.glue[line - 1],
treeView.glue[line],
treeView.bounds[line].height
]
treeView.layout()
newp = helper.deepCopy [
treeView.glue[line - 1],
treeView.glue[line],
treeView.bounds[line].height
]
# If the layout has not changed enough to affect
# anything non-local, only redraw locally.
@redrawMain()
###
if helper.deepEquals newp, oldp
rect = new @draw.NoRectangle()
rect.unite treeView.bounds[line - 1] if line > 0
rect.unite treeView.bounds[line]
rect.unite treeView.bounds[line + 1] if line + 1 < treeView.bounds.length
rect.width = Math.max rect.width, @mainCanvas.clientWidth
@redrawMain
boundingRectangle: rect
else @redrawMain()
###
# Otherwise, redraw the whole thing
else
@redrawMain()
Editor::redrawTextHighlights = (scrollIntoView = false) ->
@clearHighlightCanvas()
return unless @session?
return unless @cursorAtSocket()
textFocusView = @session.view.getViewNodeFor @getCursor()
# Determine the coordinate positions
# of the typing cursor
startRow = @getCursor().stringify()[...@hiddenInput.selectionStart].split('\n').length - 1
endRow = @getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n').length - 1
lines = @getCursor().stringify().split '\n'
startPosition = textFocusView.bounds[startRow].x + @session.view.opts.textPadding +
@session.fontWidth * last_(@getCursor().stringify()[...@hiddenInput.selectionStart].split('\n')).length +
(if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)
endPosition = textFocusView.bounds[endRow].x + @session.view.opts.textPadding +
@session.fontWidth * last_(@getCursor().stringify()[...@hiddenInput.selectionEnd].split('\n')).length +
(if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)
# Now draw the highlight/typing cursor
#
# Draw a line if it is just a cursor
if @hiddenInput.selectionStart is @hiddenInput.selectionEnd
@qualifiedFocus @getCursor(), @textCursorPath
points = [
new @session.view.draw.Point(startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding),
new @session.view.draw.Point(startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding + @session.view.opts.textHeight)
]
@textCursorPath.setPoints points
@textCursorPath.style.strokeColor = '#000'
@textCursorPath.update()
@qualifiedFocus @getCursor(), @textCursorPath
@textInputHighlighted = false
# Draw a translucent rectangle if there is a selection.
else
@textInputHighlighted = true
# TODO maybe put this in the view?
rectangles = []
if startRow is endRow
rectangles.push new @session.view.draw.Rectangle startPosition,
textFocusView.bounds[startRow].y + @session.view.opts.textPadding
endPosition - startPosition, @session.view.opts.textHeight
else
rectangles.push new @session.view.draw.Rectangle startPosition, textFocusView.bounds[startRow].y + @session.view.opts.textPadding,
textFocusView.bounds[startRow].right() - @session.view.opts.textPadding - startPosition, @session.view.opts.textHeight
for i in [startRow + 1...endRow]
rectangles.push new @session.view.draw.Rectangle textFocusView.bounds[i].x,
textFocusView.bounds[i].y + @session.view.opts.textPadding,
textFocusView.bounds[i].width,
@session.view.opts.textHeight
rectangles.push new @session.view.draw.Rectangle textFocusView.bounds[endRow].x,
textFocusView.bounds[endRow].y + @session.view.opts.textPadding,
endPosition - textFocusView.bounds[endRow].x,
@session.view.opts.textHeight
left = []; right = []
for el, i in rectangles
left.push new @session.view.draw.Point el.x, el.y
left.push new @session.view.draw.Point el.x, el.bottom()
right.push new @session.view.draw.Point el.right(), el.y
right.push new @session.view.draw.Point el.right(), el.bottom()
@textCursorPath.setPoints left.concat right.reverse()
@textCursorPath.style.strokeColor = 'none'
@textCursorPath.update()
@qualifiedFocus @getCursor(), @textCursorPath
if scrollIntoView and endPosition > @session.viewports.main.x + @mainCanvas.clientWidth
@mainScroller.scrollLeft = endPosition - @mainCanvas.clientWidth + @session.view.opts.padding
escapeString = (str) ->
str[0] + str[1...-1].replace(/(\'|\"|\n)/g, '\\$1') + str[str.length - 1]
hook 'mousedown', 7, ->
@hideDropdown()
# If we can, try to reparse the focus
# value.
#
# When reparsing occurs, we first try to treat the socket
# as a separate block (inserting parentheses, etc), then fall
# back on reparsing it with original text before giving up.
#
# For instance:
#
# (a * b)
# -> edits [b] to [b + c]
# -> reparse to b + c
# -> inserts with parens to (a * (b + c))
# -> finished.
#
# OR
#
# function (a) {}
# -> edits [a] to [a, b]
# -> reparse to a, b
# -> inserts with parens to function((a, b)) {}
# -> FAILS.
# -> Fall back to raw reparsing the parent with unparenthesized text
# -> Reparses function(a, b) {} with two paremeters.
# -> Finsihed.
Editor::reparse = (list, recovery, updates = [], originalTrigger = list) ->
# Don't reparse sockets. When we reparse sockets,
# reparse them first, then try reparsing their parent and
# make sure everything checks out.
if list.start.type is 'socketStart'
return if list.start.next is list.end
originalText = list.textContent()
originalUpdates = updates.map (location) ->
count: location.count, type: location.type
# If our language mode has a string-fixing feature (in most languages,
# this will simply autoescape quoted "strings"), apply it
if @session.mode.stringFixer?
@populateSocket list, @session.mode.stringFixer list.textContent()
# Try reparsing the parent after beforetextfocus. If it fails,
# repopulate with the original text and try again.
unless @reparse list.parent, recovery, updates, originalTrigger
@populateSocket list, originalText
originalUpdates.forEach (location, i) ->
updates[i].count = location.count
updates[i].type = location.type
@reparse list.parent, recovery, updates, originalTrigger
return
parent = list.start.parent
if parent?.type is 'indent' and not list.start.container?.parseContext?
context = parent.parseContext
else
context = (list.start.container ? list.start.parent).parseContext
try
newList = @session.mode.parse list.stringifyInPlace(),{
wrapAtRoot: parent.type isnt 'socket'
context: context
}
catch e
try
newList = @session.mode.parse recovery(list.stringifyInPlace()), {
wrapAtRoot: parent.type isnt 'socket'
context: context
}
catch e
# Seek a parent that is not a socket
# (since we should never reparse just a socket)
while parent? and parent.type is 'socket'
parent = parent.parent
# Attempt to bubble up to the parent
if parent?
return @reparse parent, recovery, updates, originalTrigger
else
@session.view.getViewNodeFor(originalTrigger).mark {color: '#F00'}
return false
return if newList.start.next is newList.end
# Exclude the document start and end tags
newList = new model.List newList.start.next, newList.end.prev
# Prepare the new node for insertion
newList.traverseOneLevel (head) =>
@prepareNode head, parent
@replace list, newList, updates
@redrawMain()
return true
Editor::setTextSelectionRange = (selectionStart, selectionEnd) ->
if selectionStart? and not selectionEnd?
selectionEnd = selectionStart
# Focus the hidden input.
if @cursorAtSocket()
@hiddenInput.focus()
if selectionStart? and selectionEnd?
@hiddenInput.setSelectionRange selectionStart, selectionEnd
else if @hiddenInput.value[0] is @hiddenInput.value[@hiddenInput.value.length - 1] and
@hiddenInput.value[0] in ['\'', '"']
@hiddenInput.setSelectionRange 1, @hiddenInput.value.length - 1
else
@hiddenInput.setSelectionRange 0, @hiddenInput.value.length
@redrawTextInput()
# Redraw.
@redrawMain(); @redrawTextInput()
Editor::cursorAtSocket = -> @getCursor().type is 'socket'
Editor::populateSocket = (socket, string) ->
unless socket.textContent() is string
lines = string.split '\n'
unless socket.start.next is socket.end
@spliceOut new model.List socket.start.next, socket.end.prev
first = last = new model.TextToken lines[0]
for line, i in lines when i > 0
last = helper.connect last, new model.NewlineToken()
last = helper.connect last, new model.TextToken line
@spliceIn (new model.List(first, last)), socket.start
Editor::populateBlock = (block, string) ->
newBlock = @session.mode.parse(string, wrapAtRoot: false).start.next.container
if newBlock
# Find the first token before the block
# that will still be around after the
# block has been removed
position = block.start.prev
while position?.type is 'newline' and not (
position.prev?.type is 'indentStart' and
position.prev.container.end is block.end.next)
position = position.prev
@spliceOut block
@spliceIn newBlock, position
return true
return false
# Convenience hit-testing function
Editor::hitTestTextInput = (point, block) ->
head = block.start
while head?
if head.type is 'socketStart' and head.container.isDroppable() and
@session.view.getViewNodeFor(head.container).path.contains point
return head.container
head = head.next
return null
# Convenience functions for setting
# the text input selection, given
# points on the main canvas.
Editor::getTextPosition = (point) ->
textFocusView = @session.view.getViewNodeFor @getCursor()
row = Math.floor((point.y - textFocusView.bounds[0].y) / (@session.fontSize + 2 * @session.view.opts.padding))
row = Math.max row, 0
row = Math.min row, textFocusView.lineLength - 1
column = Math.max 0, Math.round((point.x - textFocusView.bounds[row].x - @session.view.opts.textPadding - (if @getCursor().hasDropdown() then helper.DROPDOWN_ARROW_WIDTH else 0)) / @session.fontWidth)
lines = @getCursor().stringify().split('\n')[..row]
lines[lines.length - 1] = lines[lines.length - 1][...column]
return lines.join('\n').length
Editor::setTextInputAnchor = (point) ->
@textInputAnchor = @textInputHead = @getTextPosition point
@hiddenInput.setSelectionRange @textInputAnchor, @textInputHead
Editor::selectDoubleClick = (point) ->
position = @getTextPosition point
before = @getCursor().stringify()[...position].match(/\w*$/)[0]?.length ? 0
after = @getCursor().stringify()[position..].match(/^\w*/)[0]?.length ? 0
@textInputAnchor = position - before
@textInputHead = position + after
@hiddenInput.setSelectionRange @textInputAnchor, @textInputHead
Editor::setTextInputHead = (point) ->
@textInputHead = @getTextPosition point
@hiddenInput.setSelectionRange Math.min(@textInputAnchor, @textInputHead), Math.max(@textInputAnchor, @textInputHead)
# On mousedown, we will want to start
# selections and focus text inputs
# if we apply.
Editor::handleTextInputClick = (mainPoint, dropletDocument) ->
hitTestResult = @hitTestTextInput mainPoint, dropletDocument
# If they have clicked a socket,
# focus it.
if hitTestResult?
unless hitTestResult is @getCursor()
if hitTestResult.editable()
@undoCapture()
@setCursor hitTestResult
@redrawMain()
if hitTestResult.hasDropdown() and ((not hitTestResult.editable()) or
mainPoint.x - @session.view.getViewNodeFor(hitTestResult).bounds[0].x < helper.DROPDOWN_ARROW_WIDTH)
@showDropdown hitTestResult
@textInputSelecting = false
else
if @getCursor().hasDropdown() and
mainPoint.x - @session.view.getViewNodeFor(hitTestResult).bounds[0].x < helper.DROPDOWN_ARROW_WIDTH
@showDropdown()
@setTextInputAnchor mainPoint
@redrawTextInput()
@textInputSelecting = true
# Now that we have focused the text element
# in the Droplet model, focus the hidden input.
#
# It is important that this be done after the Droplet model
# has focused its text element, because
# the hidden input moves on the focus() event to
# the currently-focused Droplet element to make
# mobile screen scroll properly.
@hiddenInput.focus()
return true
else
return false
# Convenience hit-testing function
Editor::hitTestTextInputInPalette = (point, block) ->
head = block.start
while head?
if head.type is 'socketStart' and head.container.isDroppable() and
@session.paletteView.getViewNodeFor(head.container).path.contains point
return head.container
head = head.next
return null
Editor::handleTextInputClickInPalette = (palettePoint) ->
for entry in @session.currentPaletteBlocks
hitTestResult = @hitTestTextInputInPalette palettePoint, entry.block
# If they have clicked a socket, check to see if it is a dropdown
if hitTestResult?
if hitTestResult.hasDropdown()
@showDropdown hitTestResult, true
return true
return false
# Create the dropdown DOM element at populate time.
hook 'populate', 0, ->
@dropdownElement = document.createElement 'div'
@dropdownElement.className = 'droplet-dropdown'
@wrapperElement.appendChild @dropdownElement
@dropdownElement.innerHTML = ''
@dropdownElement.style.display = 'inline-block'
@dropdownVisible = false
# Update the dropdown to match
# the current text focus font and size.
Editor::formatDropdown = (socket = @getCursor(), view = @session.view) ->
@dropdownElement.style.fontFamily = @session.fontFamily
@dropdownElement.style.fontSize = @session.fontSize
@dropdownElement.style.minWidth = view.getViewNodeFor(socket).bounds[0].width
Editor::getDropdownList = (socket) ->
result = socket.dropdown
if result.generate
result = result.generate
if 'function' is typeof result
result = socket.dropdown()
else
result = socket.dropdown
if result.options
result = result.options
newresult = []
for key, val of result
newresult.push if 'string' is typeof val then { text: val, display: val } else val
return newresult
Editor::showDropdown = (socket = @getCursor(), inPalette = false) ->
@dropdownVisible = true
dropdownItems = []
@dropdownElement.innerHTML = ''
@dropdownElement.style.display = 'inline-block'
@formatDropdown socket, if inPalette then @session.paletteView else @session.view
for el, i in @getDropdownList(socket) then do (el) =>
div = document.createElement 'div'
div.innerHTML = el.display
div.className = 'droplet-dropdown-item'
dropdownItems.push div
div.style.paddingLeft = helper.DROPDOWN_ARROW_WIDTH
setText = (text) =>
@undoCapture()
# Attempting to populate the socket after the dropdown has closed should no-op
if @dropdownElement.style.display == 'none'
return
if inPalette
@populateSocket socket, text
@redrawPalette()
else if not socket.editable()
@populateSocket socket, text
@redrawMain()
else
if not @cursorAtSocket()
return
@populateSocket @getCursor(), text
@hiddenInput.value = text
@redrawMain()
@hideDropdown()
div.addEventListener 'mouseup', ->
if el.click
el.click(setText)
else
setText(el.text)
@dropdownElement.appendChild div
@dropdownElement.style.top = '-9999px'
@dropdownElement.style.left = '-9999px'
# Wait for a render. Then,
# if the div is scrolled vertically, add
# some padding on the right. After checking for this,
# move the dropdown element into position
setTimeout (=>
if @dropdownElement.clientHeight < @dropdownElement.scrollHeight
for el in dropdownItems
el.style.paddingRight = DROPDOWN_SCROLLBAR_PADDING
if inPalette
location = @session.paletteView.getViewNodeFor(socket).bounds[0]
@dropdownElement.style.left = location.x - @session.viewports.palette.x + @paletteCanvas.clientLeft + 'px'
@dropdownElement.style.minWidth = location.width + 'px'
dropdownTop = location.y + @session.fontSize - @session.viewports.palette.y + @paletteCanvas.clientTop
if dropdownTop + @dropdownElement.clientHeight > @paletteElement.clientHeight
dropdownTop -= (@session.fontSize + @dropdownElement.clientHeight)
@dropdownElement.style.top = dropdownTop + 'px'
else
location = @session.view.getViewNodeFor(socket).bounds[0]
@dropdownElement.style.left = location.x - @session.viewports.main.x + @dropletElement.offsetLeft + @gutter.clientWidth + 'px'
@dropdownElement.style.minWidth = location.width + 'px'
dropdownTop = location.y + @session.fontSize - @session.viewports.main.y
if dropdownTop + @dropdownElement.clientHeight > @dropletElement.clientHeight
dropdownTop -= (@session.fontSize + @dropdownElement.clientHeight)
@dropdownElement.style.top = dropdownTop + 'px'
), 0
Editor::hideDropdown = ->
@dropdownVisible = false
@dropdownElement.style.display = 'none'
@dropletElement.focus()
hook 'dblclick', 0, (point, event, state) ->
# If someone else already took this click, return.
if state.consumedHitTest then return
for dropletDocument in @getDocuments()
# Otherwise, look for a socket that
# the user has clicked
mainPoint = @trackerPointToMain point
hitTestResult = @hitTestTextInput mainPoint, @session.tree
# If they have clicked a socket,
# focus it, and
unless hitTestResult is @getCursor()
if hitTestResult? and hitTestResult.editable()
@redrawMain()
hitTestResult = @hitTestTextInput mainPoint, @session.tree
if hitTestResult? and hitTestResult.editable()
@setCursor hitTestResult
@redrawMain()
setTimeout (=>
@selectDoubleClick mainPoint
@redrawTextInput()
@textInputSelecting = false
), 0
state.consumedHitTest = true
return
# On mousemove, if we are selecting,
# we want to update the selection
# to match the mouse.
hook 'mousemove', 0, (point, event, state) ->
if @textInputSelecting
unless @cursorAtSocket()
@textInputSelecting = false; return
mainPoint = @trackerPointToMain point
@setTextInputHead mainPoint
@redrawTextInput()
# On mouseup, we want to stop selecting.
hook 'mouseup', 0, (point, event, state) ->
if @textInputSelecting
mainPoint = @trackerPointToMain point
@setTextInputHead mainPoint
@redrawTextInput()
@textInputSelecting = false
# LASSO SELECT SUPPORT
# ===============================
# The lasso select
# will have its own canvas
# for drawing the lasso. This needs
# to be added at populate-time, along
# with some fields.
hook 'populate', 0, ->
@lassoSelectRect = document.createElementNS SVG_STANDARD, 'rect'
@lassoSelectRect.setAttribute 'stroke', '#00f'
@lassoSelectRect.setAttribute 'fill', 'none'
@lassoSelectAnchor = null
@lassoSelection = null
@mainCanvas.appendChild @lassoSelectRect
Editor::clearLassoSelection = ->
@lassoSelection = null
@redrawHighlights()
# On mousedown, if nobody has taken
# a hit test yet, start a lasso select.
hook 'mousedown', 0, (point, event, state) ->
# Even if someone has taken it, we
# should remove the lasso segment that is
# already there.
unless state.clickedLassoSelection then @clearLassoSelection()
if state.consumedHitTest or state.suppressLassoSelect then return
# If it's not in the main pane, pass.
if not @trackerPointIsInMain(point) then return
if @trackerPointIsInPalette(point) then return
# If the point was actually in the main canvas,
# start a lasso select.
mainPoint = @trackerPointToMain(point).from @session.viewports.main
palettePoint = @trackerPointToPalette(point).from @session.viewports.palette
@lassoSelectAnchor = @trackerPointToMain point
# On mousemove, if we are in the middle of a
# lasso select, continue with it.
hook 'mousemove', 0, (point, event, state) ->
if @lassoSelectAnchor?
mainPoint = @trackerPointToMain point
lassoRectangle = new @draw.Rectangle(
Math.min(@lassoSelectAnchor.x, mainPoint.x),
Math.min(@lassoSelectAnchor.y, mainPoint.y),
Math.abs(@lassoSelectAnchor.x - mainPoint.x),
Math.abs(@lassoSelectAnchor.y - mainPoint.y)
)
findLassoSelect = (dropletDocument) =>
first = dropletDocument.start
until (not first?) or first.type is 'blockStart' and @session.view.getViewNodeFor(first.container).path.intersects lassoRectangle
first = first.next
last = dropletDocument.end
until (not last?) or last.type is 'blockEnd' and @session.view.getViewNodeFor(last.container).path.intersects lassoRectangle
last = last.prev
@clearHighlightCanvas()
@mainCanvas.appendChild @lassoSelectRect
@lassoSelectRect.style.display = 'block'
@lassoSelectRect.setAttribute 'x', lassoRectangle.x
@lassoSelectRect.setAttribute 'y', lassoRectangle.y
@lassoSelectRect.setAttribute 'width', lassoRectangle.width
@lassoSelectRect.setAttribute 'height', lassoRectangle.height
if first and last?
[first, last] = validateLassoSelection dropletDocument, first, last
@lassoSelection = new model.List first, last
@redrawLassoHighlight()
return true
else
@lassoSelection = null
@redrawLassoHighlight()
return false
unless @lassoSelectionDocument? and findLassoSelect @lassoSelectionDocument
for dropletDocument in @getDocuments()
if findLassoSelect dropletDocument
@lassoSelectionDocument = dropletDocument
break
Editor::redrawLassoHighlight = ->
return unless @session?
# Remove any existing selections
for dropletDocument in @getDocuments()
dropletDocumentView = @session.view.getViewNodeFor dropletDocument
dropletDocumentView.draw @session.viewports.main, {
selected: false
noText: @currentlyAnimating # TODO add some modularized way of having global view options
}
if @lassoSelection?
# Add any new selections
lassoView = @session.view.getViewNodeFor(@lassoSelection)
lassoView.absorbCache()
lassoView.draw @session.viewports.main, {selected: true}
# Convnience function for validating
# a lasso selection. A lasso selection
# cannot contain start tokens without
# their corresponding end tokens, or vice
# versa, and also must start and end
# with blocks (not Indents).
validateLassoSelection = (tree, first, last) ->
tokensToInclude = []
head = first
until head is last.next
if head instanceof model.StartToken or
head instanceof model.EndToken
tokensToInclude.push head.container.start
tokensToInclude.push head.container.end
head = head.next
first = tree.start
until first in tokensToInclude then first = first.next
last = tree.end
until last in tokensToInclude then last = last.prev
until first.type is 'blockStart'
first = first.prev
if first.type is 'blockEnd' then first = first.container.start.prev
until last.type is 'blockEnd'
last = last.next
if last.type is 'blockStart' then last = last.container.end.next
return [first, last]
# On mouseup, if we were
# doing a lasso select, insert a lasso
# select segment.
hook 'mouseup', 0, (point, event, state) ->
if @lassoSelectAnchor?
if @lassoSelection?
# Move the cursor to the selection
@setCursor @lassoSelection.end
@lassoSelectAnchor = null
@lassoSelectRect.style.display = 'none'
@redrawHighlights()
@lassoSelectionDocument = null
# On mousedown, we might want to
# pick a selected segment up; check.
hook 'mousedown', 3, (point, event, state) ->
if state.consumedHitTest then return
if @lassoSelection? and @hitTest(@trackerPointToMain(point), @lassoSelection)?
@clickedBlock = @lassoSelection
@clickedBlockPaletteEntry = null
@clickedPoint = point
state.consumedHitTest = true
state.clickedLassoSelection = true
# CURSOR OPERATION SUPPORT
# ================================
class CrossDocumentLocation
constructor: (@document, @location) ->
is: (other) -> @location.is(other.location) and @document is other.document
clone: ->
new CrossDocumentLocation(
@document,
@location.clone()
)
Editor::validCursorPosition = (destination) ->
return destination.type in ['documentStart', 'indentStart'] or
destination.type is 'blockEnd' and destination.parent.type in ['document', 'indent'] or
destination.type is 'socketStart' and destination.container.editable()
# A cursor is only allowed to be on a line.
Editor::setCursor = (destination, validate = (-> true), direction = 'after') ->
if destination? and destination instanceof CrossDocumentLocation
destination = @fromCrossDocumentLocation(destination)
# Abort if there is no destination (usually means
# someone wants to travel outside the document)
return unless destination? and @inDisplay destination
# Now set the new cursor
if destination instanceof model.Container
destination = destination.start
until @validCursorPosition(destination) and validate(destination)
destination = (if direction is 'after' then destination.next else destination.prev)
return unless destination?
destination = @toCrossDocumentLocation destination
# If the cursor was at a text input, reparse the old one
if @cursorAtSocket() and not @session.cursor.is(destination)
socket = @getCursor()
if '__comment__' not in socket.classes
@reparse socket, null, (if destination.document is @session.cursor.document then [destination.location] else [])
@hiddenInput.blur()
@dropletElement.focus()
@session.cursor = destination
# If we have messed up (usually because
# of a reparse), scramble to find a nearby
# okay place for the cursor
@correctCursor()
@redrawMain()
@highlightFlashShow()
# If we are now at a text input, populate the hidden input
if @cursorAtSocket()
if @getCursor()?.id of @session.extraMarks
delete @session.extraMarks[focus?.id]
@undoCapture()
@hiddenInput.value = @getCursor().textContent()
@hiddenInput.focus()
{start, end} = @session.mode.getDefaultSelectionRange @hiddenInput.value
@setTextSelectionRange start, end
Editor::determineCursorPosition = ->
# Do enough of the redraw to get the bounds
@session.view.getViewNodeFor(@session.tree).layout 0, @nubbyHeight
# Get a cursor that is in the model
cursor = @getCursor()
if cursor.type is 'documentStart'
bound = @session.view.getViewNodeFor(cursor.container).bounds[0]
return new @draw.Point bound.x, bound.y
else if cursor.type is 'indentStart'
line = if cursor.next.type is 'newline' then 1 else 0
bound = @session.view.getViewNodeFor(cursor.container).bounds[line]
return new @draw.Point bound.x, bound.y
else
line = @getCursor().getTextLocation().row - cursor.parent.getTextLocation().row
bound = @session.view.getViewNodeFor(cursor.parent).bounds[line]
return new @draw.Point bound.x, bound.bottom()
Editor::getCursor = ->
cursor = @fromCrossDocumentLocation @session.cursor
if cursor.type is 'socketStart'
return cursor.container
else
return cursor
Editor::scrollCursorIntoPosition = ->
axis = @determineCursorPosition().y
if axis < @session.viewports.main.y
@mainScroller.scrollTop = axis
else if axis > @session.viewports.main.bottom()
@mainScroller.scrollTop = axis - @session.viewports.main.height
@mainScroller.scrollLeft = 0
# Moves the cursor to the end of the document and scrolls it into position
# (in block and text mode)
Editor::scrollCursorToEndOfDocument = ->
if @session.currentlyUsingBlocks
pos = @session.tree.end
while pos && !@validCursorPosition(pos)
pos = pos.prev
@setCursor(pos)
@scrollCursorIntoPosition()
else
@aceEditor.scrollToLine @aceEditor.session.getLength()
# Pressing the up-arrow moves the cursor up.
hook 'keydown', 0, (event, state) ->
if event.which is UP_ARROW_KEY
@clearLassoSelection()
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, ((token) -> token.type isnt 'socketStart'), 'before'
@scrollCursorIntoPosition()
else if event.which is DOWN_ARROW_KEY
@clearLassoSelection()
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, ((token) -> token.type isnt 'socketStart'), 'after'
@scrollCursorIntoPosition()
else if event.which is RIGHT_ARROW_KEY and
(not @cursorAtSocket() or
@hiddenInput.selectionStart is @hiddenInput.value.length)
@clearLassoSelection()
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, null, 'after'
@scrollCursorIntoPosition()
event.preventDefault()
else if event.which is LEFT_ARROW_KEY and
(not @cursorAtSocket() or
@hiddenInput.selectionEnd is 0)
@clearLassoSelection()
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, null, 'before'
@scrollCursorIntoPosition()
event.preventDefault()
hook 'keydown', 0, (event, state) ->
if event.which isnt TAB_KEY then return
if event.shiftKey
prev = @getCursor().prev ? @getCursor().start?.prev
@setCursor prev, ((token) -> token.type is 'socketStart'), 'before'
else
next = @getCursor().next ? @getCursor().end?.next
@setCursor next, ((token) -> token.type is 'socketStart'), 'after'
event.preventDefault()
Editor::deleteAtCursor = ->
if @getCursor().type is 'blockEnd'
block = @getCursor().container
else if @getCursor().type is 'indentStart'
block = @getCursor().parent
else
return
@setCursor block.start, null, 'before'
@undoCapture()
@spliceOut block
@redrawMain()
hook 'keydown', 0, (event, state) ->
if not @session? or @session.readOnly
return
if event.which isnt BACKSPACE_KEY
return
if state.capturedBackspace
return
# We don't want to interrupt any text input editing
# sessions. We will, however, delete a handwritten
# block if it is currently empty.
if @lassoSelection?
@deleteLassoSelection()
event.preventDefault()
return false
else if not @cursorAtSocket() or
(@hiddenInput.value.length is 0 and @getCursor().handwritten)
@deleteAtCursor()
state.capturedBackspace = true
event.preventDefault()
return false
return true
Editor::deleteLassoSelection = ->
unless @lassoSelection?
if DEBUG_FLAG
throw new Error 'Cannot delete nonexistent lasso segment'
return null
cursorTarget = @lassoSelection.start.prev
@spliceOut @lassoSelection
@lassoSelection = null
@setCursor cursorTarget
@redrawMain()
# HANDWRITTEN BLOCK SUPPORT
# ================================
hook 'keydown', 0, (event, state) ->
if not @session? or @session.readOnly
return
if event.which is ENTER_KEY
if not @cursorAtSocket() and not event.shiftKey and not event.ctrlKey and not event.metaKey
# Construct the block; flag the socket as handwritten
newBlock = new model.Block(); newSocket = new model.Socket '', Infinity, true
newSocket.setParent newBlock
helper.connect newBlock.start, newSocket.start
helper.connect newSocket.end, newBlock.end
# Seek a place near the cursor we can actually
# put a block.
head = @getCursor()
while head.type is 'newline'
head = head.prev
newSocket.parseContext = head.parent.parseContext
@spliceIn newBlock, head #MUTATION
@redrawMain()
@newHandwrittenSocket = newSocket
else if @cursorAtSocket() and not event.shiftKey
socket = @getCursor()
@hiddenInput.blur()
@dropletElement.focus()
@setCursor @session.cursor, (token) -> token.type isnt 'socketStart'
@redrawMain()
if '__comment__' in socket.classes and @session.mode.startSingleLineComment
# Create another single line comment block just below
newBlock = new model.Block 0, 'blank', helper.ANY_DROP
newBlock.classes = ['__comment__', 'block-only']
newBlock.socketLevel = helper.BLOCK_ONLY
newTextMarker = new model.TextToken @session.mode.startSingleLineComment
newTextMarker.setParent newBlock
newSocket = new model.Socket '', 0, true
newSocket.classes = ['__comment__']
newSocket.setParent newBlock
helper.connect newBlock.start, newTextMarker
helper.connect newTextMarker, newSocket.start
helper.connect newSocket.end, newBlock.end
# Seek a place near the cursor we can actually
# put a block.
head = @getCursor()
while head.type is 'newline'
head = head.prev
@spliceIn newBlock, head #MUTATION
@redrawMain()
@newHandwrittenSocket = newSocket
hook 'keyup', 0, (event, state) ->
if not @session? or @session.readOnly
return
# prevents routing the initial enter keypress to a new handwritten
# block by focusing the block only after the enter key is released.
if event.which is ENTER_KEY
if @newHandwrittenSocket?
@setCursor @newHandwrittenSocket
@newHandwrittenSocket = null
containsCursor = (block) ->
head = block.start
until head is block.end
if head.type is 'cursor' then return true
head = head.next
return false
# ANIMATION AND ACE EDITOR SUPPORT
# ================================
Editor::copyAceEditor = ->
@gutter.style.width = @aceEditor.renderer.$gutterLayer.gutterWidth + 'px'
@resizeBlockMode()
return @setValue_raw @getAceValue()
# For animation and ace editor,
# we will need a couple convenience functions
# for getting the "absolute"-esque position
# of layouted elements (a la jQuery, without jQuery).
getOffsetTop = (element) ->
top = element.offsetTop
while (element = element.offsetParent)?
top += element.offsetTop
return top
getOffsetLeft = (element) ->
left = element.offsetLeft
while (element = element.offsetParent)?
left += element.offsetLeft
return left
Editor::computePlaintextTranslationVectors = ->
# Now we need to figure out where all the text elements are going
# to end up.
textElements = []; translationVectors = []
head = @session.tree.start
aceSession = @aceEditor.session
state = {
# Initial cursor positions are
# determined by ACE editor configuration.
x: (@aceEditor.container.getBoundingClientRect().left -
@aceElement.getBoundingClientRect().left +
@aceEditor.renderer.$gutterLayer.gutterWidth) -
@gutter.clientWidth + 5 # TODO find out where this 5 comes from
y: (@aceEditor.container.getBoundingClientRect().top -
@aceElement.getBoundingClientRect().top) -
aceSession.getScrollTop()
# Initial indent depth is 0
indent: 0
# Line height and left edge are
# determined by ACE editor configuration.
lineHeight: @aceEditor.renderer.layerConfig.lineHeight
leftEdge: (@aceEditor.container.getBoundingClientRect().left -
getOffsetLeft(@aceElement) +
@aceEditor.renderer.$gutterLayer.gutterWidth) -
@gutter.clientWidth + 5 # TODO see above
}
@measureCtx.font = @aceFontSize() + ' ' + @session.fontFamily
fontWidth = @measureCtx.measureText(' ').width
rownum = 0
until head is @session.tree.end
switch head.type
when 'text'
corner = @session.view.getViewNodeFor(head).bounds[0].upperLeftCorner()
corner.x -= @session.viewports.main.x
corner.y -= @session.viewports.main.y
translationVectors.push (new @draw.Point(state.x, state.y)).from(corner)
textElements.push @session.view.getViewNodeFor head
state.x += fontWidth * head.value.length
when 'socketStart'
if head.next is head.container.end or
head.next.type is 'text' and head.next.value is ''
state.x += fontWidth * head.container.emptyString.length
# Newline moves the cursor to the next line,
# plus some indent.
when 'newline'
# Be aware of wrapped ace editor lines.
wrappedlines = Math.max(1,
aceSession.documentToScreenRow(rownum + 1, 0) -
aceSession.documentToScreenRow(rownum, 0))
rownum += 1
state.y += state.lineHeight * wrappedlines
if head.specialIndent?
state.x = state.leftEdge + fontWidth * head.specialIndent.length
else
state.x = state.leftEdge + state.indent * fontWidth
when 'indentStart'
state.indent += head.container.depth
when 'indentEnd'
state.indent -= head.container.depth
head = head.next
return {
textElements: textElements
translationVectors: translationVectors
}
Editor::checkAndHighlightEmptySockets = ->
head = @session.tree.start
ok = true
until head is @session.tree.end
if (head.type is 'socketStart' and head.next is head.container.end or
head.type is 'socketStart' and head.next.type is 'text' and head.next.value is '') and
head.container.emptyString isnt ''
@markBlock head.container, {color: '#F00'}
ok = false
head = head.next
return ok
Editor::performMeltAnimation = (fadeTime = 500, translateTime = 1000, cb = ->) ->
if @session.currentlyUsingBlocks and not @currentlyAnimating
# If the preserveEmpty option is turned off, we will not round-trip empty sockets.
#
# Therefore, forbid melting if there is an empty socket. If there is,
# highlight it in red.
if not @session.options.preserveEmpty and not @checkAndHighlightEmptySockets()
@redrawMain()
return
@hideDropdown()
@fireEvent 'statechange', [false]
@setAceValue @getValue()
top = @findLineNumberAtCoordinate @session.viewports.main.y
@aceEditor.scrollToLine top
@aceEditor.resize true
@redrawMain noText: true
# Hide scrollbars and increase width
if @mainScroller.scrollWidth > @mainScroller.clientWidth
@mainScroller.style.overflowX = 'scroll'
else
@mainScroller.style.overflowX = 'hidden'
@mainScroller.style.overflowY = 'hidden'
@dropletElement.style.width = @wrapperElement.clientWidth + 'px'
@session.currentlyUsingBlocks = false; @currentlyAnimating = @currentlyAnimating_suppressRedraw = true
# Compute where the text will end up
# in the ace editor
{textElements, translationVectors} = @computePlaintextTranslationVectors()
translatingElements = []
for textElement, i in textElements
# Skip anything that's
# off the screen the whole time.
unless 0 < textElement.bounds[0].bottom() - @session.viewports.main.y + translationVectors[i].y and
textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y < @session.viewports.main.height
continue
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = textElement.model.value
div.style.font = @session.fontSize + 'px ' + @session.fontFamily
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y - @session.fontAscent}px"
div.className = 'droplet-transitioning-element'
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@transitionContainer.appendChild div
do (div, textElement, translationVectors, i) =>
setTimeout (=>
div.style.left = (textElement.bounds[0].x - @session.viewports.main.x + translationVectors[i].x) + 'px'
div.style.top = (textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y) + 'px'
div.style.fontSize = @aceFontSize()
), fadeTime
top = Math.max @aceEditor.getFirstVisibleRow(), 0
bottom = Math.min @aceEditor.getLastVisibleRow(), @session.view.getViewNodeFor(@session.tree).lineLength - 1
aceScrollTop = @aceEditor.session.getScrollTop()
treeView = @session.view.getViewNodeFor @session.tree
lineHeight = @aceEditor.renderer.layerConfig.lineHeight
for line in [top..bottom]
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = line + 1
div.style.left = 0
div.style.top = "#{treeView.bounds[line].y + treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent - @session.viewports.main.y}px"
div.style.font = @session.fontSize + 'px ' + @session.fontFamily
div.style.width = "#{@gutter.clientWidth}px"
translatingElements.push div
div.className = 'droplet-transitioning-element droplet-transitioning-gutter droplet-gutter-line'
# Add annotation
if @annotations[line]?
div.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
@dropletElement.appendChild div
do (div, line) =>
# Set off the css transition
setTimeout (=>
div.style.left = '0px'
div.style.top = (@aceEditor.session.documentToScreenRow(line, 0) *
lineHeight - aceScrollTop) + 'px'
div.style.fontSize = @aceFontSize()
), fadeTime
@lineNumberWrapper.style.display = 'none'
# Kick off fade-out transition
@mainCanvas.style.transition =
@highlightCanvas.style.transition = "opacity #{fadeTime}ms linear"
@mainCanvas.style.opacity = 0
paletteDisappearingWithMelt = @session.paletteEnabled and not @session.showPaletteInTextMode
if paletteDisappearingWithMelt
# Move the palette header into the background
@paletteHeader.style.zIndex = 0
setTimeout (=>
@dropletElement.style.transition = "left #{translateTime}ms"
@dropletElement.style.left = '0px'
), fadeTime
setTimeout (=>
# Translate the ICE editor div out of frame.
@dropletElement.style.transition = ''
# Translate the ACE editor div into frame.
@aceElement.style.top = '0px'
if @session.showPaletteInTextMode and @session.paletteEnabled
@aceElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@aceElement.style.left = '0px'
#if paletteDisappearingWithMelt
# @paletteWrapper.style.top = '-9999px'
# @paletteWrapper.style.left = '-9999px'
@dropletElement.style.top = '-9999px'
@dropletElement.style.left = '-9999px'
# Finalize a bunch of animations
# that should be complete by now,
# but might not actually be due to
# floating point stuff.
@currentlyAnimating = false
# Show scrollbars again
@mainScroller.style.overflow = 'auto'
for div in translatingElements
div.parentNode.removeChild div
@fireEvent 'toggledone', [@session.currentlyUsingBlocks]
if cb? then do cb
), fadeTime + translateTime
return success: true
Editor::aceFontSize = ->
parseFloat(@aceEditor.getFontSize()) + 'px'
Editor::performFreezeAnimation = (fadeTime = 500, translateTime = 500, cb = ->)->
return unless @session?
if not @session.currentlyUsingBlocks and not @currentlyAnimating
beforeTime = +(new Date())
setValueResult = @copyAceEditor()
afterTime = +(new Date())
unless setValueResult.success
if setValueResult.error
@fireEvent 'parseerror', [setValueResult.error]
return setValueResult
if @aceEditor.getFirstVisibleRow() is 0
@mainScroller.scrollTop = 0
else
@mainScroller.scrollTop = @session.view.getViewNodeFor(@session.tree).bounds[@aceEditor.getFirstVisibleRow()].y
@session.currentlyUsingBlocks = true
@currentlyAnimating = true
@fireEvent 'statechange', [true]
setTimeout (=>
# Hide scrollbars and increase width
@mainScroller.style.overflow = 'hidden'
@dropletElement.style.width = @wrapperElement.clientWidth + 'px'
@redrawMain noText: true
@currentlyAnimating_suppressRedraw = true
@aceElement.style.top = "-9999px"
@aceElement.style.left = "-9999px"
paletteAppearingWithFreeze = @session.paletteEnabled and not @session.showPaletteInTextMode
if paletteAppearingWithFreeze
@paletteWrapper.style.top = '0px'
@paletteHeader.style.zIndex = 0
@dropletElement.style.top = "0px"
if @session.paletteEnabled and not paletteAppearingWithFreeze
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@dropletElement.style.left = "0px"
{textElements, translationVectors} = @computePlaintextTranslationVectors()
translatingElements = []
for textElement, i in textElements
# Skip anything that's
# off the screen the whole time.
unless 0 < textElement.bounds[0].bottom() - @session.viewports.main.y + translationVectors[i].y and
textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y < @session.viewports.main.height
continue
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = textElement.model.value
div.style.font = @aceFontSize() + ' ' + @session.fontFamily
div.style.position = 'absolute'
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x + translationVectors[i].x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y + translationVectors[i].y}px"
div.className = 'droplet-transitioning-element'
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@transitionContainer.appendChild div
do (div, textElement) =>
setTimeout (=>
div.style.left = "#{textElement.bounds[0].x - @session.viewports.main.x}px"
div.style.top = "#{textElement.bounds[0].y - @session.viewports.main.y - @session.fontAscent}px"
div.style.fontSize = @session.fontSize + 'px'
), 0
top = Math.max @aceEditor.getFirstVisibleRow(), 0
bottom = Math.min @aceEditor.getLastVisibleRow(), @session.view.getViewNodeFor(@session.tree).lineLength - 1
treeView = @session.view.getViewNodeFor @session.tree
lineHeight = @aceEditor.renderer.layerConfig.lineHeight
aceScrollTop = @aceEditor.session.getScrollTop()
for line in [top..bottom]
div = document.createElement 'div'
div.style.whiteSpace = 'pre'
div.innerText = div.textContent = line + 1
div.style.font = @aceFontSize() + ' ' + @session.fontFamily
div.style.width = "#{@aceEditor.renderer.$gutter.clientWidth}px"
div.style.left = 0
div.style.top = "#{@aceEditor.session.documentToScreenRow(line, 0) *
lineHeight - aceScrollTop}px"
div.className = 'droplet-transitioning-element droplet-transitioning-gutter droplet-gutter-line'
# Add annotation
if @annotations[line]?
div.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
div.style.transition = "left #{translateTime}ms, top #{translateTime}ms, font-size #{translateTime}ms"
translatingElements.push div
@dropletElement.appendChild div
do (div, line) =>
setTimeout (=>
div.style.left = 0
div.style.top = "#{treeView.bounds[line].y + treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent - @session.viewports.main.y}px"
div.style.fontSize = @session.fontSize + 'px'
), 0
@mainCanvas.style.opacity = 0
setTimeout (=>
@mainCanvas.style.transition = "opacity #{fadeTime}ms linear"
@mainCanvas.style.opacity = 1
), translateTime
@dropletElement.style.transition = "left #{fadeTime}ms"
if paletteAppearingWithFreeze
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
@paletteWrapper.style.left = '0px'
setTimeout (=>
@dropletElement.style.transition = ''
# Show scrollbars again
@mainScroller.style.overflow = 'auto'
@currentlyAnimating = false
@lineNumberWrapper.style.display = 'block'
@redrawMain()
@paletteHeader.style.zIndex = 257
for div in translatingElements
div.parentNode.removeChild div
@resizeBlockMode()
@fireEvent 'toggledone', [@session.currentlyUsingBlocks]
if cb? then do cb
), translateTime + fadeTime
), 0
return success: true
Editor::enablePalette = (enabled) ->
if not @currentlyAnimating and @session.paletteEnabled != enabled
@session.paletteEnabled = enabled
@currentlyAnimating = true
if @session.currentlyUsingBlocks
activeElement = @dropletElement
else
activeElement = @aceElement
if not @session.paletteEnabled
activeElement.style.transition = "left 500ms"
activeElement.style.left = '0px'
@paletteHeader.style.zIndex = 0
@resize()
setTimeout (=>
activeElement.style.transition = ''
#@paletteWrapper.style.top = '-9999px'
#@paletteWrapper.style.left = '-9999px'
@currentlyAnimating = false
@fireEvent 'palettetoggledone', [@session.paletteEnabled]
), 500
else
@paletteWrapper.style.top = '0px'
@paletteHeader.style.zIndex = 257
setTimeout (=>
activeElement.style.transition = "left 500ms"
activeElement.style.left = "#{@paletteWrapper.clientWidth}px"
@paletteWrapper.style.left = '0px'
setTimeout (=>
activeElement.style.transition = ''
@resize()
@currentlyAnimating = false
@fireEvent 'palettetoggledone', [@session.paletteEnabled]
), 500
), 0
Editor::toggleBlocks = (cb) ->
if @session.currentlyUsingBlocks
return @performMeltAnimation 500, 1000, cb
else
return @performFreezeAnimation 500, 500, cb
# SCROLLING SUPPORT
# ================================
hook 'populate', 2, ->
@mainScroller = document.createElement 'div'
@mainScroller.className = 'droplet-main-scroller'
# @mainScrollerIntermediary -- this is so that we can be certain that
# any event directly on @mainScroller is in fact on the @mainScroller scrollbar,
# so should not be captured by editor mouse event handlers.
@mainScrollerIntermediary = document.createElement 'div'
@mainScrollerIntermediary.className = 'droplet-main-scroller-intermediary'
@mainScrollerStuffing = document.createElement 'div'
@mainScrollerStuffing.className = 'droplet-main-scroller-stuffing'
@mainScroller.appendChild @mainCanvas
@dropletElement.appendChild @mainScroller
# Prevent scrolling on wrapper element
@wrapperElement.addEventListener 'scroll', =>
@wrapperElement.scrollTop = @wrapperElement.scrollLeft = 0
@mainScroller.addEventListener 'scroll', =>
@session.viewports.main.y = @mainScroller.scrollTop
@session.viewports.main.x = @mainScroller.scrollLeft
@redrawMain()
@paletteScroller = document.createElement 'div'
@paletteScroller.className = 'droplet-palette-scroller'
@paletteScroller.appendChild @paletteCanvas
@paletteScrollerStuffing = document.createElement 'div'
@paletteScrollerStuffing.className = 'droplet-palette-scroller-stuffing'
@paletteScroller.appendChild @paletteScrollerStuffing
@paletteElement.appendChild @paletteScroller
@paletteScroller.addEventListener 'scroll', =>
@session.viewports.palette.y = @paletteScroller.scrollTop
@session.viewports.palette.x = @paletteScroller.scrollLeft
Editor::resizeMainScroller = ->
@mainScroller.style.width = "#{@dropletElement.clientWidth}px"
@mainScroller.style.height = "#{@dropletElement.clientHeight}px"
hook 'resize_palette', 0, ->
@paletteScroller.style.top = "#{@paletteHeader.clientHeight}px"
@session.viewports.palette.height = @paletteScroller.clientHeight
@session.viewports.palette.width = @paletteScroller.clientWidth
hook 'redraw_main', 1, ->
bounds = @session.view.getViewNodeFor(@session.tree).getBounds()
for record in @session.floatingBlocks
bounds.unite @session.view.getViewNodeFor(record.block).getBounds()
# We add some extra height to the bottom
# of the document so that the last block isn't
# jammed up against the edge of the screen.
#
# Default this extra space to fontSize (approx. 1 line).
height = Math.max(
bounds.bottom() + (@options.extraBottomHeight ? @session.fontSize),
@dropletElement.clientHeight
)
if height isnt @lastHeight
@lastHeight = height
@mainCanvas.setAttribute 'height', height
@mainCanvas.style.height = "#{height}px"
hook 'redraw_palette', 0, ->
bounds = new @draw.NoRectangle()
for entry in @session.currentPaletteBlocks
bounds.unite @session.paletteView.getViewNodeFor(entry.block).getBounds()
# For now, we will comment out this line
# due to bugs
#@paletteScrollerStuffing.style.width = "#{bounds.right()}px"
@paletteScrollerStuffing.style.height = "#{bounds.bottom()}px"
# MULTIPLE FONT SIZE SUPPORT
# ================================
hook 'populate', 0, ->
@session.fontSize = 15
@session.fontFamily = 'Courier New'
@measureCtx.font = '15px Courier New'
@session.fontWidth = @measureCtx.measureText(' ').width
metrics = helper.fontMetrics(@session.fontFamily, @session.fontSize)
@session.fontAscent = metrics.prettytop
@session.fontDescent = metrics.descent
Editor::setFontSize_raw = (fontSize) ->
unless @session.fontSize is fontSize
@measureCtx.font = fontSize + ' px ' + @session.fontFamily
@session.fontWidth = @measureCtx.measureText(' ').width
@session.fontSize = fontSize
@paletteHeader.style.fontSize = "#{fontSize}px"
@gutter.style.fontSize = "#{fontSize}px"
@tooltipElement.style.fontSize = "#{fontSize}px"
@session.view.opts.textHeight =
@session.paletteView.opts.textHeight =
@session.dragView.opts.textHeight = helper.getFontHeight @session.fontFamily, @session.fontSize
metrics = helper.fontMetrics(@session.fontFamily, @session.fontSize)
@session.fontAscent = metrics.prettytop
@session.fontDescent = metrics.descent
@session.view.clearCache()
@session.paletteView.clearCache()
@session.dragView.clearCache()
@session.view.draw.setGlobalFontSize @session.fontSize
@session.paletteView.draw.setGlobalFontSize @session.fontSize
@session.dragView.draw.setGlobalFontSize @session.fontSize
@gutter.style.width = @aceEditor.renderer.$gutterLayer.gutterWidth + 'px'
@redrawMain()
@rebuildPalette()
Editor::setFontFamily = (fontFamily) ->
@measureCtx.font = @session.fontSize + 'px ' + fontFamily
@draw.setGlobalFontFamily fontFamily
@session.fontFamily = fontFamily
@session.view.opts.textHeight = helper.getFontHeight @session.fontFamily, @session.fontSize
@session.fontAscent = helper.fontMetrics(@session.fontFamily, @session.fontSize).prettytop
@session.view.clearCache(); @session.dragView.clearCache()
@gutter.style.fontFamily = fontFamily
@tooltipElement.style.fontFamily = fontFamily
@redrawMain()
@rebuildPalette()
Editor::setFontSize = (fontSize) ->
@setFontSize_raw fontSize
@resizeBlockMode()
# LINE MARKING SUPPORT
# ================================
Editor::getHighlightPath = (model, style, view = @session.view) ->
path = view.getViewNodeFor(model).path.clone()
path.style.fillColor = null
path.style.strokeColor = style.color
path.style.lineWidth = 3
path.noclip = true; path.bevel = false
return path
Editor::markLine = (line, style) ->
return unless @session?
block = @session.tree.getBlockOnLine line
@session.view.getViewNodeFor(block).mark style
Editor::markBlock = (block, style) ->
return unless @session?
@session.view.getViewNodeFor(block).mark style
# ## Mark
# `mark(line, col, style)` will mark the first block after the given (line, col) coordinate
# with the given style.
Editor::mark = (location, style) ->
return unless @session?
block = @session.tree.getFromTextLocation location
block = block.container ? block
@session.view.getViewNodeFor(block).mark style
@redrawHighlights() # TODO MERGE investigate
Editor::clearLineMarks = ->
@session.view.clearMarks()
@redrawHighlights()
# LINE HOVER SUPPORT
# ================================
hook 'populate', 0, ->
@lastHoveredLine = null
hook 'mousemove', 0, (point, event, state) ->
# Do not attempt to detect this if we are currently dragging something,
# or no event handlers are bound.
if not @draggingBlock? and not @clickedBlock? and @hasEvent 'linehover'
if not @trackerPointIsInMainScroller point then return
mainPoint = @trackerPointToMain point
treeView = @session.view.getViewNodeFor @session.tree
if @lastHoveredLine? and treeView.bounds[@lastHoveredLine]? and
treeView.bounds[@lastHoveredLine].contains mainPoint
return
hoveredLine = @findLineNumberAtCoordinate mainPoint.y
unless treeView.bounds[hoveredLine].contains mainPoint
hoveredLine = null
if hoveredLine isnt @lastHoveredLine
@fireEvent 'linehover', [line: @lastHoveredLine = hoveredLine]
# GET/SET VALUE SUPPORT
# ================================
# Whitespace trimming hack enable/disable
# setter
hook 'populate', 0, ->
@trimWhitespace = false
Editor::setTrimWhitespace = (trimWhitespace) ->
@trimWhitespace = trimWhitespace
Editor::setValue_raw = (value) ->
try
if @trimWhitespace then value = value.trim()
newParse = @session.mode.parse value, {
wrapAtRoot: true
preserveEmpty: @session.options.preserveEmpty
}
unless @session.tree.start.next is @session.tree.end
removal = new model.List @session.tree.start.next, @session.tree.end.prev
@spliceOut removal
unless newParse.start.next is newParse.end
@spliceIn new model.List(newParse.start.next, newParse.end.prev), @session.tree.start
@removeBlankLines()
@redrawMain()
return success: true
catch e
return success: false, error: e
Editor::setValue = (value) ->
if not @session?
return @aceEditor.setValue value
oldScrollTop = @aceEditor.session.getScrollTop()
@setAceValue value
@resizeTextMode()
@aceEditor.session.setScrollTop oldScrollTop
if @session.currentlyUsingBlocks
result = @setValue_raw value
if result.success is false
@setEditorState false
@aceEditor.setValue value
if result.error
@fireEvent 'parseerror', [result.error]
Editor::addEmptyLine = (str) ->
if str.length is 0 or str[str.length - 1] is '\n'
return str
else
return str + '\n'
Editor::getValue = ->
if @session?.currentlyUsingBlocks
return @addEmptyLine @session.tree.stringify({
preserveEmpty: @session.options.preserveEmpty
})
else
@getAceValue()
Editor::getAceValue = ->
value = @aceEditor.getValue()
@lastAceSeenValue = value
Editor::setAceValue = (value) ->
if value isnt @lastAceSeenValue
@aceEditor.setValue value, 1
# TODO: move ace cursor to location matching droplet cursor.
@lastAceSeenValue = value
# PUBLIC EVENT BINDING HOOKS
# ===============================
Editor::on = (event, handler) ->
@bindings[event] = handler
Editor::once = (event, handler) ->
@bindings[event] = ->
handler.apply this, arguments
@bindings[event] = null
Editor::fireEvent = (event, args) ->
if event of @bindings
@bindings[event].apply this, args
Editor::hasEvent = (event) -> event of @bindings and @bindings[event]?
# SYNCHRONOUS TOGGLE SUPPORT
# ================================
Editor::setEditorState = (useBlocks) ->
@mainCanvas.style.transition = @highlightCanvas.style.transition = ''
if useBlocks
if not @session?
throw new ArgumentError 'cannot switch to blocks if a session has not been set up.'
unless @session.currentlyUsingBlocks
@setValue_raw @getAceValue()
@dropletElement.style.top = '0px'
if @session.paletteEnabled
@paletteWrapper.style.top = @paletteWrapper.style.left = '0px'
@dropletElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@paletteWrapper.style.top = '0px'
@dropletElement.style.left = '0px'
@aceElement.style.top = @aceElement.style.left = '-9999px'
@session.currentlyUsingBlocks = true
@lineNumberWrapper.style.display = 'block'
@mainCanvas.style.opacity =
@highlightCanvas.style.opacity = 1
@resizeBlockMode(); @redrawMain()
else
# Forbid melting if there is an empty socket. If there is,
# highlight it in red.
if @session? and not @session.options.preserveEmpty and not @checkAndHighlightEmptySockets()
@redrawMain()
return
@hideDropdown()
paletteVisibleInNewState = @session?.paletteEnabled and @session.showPaletteInTextMode
oldScrollTop = @aceEditor.session.getScrollTop()
if @session?.currentlyUsingBlocks
@setAceValue @getValue()
@aceEditor.resize true
@aceEditor.session.setScrollTop oldScrollTop
@dropletElement.style.top = @dropletElement.style.left = '-9999px'
@paletteWrapper.style.top = @paletteWrapper.style.left = '0px'
@aceElement.style.top = '0px'
if paletteVisibleInNewState
@aceElement.style.left = "#{@paletteWrapper.clientWidth}px"
else
@aceElement.style.left = '0px'
@session?.currentlyUsingBlocks = false
@lineNumberWrapper.style.display = 'none'
@mainCanvas.style.opacity =
@highlightCanvas.style.opacity = 0
@resizeBlockMode()
# DRAG CANVAS SHOW/HIDE HACK
# ================================
hook 'populate', 0, ->
@dragCover = document.createElement 'div'
@dragCover.className = 'droplet-drag-cover'
@dragCover.style.display = 'none'
document.body.appendChild @dragCover
# On mousedown, bring the drag
# canvas to the front so that it
# appears to "float" over all other elements
hook 'mousedown', -1, ->
if @clickedBlock?
@dragCover.style.display = 'block'
# On mouseup, throw the drag canvas away completely.
hook 'mouseup', 0, ->
@dragCanvas.style.transform = "translate(-9999px, -9999px)"
@dragCover.style.display = 'none'
# FAILSAFE END DRAG HACK
# ================================
hook 'mousedown', 10, ->
if @draggingBlock?
@endDrag()
Editor::endDrag = ->
# Ensure that the cursor is not in a socket.
if @cursorAtSocket()
@setCursor @session.cursor, (x) -> x.type isnt 'socketStart'
@clearDrag()
@draggingBlock = null
@draggingOffset = null
@lastHighlightPath?.deactivate?()
@lastHighlight = @lastHighlightPath = null
@redrawMain()
return
# PALETTE EVENT
# =================================
hook 'rebuild_palette', 0, ->
@fireEvent 'changepalette', []
# TOUCHSCREEN SUPPORT
# =================================
# We will attempt to emulate
# mouse events using touchstart/end
# data.
touchEvents =
'touchstart': 'mousedown'
'touchmove': 'mousemove'
'touchend': 'mouseup'
# A timeout for selection
TOUCH_SELECTION_TIMEOUT = 1000
Editor::touchEventToPoint = (event, index) ->
absolutePoint = new @draw.Point(
event.changedTouches[index].clientX,
event.changedTouches[index].clientY
)
return absolutePoint
Editor::queueLassoMousedown = (trackPoint, event) ->
@lassoSelectStartTimeout = setTimeout (=>
state = {}
for handler in editorBindings.mousedown
handler.call this, trackPoint, event, state), TOUCH_SELECTION_TIMEOUT
# We will bind the same way as mouse events do,
# wrapping to be compatible with a mouse event interface.
#
# When users drag with multiple fingers, we emulate scrolling.
# Otherwise, we emulate mousedown/mouseup
hook 'populate', 0, ->
@touchScrollAnchor = new @draw.Point 0, 0
@lassoSelectStartTimeout = null
@wrapperElement.addEventListener 'touchstart', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
# We keep a state object so that handlers
# can know about each other.
#
# We will suppress lasso select to
# allow scrolling.
state = {
suppressLassoSelect: true
}
# Call all the handlers.
for handler in editorBindings.mousedown
handler.call this, trackPoint, event, state
# If we did not hit anything,
# we may want to start a lasso select
# in a little bit.
if state.consumedHitTest
event.preventDefault()
else
@queueLassoMousedown trackPoint, event
@wrapperElement.addEventListener 'touchmove', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
unless @clickedBlock? or @draggingBlock?
@queueLassoMousedown trackPoint, event
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings.mousemove
handler.call this, trackPoint, event, state
# If we are in the middle of some action,
# prevent scrolling.
if @clickedBlock? or @draggingBlock? or @lassoSelectAnchor? or @textInputSelecting
event.preventDefault()
@wrapperElement.addEventListener 'touchend', (event) =>
clearTimeout @lassoSelectStartTimeout
trackPoint = @touchEventToPoint event, 0
# We keep a state object so that handlers
# can know about each other.
state = {}
# Call all the handlers.
for handler in editorBindings.mouseup
handler.call this, trackPoint, event, state
event.preventDefault()
# CURSOR DRAW SUPPORRT
# ================================
hook 'populate', 0, ->
@cursorCtx = document.createElementNS SVG_STANDARD, 'g'
@textCursorPath = new @session.view.draw.Path([], false, {
'strokeColor': '#000'
'lineWidth': '2'
'fillColor': 'rgba(0, 0, 256, 0.3)'
'cssClass': 'droplet-cursor-path'
})
@textCursorPath.setParent @mainCanvas
cursorElement = document.createElementNS SVG_STANDARD, 'path'
cursorElement.setAttribute 'fill', 'none'
cursorElement.setAttribute 'stroke', '#000'
cursorElement.setAttribute 'stroke-width', '3'
cursorElement.setAttribute 'stroke-linecap', 'round'
cursorElement.setAttribute 'd', "M#{@session.view.opts.tabOffset + CURSOR_WIDTH_DECREASE / 2} 0 " +
"Q#{@session.view.opts.tabOffset + @session.view.opts.tabWidth / 2} #{@session.view.opts.tabHeight}" +
" #{@session.view.opts.tabOffset + @session.view.opts.tabWidth - CURSOR_WIDTH_DECREASE / 2} 0"
@cursorPath = new @session.view.draw.ElementWrapper(cursorElement)
@cursorPath.setParent @mainCanvas
@mainCanvas.appendChild @cursorCtx
Editor::strokeCursor = (point) ->
return unless point?
@cursorPath.element.setAttribute 'transform', "translate(#{point.x}, #{point.y})"
@qualifiedFocus @getCursor(), @cursorPath
Editor::highlightFlashShow = ->
return unless @session?
if @flashTimeout? then clearTimeout @flashTimeout
if @cursorAtSocket()
@textCursorPath.activate()
else
@cursorPath.activate()
@highlightsCurrentlyShown = true
@flashTimeout = setTimeout (=> @flash()), 500
Editor::highlightFlashHide = ->
return unless @session?
if @flashTimeout? then clearTimeout @flashTimeout
if @cursorAtSocket()
@textCursorPath.deactivate()
else
@cursorPath.deactivate()
@highlightsCurrentlyShown = false
@flashTimeout = setTimeout (=> @flash()), 500
Editor::editorHasFocus = ->
document.activeElement in [@dropletElement, @hiddenInput, @copyPasteInput] and
document.hasFocus()
Editor::flash = ->
return unless @session?
if @lassoSelection? or @draggingBlock? or
(@cursorAtSocket() and @textInputHighlighted) or
not @highlightsCurrentlyShown or
not @editorHasFocus()
@highlightFlashShow()
else
@highlightFlashHide()
hook 'populate', 0, ->
@highlightsCurrentlyShown = false
blurCursors = =>
@highlightFlashShow()
@cursorCtx.style.opacity = CURSOR_UNFOCUSED_OPACITY
@dropletElement.addEventListener 'blur', blurCursors
@hiddenInput.addEventListener 'blur', blurCursors
@copyPasteInput.addEventListener 'blur', blurCursors
focusCursors = =>
@highlightFlashShow()
@cursorCtx.style.transition = ''
@cursorCtx.style.opacity = 1
@dropletElement.addEventListener 'focus', focusCursors
@hiddenInput.addEventListener 'focus', focusCursors
@copyPasteInput.addEventListener 'focus', focusCursors
@flashTimeout = setTimeout (=> @flash()), 0
# ONE MORE DROP CASE
# ================================
# TODO possibly move this next utility function to view?
Editor::viewOrChildrenContains = (model, point, view = @session.view) ->
modelView = view.getViewNodeFor model
if modelView.path.contains point
return true
for childObj in modelView.children
if @session.viewOrChildrenContains childObj.child, point, view
return true
return false
# LINE NUMBER GUTTER CODE
# ================================
hook 'populate', 0, ->
@gutter = document.createElement 'div'
@gutter.className = 'droplet-gutter'
@lineNumberWrapper = document.createElement 'div'
@gutter.appendChild @lineNumberWrapper
@gutterVersion = -1
@lastGutterWidth = null
@lineNumberTags = {}
@mainScroller.appendChild @gutter
# Record of embedder-set annotations
# and breakpoints used in rendering.
# Should mirror ace all the time.
@annotations = {}
@breakpoints = {}
@tooltipElement = document.createElement 'div'
@tooltipElement.className = 'droplet-tooltip'
@dropletElement.appendChild @tooltipElement
@aceEditor.on 'guttermousedown', (e) =>
# Ensure that the click actually happened
# on a line and not just in gutter space.
target = e.domEvent.target
if target.className.indexOf('ace_gutter-cell') is -1
return
# Otherwise, get the row and fire a Droplet gutter
# mousedown event.
row = e.getDocumentPosition().row
e.stop()
@fireEvent 'guttermousedown', [{line: row, event: e.domEvent}]
hook 'mousedown', 11, (point, event, state) ->
# Check if mousedown within the gutter
if not @trackerPointIsInGutter(point) then return
# Find the line that was clicked
mainPoint = @trackerPointToMain point
treeView = @session.view.getViewNodeFor @session.tree
clickedLine = @findLineNumberAtCoordinate mainPoint.y
@fireEvent 'guttermousedown', [{line: clickedLine, event: event}]
# Prevent other hooks from taking this event
return true
Editor::setBreakpoint = (row) ->
# Delegate
@aceEditor.session.setBreakpoint(row)
# Add to our own records
@breakpoints[row] = true
# Redraw gutter.
# TODO: if this ends up being a performance issue,
# selectively apply classes
@redrawGutter false
Editor::clearBreakpoint = (row) ->
@aceEditor.session.clearBreakpoint(row)
@breakpoints[row] = false
@redrawGutter false
Editor::clearBreakpoints = (row) ->
@aceEditor.session.clearBreakpoints()
@breakpoints = {}
@redrawGutter false
Editor::getBreakpoints = (row) ->
@aceEditor.session.getBreakpoints()
Editor::setAnnotations = (annotations) ->
@aceEditor.session.setAnnotations annotations
@annotations = {}
for el, i in annotations
@annotations[el.row] ?= []
@annotations[el.row].push el
@redrawGutter false
Editor::resizeGutter = ->
unless @lastGutterWidth is @aceEditor.renderer.$gutterLayer.gutterWidth
@lastGutterWidth = @aceEditor.renderer.$gutterLayer.gutterWidth
@gutter.style.width = @lastGutterWidth + 'px'
return @resize()
unless @lastGutterHeight is Math.max(@dropletElement.clientHeight, @mainCanvas.clientHeight)
@lastGutterHeight = Math.max(@dropletElement.clientHeight, @mainCanvas.clientHeight)
@gutter.style.height = @lastGutterHeight + 'px'
Editor::addLineNumberForLine = (line) ->
treeView = @session.view.getViewNodeFor @session.tree
if line of @lineNumberTags
lineDiv = @lineNumberTags[line].tag
else
lineDiv = document.createElement 'div'
lineDiv.innerText = lineDiv.textContent = line + 1
@lineNumberTags[line] = {
tag: lineDiv
lastPosition: null
}
if treeView.bounds[line].y isnt @lineNumberTags[line].lastPosition
lineDiv.className = 'droplet-gutter-line'
# Add annotation mouseover text
# and graphics
if @annotations[line]?
lineDiv.className += ' droplet_' + getMostSevereAnnotationType(@annotations[line])
title = @annotations[line].map((x) -> x.text).join('\n')
lineDiv.addEventListener 'mouseover', =>
@tooltipElement.innerText =
@tooltipElement.textContent = title
@tooltipElement.style.display = 'block'
lineDiv.addEventListener 'mousemove', (event) =>
@tooltipElement.style.left = event.pageX + 'px'
@tooltipElement.style.top = event.pageY + 'px'
lineDiv.addEventListener 'mouseout', =>
@tooltipElement.style.display = 'none'
# Add breakpoint graphics
if @breakpoints[line]
lineDiv.className += ' droplet_breakpoint'
lineDiv.style.top = "#{treeView.bounds[line].y}px"
lineDiv.style.paddingTop = "#{treeView.distanceToBase[line].above - @session.view.opts.textHeight - @session.fontAscent}px"
lineDiv.style.paddingBottom = "#{treeView.distanceToBase[line].below - @session.fontDescent}"
lineDiv.style.height = treeView.bounds[line].height + 'px'
lineDiv.style.fontSize = @session.fontSize + 'px'
@lineNumberWrapper.appendChild lineDiv
@lineNumberTags[line].lastPosition = treeView.bounds[line].y
TYPE_SEVERITY = {
'error': 2
'warning': 1
'info': 0
}
TYPE_FROM_SEVERITY = ['info', 'warning', 'error']
getMostSevereAnnotationType = (arr) ->
TYPE_FROM_SEVERITY[Math.max.apply(this, arr.map((x) -> TYPE_SEVERITY[x.type]))]
Editor::findLineNumberAtCoordinate = (coord) ->
treeView = @session.view.getViewNodeFor @session.tree
start = 0; end = treeView.bounds.length
pivot = Math.floor (start + end) / 2
while treeView.bounds[pivot].y isnt coord and start < end
if start is pivot or end is pivot
return pivot
if treeView.bounds[pivot].y > coord
end = pivot
else
start = pivot
if end < 0 then return 0
if start >= treeView.bounds.length then return treeView.bounds.length - 1
pivot = Math.floor (start + end) / 2
return pivot
hook 'redraw_main', 0, (changedBox) ->
@redrawGutter(changedBox)
Editor::redrawGutter = (changedBox = true) ->
return unless @session?
treeView = @session.view.getViewNodeFor @session.tree
top = @findLineNumberAtCoordinate @session.viewports.main.y
bottom = @findLineNumberAtCoordinate @session.viewports.main.bottom()
for line in [top..bottom]
@addLineNumberForLine line
for line, tag of @lineNumberTags
if line < top or line > bottom
@lineNumberTags[line].tag.parentNode.removeChild @lineNumberTags[line].tag
delete @lineNumberTags[line]
if changedBox
@resizeGutter()
Editor::setPaletteWidth = (width) ->
@paletteWrapper.style.width = width + 'px'
@resizeBlockMode()
# COPY AND PASTE
# ================================
hook 'populate', 1, ->
@copyPasteInput = document.createElement 'textarea'
@copyPasteInput.style.position = 'absolute'
@copyPasteInput.style.left = @copyPasteInput.style.top = '-9999px'
@dropletElement.appendChild @copyPasteInput
pressedVKey = false
pressedXKey = false
@copyPasteInput.addEventListener 'keydown', (event) ->
pressedVKey = pressedXKey = false
if event.keyCode is 86
pressedVKey = true
else if event.keyCode is 88
pressedXKey = true
@copyPasteInput.addEventListener 'input', =>
if not @session? or @session.readOnly
return
if pressedVKey and not @cursorAtSocket()
str = @copyPasteInput.value; lines = str.split '\n'
# Strip any common leading indent
# from all the lines of the pasted tet
minIndent = lines.map((line) -> line.length - line.trimLeft().length).reduce((a, b) -> Math.min(a, b))
str = lines.map((line) -> line[minIndent...]).join('\n')
str = str.replace /^\n*|\n*$/g, ''
try
blocks = @session.mode.parse str, {context: @getCursor().parent.parseContext}
blocks = new model.List blocks.start.next, blocks.end.prev
catch e
blocks = null
return unless blocks?
@undoCapture()
@spliceIn blocks, @getCursor()
@setCursor blocks.end
@redrawMain()
@copyPasteInput.setSelectionRange 0, @copyPasteInput.value.length
else if pressedXKey and @lassoSelection?
@spliceOut @lassoSelection; @lassoSelection = null
@redrawMain()
hook 'keydown', 0, (event, state) ->
if event.which in command_modifiers
unless @cursorAtSocket()
x = document.body.scrollLeft
y = document.body.scrollTop
@copyPasteInput.focus()
window.scrollTo(x, y)
if @lassoSelection?
@copyPasteInput.value = @lassoSelection.stringifyInPlace()
@copyPasteInput.setSelectionRange 0, @copyPasteInput.value.length
hook 'keyup', 0, (point, event, state) ->
if event.which in command_modifiers
if @cursorAtSocket()
@hiddenInput.focus()
else
@dropletElement.focus()
# OVRFLOW BIT
# ================================
Editor::overflowsX = ->
@documentDimensions().width > @session.viewportDimensions().width
Editor::overflowsY = ->
@documentDimensions().height > @session.viewportDimensions().height
Editor::documentDimensions = ->
bounds = @session.view.getViewNodeFor(@session.tree).totalBounds
return {
width: bounds.width
height: bounds.height
}
Editor::viewportDimensions = ->
return @session.viewports.main
# LINE LOCATION API
# =================
Editor::getLineMetrics = (row) ->
viewNode = @session.view.getViewNodeFor @session.tree
bounds = (new @session.view.draw.Rectangle()).copy(viewNode.bounds[row])
bounds.x += @mainCanvas.offsetLeft + @mainCanvas.offsetParent.offsetLeft
return {
bounds: bounds
distanceToBase: {
above: viewNode.distanceToBase[row].above
below: viewNode.distanceToBase[row].below
}
}
# DEBUG CODE
# ================================
Editor::dumpNodeForDebug = (hitTestResult, line) ->
console.log('Model node:')
console.log(hitTestResult.serialize())
console.log('View node:')
console.log(@session.view.getViewNodeFor(hitTestResult).serialize(line))
# CLOSING FOUNDATIONAL STUFF
# ================================
# Order the arrays correctly.
for key of unsortedEditorBindings
unsortedEditorBindings[key].sort (a, b) -> if a.priority > b.priority then -1 else 1
editorBindings[key] = []
for binding in unsortedEditorBindings[key]
editorBindings[key].push binding.fn
|
[
{
"context": "YYYY-MM-DD\")\n\t\tkey = keyPrefix() + \"#{divisionName}:#{dateKey}\"\n\t\tLogger.module(\"REDIS\").debug \"saveG",
"end": 1187,
"score": 0.5844635963439941,
"start": 1187,
"tag": "KEY",
"value": ""
},
{
"context": "eKey = moment.utc().startOf('day').format(\"YYYY-MM-DD... | server/redis/r-watchablegamesmanager.coffee | willroberts/duelyst | 5 | Promise = require 'bluebird'
moment = require 'moment'
Logger = require '../../app/common/logger.coffee'
config = require '../../config/config.js'
env = config.get("env")
generatePushID = require '../../app/common/generate_push_id'
# Helper returns the Game Data Redis key prefix
keyPrefix = () ->
return "#{env}:watchable_games:"
###*
# Class 'RedisWatchableGamesManager'
# Manages storage of games in Redis
# Serialized games are stored by incrementing id
# ttl sets the expiration time of keys, defaults to 72 hours
###
class RedisWatchableGamesManager
###*
# Constructor
# @param {Object} redis, a promisified redis connection
###
constructor: (redis, opts = {}) ->
# TODO: add check to ensure Redis client is already promisified
@redis = redis
return
###*
# Save json watchable game data to redis
# @param {String} the divison name for which to save/generate
# @param {Object} the json data
# @param {Function|optional} callback
# @return {Promise}
###
saveGamesDataForDivision: (divisionName, dataJson, callback) ->
divisionName = divisionName.toLowerCase()
dateKey = moment.utc().startOf('day').format("YYYY-MM-DD")
key = keyPrefix() + "#{divisionName}:#{dateKey}"
Logger.module("REDIS").debug "saveGamesDataForDivision() -> saving watchable game data for #{divisionName}"
multi = @redis.multi() # start a multi command
multi.set(key, dataJson)
multi.expire(key, config.get('watchSectionCacheTTL')) # when to expire the cache
return multi.execAsync()
.nodeify(callback)
###*
# Load json watchable game data from redis
# @param {String} the divison name for which to load
# @param {Function|optional} callback
# @return {Promise}
###
loadGamesDataForDivision: (divisionName, callback) ->
divisionName = divisionName.toLowerCase()
dateKey = moment.utc().startOf('day').format("YYYY-MM-DD")
key = keyPrefix() + "#{divisionName}:#{dateKey}"
Logger.module("REDIS").debug "loadGamesDataForDivision() -> #{divisionName}"
@redis.getAsync(key)
.then JSON.parse
.nodeify(callback)
###*
# Export a factory
###
module.exports = exports = (redis, opts) ->
RedisWatchableGamesManager = new RedisWatchableGamesManager(redis, opts)
return RedisWatchableGamesManager
| 11644 | Promise = require 'bluebird'
moment = require 'moment'
Logger = require '../../app/common/logger.coffee'
config = require '../../config/config.js'
env = config.get("env")
generatePushID = require '../../app/common/generate_push_id'
# Helper returns the Game Data Redis key prefix
keyPrefix = () ->
return "#{env}:watchable_games:"
###*
# Class 'RedisWatchableGamesManager'
# Manages storage of games in Redis
# Serialized games are stored by incrementing id
# ttl sets the expiration time of keys, defaults to 72 hours
###
class RedisWatchableGamesManager
###*
# Constructor
# @param {Object} redis, a promisified redis connection
###
constructor: (redis, opts = {}) ->
# TODO: add check to ensure Redis client is already promisified
@redis = redis
return
###*
# Save json watchable game data to redis
# @param {String} the divison name for which to save/generate
# @param {Object} the json data
# @param {Function|optional} callback
# @return {Promise}
###
saveGamesDataForDivision: (divisionName, dataJson, callback) ->
divisionName = divisionName.toLowerCase()
dateKey = moment.utc().startOf('day').format("YYYY-MM-DD")
key = keyPrefix() + "#{divisionName<KEY>}:#{dateKey}"
Logger.module("REDIS").debug "saveGamesDataForDivision() -> saving watchable game data for #{divisionName}"
multi = @redis.multi() # start a multi command
multi.set(key, dataJson)
multi.expire(key, config.get('watchSectionCacheTTL')) # when to expire the cache
return multi.execAsync()
.nodeify(callback)
###*
# Load json watchable game data from redis
# @param {String} the divison name for which to load
# @param {Function|optional} callback
# @return {Promise}
###
loadGamesDataForDivision: (divisionName, callback) ->
divisionName = divisionName.toLowerCase()
dateKey = moment.utc().startOf('day').format("YYYY-MM<KEY>-DD")
key = keyPrefix() + "#{divisionName<KEY>}:#{dateKey}"
Logger.module("REDIS").debug "loadGamesDataForDivision() -> #{divisionName}"
@redis.getAsync(key)
.then JSON.parse
.nodeify(callback)
###*
# Export a factory
###
module.exports = exports = (redis, opts) ->
RedisWatchableGamesManager = new RedisWatchableGamesManager(redis, opts)
return RedisWatchableGamesManager
| true | Promise = require 'bluebird'
moment = require 'moment'
Logger = require '../../app/common/logger.coffee'
config = require '../../config/config.js'
env = config.get("env")
generatePushID = require '../../app/common/generate_push_id'
# Helper returns the Game Data Redis key prefix
keyPrefix = () ->
return "#{env}:watchable_games:"
###*
# Class 'RedisWatchableGamesManager'
# Manages storage of games in Redis
# Serialized games are stored by incrementing id
# ttl sets the expiration time of keys, defaults to 72 hours
###
class RedisWatchableGamesManager
###*
# Constructor
# @param {Object} redis, a promisified redis connection
###
constructor: (redis, opts = {}) ->
# TODO: add check to ensure Redis client is already promisified
@redis = redis
return
###*
# Save json watchable game data to redis
# @param {String} the divison name for which to save/generate
# @param {Object} the json data
# @param {Function|optional} callback
# @return {Promise}
###
saveGamesDataForDivision: (divisionName, dataJson, callback) ->
divisionName = divisionName.toLowerCase()
dateKey = moment.utc().startOf('day').format("YYYY-MM-DD")
key = keyPrefix() + "#{divisionNamePI:KEY:<KEY>END_PI}:#{dateKey}"
Logger.module("REDIS").debug "saveGamesDataForDivision() -> saving watchable game data for #{divisionName}"
multi = @redis.multi() # start a multi command
multi.set(key, dataJson)
multi.expire(key, config.get('watchSectionCacheTTL')) # when to expire the cache
return multi.execAsync()
.nodeify(callback)
###*
# Load json watchable game data from redis
# @param {String} the divison name for which to load
# @param {Function|optional} callback
# @return {Promise}
###
loadGamesDataForDivision: (divisionName, callback) ->
divisionName = divisionName.toLowerCase()
dateKey = moment.utc().startOf('day').format("YYYY-MMPI:KEY:<KEY>END_PI-DD")
key = keyPrefix() + "#{divisionNamePI:KEY:<KEY>END_PI}:#{dateKey}"
Logger.module("REDIS").debug "loadGamesDataForDivision() -> #{divisionName}"
@redis.getAsync(key)
.then JSON.parse
.nodeify(callback)
###*
# Export a factory
###
module.exports = exports = (redis, opts) ->
RedisWatchableGamesManager = new RedisWatchableGamesManager(redis, opts)
return RedisWatchableGamesManager
|
[
{
"context": "ON.stringify(_attributes)\n\n payload = username: username, password: password, attributes: internalAttribut",
"end": 934,
"score": 0.9909452199935913,
"start": 926,
"tag": "USERNAME",
"value": "username"
},
{
"context": "utes)\n\n payload = username: username, pa... | server.coffee | emdagon/meteor-truevault-auth | 0 |
class TrueVaultException
constructor: (@code, @message) ->
toString: ->
"#{@code}, #{@message}"
class TrueVault
constructor: (@apiKey, @vaultId, @ROOT_URL = "https://api.truevault.com/v1") ->
getAuth: (token) -> Base64.encode((token or @apiKey) + ':')
getUser: (userId, full = false) ->
url = "#{@ROOT_URL}/users/#{userId}"
if full
url += '?full=1'
response = HTTP.get url, auth: @getAuth()
if response.statusCode is 200
user = response.data.user
if user.attributes
user.attributes = JSON.parse Base64.decode(user.attributes)
return user
else
error = response.error
throw new TrueVaultException error.code, error.message
createUser: (username, password, attributes = null) ->
url = "#{@ROOT_URL}/users"
_attributes = email: username
internalAttributes = Base64.decode JSON.stringify(_attributes)
payload = username: username, password: password, attributes: internalAttributes
response = HTTP.post url, data: payload, auth: @getAuth()
if response.statusCode is 200
user = response.data.user
if attributes instanceof Object
_.extend attributes _attributes
attributesId = @setUserAttributes @apiKey, _attributes
groupId = @createUserGroup user.user_id, attributesId
if user and attributesId and groupId
return user: user, attributesId: attributesId
else
console.error 'Failed trying to create User\'s attributes or group:', user, attributesId, groupId
throw new TrueVaultException 500, 'Failed trying to create the User'
else
error = response.error
throw new TrueVaultException error.code, error.message
updateUser: (userId, password = null, attributes = null, username = null) ->
if not password and not attributes
return null
url = "#{@ROOT_URL}/users/#{userId}"
payload = {}
if attributes instanceof Object
user = @getUser userId, true
if user
payload.attributes = Base64.encode json.stringify(attributes)
if password
payload.password = password
if username
payload.username = username
response = HTTP.put url, data: payload, auth: @getAuth()
if response.statusCode is 200
return response.data.user
else
error = response.error
throw new TrueVaultException error.code, error.message
searchUser: (email) ->
url = "#{@ROOT_URL}/users/search"
search = Base64.encode JSON.stringify(email: email)
payload = search_option: search
response = HTTP.post url, data: payload, auth: @getAuth()
if response.statusCode is 200
return response.data.users
else
error = response.error
throw new TrueVaultException error.code, error.message
verifyToken: (userId, token) ->
url = "#{@ROOT_URL}/auth/me"
response = HTTP.get url, auth: @getAuth(token)
data = response.data
if response.statusCode is 200 and data.user.user_id is userId
return data.user
else
error = response.error
throw new TrueVaultException error.code, error.message
setUserAttributes: (tokenOrKey, attributes, documentId = null) ->
url = "#{@ROOT_URL}/vaults/#{@vaultId}/documents"
if documentId is not null
_attributes = {}
url += "/" + documentId
response = HTTP.get url, auth: @getAuth(tokenOrKey)
data = response.data
if response.statusCode is 200 and data.documents
_attributes = Base64.decode data.documents[0].document
_.extend _attributes, attributes
payload = document: Base64.encode(JSON.stringify _attributes)
response = HTTP.put url, data: payload, auth: @getAuth(tokenOrKey)
else
payload = document: Base64.encode(JSON.stringify attributes)
response = HTTP.post url, data: payload, auth: @getAuth(tokenOrKey)
data = response.data
if response.statusCode is 200 and data.document_id
return data.document_id
else
error = response.error
throw new TrueVaultException error.code, error.message
createUserGroup: (userId, attributesDocumentId) ->
url = "#{@ROOT_URL}/groups"
policy = [{
Resources: ["Vault::#{@vaultId}::Document::#{attributesDocumentId}"]
Activities: "RU"
}]
payload = name: userId, policy: Base64.encode(JSON.stringify policy), user_ids: userId
response = HTTP.post url, data: payload, auth: @getAuth
data = response.data
if response.statusCode is 200 and data.group
return data.group.group_id
else
error = response.error
throw new TrueVaultException error.code, error.message
| 54313 |
class TrueVaultException
constructor: (@code, @message) ->
toString: ->
"#{@code}, #{@message}"
class TrueVault
constructor: (@apiKey, @vaultId, @ROOT_URL = "https://api.truevault.com/v1") ->
getAuth: (token) -> Base64.encode((token or @apiKey) + ':')
getUser: (userId, full = false) ->
url = "#{@ROOT_URL}/users/#{userId}"
if full
url += '?full=1'
response = HTTP.get url, auth: @getAuth()
if response.statusCode is 200
user = response.data.user
if user.attributes
user.attributes = JSON.parse Base64.decode(user.attributes)
return user
else
error = response.error
throw new TrueVaultException error.code, error.message
createUser: (username, password, attributes = null) ->
url = "#{@ROOT_URL}/users"
_attributes = email: username
internalAttributes = Base64.decode JSON.stringify(_attributes)
payload = username: username, password: <PASSWORD>, attributes: internalAttributes
response = HTTP.post url, data: payload, auth: @getAuth()
if response.statusCode is 200
user = response.data.user
if attributes instanceof Object
_.extend attributes _attributes
attributesId = @setUserAttributes @apiKey, _attributes
groupId = @createUserGroup user.user_id, attributesId
if user and attributesId and groupId
return user: user, attributesId: attributesId
else
console.error 'Failed trying to create User\'s attributes or group:', user, attributesId, groupId
throw new TrueVaultException 500, 'Failed trying to create the User'
else
error = response.error
throw new TrueVaultException error.code, error.message
updateUser: (userId, password = null, attributes = null, username = null) ->
if not password and not attributes
return null
url = "#{@ROOT_URL}/users/#{userId}"
payload = {}
if attributes instanceof Object
user = @getUser userId, true
if user
payload.attributes = Base64.encode json.stringify(attributes)
if password
payload.password = <PASSWORD>
if username
payload.username = username
response = HTTP.put url, data: payload, auth: @getAuth()
if response.statusCode is 200
return response.data.user
else
error = response.error
throw new TrueVaultException error.code, error.message
searchUser: (email) ->
url = "#{@ROOT_URL}/users/search"
search = Base64.encode JSON.stringify(email: email)
payload = search_option: search
response = HTTP.post url, data: payload, auth: @getAuth()
if response.statusCode is 200
return response.data.users
else
error = response.error
throw new TrueVaultException error.code, error.message
verifyToken: (userId, token) ->
url = "#{@ROOT_URL}/auth/me"
response = HTTP.get url, auth: @getAuth(token)
data = response.data
if response.statusCode is 200 and data.user.user_id is userId
return data.user
else
error = response.error
throw new TrueVaultException error.code, error.message
setUserAttributes: (tokenOrKey, attributes, documentId = null) ->
url = "#{@ROOT_URL}/vaults/#{@vaultId}/documents"
if documentId is not null
_attributes = {}
url += "/" + documentId
response = HTTP.get url, auth: @getAuth(tokenOrKey)
data = response.data
if response.statusCode is 200 and data.documents
_attributes = Base64.decode data.documents[0].document
_.extend _attributes, attributes
payload = document: Base64.encode(JSON.stringify _attributes)
response = HTTP.put url, data: payload, auth: @getAuth(tokenOrKey)
else
payload = document: Base64.encode(JSON.stringify attributes)
response = HTTP.post url, data: payload, auth: @getAuth(tokenOrKey)
data = response.data
if response.statusCode is 200 and data.document_id
return data.document_id
else
error = response.error
throw new TrueVaultException error.code, error.message
createUserGroup: (userId, attributesDocumentId) ->
url = "#{@ROOT_URL}/groups"
policy = [{
Resources: ["Vault::#{@vaultId}::Document::#{attributesDocumentId}"]
Activities: "RU"
}]
payload = name: userId, policy: Base64.encode(JSON.stringify policy), user_ids: userId
response = HTTP.post url, data: payload, auth: @getAuth
data = response.data
if response.statusCode is 200 and data.group
return data.group.group_id
else
error = response.error
throw new TrueVaultException error.code, error.message
| true |
class TrueVaultException
constructor: (@code, @message) ->
toString: ->
"#{@code}, #{@message}"
class TrueVault
constructor: (@apiKey, @vaultId, @ROOT_URL = "https://api.truevault.com/v1") ->
getAuth: (token) -> Base64.encode((token or @apiKey) + ':')
getUser: (userId, full = false) ->
url = "#{@ROOT_URL}/users/#{userId}"
if full
url += '?full=1'
response = HTTP.get url, auth: @getAuth()
if response.statusCode is 200
user = response.data.user
if user.attributes
user.attributes = JSON.parse Base64.decode(user.attributes)
return user
else
error = response.error
throw new TrueVaultException error.code, error.message
createUser: (username, password, attributes = null) ->
url = "#{@ROOT_URL}/users"
_attributes = email: username
internalAttributes = Base64.decode JSON.stringify(_attributes)
payload = username: username, password: PI:PASSWORD:<PASSWORD>END_PI, attributes: internalAttributes
response = HTTP.post url, data: payload, auth: @getAuth()
if response.statusCode is 200
user = response.data.user
if attributes instanceof Object
_.extend attributes _attributes
attributesId = @setUserAttributes @apiKey, _attributes
groupId = @createUserGroup user.user_id, attributesId
if user and attributesId and groupId
return user: user, attributesId: attributesId
else
console.error 'Failed trying to create User\'s attributes or group:', user, attributesId, groupId
throw new TrueVaultException 500, 'Failed trying to create the User'
else
error = response.error
throw new TrueVaultException error.code, error.message
updateUser: (userId, password = null, attributes = null, username = null) ->
if not password and not attributes
return null
url = "#{@ROOT_URL}/users/#{userId}"
payload = {}
if attributes instanceof Object
user = @getUser userId, true
if user
payload.attributes = Base64.encode json.stringify(attributes)
if password
payload.password = PI:PASSWORD:<PASSWORD>END_PI
if username
payload.username = username
response = HTTP.put url, data: payload, auth: @getAuth()
if response.statusCode is 200
return response.data.user
else
error = response.error
throw new TrueVaultException error.code, error.message
searchUser: (email) ->
url = "#{@ROOT_URL}/users/search"
search = Base64.encode JSON.stringify(email: email)
payload = search_option: search
response = HTTP.post url, data: payload, auth: @getAuth()
if response.statusCode is 200
return response.data.users
else
error = response.error
throw new TrueVaultException error.code, error.message
verifyToken: (userId, token) ->
url = "#{@ROOT_URL}/auth/me"
response = HTTP.get url, auth: @getAuth(token)
data = response.data
if response.statusCode is 200 and data.user.user_id is userId
return data.user
else
error = response.error
throw new TrueVaultException error.code, error.message
setUserAttributes: (tokenOrKey, attributes, documentId = null) ->
url = "#{@ROOT_URL}/vaults/#{@vaultId}/documents"
if documentId is not null
_attributes = {}
url += "/" + documentId
response = HTTP.get url, auth: @getAuth(tokenOrKey)
data = response.data
if response.statusCode is 200 and data.documents
_attributes = Base64.decode data.documents[0].document
_.extend _attributes, attributes
payload = document: Base64.encode(JSON.stringify _attributes)
response = HTTP.put url, data: payload, auth: @getAuth(tokenOrKey)
else
payload = document: Base64.encode(JSON.stringify attributes)
response = HTTP.post url, data: payload, auth: @getAuth(tokenOrKey)
data = response.data
if response.statusCode is 200 and data.document_id
return data.document_id
else
error = response.error
throw new TrueVaultException error.code, error.message
createUserGroup: (userId, attributesDocumentId) ->
url = "#{@ROOT_URL}/groups"
policy = [{
Resources: ["Vault::#{@vaultId}::Document::#{attributesDocumentId}"]
Activities: "RU"
}]
payload = name: userId, policy: Base64.encode(JSON.stringify policy), user_ids: userId
response = HTTP.post url, data: payload, auth: @getAuth
data = response.data
if response.statusCode is 200 and data.group
return data.group.group_id
else
error = response.error
throw new TrueVaultException error.code, error.message
|
[
{
"context": "(key)->\n key is camelCase(key) or key.match /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/ # we need a custom d",
"end": 3302,
"score": 0.7000575661659241,
"start": 3295,
"tag": "KEY",
"value": "d{4}-\\d"
},
{
"context": " key is camelCase(key) or key.match /^\\d{4... | src/models/firebase-model.coffee | citizencode/swarmbot | 21 | {log, p, json, pjson, type} = require 'lightsaber'
{ assign, camelCase, last } = require 'lodash'
swarmbot = require './swarmbot'
class FirebaseModel
@find: (name, options={})->
new @ {name}, options
.fetchIfNeeded()
@findBy: Promise.promisify (attrName, attrValue, cb)->
# @assertValidKey attrName
swarmbot.firebase().child(@::urlRoot)
.orderByChild(attrName)
.equalTo(attrValue)
.limitToFirst(1)
.once 'value', (snapshot)=>
if snapshot.val()
key = Object.keys(snapshot.val())[0]
cb(null, new @({}, snapshot: snapshot.child(key)))
else
cb(new Promise.OperationalError("Cannot find a model with #{attrName} equal to #{attrValue}."))
, cb # error
constructor: (@attributes={}, options={})->
@assertValidKeysWithin @attributes
@hasParent = @hasParent || false
@parent = options.parent
throw new Error "urlRoot must be set." unless @urlRoot
throw new Error "This model requires a parent." if @hasParent && !@parent
throw new Error "please pass name, not id in attributes" if @attributes.id?
throw new Error "@attributes must contain 'name'; got #{pjson @attributes}" if !@attributes.name? and !options.snapshot?
@snapshot = if options.snapshot
options.snapshot
else if @parent?.snapshot?
@parent.snapshot.child(@urlRoot).child(@key())
@parseSnapshot() if @snapshot?
# Firebase-safe key
# Converts each illegal character: .#$[] to a single dash
# if .name is 'strange .#$[] chars!'
# .key will be 'strange ----- chars!'
key: ->
if not @attributes.name?
@fetch().then => throw new Error "before fetching, @attributes.name was not found for #{pjson @attributes}"
throw new Error "@attributes.name not found, got #{pjson @attributes}"
key = @attributes.name.replace(/[.#$\[\]]/g, '-')
firebase: ->
swarmbot.firebase().child(@firebasePath())
firebasePath: ->
parentPath = if @hasParent then @parent.firebasePath() else ''
[ parentPath, @urlRoot, @key() ].join '/'
get: (attr)->
@assertValidKey attr
@attributes[attr]
set: (attr, val)->
@attributes[attr] = val
@save()
update: (newAttributes)->
assign @attributes, newAttributes
@save()
fetch: Promise.promisify (cb)->
throw new Error "No 'name' attribute is set, cannot fetch" unless @get('name')
@firebase().once 'value', (@snapshot)=>
@parseSnapshot()
cb(null, @)
, cb # failure callback
fetchIfNeeded: ->
if @snapshot?
Promise.resolve(@)
else
@fetch()
save: Promise.promisify (cb)->
@assertValidKeysWithin @attributes
@firebase().update @attributes, (error)=> cb error, @
exists: ->
@snapshot.exists()
parseSnapshot: ->
assign @attributes, @snapshot.val()
@
assertValidKeysWithin: (attributes, fullAttributes)->
fullAttributes ?= attributes
for own key, value of attributes
@assertValidKey key, fullAttributes
assertValidKey: (key, attributes=null)->
if not @validKey key
message = "Expected all DB keys to be camel case or dates, but got '#{key}'"
message += " within #{pjson attributes}" if attributes
throw new Error message
validKey: (key)->
key is camelCase(key) or key.match /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/ # we need a custom date pattern, because to make a valid firebase key, we've made an invalid date string
module.exports = FirebaseModel
| 79785 | {log, p, json, pjson, type} = require 'lightsaber'
{ assign, camelCase, last } = require 'lodash'
swarmbot = require './swarmbot'
class FirebaseModel
@find: (name, options={})->
new @ {name}, options
.fetchIfNeeded()
@findBy: Promise.promisify (attrName, attrValue, cb)->
# @assertValidKey attrName
swarmbot.firebase().child(@::urlRoot)
.orderByChild(attrName)
.equalTo(attrValue)
.limitToFirst(1)
.once 'value', (snapshot)=>
if snapshot.val()
key = Object.keys(snapshot.val())[0]
cb(null, new @({}, snapshot: snapshot.child(key)))
else
cb(new Promise.OperationalError("Cannot find a model with #{attrName} equal to #{attrValue}."))
, cb # error
constructor: (@attributes={}, options={})->
@assertValidKeysWithin @attributes
@hasParent = @hasParent || false
@parent = options.parent
throw new Error "urlRoot must be set." unless @urlRoot
throw new Error "This model requires a parent." if @hasParent && !@parent
throw new Error "please pass name, not id in attributes" if @attributes.id?
throw new Error "@attributes must contain 'name'; got #{pjson @attributes}" if !@attributes.name? and !options.snapshot?
@snapshot = if options.snapshot
options.snapshot
else if @parent?.snapshot?
@parent.snapshot.child(@urlRoot).child(@key())
@parseSnapshot() if @snapshot?
# Firebase-safe key
# Converts each illegal character: .#$[] to a single dash
# if .name is 'strange .#$[] chars!'
# .key will be 'strange ----- chars!'
key: ->
if not @attributes.name?
@fetch().then => throw new Error "before fetching, @attributes.name was not found for #{pjson @attributes}"
throw new Error "@attributes.name not found, got #{pjson @attributes}"
key = @attributes.name.replace(/[.#$\[\]]/g, '-')
firebase: ->
swarmbot.firebase().child(@firebasePath())
firebasePath: ->
parentPath = if @hasParent then @parent.firebasePath() else ''
[ parentPath, @urlRoot, @key() ].join '/'
get: (attr)->
@assertValidKey attr
@attributes[attr]
set: (attr, val)->
@attributes[attr] = val
@save()
update: (newAttributes)->
assign @attributes, newAttributes
@save()
fetch: Promise.promisify (cb)->
throw new Error "No 'name' attribute is set, cannot fetch" unless @get('name')
@firebase().once 'value', (@snapshot)=>
@parseSnapshot()
cb(null, @)
, cb # failure callback
fetchIfNeeded: ->
if @snapshot?
Promise.resolve(@)
else
@fetch()
save: Promise.promisify (cb)->
@assertValidKeysWithin @attributes
@firebase().update @attributes, (error)=> cb error, @
exists: ->
@snapshot.exists()
parseSnapshot: ->
assign @attributes, @snapshot.val()
@
assertValidKeysWithin: (attributes, fullAttributes)->
fullAttributes ?= attributes
for own key, value of attributes
@assertValidKey key, fullAttributes
assertValidKey: (key, attributes=null)->
if not @validKey key
message = "Expected all DB keys to be camel case or dates, but got '#{key}'"
message += " within #{pjson attributes}" if attributes
throw new Error message
validKey: (key)->
key is camelCase(key) or key.match /^\<KEY>{2}-\<KEY>{2}T\d{2}:\d{2}:\d{2}/ # we need a custom date pattern, because to make a valid firebase key, we've made an invalid date string
module.exports = FirebaseModel
| true | {log, p, json, pjson, type} = require 'lightsaber'
{ assign, camelCase, last } = require 'lodash'
swarmbot = require './swarmbot'
class FirebaseModel
@find: (name, options={})->
new @ {name}, options
.fetchIfNeeded()
@findBy: Promise.promisify (attrName, attrValue, cb)->
# @assertValidKey attrName
swarmbot.firebase().child(@::urlRoot)
.orderByChild(attrName)
.equalTo(attrValue)
.limitToFirst(1)
.once 'value', (snapshot)=>
if snapshot.val()
key = Object.keys(snapshot.val())[0]
cb(null, new @({}, snapshot: snapshot.child(key)))
else
cb(new Promise.OperationalError("Cannot find a model with #{attrName} equal to #{attrValue}."))
, cb # error
constructor: (@attributes={}, options={})->
@assertValidKeysWithin @attributes
@hasParent = @hasParent || false
@parent = options.parent
throw new Error "urlRoot must be set." unless @urlRoot
throw new Error "This model requires a parent." if @hasParent && !@parent
throw new Error "please pass name, not id in attributes" if @attributes.id?
throw new Error "@attributes must contain 'name'; got #{pjson @attributes}" if !@attributes.name? and !options.snapshot?
@snapshot = if options.snapshot
options.snapshot
else if @parent?.snapshot?
@parent.snapshot.child(@urlRoot).child(@key())
@parseSnapshot() if @snapshot?
# Firebase-safe key
# Converts each illegal character: .#$[] to a single dash
# if .name is 'strange .#$[] chars!'
# .key will be 'strange ----- chars!'
key: ->
if not @attributes.name?
@fetch().then => throw new Error "before fetching, @attributes.name was not found for #{pjson @attributes}"
throw new Error "@attributes.name not found, got #{pjson @attributes}"
key = @attributes.name.replace(/[.#$\[\]]/g, '-')
firebase: ->
swarmbot.firebase().child(@firebasePath())
firebasePath: ->
parentPath = if @hasParent then @parent.firebasePath() else ''
[ parentPath, @urlRoot, @key() ].join '/'
get: (attr)->
@assertValidKey attr
@attributes[attr]
set: (attr, val)->
@attributes[attr] = val
@save()
update: (newAttributes)->
assign @attributes, newAttributes
@save()
fetch: Promise.promisify (cb)->
throw new Error "No 'name' attribute is set, cannot fetch" unless @get('name')
@firebase().once 'value', (@snapshot)=>
@parseSnapshot()
cb(null, @)
, cb # failure callback
fetchIfNeeded: ->
if @snapshot?
Promise.resolve(@)
else
@fetch()
save: Promise.promisify (cb)->
@assertValidKeysWithin @attributes
@firebase().update @attributes, (error)=> cb error, @
exists: ->
@snapshot.exists()
parseSnapshot: ->
assign @attributes, @snapshot.val()
@
assertValidKeysWithin: (attributes, fullAttributes)->
fullAttributes ?= attributes
for own key, value of attributes
@assertValidKey key, fullAttributes
assertValidKey: (key, attributes=null)->
if not @validKey key
message = "Expected all DB keys to be camel case or dates, but got '#{key}'"
message += " within #{pjson attributes}" if attributes
throw new Error message
validKey: (key)->
key is camelCase(key) or key.match /^\PI:KEY:<KEY>END_PI{2}-\PI:KEY:<KEY>END_PI{2}T\d{2}:\d{2}:\d{2}/ # we need a custom date pattern, because to make a valid firebase key, we've made an invalid date string
module.exports = FirebaseModel
|
[
{
"context": "n}\" else \"#{n}\"\n\n key: (d, i) ->\n \"#{d.year()}-#{d.mon()}-#{d.day()}-#{i}\"\n\n path: (d, i) ->\n ",
"end": 963,
"score": 0.6290526390075684,
"start": 963,
"tag": "KEY",
"value": ""
},
{
"context": "{n}\"\n\n key: (d, i) ->\n \"#{d.year()}-#{d.mon()}-#... | src/WeatherModel.coffee | higuma/tenki-data-map | 11 | CACHE_LIMIT = 100
cache = {}
queue = []
class WeatherModel
# <- Conrtroller
constructor: (@ctl) ->
getData: (day, hour) ->
key = @key day, (hour / 6) >> 0
data = cache[key]
if @isData data
queue.splice queue.indexOf(key), 1
queue.push key
data
isData: (data) -> $.type(data) == 'string'
isFetching: (data) -> data? && $.type(data) != 'string'
xhr: (day, hour) ->
index = (hour / 6) >> 0
key = @key day, index
if cache[key]?
@getData day hour # move to the top of cache
return
cache[key] = promise = $.get @path(day, index)
promise.done (data) =>
cache[key] = data
delete cache[queue.shift()] if queue.length >= CACHE_LIMIT
queue.push key
@ctl.xhrDone day, hour, data
promise.fail (xhrObj) =>
delete cache[key]
@ctl.xhrFail day, hour, xhrObj
# internal
sNN: (n) -> if n < 10 then "0#{n}" else "#{n}"
key: (d, i) ->
"#{d.year()}-#{d.mon()}-#{d.day()}-#{i}"
path: (d, i) ->
"data/hourly/map/#{d.year()}/#{@sNN d.mon()}#{@sNN d.day()}/#{i}.csv"
window.WeatherModel = WeatherModel
| 149802 | CACHE_LIMIT = 100
cache = {}
queue = []
class WeatherModel
# <- Conrtroller
constructor: (@ctl) ->
getData: (day, hour) ->
key = @key day, (hour / 6) >> 0
data = cache[key]
if @isData data
queue.splice queue.indexOf(key), 1
queue.push key
data
isData: (data) -> $.type(data) == 'string'
isFetching: (data) -> data? && $.type(data) != 'string'
xhr: (day, hour) ->
index = (hour / 6) >> 0
key = @key day, index
if cache[key]?
@getData day hour # move to the top of cache
return
cache[key] = promise = $.get @path(day, index)
promise.done (data) =>
cache[key] = data
delete cache[queue.shift()] if queue.length >= CACHE_LIMIT
queue.push key
@ctl.xhrDone day, hour, data
promise.fail (xhrObj) =>
delete cache[key]
@ctl.xhrFail day, hour, xhrObj
# internal
sNN: (n) -> if n < 10 then "0#{n}" else "#{n}"
key: (d, i) ->
"#{d.year()}<KEY>-#{d.mon()}<KEY>-#{d.day()}<KEY>-#{i}"
path: (d, i) ->
"data/hourly/map/#{d.year()}/#{@sNN d.mon()}#{@sNN d.day()}/#{i}.csv"
window.WeatherModel = WeatherModel
| true | CACHE_LIMIT = 100
cache = {}
queue = []
class WeatherModel
# <- Conrtroller
constructor: (@ctl) ->
getData: (day, hour) ->
key = @key day, (hour / 6) >> 0
data = cache[key]
if @isData data
queue.splice queue.indexOf(key), 1
queue.push key
data
isData: (data) -> $.type(data) == 'string'
isFetching: (data) -> data? && $.type(data) != 'string'
xhr: (day, hour) ->
index = (hour / 6) >> 0
key = @key day, index
if cache[key]?
@getData day hour # move to the top of cache
return
cache[key] = promise = $.get @path(day, index)
promise.done (data) =>
cache[key] = data
delete cache[queue.shift()] if queue.length >= CACHE_LIMIT
queue.push key
@ctl.xhrDone day, hour, data
promise.fail (xhrObj) =>
delete cache[key]
@ctl.xhrFail day, hour, xhrObj
# internal
sNN: (n) -> if n < 10 then "0#{n}" else "#{n}"
key: (d, i) ->
"#{d.year()}PI:KEY:<KEY>END_PI-#{d.mon()}PI:KEY:<KEY>END_PI-#{d.day()}PI:KEY:<KEY>END_PI-#{i}"
path: (d, i) ->
"data/hourly/map/#{d.year()}/#{@sNN d.mon()}#{@sNN d.day()}/#{i}.csv"
window.WeatherModel = WeatherModel
|
[
{
"context": "# grunt-react-render\n# https://github.com/alexander/grunt-react-render\n\n# Copyright (c) 2014 AlexMost",
"end": 51,
"score": 0.9997047185897827,
"start": 42,
"tag": "USERNAME",
"value": "alexander"
},
{
"context": "alexander/grunt-react-render\n\n# Copyright (c) 2014 ... | test/test_basic_component_render.coffee | AlexMost/grunt-react-render | 1 | # grunt-react-render
# https://github.com/alexander/grunt-react-render
# Copyright (c) 2014 AlexMost
# Licensed under the MIT license.
{processFile} = require '../src/lib'
cheerio = require 'cheerio'
fs = require 'fs'
path = require 'path'
exports.test_component_render = (test) ->
filePath = path.resolve './test/fixtures/render1comp.html'
destPath = path.join (path.resolve './test/tmp'), 'render1comp.result.html'
processFile filePath, destPath, (error) ->
test.ok !error
fs.readFile destPath, (err, content) ->
test.ok !err, "failed to read rendered file"
test.ok Boolean(content)
$ = cheerio.load content.toString()
test.ok(
$('#comp1').length is 1
"React component1 was not rendered"
)
test.ok(
$('#comp2').length is 1
"React component2 was not rendered"
)
test.ok(
$('#comp1').text() is 'testDiv p1=val1'
"React component1 props not rendered"
)
test.done() | 41670 | # grunt-react-render
# https://github.com/alexander/grunt-react-render
# Copyright (c) 2014 <NAME>
# Licensed under the MIT license.
{processFile} = require '../src/lib'
cheerio = require 'cheerio'
fs = require 'fs'
path = require 'path'
exports.test_component_render = (test) ->
filePath = path.resolve './test/fixtures/render1comp.html'
destPath = path.join (path.resolve './test/tmp'), 'render1comp.result.html'
processFile filePath, destPath, (error) ->
test.ok !error
fs.readFile destPath, (err, content) ->
test.ok !err, "failed to read rendered file"
test.ok Boolean(content)
$ = cheerio.load content.toString()
test.ok(
$('#comp1').length is 1
"React component1 was not rendered"
)
test.ok(
$('#comp2').length is 1
"React component2 was not rendered"
)
test.ok(
$('#comp1').text() is 'testDiv p1=val1'
"React component1 props not rendered"
)
test.done() | true | # grunt-react-render
# https://github.com/alexander/grunt-react-render
# Copyright (c) 2014 PI:NAME:<NAME>END_PI
# Licensed under the MIT license.
{processFile} = require '../src/lib'
cheerio = require 'cheerio'
fs = require 'fs'
path = require 'path'
exports.test_component_render = (test) ->
filePath = path.resolve './test/fixtures/render1comp.html'
destPath = path.join (path.resolve './test/tmp'), 'render1comp.result.html'
processFile filePath, destPath, (error) ->
test.ok !error
fs.readFile destPath, (err, content) ->
test.ok !err, "failed to read rendered file"
test.ok Boolean(content)
$ = cheerio.load content.toString()
test.ok(
$('#comp1').length is 1
"React component1 was not rendered"
)
test.ok(
$('#comp2').length is 1
"React component2 was not rendered"
)
test.ok(
$('#comp1').text() is 'testDiv p1=val1'
"React component1 props not rendered"
)
test.done() |
[
{
"context": "=hallo\n## http://localhost:9088/api-docs/\n## user: test, pass: asdf\n##\nmodule.exports =\n\n type: 'http.",
"end": 126,
"score": 0.9947658777236938,
"start": 122,
"tag": "USERNAME",
"value": "test"
},
{
"context": "tp://localhost:9088/api-docs/\n## user: test, pas... | examples/omarpc-swagger/app.coffee | nero-networks/floyd | 0 | ##
## Swagger RpcServer Example
##
## http://localhost:9088/api/echo?in=hallo
## http://localhost:9088/api-docs/
## user: test, pass: asdf
##
module.exports =
type: 'http.Server'
data:
port: 9088
#logger:
# level: 'DEBUG'
sessions:
cookie: false # deactivates cookie SID middleware
children: [
## substitute the users db with data
id: 'users'
memory:
test:
roles: ["tester"]
pass: '8e19a8e1ab8ee4ec4686a558b0bb221d-SHA256-4-1500-999126a0c5af65781f9b72f4e538d2d8'
,
## setup a RpcServer context
type: 'omarpc.SwaggerContext'
,
## setup a simple Context with a protected method
id: 'test'
permissions:
secret:
roles: 'tester'
## this method is public for everyone
echo: (str, fn)->
fn null, str
## only users with the tester role can access this method
secret: (fn)->
fn null, 'Secret: 42'
]
| 36 | ##
## Swagger RpcServer Example
##
## http://localhost:9088/api/echo?in=hallo
## http://localhost:9088/api-docs/
## user: test, pass: <PASSWORD>
##
module.exports =
type: 'http.Server'
data:
port: 9088
#logger:
# level: 'DEBUG'
sessions:
cookie: false # deactivates cookie SID middleware
children: [
## substitute the users db with data
id: 'users'
memory:
test:
roles: ["tester"]
pass: '<PASSWORD>-<PASSWORD>'
,
## setup a RpcServer context
type: 'omarpc.SwaggerContext'
,
## setup a simple Context with a protected method
id: 'test'
permissions:
secret:
roles: 'tester'
## this method is public for everyone
echo: (str, fn)->
fn null, str
## only users with the tester role can access this method
secret: (fn)->
fn null, 'Secret: 42'
]
| true | ##
## Swagger RpcServer Example
##
## http://localhost:9088/api/echo?in=hallo
## http://localhost:9088/api-docs/
## user: test, pass: PI:PASSWORD:<PASSWORD>END_PI
##
module.exports =
type: 'http.Server'
data:
port: 9088
#logger:
# level: 'DEBUG'
sessions:
cookie: false # deactivates cookie SID middleware
children: [
## substitute the users db with data
id: 'users'
memory:
test:
roles: ["tester"]
pass: 'PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI'
,
## setup a RpcServer context
type: 'omarpc.SwaggerContext'
,
## setup a simple Context with a protected method
id: 'test'
permissions:
secret:
roles: 'tester'
## this method is public for everyone
echo: (str, fn)->
fn null, str
## only users with the tester role can access this method
secret: (fn)->
fn null, 'Secret: 42'
]
|
[
{
"context": ".fm/progressive?$DIFMKEY#/di-progressive\" \"http://212.7.196.96:8000/#/pure-progressive\"\n#\n# TODO buffering issue",
"end": 118,
"score": 0.9996511340141296,
"start": 106,
"tag": "IP_ADDRESS",
"value": "212.7.196.96"
}
] | repeater.iced | idiomatic/radio-repeater | 0 | #!/usr/bin/env iced
#
# iced radio.iced "http://prem1.di.fm/progressive?$DIFMKEY#/di-progressive" "http://212.7.196.96:8000/#/pure-progressive"
#
# TODO buffering issues: perhaps send some backlog?
# TODO port from command line switches
# TODO merge with archiver; differentiate mode with subcommands
stream = require 'stream'
util = require 'util'
koa = require 'koa'
route = require 'koa-route'
icy = require 'icy'
port = 8000
once = (fn) ->
(args...) ->
fn_ = fn
fn = undefined
fn_?(args...)
class NullWriter extends stream.Writable
_write: (chunk, encoding, cb) ->
cb()
class Repeater
metadataInterval: 4096
breather: 3000
constructor: (@inboundURL) ->
@inbound = null
@metadata = null
@httpPrefix = null
run: ->
do =>
loop
await @connect defer err
await
done = once defer()
@inbound?.on 'close', ->
console.log "closed"
done()
@inbound?.on 'end', ->
console.log "ended"
done()
console.log "retrying #{@inboundURL}"
await setTimeout(defer(), @breather)
return this
connect: (cb) =>
await
@metadata = null
#done = defer err, @inbound
#console.log "connecting to #{@inboundURL}"
#icy.get(@inboundURL, (inbound) => done(null, inbound))
# .on('error', done)
console.log "connecting to #{@inboundURL}"
icy.get(@inboundURL, defer @inbound)
#return cb?(err) if err
@inbound.on 'metadata', (metadata) =>
@metadata = icy.parse(metadata)
@inbound.on 'error', (err) =>
console.log "#{@inboundURL} error #{err}"
# HACK: inbound should not pause if nobody is listening; discard instead
@inbound.pipe(new NullWriter)
cb()
handler: =>
channel = this
return (next) ->
ua = @headers['user-agent']
console.log("connection from #{@ip} (#{ua})")
# warning: if inbound disconnects, so do all clients
{inbound} = channel
ih = inbound.headers
@status = 200
@set
'accept-ranges': 'none'
'content-type': ih['content-type'] or 'audio/mpeg'
'icy-br': ih['icy-br'] or ''
'icy-bitrate': ih['icy-bitrate'] or ''
'icy-audio-info': ih['icy-audio-info'] or ''
'icy-description': ih['icy-description'] or ''
'icy-genre': ih['icy-genre'] or ''
'icy-name': ih['icy-name'] or ''
'icy-pub': ih['icy-pub'] or 0
'icy-url': @request.href or ih['icy-url'] or ''
'icy-metaint': channel.metadataInterval
if @headers['icy-metadata']
outbound = icy.Writer(channel.metadataInterval)
# send initial metadata, before next title change
metadata = =>
if channel.metadata
outbound.queue(channel.metadata)
metadata()
inbound.on('metadata', metadata)
else
outbound = stream.PassThrough()
close = =>
inbound.unpipe(outbound)
inbound.removeListener('metadata', metadata or ->)
@socket.removeListener('close', close)
@socket.on('close', close)
inbound.pipe(outbound)
#@body = outbound
# HACK: buffer output
@body = outbound.pipe(new stream.PassThrough)
yield return
if require.main is module
[_, _, argv...] = process.argv
app = koa()
httpPrefixes = []
for channel, i in argv
[inboundURL, httpPrefix] = channel.split('#')
httpPrefix ?= "/channel-#{i}"
httpPrefixes.push(httpPrefix)
c = new Repeater(inboundURL).run()
app.use(route.get(httpPrefix, c.handler()))
app.use route.get '/', (next) ->
if @headers.accepts is 'application/json'
@body = httpPrefixes
else
yield next
app.listen(port)
module.exports = {Repeater}
| 81188 | #!/usr/bin/env iced
#
# iced radio.iced "http://prem1.di.fm/progressive?$DIFMKEY#/di-progressive" "http://172.16.58.3:8000/#/pure-progressive"
#
# TODO buffering issues: perhaps send some backlog?
# TODO port from command line switches
# TODO merge with archiver; differentiate mode with subcommands
stream = require 'stream'
util = require 'util'
koa = require 'koa'
route = require 'koa-route'
icy = require 'icy'
port = 8000
once = (fn) ->
(args...) ->
fn_ = fn
fn = undefined
fn_?(args...)
class NullWriter extends stream.Writable
_write: (chunk, encoding, cb) ->
cb()
class Repeater
metadataInterval: 4096
breather: 3000
constructor: (@inboundURL) ->
@inbound = null
@metadata = null
@httpPrefix = null
run: ->
do =>
loop
await @connect defer err
await
done = once defer()
@inbound?.on 'close', ->
console.log "closed"
done()
@inbound?.on 'end', ->
console.log "ended"
done()
console.log "retrying #{@inboundURL}"
await setTimeout(defer(), @breather)
return this
connect: (cb) =>
await
@metadata = null
#done = defer err, @inbound
#console.log "connecting to #{@inboundURL}"
#icy.get(@inboundURL, (inbound) => done(null, inbound))
# .on('error', done)
console.log "connecting to #{@inboundURL}"
icy.get(@inboundURL, defer @inbound)
#return cb?(err) if err
@inbound.on 'metadata', (metadata) =>
@metadata = icy.parse(metadata)
@inbound.on 'error', (err) =>
console.log "#{@inboundURL} error #{err}"
# HACK: inbound should not pause if nobody is listening; discard instead
@inbound.pipe(new NullWriter)
cb()
handler: =>
channel = this
return (next) ->
ua = @headers['user-agent']
console.log("connection from #{@ip} (#{ua})")
# warning: if inbound disconnects, so do all clients
{inbound} = channel
ih = inbound.headers
@status = 200
@set
'accept-ranges': 'none'
'content-type': ih['content-type'] or 'audio/mpeg'
'icy-br': ih['icy-br'] or ''
'icy-bitrate': ih['icy-bitrate'] or ''
'icy-audio-info': ih['icy-audio-info'] or ''
'icy-description': ih['icy-description'] or ''
'icy-genre': ih['icy-genre'] or ''
'icy-name': ih['icy-name'] or ''
'icy-pub': ih['icy-pub'] or 0
'icy-url': @request.href or ih['icy-url'] or ''
'icy-metaint': channel.metadataInterval
if @headers['icy-metadata']
outbound = icy.Writer(channel.metadataInterval)
# send initial metadata, before next title change
metadata = =>
if channel.metadata
outbound.queue(channel.metadata)
metadata()
inbound.on('metadata', metadata)
else
outbound = stream.PassThrough()
close = =>
inbound.unpipe(outbound)
inbound.removeListener('metadata', metadata or ->)
@socket.removeListener('close', close)
@socket.on('close', close)
inbound.pipe(outbound)
#@body = outbound
# HACK: buffer output
@body = outbound.pipe(new stream.PassThrough)
yield return
if require.main is module
[_, _, argv...] = process.argv
app = koa()
httpPrefixes = []
for channel, i in argv
[inboundURL, httpPrefix] = channel.split('#')
httpPrefix ?= "/channel-#{i}"
httpPrefixes.push(httpPrefix)
c = new Repeater(inboundURL).run()
app.use(route.get(httpPrefix, c.handler()))
app.use route.get '/', (next) ->
if @headers.accepts is 'application/json'
@body = httpPrefixes
else
yield next
app.listen(port)
module.exports = {Repeater}
| true | #!/usr/bin/env iced
#
# iced radio.iced "http://prem1.di.fm/progressive?$DIFMKEY#/di-progressive" "http://PI:IP_ADDRESS:172.16.58.3END_PI:8000/#/pure-progressive"
#
# TODO buffering issues: perhaps send some backlog?
# TODO port from command line switches
# TODO merge with archiver; differentiate mode with subcommands
stream = require 'stream'
util = require 'util'
koa = require 'koa'
route = require 'koa-route'
icy = require 'icy'
port = 8000
once = (fn) ->
(args...) ->
fn_ = fn
fn = undefined
fn_?(args...)
class NullWriter extends stream.Writable
_write: (chunk, encoding, cb) ->
cb()
class Repeater
metadataInterval: 4096
breather: 3000
constructor: (@inboundURL) ->
@inbound = null
@metadata = null
@httpPrefix = null
run: ->
do =>
loop
await @connect defer err
await
done = once defer()
@inbound?.on 'close', ->
console.log "closed"
done()
@inbound?.on 'end', ->
console.log "ended"
done()
console.log "retrying #{@inboundURL}"
await setTimeout(defer(), @breather)
return this
connect: (cb) =>
await
@metadata = null
#done = defer err, @inbound
#console.log "connecting to #{@inboundURL}"
#icy.get(@inboundURL, (inbound) => done(null, inbound))
# .on('error', done)
console.log "connecting to #{@inboundURL}"
icy.get(@inboundURL, defer @inbound)
#return cb?(err) if err
@inbound.on 'metadata', (metadata) =>
@metadata = icy.parse(metadata)
@inbound.on 'error', (err) =>
console.log "#{@inboundURL} error #{err}"
# HACK: inbound should not pause if nobody is listening; discard instead
@inbound.pipe(new NullWriter)
cb()
handler: =>
channel = this
return (next) ->
ua = @headers['user-agent']
console.log("connection from #{@ip} (#{ua})")
# warning: if inbound disconnects, so do all clients
{inbound} = channel
ih = inbound.headers
@status = 200
@set
'accept-ranges': 'none'
'content-type': ih['content-type'] or 'audio/mpeg'
'icy-br': ih['icy-br'] or ''
'icy-bitrate': ih['icy-bitrate'] or ''
'icy-audio-info': ih['icy-audio-info'] or ''
'icy-description': ih['icy-description'] or ''
'icy-genre': ih['icy-genre'] or ''
'icy-name': ih['icy-name'] or ''
'icy-pub': ih['icy-pub'] or 0
'icy-url': @request.href or ih['icy-url'] or ''
'icy-metaint': channel.metadataInterval
if @headers['icy-metadata']
outbound = icy.Writer(channel.metadataInterval)
# send initial metadata, before next title change
metadata = =>
if channel.metadata
outbound.queue(channel.metadata)
metadata()
inbound.on('metadata', metadata)
else
outbound = stream.PassThrough()
close = =>
inbound.unpipe(outbound)
inbound.removeListener('metadata', metadata or ->)
@socket.removeListener('close', close)
@socket.on('close', close)
inbound.pipe(outbound)
#@body = outbound
# HACK: buffer output
@body = outbound.pipe(new stream.PassThrough)
yield return
if require.main is module
[_, _, argv...] = process.argv
app = koa()
httpPrefixes = []
for channel, i in argv
[inboundURL, httpPrefix] = channel.split('#')
httpPrefix ?= "/channel-#{i}"
httpPrefixes.push(httpPrefix)
c = new Repeater(inboundURL).run()
app.use(route.get(httpPrefix, c.handler()))
app.use route.get '/', (next) ->
if @headers.accepts is 'application/json'
@body = httpPrefixes
else
yield next
app.listen(port)
module.exports = {Repeater}
|
[
{
"context": "ot of scantwo results (2-dim, 2-QTL genome scan)\n# Karl W Broman\n\niplotScantwo = (widgetdiv, scantwo_data, pheno_a",
"end": 94,
"score": 0.9998164176940918,
"start": 81,
"tag": "NAME",
"value": "Karl W Broman"
}
] | inst/htmlwidgets/lib/qtlcharts/iplotScantwo.coffee | cran/qtlcharts | 64 | # iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan)
# Karl W Broman
iplotScantwo = (widgetdiv, scantwo_data, pheno_and_geno, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 1200 # total height of chart in pixels
width = chartOpts?.width ? 1100 # total width of chart in pixels
chrGap = chartOpts?.chrGap ? 2 # gaps between chr in heat map
wright = chartOpts?.wright ? width/2 # width (in pixels) of right panels
hbot = chartOpts?.hbot ? height/5 # height (in pixels) of each of the lower panels
margin = chartOpts?.margin ? {left:60, top:50, right:10, bottom: 40, inner: 5} # margins in each panel
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # axis positions in heatmap
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
rectcolor = chartOpts?.rectcolor ? "#e6e6e6" # color for background rectangle
altrectcolor = chartOpts?.altrectcolor ? "#c8c8c8" # alternate rectangle in lower panels
chrlinecolor = chartOpts?.chrlinecolor ? "" # color of lines between chromosomes (if "", leave off)
chrlinewidth = chartOpts?.chrlinewidth ? 2 # width of lines between chromosomes
nullcolor = chartOpts?.nullcolor ? "#e6e6e6" # color of null pixels in heat map
boxcolor = chartOpts?.boxcolor ? "black" # color of box around each panel
boxwidth = chartOpts?.boxwidth ? 2 # width of box around each panel
linecolor = chartOpts?.linecolor ? "slateblue" # line color in lower panels
linewidth = chartOpts?.linewidth ? 2 # line width in lower panels
pointsize = chartOpts?.pointsize ? 2 # point size in right panels
pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle in right panels
cicolors = chartOpts?.cicolors ? null # colors for CIs in QTL effect plot; also used for points in phe x gen plot
segwidth = chartOpts?.segwidth ? 0.4 # segment width in CI chart as proportion of distance between categories
segstrokewidth = chartOpts?.segstrokewidth ? 3 # stroke width for segments in CI chart
color = chartOpts?.color ? "slateblue" # color for heat map
oneAtTop = chartOpts?.oneAtTop ? false # whether to put chr 1 at top of heatmap
zthresh = chartOpts?.zthresh ? 0 # LOD values below this threshold aren't shown (on LOD_full scale)
ylab_eff = chartOpts?.ylab_eff ? "Phenotype" # y-axis label in dot and ci charts
xlab_lod = chartOpts?.xlab_lod ? "Chromosome" # x-axis label in lod charts
ylab_lod = chartOpts?.ylab_lod ? "LOD score" # y-axis label in lod charts
nyticks_lod = chartOpts?.nyticks_lod ? 5 # no. ticks on y-axis in LOD curve panels
yticks_lod = chartOpts?.yticks_lod ? null # vector of tick positions on y-axis in LOD curve panels
nyticks_ci = chartOpts?.nyticks_ci ? 5 # no. ticks on y-axis in CI panel
yticks_ci = chartOpts?.yticks_ci ? null # vector of tick positions on y-axis in CI panel
nyticks_pxg = chartOpts?.nyticks_pxg ? 5 # no. ticks on y-axis in dot chart of phenotype x genotype
yticks_pxg = chartOpts?.yticks_pxg ? null # vector of tick positions on y-axis in dot chart of phenotype x genotype
# chartOpts end
# make sure list args have all necessary bits
margin = d3panels.check_listarg_v_default(margin, {left:60, top:50, right:10, bottom: 40, inner: 5})
axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5})
# htmlwidget div element containing the chart, and its ID
div = d3.select(widgetdiv)
widgetdivid = div.attr("id")
svg = div.select("svg")
# force chrnames to be a list
scantwo_data.chrnames = d3panels.forceAsArray(scantwo_data.chrnames)
scantwo_data.nmar = d3panels.forceAsArray(scantwo_data.nmar)
# size of heatmap region
w = d3.min([height-hbot*2, width-wright])
heatmap_width = w
heatmap_height = w
hright = heatmap_height/2
width = heatmap_width + wright
height = heatmap_height + hbot*2
wbot = width/2
# selected LODs on left and right
leftvalue = "int"
rightvalue = "fv1"
# keep track of chromosome heatmap selections
cur_chr1 = cur_chr2 = ''
# cicolors: check they're the right length or construct them
if pheno_and_geno?
gn = pheno_and_geno.genonames
ncat = d3.max(gn[x].length for x of gn)
if cicolors? # cicolors provided; expand to ncat
cicolors = d3panels.expand2vector(cicolors, ncat)
n = cicolors.length
if n < ncat # not enough, display error
d3panels.displayError("length(cicolors) (#{n}) < maximum no. genotypes (#{ncat})")
cicolors = (cicolors[i % n] for i in [0...ncat])
else # not provided; select them
cicolors = d3panels.selectGroupColors(ncat, "dark")
# drop-down menus
options = ["full", "fv1", "int", "add", "av1"]
form = div.insert("div", ":first-child")
.attr("id", "form")
.attr("class", "qtlcharts")
.attr("height", "24px")
left = form.append("div")
.text(if oneAtTop then "bottom-left: " else "top-left: ")
.style("float", "left")
.style("margin-left", "50px")
leftsel = left.append("select")
.attr("id", "leftselect_#{widgetdivid}")
.attr("name", "left")
leftsel.selectAll("empty")
.data(options)
.enter()
.append("option")
.attr("value", (d) -> d)
.text((d) -> d)
.attr("selected", (d) ->
return "selected" if d==leftvalue
null)
right = form.append("div")
.text(if oneAtTop then "top-right: " else "bottom-right: ")
.style("float", "left")
.style("margin-left", "50px")
rightsel = right.append("select")
.attr("id", "rightselect_#{widgetdivid}")
.attr("name", "right")
rightsel.selectAll("empty")
.data(options)
.enter()
.append("option")
.attr("value", (d) -> d)
.text((d) -> d)
.attr("selected", (d) ->
return "selected" if d==rightvalue
null)
submit = form.append("div")
.style("float", "left")
.style("margin-left", "50px")
.append("button")
.attr("name", "refresh")
.text("Refresh")
.on "click", () ->
cur_chr1 = cur_chr2 = ''
leftsel = document.getElementById("leftselect_#{widgetdivid}")
leftvalue = leftsel.options[leftsel.selectedIndex].value
rightsel = document.getElementById("rightselect_#{widgetdivid}")
rightvalue = rightsel.options[rightsel.selectedIndex].value
scantwo_data.lod = lod_for_heatmap(scantwo_data, leftvalue, rightvalue)
mylod2dheatmap.remove()
mylod2dheatmap(div.select("g#chrheatmap"), scantwo_data)
add_cell_tooltips()
# add the full,add,int,fv1,av1 lod matrices to scantwo_data
# (and remove the non-symmetric ones)
scantwo_data = add_symmetric_lod(scantwo_data)
scantwo_data.lod = lod_for_heatmap(scantwo_data, leftvalue, rightvalue)
mylod2dheatmap = d3panels.lod2dheatmap({
height:heatmap_height
width:heatmap_width
margin:margin
axispos:axispos
chrGap:chrGap
chrlinecolor:chrlinecolor
chrlinewidth:chrlinewidth
xlab: xlab_lod
ylab: ylab_lod
rectcolor:"white"
nullcolor:nullcolor
boxcolor:boxcolor
boxwidth:boxwidth
colors:["white",color]
zlim:[0, scantwo_data.max.full]
zthresh:zthresh
oneAtTop:oneAtTop
tipclass:widgetdivid})
g_heatmap = svg.append("g")
.attr("id", "chrheatmap")
mylod2dheatmap(g_heatmap, scantwo_data)
# function to add tool tips and handle clicking
add_cell_tooltips = () ->
d3panels.tooltip_text(mylod2dheatmap.celltip(), (d) ->
mari = scantwo_data.marker[d.xindex]
marj = scantwo_data.marker[d.yindex]
if +d.xindex > +d.yindex # +'s ensure number not string
leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.xindex][d.yindex])
rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.yindex][d.xindex])
return "(#{marj} #{mari}) #{rightvalue} = #{rightlod}, #{leftvalue} = #{leftlod}"
else if +d.yindex > +d.xindex
leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.yindex][d.xindex])
rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.xindex][d.yindex])
return "(#{marj} #{mari}) #{leftvalue} = #{leftlod}, #{rightvalue} = #{rightlod}"
else
return mari
)
mylod2dheatmap.cells()
.on "click", (event, d) ->
mari = scantwo_data.marker[d.xindex]
marj = scantwo_data.marker[d.yindex]
return null if d.xindex == d.yindex # skip the diagonal case
# plot the cross-sections as genome scans, below
plot_scan(d.xindex, 0, 0, leftvalue)
plot_scan(d.xindex, 1, 0, rightvalue)
plot_scan(d.yindex, 0, 1, leftvalue)
plot_scan(d.yindex, 1, 1, rightvalue)
# plot the effect plot and phe x gen plot to right
if pheno_and_geno?
plot_effects(d.xindex, d.yindex)
add_cell_tooltips()
# to hold groups and positions of scan and effect plots
mylodchart = [[null,null], [null,null]]
scans_hpos = [0, wbot]
scans_vpos = [heatmap_height, heatmap_height+hbot]
mydotchart = null
mycichart = null
eff_hpos = [heatmap_width, heatmap_width]
eff_vpos = [0, heatmap_height/2]
g_scans = [[null,null],[null,null]]
plot_scan = (markerindex, panelrow, panelcol, lod) ->
data =
chrname: scantwo_data.chrnames
chr: scantwo_data.chr
pos: scantwo_data.pos
lod: (x for x in scantwo_data[lod][markerindex])
marker: scantwo_data.marker
mylodchart[panelrow][panelcol].remove() if mylodchart[panelrow][panelcol]?
mylodchart[panelrow][panelcol] = d3panels.lodchart({
height:hbot
width:wbot
margin:margin
axispos:axispos
ylim:[0.0, scantwo_data.max[lod]*1.05]
nyticks:nyticks_lod
yticks:yticks_lod
rectcolor:rectcolor
altrectcolor:altrectcolor
chrlinecolor:chrlinecolor
chrlinewidth:chrlinewidth
boxcolor:boxcolor
boxwidth:boxwidth
linewidth:linewidth
linecolor:linecolor
pointsize:0
pointcolor:""
pointstroke:""
lodvarname:"lod"
chrGap:chrGap
xlab:xlab_lod
ylab:ylab_lod
title:"#{data.marker[markerindex]} : #{lod}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_scans[panelrow][panelcol]? # only create it once
g_scans[panelrow][panelcol] = svg.append("g")
.attr("id", "scan_#{panelrow+1}_#{panelcol+1}")
.attr("transform", "translate(#{scans_hpos[panelcol]}, #{scans_vpos[panelrow]})")
mylodchart[panelrow][panelcol](g_scans[panelrow][panelcol], data)
g_eff = [null, null]
plot_effects = (markerindex1, markerindex2) ->
mar1 = scantwo_data.marker[markerindex1]
mar2 = scantwo_data.marker[markerindex2]
g1 = pheno_and_geno.geno[mar1]
g2 = pheno_and_geno.geno[mar2]
chr1 = pheno_and_geno.chr[mar1]
chr2 = pheno_and_geno.chr[mar2]
chrtype1 = pheno_and_geno.chrtype[chr1]
chrtype2 = pheno_and_geno.chrtype[chr2]
g = []
gn1 = []
gn2 = []
cicolors_expanded = []
# need to deal separately with X chr
# [this mess is because if females are AA/AB/BB and males AY/BY
# we want to just show 3x3 + 2x2 = 13 possible two-locus genotypes,
# not all (3+2)x(3+2) = 25]
if chr1 == chr2 and chrtype1=="X" and pheno_and_geno.X_geno_by_sex?
fgnames = pheno_and_geno.X_geno_by_sex[0]
mgnames = pheno_and_geno.X_geno_by_sex[1]
ngf = fgnames.length
ngm = mgnames.length
tmp = [0...(ngf+ngm)]
m = ((-1 for i of tmp) for j of tmp)
k = 0
for i in [0...ngf]
for j in [0...ngf]
gn1.push(fgnames[j])
gn2.push(fgnames[i])
cicolors_expanded.push(cicolors[i])
m[i][j] = k
k++
for i in [0...ngm]
for j in [0...ngm]
gn1.push(mgnames[j])
gn2.push(mgnames[i])
cicolors_expanded.push(cicolors[i])
m[i+ngf][j+ngf] = k
k++
g = (m[g1[i]-1][g2[i]-1]+1 for i of g1)
else
gnames1 = pheno_and_geno.genonames[chr1]
gnames2 = pheno_and_geno.genonames[chr2]
ng1 = gnames1.length
ng2 = gnames2.length
g = (g1[i] + (g2[i]-1)*ng1 for i of g1)
for i in [0...ng2]
for j in [0...ng1]
gn1.push(gnames1[j])
gn2.push(gnames2[i])
cicolors_expanded.push(cicolors[i])
pxg_data =
x:g
y:pheno_and_geno.pheno
indID:pheno_and_geno.indID
# remove the CI chart no matter what
mycichart.remove() if mycichart?
if cur_chr1 != chr1 or cur_chr2 != chr2
mydotchart.remove() if mydotchart?
mydotchart = d3panels.dotchart({
height:hright
width:wright
margin:margin
axispos:axispos
rectcolor:rectcolor
boxcolor:boxcolor
boxwidth:boxwidth
pointsize:pointsize
pointstroke:pointstroke
xcategories:[1..gn1.length]
xcatlabels:gn1
xlab:""
ylab:ylab_eff
nyticks:nyticks_pxg
yticks:yticks_pxg
dataByInd:false
title:"#{mar1} : #{mar2}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_eff[1]? # only create it once
g_eff[1] = svg.append("g")
.attr("id", "eff_1")
.attr("transform", "translate(#{eff_hpos[1]}, #{eff_vpos[1]})")
mydotchart(g_eff[1], pxg_data)
# revise point colors
mydotchart.points()
.attr("fill", (d,i) ->
cicolors_expanded[g[i]-1])
else # same chr pair as before: animate points
# remove marker text
d3.select("#markerlab1").remove()
d3.select("#xaxislab1").remove()
# grab scale and get info to take inverse
xscale = mydotchart.xscale()
pos1 = xscale(1)
dpos = xscale(2) - xscale(1)
point_jitter = (d) ->
u = (d - pos1)/dpos
u - Math.round(u)
# move points to new x-axis position
points = mydotchart.points()
.transition().duration(1000)
.attr("cx", (d,i) ->
cx = d3.select(this).attr("cx")
u = point_jitter(cx)
xscale(g[i] + u))
.attr("fill", (d,i) -> cicolors_expanded[g[i]-1])
# use force to move them apart again
scaledPoints = []
points.each((d,i) -> scaledPoints.push({
x: +d3.select(this).attr("cx")
y: +d3.select(this).attr("cy")
fy: +d3.select(this).attr("cy")
truex: xscale(g[i])}))
force = d3.forceSimulation(scaledPoints)
.force("x", d3.forceX((d) -> d.truex))
.force("collide", d3.forceCollide(pointsize*1.1))
.stop()
[0..30].map((d) ->
force.tick()
points.attr("cx", (d,i) -> scaledPoints[i].x))
cur_chr1 = chr1
cur_chr2 = chr2
cis = d3panels.ci_by_group(g, pheno_and_geno.pheno, 2)
ci_data =
mean: (cis[x]?.mean ? null for x in [1..gn1.length])
low: (cis[x]?.low ? null for x in [1..gn1.length])
high: (cis[x]?.high ? null for x in [1..gn1.length])
categories: [1..gn1.length]
mycichart = d3panels.cichart({
height:hright
width:wright
margin:margin
axispos:axispos
rectcolor:rectcolor
boxcolor:boxcolor
boxwidth:boxwidth
segcolor:cicolors_expanded
segwidth:segwidth
segstrokewidth:segstrokewidth
vertsegcolor:cicolors_expanded
segstrokewidth:linewidth
xlab:""
ylab:ylab_eff
nyticks:nyticks_ci
yticks:yticks_ci
xcatlabels:gn1
title:"#{mar1} : #{mar2}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_eff[0]? # only create it once
g_eff[0] = svg.append("g")
.attr("id", "eff_0")
.attr("transform", "translate(#{eff_hpos[0]}, #{eff_vpos[0]})")
mycichart(g_eff[0], ci_data)
effcharts = [mycichart, mydotchart]
# add second row of labels
for p in [0..1]
effcharts[p].svg() # second row of genotypes
.append("g").attr("class", "x axis").attr("id", "xaxislab#{p}")
.selectAll("empty")
.data(gn2)
.enter()
.append("text")
.attr("x", (d,i) -> mydotchart.xscale()(i+1))
.attr("y", hright-margin.bottom/2+axispos.xlabel)
.text((d) -> d)
effcharts[p].svg() # marker name labels
.append("g").attr("class", "x axis").attr("id", "markerlab#{p}")
.selectAll("empty")
.data([mar1, mar2])
.enter()
.append("text")
.attr("x", (margin.left + mydotchart.xscale()(1))/2.0)
.attr("y", (d,i) ->
hright - margin.bottom/(i+1) + axispos.xlabel)
.style("text-anchor", "end")
.text((d) -> d + ":")
if chartOpts.heading?
d3.select("div#htmlwidget_container")
.insert("h2", ":first-child")
.html(chartOpts.heading)
.style("font-family", "sans-serif")
if chartOpts.caption?
d3.select("body")
.append("p")
.attr("class", "caption")
.html(chartOpts.caption)
if chartOpts.footer?
d3.select("body")
.append("div")
.html(chartOpts.footer)
.style("font-family", "sans-serif")
# add full,add,int,av1,fv1 lod scores to scantwo_data
add_symmetric_lod = (scantwo_data) ->
scantwo_data.full = scantwo_data.lod.map (d) -> d.map (dd) -> dd
scantwo_data.add = scantwo_data.lod.map (d) -> d.map (dd) -> dd
scantwo_data.fv1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd
scantwo_data.av1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd
scantwo_data.int = scantwo_data.lod.map (d) -> d.map (dd) -> dd
for i in [0...(scantwo_data.lod.length-1)]
for j in [i...scantwo_data.lod[i].length]
scantwo_data.full[i][j] = scantwo_data.lod[j][i]
scantwo_data.add[j][i] = scantwo_data.lod[i][j]
scantwo_data.fv1[i][j] = scantwo_data.lodv1[j][i]
scantwo_data.av1[j][i] = scantwo_data.lodv1[i][j]
scantwo_data.one = []
for i in [0...scantwo_data.lod.length]
scantwo_data.one.push(scantwo_data.lod[i])
for j in [0...scantwo_data.lod.length]
scantwo_data.int[i][j] = scantwo_data.full[i][j] - scantwo_data.add[i][j]
# delete the non-symmetric versions
scantwo_data.lod = null
scantwo_data.lodv1 = null
scantwo_data.max = {}
for i in ["full", "add", "fv1", "av1", "int"]
scantwo_data.max[i] = d3panels.matrixMax(scantwo_data[i])
scantwo_data
lod_for_heatmap = (scantwo_data, left, right) ->
# make copy of lod
z = scantwo_data.full.map (d) -> d.map (dd) -> dd
for i in [0...z.length]
for j in [0...z.length]
thelod = if j < i then right else left
z[i][j] = scantwo_data[thelod][i][j]/scantwo_data.max[thelod]*scantwo_data.max["full"]
z # return the matrix we created
| 69309 | # iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan)
# <NAME>
iplotScantwo = (widgetdiv, scantwo_data, pheno_and_geno, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 1200 # total height of chart in pixels
width = chartOpts?.width ? 1100 # total width of chart in pixels
chrGap = chartOpts?.chrGap ? 2 # gaps between chr in heat map
wright = chartOpts?.wright ? width/2 # width (in pixels) of right panels
hbot = chartOpts?.hbot ? height/5 # height (in pixels) of each of the lower panels
margin = chartOpts?.margin ? {left:60, top:50, right:10, bottom: 40, inner: 5} # margins in each panel
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # axis positions in heatmap
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
rectcolor = chartOpts?.rectcolor ? "#e6e6e6" # color for background rectangle
altrectcolor = chartOpts?.altrectcolor ? "#c8c8c8" # alternate rectangle in lower panels
chrlinecolor = chartOpts?.chrlinecolor ? "" # color of lines between chromosomes (if "", leave off)
chrlinewidth = chartOpts?.chrlinewidth ? 2 # width of lines between chromosomes
nullcolor = chartOpts?.nullcolor ? "#e6e6e6" # color of null pixels in heat map
boxcolor = chartOpts?.boxcolor ? "black" # color of box around each panel
boxwidth = chartOpts?.boxwidth ? 2 # width of box around each panel
linecolor = chartOpts?.linecolor ? "slateblue" # line color in lower panels
linewidth = chartOpts?.linewidth ? 2 # line width in lower panels
pointsize = chartOpts?.pointsize ? 2 # point size in right panels
pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle in right panels
cicolors = chartOpts?.cicolors ? null # colors for CIs in QTL effect plot; also used for points in phe x gen plot
segwidth = chartOpts?.segwidth ? 0.4 # segment width in CI chart as proportion of distance between categories
segstrokewidth = chartOpts?.segstrokewidth ? 3 # stroke width for segments in CI chart
color = chartOpts?.color ? "slateblue" # color for heat map
oneAtTop = chartOpts?.oneAtTop ? false # whether to put chr 1 at top of heatmap
zthresh = chartOpts?.zthresh ? 0 # LOD values below this threshold aren't shown (on LOD_full scale)
ylab_eff = chartOpts?.ylab_eff ? "Phenotype" # y-axis label in dot and ci charts
xlab_lod = chartOpts?.xlab_lod ? "Chromosome" # x-axis label in lod charts
ylab_lod = chartOpts?.ylab_lod ? "LOD score" # y-axis label in lod charts
nyticks_lod = chartOpts?.nyticks_lod ? 5 # no. ticks on y-axis in LOD curve panels
yticks_lod = chartOpts?.yticks_lod ? null # vector of tick positions on y-axis in LOD curve panels
nyticks_ci = chartOpts?.nyticks_ci ? 5 # no. ticks on y-axis in CI panel
yticks_ci = chartOpts?.yticks_ci ? null # vector of tick positions on y-axis in CI panel
nyticks_pxg = chartOpts?.nyticks_pxg ? 5 # no. ticks on y-axis in dot chart of phenotype x genotype
yticks_pxg = chartOpts?.yticks_pxg ? null # vector of tick positions on y-axis in dot chart of phenotype x genotype
# chartOpts end
# make sure list args have all necessary bits
margin = d3panels.check_listarg_v_default(margin, {left:60, top:50, right:10, bottom: 40, inner: 5})
axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5})
# htmlwidget div element containing the chart, and its ID
div = d3.select(widgetdiv)
widgetdivid = div.attr("id")
svg = div.select("svg")
# force chrnames to be a list
scantwo_data.chrnames = d3panels.forceAsArray(scantwo_data.chrnames)
scantwo_data.nmar = d3panels.forceAsArray(scantwo_data.nmar)
# size of heatmap region
w = d3.min([height-hbot*2, width-wright])
heatmap_width = w
heatmap_height = w
hright = heatmap_height/2
width = heatmap_width + wright
height = heatmap_height + hbot*2
wbot = width/2
# selected LODs on left and right
leftvalue = "int"
rightvalue = "fv1"
# keep track of chromosome heatmap selections
cur_chr1 = cur_chr2 = ''
# cicolors: check they're the right length or construct them
if pheno_and_geno?
gn = pheno_and_geno.genonames
ncat = d3.max(gn[x].length for x of gn)
if cicolors? # cicolors provided; expand to ncat
cicolors = d3panels.expand2vector(cicolors, ncat)
n = cicolors.length
if n < ncat # not enough, display error
d3panels.displayError("length(cicolors) (#{n}) < maximum no. genotypes (#{ncat})")
cicolors = (cicolors[i % n] for i in [0...ncat])
else # not provided; select them
cicolors = d3panels.selectGroupColors(ncat, "dark")
# drop-down menus
options = ["full", "fv1", "int", "add", "av1"]
form = div.insert("div", ":first-child")
.attr("id", "form")
.attr("class", "qtlcharts")
.attr("height", "24px")
left = form.append("div")
.text(if oneAtTop then "bottom-left: " else "top-left: ")
.style("float", "left")
.style("margin-left", "50px")
leftsel = left.append("select")
.attr("id", "leftselect_#{widgetdivid}")
.attr("name", "left")
leftsel.selectAll("empty")
.data(options)
.enter()
.append("option")
.attr("value", (d) -> d)
.text((d) -> d)
.attr("selected", (d) ->
return "selected" if d==leftvalue
null)
right = form.append("div")
.text(if oneAtTop then "top-right: " else "bottom-right: ")
.style("float", "left")
.style("margin-left", "50px")
rightsel = right.append("select")
.attr("id", "rightselect_#{widgetdivid}")
.attr("name", "right")
rightsel.selectAll("empty")
.data(options)
.enter()
.append("option")
.attr("value", (d) -> d)
.text((d) -> d)
.attr("selected", (d) ->
return "selected" if d==rightvalue
null)
submit = form.append("div")
.style("float", "left")
.style("margin-left", "50px")
.append("button")
.attr("name", "refresh")
.text("Refresh")
.on "click", () ->
cur_chr1 = cur_chr2 = ''
leftsel = document.getElementById("leftselect_#{widgetdivid}")
leftvalue = leftsel.options[leftsel.selectedIndex].value
rightsel = document.getElementById("rightselect_#{widgetdivid}")
rightvalue = rightsel.options[rightsel.selectedIndex].value
scantwo_data.lod = lod_for_heatmap(scantwo_data, leftvalue, rightvalue)
mylod2dheatmap.remove()
mylod2dheatmap(div.select("g#chrheatmap"), scantwo_data)
add_cell_tooltips()
# add the full,add,int,fv1,av1 lod matrices to scantwo_data
# (and remove the non-symmetric ones)
scantwo_data = add_symmetric_lod(scantwo_data)
scantwo_data.lod = lod_for_heatmap(scantwo_data, leftvalue, rightvalue)
mylod2dheatmap = d3panels.lod2dheatmap({
height:heatmap_height
width:heatmap_width
margin:margin
axispos:axispos
chrGap:chrGap
chrlinecolor:chrlinecolor
chrlinewidth:chrlinewidth
xlab: xlab_lod
ylab: ylab_lod
rectcolor:"white"
nullcolor:nullcolor
boxcolor:boxcolor
boxwidth:boxwidth
colors:["white",color]
zlim:[0, scantwo_data.max.full]
zthresh:zthresh
oneAtTop:oneAtTop
tipclass:widgetdivid})
g_heatmap = svg.append("g")
.attr("id", "chrheatmap")
mylod2dheatmap(g_heatmap, scantwo_data)
# function to add tool tips and handle clicking
add_cell_tooltips = () ->
d3panels.tooltip_text(mylod2dheatmap.celltip(), (d) ->
mari = scantwo_data.marker[d.xindex]
marj = scantwo_data.marker[d.yindex]
if +d.xindex > +d.yindex # +'s ensure number not string
leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.xindex][d.yindex])
rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.yindex][d.xindex])
return "(#{marj} #{mari}) #{rightvalue} = #{rightlod}, #{leftvalue} = #{leftlod}"
else if +d.yindex > +d.xindex
leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.yindex][d.xindex])
rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.xindex][d.yindex])
return "(#{marj} #{mari}) #{leftvalue} = #{leftlod}, #{rightvalue} = #{rightlod}"
else
return mari
)
mylod2dheatmap.cells()
.on "click", (event, d) ->
mari = scantwo_data.marker[d.xindex]
marj = scantwo_data.marker[d.yindex]
return null if d.xindex == d.yindex # skip the diagonal case
# plot the cross-sections as genome scans, below
plot_scan(d.xindex, 0, 0, leftvalue)
plot_scan(d.xindex, 1, 0, rightvalue)
plot_scan(d.yindex, 0, 1, leftvalue)
plot_scan(d.yindex, 1, 1, rightvalue)
# plot the effect plot and phe x gen plot to right
if pheno_and_geno?
plot_effects(d.xindex, d.yindex)
add_cell_tooltips()
# to hold groups and positions of scan and effect plots
mylodchart = [[null,null], [null,null]]
scans_hpos = [0, wbot]
scans_vpos = [heatmap_height, heatmap_height+hbot]
mydotchart = null
mycichart = null
eff_hpos = [heatmap_width, heatmap_width]
eff_vpos = [0, heatmap_height/2]
g_scans = [[null,null],[null,null]]
plot_scan = (markerindex, panelrow, panelcol, lod) ->
data =
chrname: scantwo_data.chrnames
chr: scantwo_data.chr
pos: scantwo_data.pos
lod: (x for x in scantwo_data[lod][markerindex])
marker: scantwo_data.marker
mylodchart[panelrow][panelcol].remove() if mylodchart[panelrow][panelcol]?
mylodchart[panelrow][panelcol] = d3panels.lodchart({
height:hbot
width:wbot
margin:margin
axispos:axispos
ylim:[0.0, scantwo_data.max[lod]*1.05]
nyticks:nyticks_lod
yticks:yticks_lod
rectcolor:rectcolor
altrectcolor:altrectcolor
chrlinecolor:chrlinecolor
chrlinewidth:chrlinewidth
boxcolor:boxcolor
boxwidth:boxwidth
linewidth:linewidth
linecolor:linecolor
pointsize:0
pointcolor:""
pointstroke:""
lodvarname:"lod"
chrGap:chrGap
xlab:xlab_lod
ylab:ylab_lod
title:"#{data.marker[markerindex]} : #{lod}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_scans[panelrow][panelcol]? # only create it once
g_scans[panelrow][panelcol] = svg.append("g")
.attr("id", "scan_#{panelrow+1}_#{panelcol+1}")
.attr("transform", "translate(#{scans_hpos[panelcol]}, #{scans_vpos[panelrow]})")
mylodchart[panelrow][panelcol](g_scans[panelrow][panelcol], data)
g_eff = [null, null]
plot_effects = (markerindex1, markerindex2) ->
mar1 = scantwo_data.marker[markerindex1]
mar2 = scantwo_data.marker[markerindex2]
g1 = pheno_and_geno.geno[mar1]
g2 = pheno_and_geno.geno[mar2]
chr1 = pheno_and_geno.chr[mar1]
chr2 = pheno_and_geno.chr[mar2]
chrtype1 = pheno_and_geno.chrtype[chr1]
chrtype2 = pheno_and_geno.chrtype[chr2]
g = []
gn1 = []
gn2 = []
cicolors_expanded = []
# need to deal separately with X chr
# [this mess is because if females are AA/AB/BB and males AY/BY
# we want to just show 3x3 + 2x2 = 13 possible two-locus genotypes,
# not all (3+2)x(3+2) = 25]
if chr1 == chr2 and chrtype1=="X" and pheno_and_geno.X_geno_by_sex?
fgnames = pheno_and_geno.X_geno_by_sex[0]
mgnames = pheno_and_geno.X_geno_by_sex[1]
ngf = fgnames.length
ngm = mgnames.length
tmp = [0...(ngf+ngm)]
m = ((-1 for i of tmp) for j of tmp)
k = 0
for i in [0...ngf]
for j in [0...ngf]
gn1.push(fgnames[j])
gn2.push(fgnames[i])
cicolors_expanded.push(cicolors[i])
m[i][j] = k
k++
for i in [0...ngm]
for j in [0...ngm]
gn1.push(mgnames[j])
gn2.push(mgnames[i])
cicolors_expanded.push(cicolors[i])
m[i+ngf][j+ngf] = k
k++
g = (m[g1[i]-1][g2[i]-1]+1 for i of g1)
else
gnames1 = pheno_and_geno.genonames[chr1]
gnames2 = pheno_and_geno.genonames[chr2]
ng1 = gnames1.length
ng2 = gnames2.length
g = (g1[i] + (g2[i]-1)*ng1 for i of g1)
for i in [0...ng2]
for j in [0...ng1]
gn1.push(gnames1[j])
gn2.push(gnames2[i])
cicolors_expanded.push(cicolors[i])
pxg_data =
x:g
y:pheno_and_geno.pheno
indID:pheno_and_geno.indID
# remove the CI chart no matter what
mycichart.remove() if mycichart?
if cur_chr1 != chr1 or cur_chr2 != chr2
mydotchart.remove() if mydotchart?
mydotchart = d3panels.dotchart({
height:hright
width:wright
margin:margin
axispos:axispos
rectcolor:rectcolor
boxcolor:boxcolor
boxwidth:boxwidth
pointsize:pointsize
pointstroke:pointstroke
xcategories:[1..gn1.length]
xcatlabels:gn1
xlab:""
ylab:ylab_eff
nyticks:nyticks_pxg
yticks:yticks_pxg
dataByInd:false
title:"#{mar1} : #{mar2}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_eff[1]? # only create it once
g_eff[1] = svg.append("g")
.attr("id", "eff_1")
.attr("transform", "translate(#{eff_hpos[1]}, #{eff_vpos[1]})")
mydotchart(g_eff[1], pxg_data)
# revise point colors
mydotchart.points()
.attr("fill", (d,i) ->
cicolors_expanded[g[i]-1])
else # same chr pair as before: animate points
# remove marker text
d3.select("#markerlab1").remove()
d3.select("#xaxislab1").remove()
# grab scale and get info to take inverse
xscale = mydotchart.xscale()
pos1 = xscale(1)
dpos = xscale(2) - xscale(1)
point_jitter = (d) ->
u = (d - pos1)/dpos
u - Math.round(u)
# move points to new x-axis position
points = mydotchart.points()
.transition().duration(1000)
.attr("cx", (d,i) ->
cx = d3.select(this).attr("cx")
u = point_jitter(cx)
xscale(g[i] + u))
.attr("fill", (d,i) -> cicolors_expanded[g[i]-1])
# use force to move them apart again
scaledPoints = []
points.each((d,i) -> scaledPoints.push({
x: +d3.select(this).attr("cx")
y: +d3.select(this).attr("cy")
fy: +d3.select(this).attr("cy")
truex: xscale(g[i])}))
force = d3.forceSimulation(scaledPoints)
.force("x", d3.forceX((d) -> d.truex))
.force("collide", d3.forceCollide(pointsize*1.1))
.stop()
[0..30].map((d) ->
force.tick()
points.attr("cx", (d,i) -> scaledPoints[i].x))
cur_chr1 = chr1
cur_chr2 = chr2
cis = d3panels.ci_by_group(g, pheno_and_geno.pheno, 2)
ci_data =
mean: (cis[x]?.mean ? null for x in [1..gn1.length])
low: (cis[x]?.low ? null for x in [1..gn1.length])
high: (cis[x]?.high ? null for x in [1..gn1.length])
categories: [1..gn1.length]
mycichart = d3panels.cichart({
height:hright
width:wright
margin:margin
axispos:axispos
rectcolor:rectcolor
boxcolor:boxcolor
boxwidth:boxwidth
segcolor:cicolors_expanded
segwidth:segwidth
segstrokewidth:segstrokewidth
vertsegcolor:cicolors_expanded
segstrokewidth:linewidth
xlab:""
ylab:ylab_eff
nyticks:nyticks_ci
yticks:yticks_ci
xcatlabels:gn1
title:"#{mar1} : #{mar2}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_eff[0]? # only create it once
g_eff[0] = svg.append("g")
.attr("id", "eff_0")
.attr("transform", "translate(#{eff_hpos[0]}, #{eff_vpos[0]})")
mycichart(g_eff[0], ci_data)
effcharts = [mycichart, mydotchart]
# add second row of labels
for p in [0..1]
effcharts[p].svg() # second row of genotypes
.append("g").attr("class", "x axis").attr("id", "xaxislab#{p}")
.selectAll("empty")
.data(gn2)
.enter()
.append("text")
.attr("x", (d,i) -> mydotchart.xscale()(i+1))
.attr("y", hright-margin.bottom/2+axispos.xlabel)
.text((d) -> d)
effcharts[p].svg() # marker name labels
.append("g").attr("class", "x axis").attr("id", "markerlab#{p}")
.selectAll("empty")
.data([mar1, mar2])
.enter()
.append("text")
.attr("x", (margin.left + mydotchart.xscale()(1))/2.0)
.attr("y", (d,i) ->
hright - margin.bottom/(i+1) + axispos.xlabel)
.style("text-anchor", "end")
.text((d) -> d + ":")
if chartOpts.heading?
d3.select("div#htmlwidget_container")
.insert("h2", ":first-child")
.html(chartOpts.heading)
.style("font-family", "sans-serif")
if chartOpts.caption?
d3.select("body")
.append("p")
.attr("class", "caption")
.html(chartOpts.caption)
if chartOpts.footer?
d3.select("body")
.append("div")
.html(chartOpts.footer)
.style("font-family", "sans-serif")
# add full,add,int,av1,fv1 lod scores to scantwo_data
add_symmetric_lod = (scantwo_data) ->
scantwo_data.full = scantwo_data.lod.map (d) -> d.map (dd) -> dd
scantwo_data.add = scantwo_data.lod.map (d) -> d.map (dd) -> dd
scantwo_data.fv1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd
scantwo_data.av1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd
scantwo_data.int = scantwo_data.lod.map (d) -> d.map (dd) -> dd
for i in [0...(scantwo_data.lod.length-1)]
for j in [i...scantwo_data.lod[i].length]
scantwo_data.full[i][j] = scantwo_data.lod[j][i]
scantwo_data.add[j][i] = scantwo_data.lod[i][j]
scantwo_data.fv1[i][j] = scantwo_data.lodv1[j][i]
scantwo_data.av1[j][i] = scantwo_data.lodv1[i][j]
scantwo_data.one = []
for i in [0...scantwo_data.lod.length]
scantwo_data.one.push(scantwo_data.lod[i])
for j in [0...scantwo_data.lod.length]
scantwo_data.int[i][j] = scantwo_data.full[i][j] - scantwo_data.add[i][j]
# delete the non-symmetric versions
scantwo_data.lod = null
scantwo_data.lodv1 = null
scantwo_data.max = {}
for i in ["full", "add", "fv1", "av1", "int"]
scantwo_data.max[i] = d3panels.matrixMax(scantwo_data[i])
scantwo_data
lod_for_heatmap = (scantwo_data, left, right) ->
# make copy of lod
z = scantwo_data.full.map (d) -> d.map (dd) -> dd
for i in [0...z.length]
for j in [0...z.length]
thelod = if j < i then right else left
z[i][j] = scantwo_data[thelod][i][j]/scantwo_data.max[thelod]*scantwo_data.max["full"]
z # return the matrix we created
| true | # iplotScantwo: interactive plot of scantwo results (2-dim, 2-QTL genome scan)
# PI:NAME:<NAME>END_PI
iplotScantwo = (widgetdiv, scantwo_data, pheno_and_geno, chartOpts) ->
# chartOpts start
height = chartOpts?.height ? 1200 # total height of chart in pixels
width = chartOpts?.width ? 1100 # total width of chart in pixels
chrGap = chartOpts?.chrGap ? 2 # gaps between chr in heat map
wright = chartOpts?.wright ? width/2 # width (in pixels) of right panels
hbot = chartOpts?.hbot ? height/5 # height (in pixels) of each of the lower panels
margin = chartOpts?.margin ? {left:60, top:50, right:10, bottom: 40, inner: 5} # margins in each panel
axispos = chartOpts?.axispos ? {xtitle:25, ytitle:30, xlabel:5, ylabel:5} # axis positions in heatmap
titlepos = chartOpts?.titlepos ? 20 # position of chart title in pixels
rectcolor = chartOpts?.rectcolor ? "#e6e6e6" # color for background rectangle
altrectcolor = chartOpts?.altrectcolor ? "#c8c8c8" # alternate rectangle in lower panels
chrlinecolor = chartOpts?.chrlinecolor ? "" # color of lines between chromosomes (if "", leave off)
chrlinewidth = chartOpts?.chrlinewidth ? 2 # width of lines between chromosomes
nullcolor = chartOpts?.nullcolor ? "#e6e6e6" # color of null pixels in heat map
boxcolor = chartOpts?.boxcolor ? "black" # color of box around each panel
boxwidth = chartOpts?.boxwidth ? 2 # width of box around each panel
linecolor = chartOpts?.linecolor ? "slateblue" # line color in lower panels
linewidth = chartOpts?.linewidth ? 2 # line width in lower panels
pointsize = chartOpts?.pointsize ? 2 # point size in right panels
pointstroke = chartOpts?.pointstroke ? "black" # color of outer circle in right panels
cicolors = chartOpts?.cicolors ? null # colors for CIs in QTL effect plot; also used for points in phe x gen plot
segwidth = chartOpts?.segwidth ? 0.4 # segment width in CI chart as proportion of distance between categories
segstrokewidth = chartOpts?.segstrokewidth ? 3 # stroke width for segments in CI chart
color = chartOpts?.color ? "slateblue" # color for heat map
oneAtTop = chartOpts?.oneAtTop ? false # whether to put chr 1 at top of heatmap
zthresh = chartOpts?.zthresh ? 0 # LOD values below this threshold aren't shown (on LOD_full scale)
ylab_eff = chartOpts?.ylab_eff ? "Phenotype" # y-axis label in dot and ci charts
xlab_lod = chartOpts?.xlab_lod ? "Chromosome" # x-axis label in lod charts
ylab_lod = chartOpts?.ylab_lod ? "LOD score" # y-axis label in lod charts
nyticks_lod = chartOpts?.nyticks_lod ? 5 # no. ticks on y-axis in LOD curve panels
yticks_lod = chartOpts?.yticks_lod ? null # vector of tick positions on y-axis in LOD curve panels
nyticks_ci = chartOpts?.nyticks_ci ? 5 # no. ticks on y-axis in CI panel
yticks_ci = chartOpts?.yticks_ci ? null # vector of tick positions on y-axis in CI panel
nyticks_pxg = chartOpts?.nyticks_pxg ? 5 # no. ticks on y-axis in dot chart of phenotype x genotype
yticks_pxg = chartOpts?.yticks_pxg ? null # vector of tick positions on y-axis in dot chart of phenotype x genotype
# chartOpts end
# make sure list args have all necessary bits
margin = d3panels.check_listarg_v_default(margin, {left:60, top:50, right:10, bottom: 40, inner: 5})
axispos = d3panels.check_listarg_v_default(axispos, {xtitle:25, ytitle:30, xlabel:5, ylabel:5})
# htmlwidget div element containing the chart, and its ID
div = d3.select(widgetdiv)
widgetdivid = div.attr("id")
svg = div.select("svg")
# force chrnames to be a list
scantwo_data.chrnames = d3panels.forceAsArray(scantwo_data.chrnames)
scantwo_data.nmar = d3panels.forceAsArray(scantwo_data.nmar)
# size of heatmap region
w = d3.min([height-hbot*2, width-wright])
heatmap_width = w
heatmap_height = w
hright = heatmap_height/2
width = heatmap_width + wright
height = heatmap_height + hbot*2
wbot = width/2
# selected LODs on left and right
leftvalue = "int"
rightvalue = "fv1"
# keep track of chromosome heatmap selections
cur_chr1 = cur_chr2 = ''
# cicolors: check they're the right length or construct them
if pheno_and_geno?
gn = pheno_and_geno.genonames
ncat = d3.max(gn[x].length for x of gn)
if cicolors? # cicolors provided; expand to ncat
cicolors = d3panels.expand2vector(cicolors, ncat)
n = cicolors.length
if n < ncat # not enough, display error
d3panels.displayError("length(cicolors) (#{n}) < maximum no. genotypes (#{ncat})")
cicolors = (cicolors[i % n] for i in [0...ncat])
else # not provided; select them
cicolors = d3panels.selectGroupColors(ncat, "dark")
# drop-down menus
options = ["full", "fv1", "int", "add", "av1"]
form = div.insert("div", ":first-child")
.attr("id", "form")
.attr("class", "qtlcharts")
.attr("height", "24px")
left = form.append("div")
.text(if oneAtTop then "bottom-left: " else "top-left: ")
.style("float", "left")
.style("margin-left", "50px")
leftsel = left.append("select")
.attr("id", "leftselect_#{widgetdivid}")
.attr("name", "left")
leftsel.selectAll("empty")
.data(options)
.enter()
.append("option")
.attr("value", (d) -> d)
.text((d) -> d)
.attr("selected", (d) ->
return "selected" if d==leftvalue
null)
right = form.append("div")
.text(if oneAtTop then "top-right: " else "bottom-right: ")
.style("float", "left")
.style("margin-left", "50px")
rightsel = right.append("select")
.attr("id", "rightselect_#{widgetdivid}")
.attr("name", "right")
rightsel.selectAll("empty")
.data(options)
.enter()
.append("option")
.attr("value", (d) -> d)
.text((d) -> d)
.attr("selected", (d) ->
return "selected" if d==rightvalue
null)
submit = form.append("div")
.style("float", "left")
.style("margin-left", "50px")
.append("button")
.attr("name", "refresh")
.text("Refresh")
.on "click", () ->
cur_chr1 = cur_chr2 = ''
leftsel = document.getElementById("leftselect_#{widgetdivid}")
leftvalue = leftsel.options[leftsel.selectedIndex].value
rightsel = document.getElementById("rightselect_#{widgetdivid}")
rightvalue = rightsel.options[rightsel.selectedIndex].value
scantwo_data.lod = lod_for_heatmap(scantwo_data, leftvalue, rightvalue)
mylod2dheatmap.remove()
mylod2dheatmap(div.select("g#chrheatmap"), scantwo_data)
add_cell_tooltips()
# add the full,add,int,fv1,av1 lod matrices to scantwo_data
# (and remove the non-symmetric ones)
scantwo_data = add_symmetric_lod(scantwo_data)
scantwo_data.lod = lod_for_heatmap(scantwo_data, leftvalue, rightvalue)
mylod2dheatmap = d3panels.lod2dheatmap({
height:heatmap_height
width:heatmap_width
margin:margin
axispos:axispos
chrGap:chrGap
chrlinecolor:chrlinecolor
chrlinewidth:chrlinewidth
xlab: xlab_lod
ylab: ylab_lod
rectcolor:"white"
nullcolor:nullcolor
boxcolor:boxcolor
boxwidth:boxwidth
colors:["white",color]
zlim:[0, scantwo_data.max.full]
zthresh:zthresh
oneAtTop:oneAtTop
tipclass:widgetdivid})
g_heatmap = svg.append("g")
.attr("id", "chrheatmap")
mylod2dheatmap(g_heatmap, scantwo_data)
# function to add tool tips and handle clicking
add_cell_tooltips = () ->
d3panels.tooltip_text(mylod2dheatmap.celltip(), (d) ->
mari = scantwo_data.marker[d.xindex]
marj = scantwo_data.marker[d.yindex]
if +d.xindex > +d.yindex # +'s ensure number not string
leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.xindex][d.yindex])
rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.yindex][d.xindex])
return "(#{marj} #{mari}) #{rightvalue} = #{rightlod}, #{leftvalue} = #{leftlod}"
else if +d.yindex > +d.xindex
leftlod = d3.format(".1f")(scantwo_data[leftvalue][d.yindex][d.xindex])
rightlod = d3.format(".1f")(scantwo_data[rightvalue][d.xindex][d.yindex])
return "(#{marj} #{mari}) #{leftvalue} = #{leftlod}, #{rightvalue} = #{rightlod}"
else
return mari
)
mylod2dheatmap.cells()
.on "click", (event, d) ->
mari = scantwo_data.marker[d.xindex]
marj = scantwo_data.marker[d.yindex]
return null if d.xindex == d.yindex # skip the diagonal case
# plot the cross-sections as genome scans, below
plot_scan(d.xindex, 0, 0, leftvalue)
plot_scan(d.xindex, 1, 0, rightvalue)
plot_scan(d.yindex, 0, 1, leftvalue)
plot_scan(d.yindex, 1, 1, rightvalue)
# plot the effect plot and phe x gen plot to right
if pheno_and_geno?
plot_effects(d.xindex, d.yindex)
add_cell_tooltips()
# to hold groups and positions of scan and effect plots
mylodchart = [[null,null], [null,null]]
scans_hpos = [0, wbot]
scans_vpos = [heatmap_height, heatmap_height+hbot]
mydotchart = null
mycichart = null
eff_hpos = [heatmap_width, heatmap_width]
eff_vpos = [0, heatmap_height/2]
g_scans = [[null,null],[null,null]]
plot_scan = (markerindex, panelrow, panelcol, lod) ->
data =
chrname: scantwo_data.chrnames
chr: scantwo_data.chr
pos: scantwo_data.pos
lod: (x for x in scantwo_data[lod][markerindex])
marker: scantwo_data.marker
mylodchart[panelrow][panelcol].remove() if mylodchart[panelrow][panelcol]?
mylodchart[panelrow][panelcol] = d3panels.lodchart({
height:hbot
width:wbot
margin:margin
axispos:axispos
ylim:[0.0, scantwo_data.max[lod]*1.05]
nyticks:nyticks_lod
yticks:yticks_lod
rectcolor:rectcolor
altrectcolor:altrectcolor
chrlinecolor:chrlinecolor
chrlinewidth:chrlinewidth
boxcolor:boxcolor
boxwidth:boxwidth
linewidth:linewidth
linecolor:linecolor
pointsize:0
pointcolor:""
pointstroke:""
lodvarname:"lod"
chrGap:chrGap
xlab:xlab_lod
ylab:ylab_lod
title:"#{data.marker[markerindex]} : #{lod}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_scans[panelrow][panelcol]? # only create it once
g_scans[panelrow][panelcol] = svg.append("g")
.attr("id", "scan_#{panelrow+1}_#{panelcol+1}")
.attr("transform", "translate(#{scans_hpos[panelcol]}, #{scans_vpos[panelrow]})")
mylodchart[panelrow][panelcol](g_scans[panelrow][panelcol], data)
g_eff = [null, null]
plot_effects = (markerindex1, markerindex2) ->
mar1 = scantwo_data.marker[markerindex1]
mar2 = scantwo_data.marker[markerindex2]
g1 = pheno_and_geno.geno[mar1]
g2 = pheno_and_geno.geno[mar2]
chr1 = pheno_and_geno.chr[mar1]
chr2 = pheno_and_geno.chr[mar2]
chrtype1 = pheno_and_geno.chrtype[chr1]
chrtype2 = pheno_and_geno.chrtype[chr2]
g = []
gn1 = []
gn2 = []
cicolors_expanded = []
# need to deal separately with X chr
# [this mess is because if females are AA/AB/BB and males AY/BY
# we want to just show 3x3 + 2x2 = 13 possible two-locus genotypes,
# not all (3+2)x(3+2) = 25]
if chr1 == chr2 and chrtype1=="X" and pheno_and_geno.X_geno_by_sex?
fgnames = pheno_and_geno.X_geno_by_sex[0]
mgnames = pheno_and_geno.X_geno_by_sex[1]
ngf = fgnames.length
ngm = mgnames.length
tmp = [0...(ngf+ngm)]
m = ((-1 for i of tmp) for j of tmp)
k = 0
for i in [0...ngf]
for j in [0...ngf]
gn1.push(fgnames[j])
gn2.push(fgnames[i])
cicolors_expanded.push(cicolors[i])
m[i][j] = k
k++
for i in [0...ngm]
for j in [0...ngm]
gn1.push(mgnames[j])
gn2.push(mgnames[i])
cicolors_expanded.push(cicolors[i])
m[i+ngf][j+ngf] = k
k++
g = (m[g1[i]-1][g2[i]-1]+1 for i of g1)
else
gnames1 = pheno_and_geno.genonames[chr1]
gnames2 = pheno_and_geno.genonames[chr2]
ng1 = gnames1.length
ng2 = gnames2.length
g = (g1[i] + (g2[i]-1)*ng1 for i of g1)
for i in [0...ng2]
for j in [0...ng1]
gn1.push(gnames1[j])
gn2.push(gnames2[i])
cicolors_expanded.push(cicolors[i])
pxg_data =
x:g
y:pheno_and_geno.pheno
indID:pheno_and_geno.indID
# remove the CI chart no matter what
mycichart.remove() if mycichart?
if cur_chr1 != chr1 or cur_chr2 != chr2
mydotchart.remove() if mydotchart?
mydotchart = d3panels.dotchart({
height:hright
width:wright
margin:margin
axispos:axispos
rectcolor:rectcolor
boxcolor:boxcolor
boxwidth:boxwidth
pointsize:pointsize
pointstroke:pointstroke
xcategories:[1..gn1.length]
xcatlabels:gn1
xlab:""
ylab:ylab_eff
nyticks:nyticks_pxg
yticks:yticks_pxg
dataByInd:false
title:"#{mar1} : #{mar2}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_eff[1]? # only create it once
g_eff[1] = svg.append("g")
.attr("id", "eff_1")
.attr("transform", "translate(#{eff_hpos[1]}, #{eff_vpos[1]})")
mydotchart(g_eff[1], pxg_data)
# revise point colors
mydotchart.points()
.attr("fill", (d,i) ->
cicolors_expanded[g[i]-1])
else # same chr pair as before: animate points
# remove marker text
d3.select("#markerlab1").remove()
d3.select("#xaxislab1").remove()
# grab scale and get info to take inverse
xscale = mydotchart.xscale()
pos1 = xscale(1)
dpos = xscale(2) - xscale(1)
point_jitter = (d) ->
u = (d - pos1)/dpos
u - Math.round(u)
# move points to new x-axis position
points = mydotchart.points()
.transition().duration(1000)
.attr("cx", (d,i) ->
cx = d3.select(this).attr("cx")
u = point_jitter(cx)
xscale(g[i] + u))
.attr("fill", (d,i) -> cicolors_expanded[g[i]-1])
# use force to move them apart again
scaledPoints = []
points.each((d,i) -> scaledPoints.push({
x: +d3.select(this).attr("cx")
y: +d3.select(this).attr("cy")
fy: +d3.select(this).attr("cy")
truex: xscale(g[i])}))
force = d3.forceSimulation(scaledPoints)
.force("x", d3.forceX((d) -> d.truex))
.force("collide", d3.forceCollide(pointsize*1.1))
.stop()
[0..30].map((d) ->
force.tick()
points.attr("cx", (d,i) -> scaledPoints[i].x))
cur_chr1 = chr1
cur_chr2 = chr2
cis = d3panels.ci_by_group(g, pheno_and_geno.pheno, 2)
ci_data =
mean: (cis[x]?.mean ? null for x in [1..gn1.length])
low: (cis[x]?.low ? null for x in [1..gn1.length])
high: (cis[x]?.high ? null for x in [1..gn1.length])
categories: [1..gn1.length]
mycichart = d3panels.cichart({
height:hright
width:wright
margin:margin
axispos:axispos
rectcolor:rectcolor
boxcolor:boxcolor
boxwidth:boxwidth
segcolor:cicolors_expanded
segwidth:segwidth
segstrokewidth:segstrokewidth
vertsegcolor:cicolors_expanded
segstrokewidth:linewidth
xlab:""
ylab:ylab_eff
nyticks:nyticks_ci
yticks:yticks_ci
xcatlabels:gn1
title:"#{mar1} : #{mar2}"
titlepos:titlepos
tipclass:widgetdivid})
unless g_eff[0]? # only create it once
g_eff[0] = svg.append("g")
.attr("id", "eff_0")
.attr("transform", "translate(#{eff_hpos[0]}, #{eff_vpos[0]})")
mycichart(g_eff[0], ci_data)
effcharts = [mycichart, mydotchart]
# add second row of labels
for p in [0..1]
effcharts[p].svg() # second row of genotypes
.append("g").attr("class", "x axis").attr("id", "xaxislab#{p}")
.selectAll("empty")
.data(gn2)
.enter()
.append("text")
.attr("x", (d,i) -> mydotchart.xscale()(i+1))
.attr("y", hright-margin.bottom/2+axispos.xlabel)
.text((d) -> d)
effcharts[p].svg() # marker name labels
.append("g").attr("class", "x axis").attr("id", "markerlab#{p}")
.selectAll("empty")
.data([mar1, mar2])
.enter()
.append("text")
.attr("x", (margin.left + mydotchart.xscale()(1))/2.0)
.attr("y", (d,i) ->
hright - margin.bottom/(i+1) + axispos.xlabel)
.style("text-anchor", "end")
.text((d) -> d + ":")
if chartOpts.heading?
d3.select("div#htmlwidget_container")
.insert("h2", ":first-child")
.html(chartOpts.heading)
.style("font-family", "sans-serif")
if chartOpts.caption?
d3.select("body")
.append("p")
.attr("class", "caption")
.html(chartOpts.caption)
if chartOpts.footer?
d3.select("body")
.append("div")
.html(chartOpts.footer)
.style("font-family", "sans-serif")
# add full,add,int,av1,fv1 lod scores to scantwo_data
add_symmetric_lod = (scantwo_data) ->
scantwo_data.full = scantwo_data.lod.map (d) -> d.map (dd) -> dd
scantwo_data.add = scantwo_data.lod.map (d) -> d.map (dd) -> dd
scantwo_data.fv1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd
scantwo_data.av1 = scantwo_data.lodv1.map (d) -> d.map (dd) -> dd
scantwo_data.int = scantwo_data.lod.map (d) -> d.map (dd) -> dd
for i in [0...(scantwo_data.lod.length-1)]
for j in [i...scantwo_data.lod[i].length]
scantwo_data.full[i][j] = scantwo_data.lod[j][i]
scantwo_data.add[j][i] = scantwo_data.lod[i][j]
scantwo_data.fv1[i][j] = scantwo_data.lodv1[j][i]
scantwo_data.av1[j][i] = scantwo_data.lodv1[i][j]
scantwo_data.one = []
for i in [0...scantwo_data.lod.length]
scantwo_data.one.push(scantwo_data.lod[i])
for j in [0...scantwo_data.lod.length]
scantwo_data.int[i][j] = scantwo_data.full[i][j] - scantwo_data.add[i][j]
# delete the non-symmetric versions
scantwo_data.lod = null
scantwo_data.lodv1 = null
scantwo_data.max = {}
for i in ["full", "add", "fv1", "av1", "int"]
scantwo_data.max[i] = d3panels.matrixMax(scantwo_data[i])
scantwo_data
lod_for_heatmap = (scantwo_data, left, right) ->
# make copy of lod
z = scantwo_data.full.map (d) -> d.map (dd) -> dd
for i in [0...z.length]
for j in [0...z.length]
thelod = if j < i then right else left
z[i][j] = scantwo_data[thelod][i][j]/scantwo_data.max[thelod]*scantwo_data.max["full"]
z # return the matrix we created
|
[
{
"context": "oller = @controllerFor('documents')\n eventKey = eventType + 'Documents'\n isLoadingProperty = eventType +",
"end": 2302,
"score": 0.8170198202133179,
"start": 2293,
"tag": "KEY",
"value": "eventType"
},
{
"context": "ollerFor('documents')\n eventKey = eventTyp... | app/assets/javascripts/species/routes/documents_route.js.coffee | unepwcmc/SAPI | 6 | Species.DocumentsRoute = Ember.Route.extend Species.Spinner,
Species.GeoEntityLoader, Species.EventLoader,
Species.DocumentTagLoader, Species.DocumentLoader,
beforeModel: (transition) ->
queryParams = transition.queryParams
@ensureGeoEntitiesLoaded(@controllerFor('search'))
@ensureEventsLoaded(@controllerFor('elibrarySearch'))
@ensureDocumentTagsLoaded(@controllerFor('elibrarySearch'))
#dirty hack to check if we have an array or comma separated string here
if queryParams.geo_entities_ids && queryParams.geo_entities_ids.substring
queryParams.geo_entities_ids = queryParams.geo_entities_ids.split(',')
if queryParams.events_ids && queryParams.events_ids.substring
queryParams.events_ids = queryParams.events_ids.split(',')
queryParams.geo_entities_ids = [] if queryParams.geo_entities_ids == true
queryParams.events_ids = [] if queryParams.events_ids == true
@controllerFor('elibrarySearch').setFilters(queryParams)
$(@spinnerSelector).css("visibility", "visible")
$('tr.group i.fa-minus-circle').click()
model: (params, transition) ->
queryParams = params.queryParams
@resetDocumentsResults()
if queryParams['event_type']
@loadDocumentsForEventType(queryParams['event_type'], queryParams)
else
@get('eventTypes').forEach((eventType) =>
eventQueryParams = $.extend({}, queryParams, {event_type: eventType})
@loadDocumentsForEventType(eventType, eventQueryParams)
)
afterModel: (model, transition) ->
$(@spinnerSelector).css("visibility", "hidden")
renderTemplate: ->
# Render the `documents` template into
# the default outlet, and display the `documents`
# controller.
@render('documents', {
into: 'application',
outlet: 'main',
controller: @controllerFor('documents')
})
# Render the `elibrary_search_form` template into
# the outlet `search`, and display the `search`
# controller.
@render('elibrarySearchForm', {
into: 'documents',
outlet: 'search',
controller: @controllerFor('elibrarySearch')
})
loadDocumentsForEventType: (eventType, eventQueryParams) ->
eventType = @getEventTypeKey(eventType).camelize()
controller = @controllerFor('documents')
eventKey = eventType + 'Documents'
isLoadingProperty = eventType + 'DocsIsLoading'
controller.set(isLoadingProperty, true)
@loadDocuments(eventQueryParams, (documents) =>
controller.set(eventKey, documents)
)
resetDocumentsResults: () ->
controller = @controllerFor('documents')
controller.set('euSrgDocuments', {})
controller.set('citesCopProposalsDocuments', {})
controller.set('citesAcDocuments', {})
controller.set('citesPcDocuments', {})
controller.set('idMaterialsDocuments', {})
controller.set('otherDocuments', {})
actions:
queryParamsDidChange: (changed, totalPresent, removed) ->
@refresh() | 57087 | Species.DocumentsRoute = Ember.Route.extend Species.Spinner,
Species.GeoEntityLoader, Species.EventLoader,
Species.DocumentTagLoader, Species.DocumentLoader,
beforeModel: (transition) ->
queryParams = transition.queryParams
@ensureGeoEntitiesLoaded(@controllerFor('search'))
@ensureEventsLoaded(@controllerFor('elibrarySearch'))
@ensureDocumentTagsLoaded(@controllerFor('elibrarySearch'))
#dirty hack to check if we have an array or comma separated string here
if queryParams.geo_entities_ids && queryParams.geo_entities_ids.substring
queryParams.geo_entities_ids = queryParams.geo_entities_ids.split(',')
if queryParams.events_ids && queryParams.events_ids.substring
queryParams.events_ids = queryParams.events_ids.split(',')
queryParams.geo_entities_ids = [] if queryParams.geo_entities_ids == true
queryParams.events_ids = [] if queryParams.events_ids == true
@controllerFor('elibrarySearch').setFilters(queryParams)
$(@spinnerSelector).css("visibility", "visible")
$('tr.group i.fa-minus-circle').click()
model: (params, transition) ->
queryParams = params.queryParams
@resetDocumentsResults()
if queryParams['event_type']
@loadDocumentsForEventType(queryParams['event_type'], queryParams)
else
@get('eventTypes').forEach((eventType) =>
eventQueryParams = $.extend({}, queryParams, {event_type: eventType})
@loadDocumentsForEventType(eventType, eventQueryParams)
)
afterModel: (model, transition) ->
$(@spinnerSelector).css("visibility", "hidden")
renderTemplate: ->
# Render the `documents` template into
# the default outlet, and display the `documents`
# controller.
@render('documents', {
into: 'application',
outlet: 'main',
controller: @controllerFor('documents')
})
# Render the `elibrary_search_form` template into
# the outlet `search`, and display the `search`
# controller.
@render('elibrarySearchForm', {
into: 'documents',
outlet: 'search',
controller: @controllerFor('elibrarySearch')
})
loadDocumentsForEventType: (eventType, eventQueryParams) ->
eventType = @getEventTypeKey(eventType).camelize()
controller = @controllerFor('documents')
eventKey = <KEY> + '<KEY>'
isLoadingProperty = eventType + 'DocsIsLoading'
controller.set(isLoadingProperty, true)
@loadDocuments(eventQueryParams, (documents) =>
controller.set(eventKey, documents)
)
resetDocumentsResults: () ->
controller = @controllerFor('documents')
controller.set('euSrgDocuments', {})
controller.set('citesCopProposalsDocuments', {})
controller.set('citesAcDocuments', {})
controller.set('citesPcDocuments', {})
controller.set('idMaterialsDocuments', {})
controller.set('otherDocuments', {})
actions:
queryParamsDidChange: (changed, totalPresent, removed) ->
@refresh() | true | Species.DocumentsRoute = Ember.Route.extend Species.Spinner,
Species.GeoEntityLoader, Species.EventLoader,
Species.DocumentTagLoader, Species.DocumentLoader,
beforeModel: (transition) ->
queryParams = transition.queryParams
@ensureGeoEntitiesLoaded(@controllerFor('search'))
@ensureEventsLoaded(@controllerFor('elibrarySearch'))
@ensureDocumentTagsLoaded(@controllerFor('elibrarySearch'))
#dirty hack to check if we have an array or comma separated string here
if queryParams.geo_entities_ids && queryParams.geo_entities_ids.substring
queryParams.geo_entities_ids = queryParams.geo_entities_ids.split(',')
if queryParams.events_ids && queryParams.events_ids.substring
queryParams.events_ids = queryParams.events_ids.split(',')
queryParams.geo_entities_ids = [] if queryParams.geo_entities_ids == true
queryParams.events_ids = [] if queryParams.events_ids == true
@controllerFor('elibrarySearch').setFilters(queryParams)
$(@spinnerSelector).css("visibility", "visible")
$('tr.group i.fa-minus-circle').click()
model: (params, transition) ->
queryParams = params.queryParams
@resetDocumentsResults()
if queryParams['event_type']
@loadDocumentsForEventType(queryParams['event_type'], queryParams)
else
@get('eventTypes').forEach((eventType) =>
eventQueryParams = $.extend({}, queryParams, {event_type: eventType})
@loadDocumentsForEventType(eventType, eventQueryParams)
)
afterModel: (model, transition) ->
$(@spinnerSelector).css("visibility", "hidden")
renderTemplate: ->
# Render the `documents` template into
# the default outlet, and display the `documents`
# controller.
@render('documents', {
into: 'application',
outlet: 'main',
controller: @controllerFor('documents')
})
# Render the `elibrary_search_form` template into
# the outlet `search`, and display the `search`
# controller.
@render('elibrarySearchForm', {
into: 'documents',
outlet: 'search',
controller: @controllerFor('elibrarySearch')
})
loadDocumentsForEventType: (eventType, eventQueryParams) ->
eventType = @getEventTypeKey(eventType).camelize()
controller = @controllerFor('documents')
eventKey = PI:KEY:<KEY>END_PI + 'PI:KEY:<KEY>END_PI'
isLoadingProperty = eventType + 'DocsIsLoading'
controller.set(isLoadingProperty, true)
@loadDocuments(eventQueryParams, (documents) =>
controller.set(eventKey, documents)
)
resetDocumentsResults: () ->
controller = @controllerFor('documents')
controller.set('euSrgDocuments', {})
controller.set('citesCopProposalsDocuments', {})
controller.set('citesAcDocuments', {})
controller.set('citesPcDocuments', {})
controller.set('idMaterialsDocuments', {})
controller.set('otherDocuments', {})
actions:
queryParamsDidChange: (changed, totalPresent, removed) ->
@refresh() |
[
{
"context": "$3')\r\n\r\n\tmailTo: (text) ->\r\n\r\n\t\ttext\r\n\t\t\t# [email:aleksnick@list.ru Отправить письмо]\r\n\t\t\t.replace(/\\[e\\-?mail:([a-zA",
"end": 20907,
"score": 0.9999263286590576,
"start": 20890,
"tag": "EMAIL",
"value": "aleksnick@list.ru"
},
{
"context": ")\\]/g... | app/models/markup.coffee | standart-n/sn-oz-client | 0 |
# Markup
require('_')
module.exports = class Markup
constructor: (@options = {}) ->
this.defaults =
images:
url: ''
files:
url: ''
gismeteo:
url: ''
_.defaults(this.options,this.defaults)
render: (text) ->
#text = text.toString()
text = @before(text) # предоработка
text = @formating(text) # жирный и курсив
text = @headings(text) # заголовки
text = @icons(text) # иконки
text = @externalLinks(text) # внешние ссылки
text = @fileLinks(text) # ссылки на файлы
text = @internalLinks(text) # внутренние ссылки
text = @mailTo(text) # ссылки на email-адреса
text = @image(text) # изображения
text = @fonts(text) # шрифты
text = @anchor(text) # якоря
text = @ind(text) # абзацы
text = @weather(text) # погода
text = @spoiler(text) # спойлеры
text = @header(text) # заголовки с подчеркиванием
text = @spaces(text) # переносы строк
text = @noevent(text) # пустые ссылки ( href="#" )
text
before: (text) ->
text
.replace(/\|\n/g, '')
.replace(/\]\n\n/g, ']<br><br>')
.replace(/\]\n/g, ']<br>')
.replace(/>\n\n/g, '>\n')
formating: (text) ->
text
# ''''' bold and italic '''''
.replace(/'''''(.*?)'''''/g, "<i><b>$1</b></i>")
# ''' bold '''
.replace(/'''(.*?)'''/g, "<b>$1</b>")
# '' italic ''
.replace(/''(.*?)''/g, "<i>$1</i>")
headings: (text) ->
# ======h6======
text = `text.replace(/======(.*?)======\n?/g, "<h6>$1</h6>")`
# =====h5=====
text = `text.replace(/=====(.*?)=====\n?/g, "<h5>$1</h5>")`
# ====h4====
text = `text.replace(/====(.*?)====\n?/g, "<h4>$1</h4>")`
# ===h3===
text = `text.replace(/===(.*?)===\n?/g, "<h3>$1</h3>")`
# ==h2==
text = `text.replace(/==(.*?)==\n?/g, "<h2>$1</h2>")`
icons: (text) ->
text
# [i:icon-refresh white]
.replace(/\[(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)\]/g, '<i class="icon-$2 icon-white"></i> ')
# [i:refresh white]
.replace(/\[(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)\]/g, '<i class="icon-$2 icon-white"></i> ')
# [i:icon-refresh]
.replace(/\[(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)\]/g, '<i class="icon-$2"></i> ')
# [i:refresh]
.replace(/\[(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)\]/g, '<i class="icon-$2"></i> ')
# i:icon-refresh white
.replace(/([\s]+)(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)([\s]+)/g, '$1<i class="icon-$3 icon-white"></i>$4')
# i:refresh white
.replace(/([\s]+)(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)([\s]+)/g, '$1<i class="icon-$3 icon-white"></i>$4')
# i:icon-refresh
.replace(/([\s]+)(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)([\s]+)/g, '$1<i class="icon-$3"></i>$4')
# i:refresh
.replace(/([\s]+)(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)([\s]+)/g, '$1<i class="icon-$3"></i>$4')
internalLinks: (text) ->
text
# [buttom primary #main/text/main На главную | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" data-placement="$6" rel="tooltip" title="$5">$4</a>')
# [buttom primary #main/text/main На главную | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5">$4</a>')
# [buttom primary #main/text/main | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" data-placement="$5" rel="tooltip" title="$4">$3</a>')
# [buttom primary #main/text/main | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4">$3</a>')
# [buttom primary #main/text/main На главную]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn btn-$2" href="#$3">$4</a>')
# [buttom primary #main/text/main]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a class="btn btn-$2" href="#$1">$1</a>')
# [buttom #main/text/main На главную | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$2" class="btn tooltip-toggle" data-placement="$5" rel="tooltip" title="$4">$3</a>')
# [buttom #main/text/main На главную | Подсказка]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g,'<a href="#$2" class="btn tooltip-toggle" rel="tooltip" title="$4">$3</a>')
# [buttom #main/text/main | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$2" class="btn tooltip-toggle" data-placement="$4" rel="tooltip" title="$3">$2</a>')
# [buttom #main/text/main | Подсказка]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$2" class="btn tooltip-toggle" rel="tooltip" title="$3">$2</a>')
# [buttom #main/text/main На главную]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="#$2">$3</a>')
# [buttom #main/text/main]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a href="#$1">$1</a>')
# [#main/text/main На главную | Подсказка bottom]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$1" class="tooltip-toggle" data-placement="$4" rel="tooltip" title="$3">$2</a>')
# [#main/text/main На главную | Подсказка]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1" class="tooltip-toggle" rel="tooltip" title="$3">$2</a>')
# [#main/text/main | Подсказка bottom]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$1" class="tooltip-toggle" data-placement="$3" rel="tooltip" title="$2">$1</a>')
# [#main/text/main | Подсказка]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1" class="tooltip-toggle" rel="tooltip" title="$2">$1</a>')
# [#main/text/main На главную]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1">$2</a>')
# [#main/text/main]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a href="#$1">$1</a>')
# #main/text/main
.replace(/([\s+])#([a-zA-Z0-9\-\.\/\?%\#_\:]+)([\s]+)/g, '$1<a href="#$2">$2</a>$3')
externalLinks: (text) ->
text
# [buttom primary http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+) (left|top|right|bottom)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" data-placement="$6" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary http://yandex.ru Яндекс | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary http://yandex.ru | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" data-placement="$5" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary http://yandex.ru | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary http://yandex.ru Яндекс]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2" target="_blank">$4</a>')
# [buttom primary http://yandex.ru]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn btn-$2" href="http://$2" target="_blank">$2</a>')
# [buttom http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+) (left|top|right|bottom)\]/g, '<a href="http://$2" class="btn tooltip-toggle" data-placement="$5" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom http://yandex.ru Яндекс | Подсказка]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$2" class="btn tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom http://yandex.ru | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$2" class="btn tooltip-toggle" data-placement="$4" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom http://yandex.ru | Подсказка]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$2" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom http://yandex.ru Яндекс]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="http://$2" target="_blank">$3</a>')
# [buttom http://yandex.ru]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn" href="http://$2" target="_blank">$2</a>')
# [http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$1" class="tooltip-toggle" data-placement="$4" rel="tooltip" title="$3" target="_blank">$2</a>')
# [http://yandex.ru Яндекс | Подсказка]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [http://yandex.ru | Подсказка bottom]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$1" class="tooltip-toggle" data-placement="$3" rel="tooltip" title="$2" target="_blank">$1</a>')
# [http://yandex.ru | Подсказка]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" class="tooltip-toggle" rel="tooltip" title="$2" target="_blank">$1</a>')
# [http://yandex.ru Яндекс]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" target="_blank">$2</a>')
# [http://yandex.ru]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a href="http://$1" target="_blank">$1</a>')
# http://yandex.ru
.replace(/([\s]+)https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g, '$1<a href="http://$2" target="_blank">$2</a>$3')
fileLinks: (text) ->
text
# [buttom primary file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" data-placement="$6" title="$5" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip Скачатьа bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" data-placement="$5" title="$4" target="_blank">$3</a>')
# [buttom primary file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary file:20120322/download.zip Скачать]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn btn-$2" href="' + @options.files.url + '$3" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn btn-$2" href="' + @options.files.url + '$3" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" data-placement="$5" title="$4" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачатьа bottom]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" data-placement="$4" title="$3" target="_blank">$2</a>')
# [buttom file:20120322/download.zip Скачатьа | Подсказка]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom file:20120322/download.zip Скачать]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="' + @options.files.url + '$2" target="_blank">$3</a>')
# [buttom file:20120322/download.zip]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn" href="' + @options.files.url + '$2" target="_blank">$2</a>')
# [file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" data-placement="$4" title="$3" target="_blank">$2</a>')
# [file:20120322/download.zip Скачать | Подсказка]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [file:20120322/download.zip Скачатьа bottom]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" data-placement="$3" title="$2" target="_blank">$1</a>')
# [file:20120322/download.zip Скачатьа | Подсказка]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" title="$2" target="_blank">$1</a>')
# [file:20120322/download.zip Скачать]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" target="_blank">$2</a>')
# [file:20120322/download.zip]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a href="' + @options.files.url + '$1" target="_blank">$1</a>')
# file:20120322/download.zip
.replace(/([\s]+)files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g, '$1<a href="' + @options.files.url + '$2" target="_blank">$2</a>$3')
mailTo: (text) ->
text
# [email:aleksnick@list.ru Отправить письмо]
.replace(/\[e\-?mail:([a-zA-Z0-9@\-\.\/\?%\#_]+)[\s]+(.*?)\]/g, '<a href="mailto:$1">$2</a>')
# [email:aleksnick@list.ru]
.replace(/\[e\-?mail:([a-zA-Z0-9@\-\.\/\?%\#_]+)\]/g, '<a href="mailto:$1">$1</a>')
image: (text, options) ->
text
# [image:20130523/image.png left]
.replace(/\[(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+(right|left)\]/g,'<img class="pull-$3" src="' + @options.images.url + '$2">')
# [image:20130523/image.png]
.replace(/\[(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g,'<img src="' + @options.images.url + '$2">')
# image:20130523/image.png left
.replace(/([\s]+)(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+(right|left)([\s]+)/g,'$1<img class="pull-$4" src="' + @options.images.url + '$3">$5')
# image:20130523/image.png
.replace(/([\s]+)(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g,'$1<img src="' + @options.images.url + '$3">$4')
fonts: (text) ->
text
# [badge success Бэйдж]
.replace(/\[badge[\s]+(success|warning|important|info|inverse)\][\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)/g, '<span class="badge badge-$1">$2</span>')
# [badge Бэйдж success]
.replace(/\[badge[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(success|warning|important|info|inverse)\]/g, '<span class="badge badge-$2">$1</span>')
# [badge Бэйдж]
.replace(/\[badge[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="badge">$1</span>')
# [label success Лэйбл]
.replace(/\[label[\s]+(success|warning|important|info|inverse)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="label label-$1">$2</span>')
# [label Лэйбл success]
.replace(/\[label[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(success|warning|important|info|inverse)\]/g, '<span class="label label-$2">$1</span>')
# [label Лэйбл]
.replace(/\[label[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="label">$1</span>')
# [color:#ff0000 Текст]
.replace(/\[color:\#([a-zA-Z0-9]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<font style="color:#$1">$2</font>')
# [color:red Текст]
.replace(/\[color:([a-zA-Z0-9]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="$1">$2</span>')
# [[color:#ff0000] Текст]
.replace(/\[\[color:\#([a-zA-Z0-9]+)\](.*?)\]/g, '<font style="color:#$1">$2</font>')
# [[color:red] Текст]
.replace(/\[\[color:([a-zA-Z0-9]+)\](.*?)\]/g, '<span class="$1">$2</span>')
ind: (text) ->
text
# <<<reestr
.replace(/<<<\#?\:?([a-zA-Z0-9\-\.\/\?\_]+)\n?/g, '<div class="well well-small"><a id="anchor-$1"></a>')
# <<<
.replace(/<<<\n?/g, '<div class="well well-small">')
# >>>
.replace(/>>>\n?/g, '</div>')
anchor: (text) ->
text
# [anchor:reestr] -> <a id="anchor-reestr"></a> Якорь
.replace(/\[anchor:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]\n?/g, '<a id="anchor-$1"></a>')
weather: (text) ->
# [gismeteo]
text.replace(/\[gismeteo\]\n?/g, '<iframe src="' + @options.gismeteo.url + '" width="96%" height="160" scrolling="no" marginheight="0" marginwidth="0" frameborder="0"></iframe> ')
spoiler: (text) ->
text
# <<[button primary Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="btn btn-$2 spoiler-caption spoiler-close">'+
'<span class="caret"></span> $3</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
# <<[button Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[b(tn|utton)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="btn spoiler-caption spoiler-close">'+
'<span class="caret"></span> $2</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
# <<[Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="spoiler-caption spoiler-close">'+
'$1</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
.replace(/>>\n?/g,'</pre></div></p></div>')
header: (text) ->
text
# <[
# Заголовок с нижним подчеркиванием
# ]>
.replace(/<\[\n?/g,'<div class="page-header">')
.replace(/\]>\n?/g,'</div>')
spaces: (text) ->
text
.replace(/^\n/, "")
.replace(/\n\n/g, "<br><br>")
.replace(/>\n?/g, '>')
.replace(/<pre><br>/g, '<pre>')
.replace(/\n/g, "<br>")
noevent: (text) ->
text
# <a href="#">Ссылка</a> -> <a href="#" data-noevent="true">Ссылка</a>
.replace(/(href="#")/g,'$1 data-noevent="true"')
| 56835 |
# Markup
require('_')
module.exports = class Markup
constructor: (@options = {}) ->
this.defaults =
images:
url: ''
files:
url: ''
gismeteo:
url: ''
_.defaults(this.options,this.defaults)
render: (text) ->
#text = text.toString()
text = @before(text) # предоработка
text = @formating(text) # жирный и курсив
text = @headings(text) # заголовки
text = @icons(text) # иконки
text = @externalLinks(text) # внешние ссылки
text = @fileLinks(text) # ссылки на файлы
text = @internalLinks(text) # внутренние ссылки
text = @mailTo(text) # ссылки на email-адреса
text = @image(text) # изображения
text = @fonts(text) # шрифты
text = @anchor(text) # якоря
text = @ind(text) # абзацы
text = @weather(text) # погода
text = @spoiler(text) # спойлеры
text = @header(text) # заголовки с подчеркиванием
text = @spaces(text) # переносы строк
text = @noevent(text) # пустые ссылки ( href="#" )
text
before: (text) ->
text
.replace(/\|\n/g, '')
.replace(/\]\n\n/g, ']<br><br>')
.replace(/\]\n/g, ']<br>')
.replace(/>\n\n/g, '>\n')
formating: (text) ->
text
# ''''' bold and italic '''''
.replace(/'''''(.*?)'''''/g, "<i><b>$1</b></i>")
# ''' bold '''
.replace(/'''(.*?)'''/g, "<b>$1</b>")
# '' italic ''
.replace(/''(.*?)''/g, "<i>$1</i>")
headings: (text) ->
# ======h6======
text = `text.replace(/======(.*?)======\n?/g, "<h6>$1</h6>")`
# =====h5=====
text = `text.replace(/=====(.*?)=====\n?/g, "<h5>$1</h5>")`
# ====h4====
text = `text.replace(/====(.*?)====\n?/g, "<h4>$1</h4>")`
# ===h3===
text = `text.replace(/===(.*?)===\n?/g, "<h3>$1</h3>")`
# ==h2==
text = `text.replace(/==(.*?)==\n?/g, "<h2>$1</h2>")`
icons: (text) ->
text
# [i:icon-refresh white]
.replace(/\[(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)\]/g, '<i class="icon-$2 icon-white"></i> ')
# [i:refresh white]
.replace(/\[(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)\]/g, '<i class="icon-$2 icon-white"></i> ')
# [i:icon-refresh]
.replace(/\[(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)\]/g, '<i class="icon-$2"></i> ')
# [i:refresh]
.replace(/\[(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)\]/g, '<i class="icon-$2"></i> ')
# i:icon-refresh white
.replace(/([\s]+)(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)([\s]+)/g, '$1<i class="icon-$3 icon-white"></i>$4')
# i:refresh white
.replace(/([\s]+)(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)([\s]+)/g, '$1<i class="icon-$3 icon-white"></i>$4')
# i:icon-refresh
.replace(/([\s]+)(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)([\s]+)/g, '$1<i class="icon-$3"></i>$4')
# i:refresh
.replace(/([\s]+)(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)([\s]+)/g, '$1<i class="icon-$3"></i>$4')
internalLinks: (text) ->
text
# [buttom primary #main/text/main На главную | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" data-placement="$6" rel="tooltip" title="$5">$4</a>')
# [buttom primary #main/text/main На главную | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5">$4</a>')
# [buttom primary #main/text/main | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" data-placement="$5" rel="tooltip" title="$4">$3</a>')
# [buttom primary #main/text/main | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4">$3</a>')
# [buttom primary #main/text/main На главную]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn btn-$2" href="#$3">$4</a>')
# [buttom primary #main/text/main]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a class="btn btn-$2" href="#$1">$1</a>')
# [buttom #main/text/main На главную | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$2" class="btn tooltip-toggle" data-placement="$5" rel="tooltip" title="$4">$3</a>')
# [buttom #main/text/main На главную | Подсказка]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g,'<a href="#$2" class="btn tooltip-toggle" rel="tooltip" title="$4">$3</a>')
# [buttom #main/text/main | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$2" class="btn tooltip-toggle" data-placement="$4" rel="tooltip" title="$3">$2</a>')
# [buttom #main/text/main | Подсказка]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$2" class="btn tooltip-toggle" rel="tooltip" title="$3">$2</a>')
# [buttom #main/text/main На главную]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="#$2">$3</a>')
# [buttom #main/text/main]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a href="#$1">$1</a>')
# [#main/text/main На главную | Подсказка bottom]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$1" class="tooltip-toggle" data-placement="$4" rel="tooltip" title="$3">$2</a>')
# [#main/text/main На главную | Подсказка]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1" class="tooltip-toggle" rel="tooltip" title="$3">$2</a>')
# [#main/text/main | Подсказка bottom]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$1" class="tooltip-toggle" data-placement="$3" rel="tooltip" title="$2">$1</a>')
# [#main/text/main | Подсказка]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1" class="tooltip-toggle" rel="tooltip" title="$2">$1</a>')
# [#main/text/main На главную]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1">$2</a>')
# [#main/text/main]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a href="#$1">$1</a>')
# #main/text/main
.replace(/([\s+])#([a-zA-Z0-9\-\.\/\?%\#_\:]+)([\s]+)/g, '$1<a href="#$2">$2</a>$3')
externalLinks: (text) ->
text
# [buttom primary http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+) (left|top|right|bottom)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" data-placement="$6" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary http://yandex.ru Яндекс | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary http://yandex.ru | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" data-placement="$5" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary http://yandex.ru | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary http://yandex.ru Яндекс]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2" target="_blank">$4</a>')
# [buttom primary http://yandex.ru]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn btn-$2" href="http://$2" target="_blank">$2</a>')
# [buttom http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+) (left|top|right|bottom)\]/g, '<a href="http://$2" class="btn tooltip-toggle" data-placement="$5" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom http://yandex.ru Яндекс | Подсказка]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$2" class="btn tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom http://yandex.ru | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$2" class="btn tooltip-toggle" data-placement="$4" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom http://yandex.ru | Подсказка]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$2" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom http://yandex.ru Яндекс]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="http://$2" target="_blank">$3</a>')
# [buttom http://yandex.ru]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn" href="http://$2" target="_blank">$2</a>')
# [http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$1" class="tooltip-toggle" data-placement="$4" rel="tooltip" title="$3" target="_blank">$2</a>')
# [http://yandex.ru Яндекс | Подсказка]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [http://yandex.ru | Подсказка bottom]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$1" class="tooltip-toggle" data-placement="$3" rel="tooltip" title="$2" target="_blank">$1</a>')
# [http://yandex.ru | Подсказка]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" class="tooltip-toggle" rel="tooltip" title="$2" target="_blank">$1</a>')
# [http://yandex.ru Яндекс]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" target="_blank">$2</a>')
# [http://yandex.ru]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a href="http://$1" target="_blank">$1</a>')
# http://yandex.ru
.replace(/([\s]+)https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g, '$1<a href="http://$2" target="_blank">$2</a>$3')
fileLinks: (text) ->
text
# [buttom primary file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" data-placement="$6" title="$5" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip Скачатьа bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" data-placement="$5" title="$4" target="_blank">$3</a>')
# [buttom primary file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary file:20120322/download.zip Скачать]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn btn-$2" href="' + @options.files.url + '$3" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn btn-$2" href="' + @options.files.url + '$3" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" data-placement="$5" title="$4" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачатьа bottom]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" data-placement="$4" title="$3" target="_blank">$2</a>')
# [buttom file:20120322/download.zip Скачатьа | Подсказка]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom file:20120322/download.zip Скачать]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="' + @options.files.url + '$2" target="_blank">$3</a>')
# [buttom file:20120322/download.zip]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn" href="' + @options.files.url + '$2" target="_blank">$2</a>')
# [file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" data-placement="$4" title="$3" target="_blank">$2</a>')
# [file:20120322/download.zip Скачать | Подсказка]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [file:20120322/download.zip Скачатьа bottom]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" data-placement="$3" title="$2" target="_blank">$1</a>')
# [file:20120322/download.zip Скачатьа | Подсказка]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" title="$2" target="_blank">$1</a>')
# [file:20120322/download.zip Скачать]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" target="_blank">$2</a>')
# [file:20120322/download.zip]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a href="' + @options.files.url + '$1" target="_blank">$1</a>')
# file:20120322/download.zip
.replace(/([\s]+)files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g, '$1<a href="' + @options.files.url + '$2" target="_blank">$2</a>$3')
mailTo: (text) ->
text
# [email:<EMAIL> Отправить письмо]
.replace(/\[e\-?mail:([a-zA-Z0-9@\-\.\/\?%\#_]+)[\s]+(.*?)\]/g, '<a href="mailto:$1">$2</a>')
# [email:<EMAIL>]
.replace(/\[e\-?mail:([a-zA-Z0-9@\-\.\/\?%\#_]+)\]/g, '<a href="mailto:$1">$1</a>')
image: (text, options) ->
text
# [image:20130523/image.png left]
.replace(/\[(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+(right|left)\]/g,'<img class="pull-$3" src="' + @options.images.url + '$2">')
# [image:20130523/image.png]
.replace(/\[(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g,'<img src="' + @options.images.url + '$2">')
# image:20130523/image.png left
.replace(/([\s]+)(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+(right|left)([\s]+)/g,'$1<img class="pull-$4" src="' + @options.images.url + '$3">$5')
# image:20130523/image.png
.replace(/([\s]+)(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g,'$1<img src="' + @options.images.url + '$3">$4')
fonts: (text) ->
text
# [badge success Бэйдж]
.replace(/\[badge[\s]+(success|warning|important|info|inverse)\][\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)/g, '<span class="badge badge-$1">$2</span>')
# [badge Бэйдж success]
.replace(/\[badge[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(success|warning|important|info|inverse)\]/g, '<span class="badge badge-$2">$1</span>')
# [badge Бэйдж]
.replace(/\[badge[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="badge">$1</span>')
# [label success Лэйбл]
.replace(/\[label[\s]+(success|warning|important|info|inverse)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="label label-$1">$2</span>')
# [label Лэйбл success]
.replace(/\[label[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(success|warning|important|info|inverse)\]/g, '<span class="label label-$2">$1</span>')
# [label Лэйбл]
.replace(/\[label[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="label">$1</span>')
# [color:#ff0000 Текст]
.replace(/\[color:\#([a-zA-Z0-9]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<font style="color:#$1">$2</font>')
# [color:red Текст]
.replace(/\[color:([a-zA-Z0-9]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="$1">$2</span>')
# [[color:#ff0000] Текст]
.replace(/\[\[color:\#([a-zA-Z0-9]+)\](.*?)\]/g, '<font style="color:#$1">$2</font>')
# [[color:red] Текст]
.replace(/\[\[color:([a-zA-Z0-9]+)\](.*?)\]/g, '<span class="$1">$2</span>')
ind: (text) ->
text
# <<<reestr
.replace(/<<<\#?\:?([a-zA-Z0-9\-\.\/\?\_]+)\n?/g, '<div class="well well-small"><a id="anchor-$1"></a>')
# <<<
.replace(/<<<\n?/g, '<div class="well well-small">')
# >>>
.replace(/>>>\n?/g, '</div>')
anchor: (text) ->
text
# [anchor:reestr] -> <a id="anchor-reestr"></a> Якорь
.replace(/\[anchor:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]\n?/g, '<a id="anchor-$1"></a>')
weather: (text) ->
# [gismeteo]
text.replace(/\[gismeteo\]\n?/g, '<iframe src="' + @options.gismeteo.url + '" width="96%" height="160" scrolling="no" marginheight="0" marginwidth="0" frameborder="0"></iframe> ')
spoiler: (text) ->
text
# <<[button primary Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="btn btn-$2 spoiler-caption spoiler-close">'+
'<span class="caret"></span> $3</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
# <<[button Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[b(tn|utton)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="btn spoiler-caption spoiler-close">'+
'<span class="caret"></span> $2</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
# <<[Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="spoiler-caption spoiler-close">'+
'$1</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
.replace(/>>\n?/g,'</pre></div></p></div>')
header: (text) ->
text
# <[
# Заголовок с нижним подчеркиванием
# ]>
.replace(/<\[\n?/g,'<div class="page-header">')
.replace(/\]>\n?/g,'</div>')
spaces: (text) ->
text
.replace(/^\n/, "")
.replace(/\n\n/g, "<br><br>")
.replace(/>\n?/g, '>')
.replace(/<pre><br>/g, '<pre>')
.replace(/\n/g, "<br>")
noevent: (text) ->
text
# <a href="#">Ссылка</a> -> <a href="#" data-noevent="true">Ссылка</a>
.replace(/(href="#")/g,'$1 data-noevent="true"')
| true |
# Markup
require('_')
module.exports = class Markup
constructor: (@options = {}) ->
this.defaults =
images:
url: ''
files:
url: ''
gismeteo:
url: ''
_.defaults(this.options,this.defaults)
render: (text) ->
#text = text.toString()
text = @before(text) # предоработка
text = @formating(text) # жирный и курсив
text = @headings(text) # заголовки
text = @icons(text) # иконки
text = @externalLinks(text) # внешние ссылки
text = @fileLinks(text) # ссылки на файлы
text = @internalLinks(text) # внутренние ссылки
text = @mailTo(text) # ссылки на email-адреса
text = @image(text) # изображения
text = @fonts(text) # шрифты
text = @anchor(text) # якоря
text = @ind(text) # абзацы
text = @weather(text) # погода
text = @spoiler(text) # спойлеры
text = @header(text) # заголовки с подчеркиванием
text = @spaces(text) # переносы строк
text = @noevent(text) # пустые ссылки ( href="#" )
text
before: (text) ->
text
.replace(/\|\n/g, '')
.replace(/\]\n\n/g, ']<br><br>')
.replace(/\]\n/g, ']<br>')
.replace(/>\n\n/g, '>\n')
formating: (text) ->
text
# ''''' bold and italic '''''
.replace(/'''''(.*?)'''''/g, "<i><b>$1</b></i>")
# ''' bold '''
.replace(/'''(.*?)'''/g, "<b>$1</b>")
# '' italic ''
.replace(/''(.*?)''/g, "<i>$1</i>")
headings: (text) ->
# ======h6======
text = `text.replace(/======(.*?)======\n?/g, "<h6>$1</h6>")`
# =====h5=====
text = `text.replace(/=====(.*?)=====\n?/g, "<h5>$1</h5>")`
# ====h4====
text = `text.replace(/====(.*?)====\n?/g, "<h4>$1</h4>")`
# ===h3===
text = `text.replace(/===(.*?)===\n?/g, "<h3>$1</h3>")`
# ==h2==
text = `text.replace(/==(.*?)==\n?/g, "<h2>$1</h2>")`
icons: (text) ->
text
# [i:icon-refresh white]
.replace(/\[(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)\]/g, '<i class="icon-$2 icon-white"></i> ')
# [i:refresh white]
.replace(/\[(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)\]/g, '<i class="icon-$2 icon-white"></i> ')
# [i:icon-refresh]
.replace(/\[(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)\]/g, '<i class="icon-$2"></i> ')
# [i:refresh]
.replace(/\[(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)\]/g, '<i class="icon-$2"></i> ')
# i:icon-refresh white
.replace(/([\s]+)(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)([\s]+)/g, '$1<i class="icon-$3 icon-white"></i>$4')
# i:refresh white
.replace(/([\s]+)(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)[\s]+(inverse|white)([\s]+)/g, '$1<i class="icon-$3 icon-white"></i>$4')
# i:icon-refresh
.replace(/([\s]+)(i|ico|icon|icons):icon-([a-zA-Z0-9\_\-]+)([\s]+)/g, '$1<i class="icon-$3"></i>$4')
# i:refresh
.replace(/([\s]+)(i|ico|icon|icons):([a-zA-Z0-9\_\-]+)([\s]+)/g, '$1<i class="icon-$3"></i>$4')
internalLinks: (text) ->
text
# [buttom primary #main/text/main На главную | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" data-placement="$6" rel="tooltip" title="$5">$4</a>')
# [buttom primary #main/text/main На главную | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5">$4</a>')
# [buttom primary #main/text/main | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" data-placement="$5" rel="tooltip" title="$4">$3</a>')
# [buttom primary #main/text/main | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4">$3</a>')
# [buttom primary #main/text/main На главную]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn btn-$2" href="#$3">$4</a>')
# [buttom primary #main/text/main]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a class="btn btn-$2" href="#$1">$1</a>')
# [buttom #main/text/main На главную | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$2" class="btn tooltip-toggle" data-placement="$5" rel="tooltip" title="$4">$3</a>')
# [buttom #main/text/main На главную | Подсказка]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g,'<a href="#$2" class="btn tooltip-toggle" rel="tooltip" title="$4">$3</a>')
# [buttom #main/text/main | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$2" class="btn tooltip-toggle" data-placement="$4" rel="tooltip" title="$3">$2</a>')
# [buttom #main/text/main | Подсказка]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$2" class="btn tooltip-toggle" rel="tooltip" title="$3">$2</a>')
# [buttom #main/text/main На главную]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="#$2">$3</a>')
# [buttom #main/text/main]
.replace(/\[b(tn|utton)[\s]+#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a href="#$1">$1</a>')
# [#main/text/main На главную | Подсказка bottom]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$1" class="tooltip-toggle" data-placement="$4" rel="tooltip" title="$3">$2</a>')
# [#main/text/main На главную | Подсказка]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1" class="tooltip-toggle" rel="tooltip" title="$3">$2</a>')
# [#main/text/main | Подсказка bottom]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="#$1" class="tooltip-toggle" data-placement="$3" rel="tooltip" title="$2">$1</a>')
# [#main/text/main | Подсказка]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1" class="tooltip-toggle" rel="tooltip" title="$2">$1</a>')
# [#main/text/main На главную]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="#$1">$2</a>')
# [#main/text/main]
.replace(/\[#([a-zA-Z0-9\-\.\/\?%\#_\:]+)\]/g, '<a href="#$1">$1</a>')
# #main/text/main
.replace(/([\s+])#([a-zA-Z0-9\-\.\/\?%\#_\:]+)([\s]+)/g, '$1<a href="#$2">$2</a>$3')
externalLinks: (text) ->
text
# [buttom primary http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+) (left|top|right|bottom)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" data-placement="$6" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary http://yandex.ru Яндекс | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary http://yandex.ru | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" data-placement="$5" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary http://yandex.ru | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary http://yandex.ru Яндекс]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$3" class="btn btn-$2" target="_blank">$4</a>')
# [buttom primary http://yandex.ru]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn btn-$2" href="http://$2" target="_blank">$2</a>')
# [buttom http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+) (left|top|right|bottom)\]/g, '<a href="http://$2" class="btn tooltip-toggle" data-placement="$5" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom http://yandex.ru Яндекс | Подсказка]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$2" class="btn tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom http://yandex.ru | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$2" class="btn tooltip-toggle" data-placement="$4" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom http://yandex.ru | Подсказка]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$2" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom http://yandex.ru Яндекс]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="http://$2" target="_blank">$3</a>')
# [buttom http://yandex.ru]
.replace(/\[b(tn|utton)[\s]+https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn" href="http://$2" target="_blank">$2</a>')
# [http://yandex.ru Яндекс | Подсказка bottom]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$1" class="tooltip-toggle" data-placement="$4" rel="tooltip" title="$3" target="_blank">$2</a>')
# [http://yandex.ru Яндекс | Подсказка]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [http://yandex.ru | Подсказка bottom]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="http://$1" class="tooltip-toggle" data-placement="$3" rel="tooltip" title="$2" target="_blank">$1</a>')
# [http://yandex.ru | Подсказка]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" class="tooltip-toggle" rel="tooltip" title="$2" target="_blank">$1</a>')
# [http://yandex.ru Яндекс]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="http://$1" target="_blank">$2</a>')
# [http://yandex.ru]
.replace(/\[https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a href="http://$1" target="_blank">$1</a>')
# http://yandex.ru
.replace(/([\s]+)https?:\/\/([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g, '$1<a href="http://$2" target="_blank">$2</a>$3')
fileLinks: (text) ->
text
# [buttom primary file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" data-placement="$6" title="$5" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$5" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip Скачатьа bottom]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" data-placement="$5" title="$4" target="_blank">$3</a>')
# [buttom primary file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$3" class="btn btn-$2 tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom primary file:20120322/download.zip Скачать]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn btn-$2" href="' + @options.files.url + '$3" target="_blank">$4</a>')
# [buttom primary file:20120322/download.zip]
.replace(/\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn btn-$2" href="' + @options.files.url + '$3" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" data-placement="$5" title="$4" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачать | Подсказка]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" title="$4" target="_blank">$3</a>')
# [buttom file:20120322/download.zip Скачатьа bottom]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" data-placement="$4" title="$3" target="_blank">$2</a>')
# [buttom file:20120322/download.zip Скачатьа | Подсказка]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$2" class="btn tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [buttom file:20120322/download.zip Скачать]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a class="btn" href="' + @options.files.url + '$2" target="_blank">$3</a>')
# [buttom file:20120322/download.zip]
.replace(/\[b(tn|utton)[\s]+files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a class="btn" href="' + @options.files.url + '$2" target="_blank">$2</a>')
# [file:20120322/download.zip Скачать | Подсказка bottom]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" data-placement="$4" title="$3" target="_blank">$2</a>')
# [file:20120322/download.zip Скачать | Подсказка]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" title="$3" target="_blank">$2</a>')
# [file:20120322/download.zip Скачатьа bottom]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(left|top|right|bottom)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" data-placement="$3" title="$2" target="_blank">$1</a>')
# [file:20120322/download.zip Скачатьа | Подсказка]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+\|[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" class="tooltip-toggle" rel="tooltip" title="$2" target="_blank">$1</a>')
# [file:20120322/download.zip Скачать]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<a href="' + @options.files.url + '$1" target="_blank">$2</a>')
# [file:20120322/download.zip]
.replace(/\[files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g, '<a href="' + @options.files.url + '$1" target="_blank">$1</a>')
# file:20120322/download.zip
.replace(/([\s]+)files?:([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g, '$1<a href="' + @options.files.url + '$2" target="_blank">$2</a>$3')
mailTo: (text) ->
text
# [email:PI:EMAIL:<EMAIL>END_PI Отправить письмо]
.replace(/\[e\-?mail:([a-zA-Z0-9@\-\.\/\?%\#_]+)[\s]+(.*?)\]/g, '<a href="mailto:$1">$2</a>')
# [email:PI:EMAIL:<EMAIL>END_PI]
.replace(/\[e\-?mail:([a-zA-Z0-9@\-\.\/\?%\#_]+)\]/g, '<a href="mailto:$1">$1</a>')
image: (text, options) ->
text
# [image:20130523/image.png left]
.replace(/\[(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+(right|left)\]/g,'<img class="pull-$3" src="' + @options.images.url + '$2">')
# [image:20130523/image.png]
.replace(/\[(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]/g,'<img src="' + @options.images.url + '$2">')
# image:20130523/image.png left
.replace(/([\s]+)(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)[\s]+(right|left)([\s]+)/g,'$1<img class="pull-$4" src="' + @options.images.url + '$3">$5')
# image:20130523/image.png
.replace(/([\s]+)(img|image|picture|photo):([a-zA-Z0-9\-\.\/\?\%\#\_]+)([\s]+)/g,'$1<img src="' + @options.images.url + '$3">$4')
fonts: (text) ->
text
# [badge success Бэйдж]
.replace(/\[badge[\s]+(success|warning|important|info|inverse)\][\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)/g, '<span class="badge badge-$1">$2</span>')
# [badge Бэйдж success]
.replace(/\[badge[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(success|warning|important|info|inverse)\]/g, '<span class="badge badge-$2">$1</span>')
# [badge Бэйдж]
.replace(/\[badge[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="badge">$1</span>')
# [label success Лэйбл]
.replace(/\[label[\s]+(success|warning|important|info|inverse)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="label label-$1">$2</span>')
# [label Лэйбл success]
.replace(/\[label[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)[\s]+(success|warning|important|info|inverse)\]/g, '<span class="label label-$2">$1</span>')
# [label Лэйбл]
.replace(/\[label[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="label">$1</span>')
# [color:#ff0000 Текст]
.replace(/\[color:\#([a-zA-Z0-9]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<font style="color:#$1">$2</font>')
# [color:red Текст]
.replace(/\[color:([a-zA-Z0-9]+)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]/g, '<span class="$1">$2</span>')
# [[color:#ff0000] Текст]
.replace(/\[\[color:\#([a-zA-Z0-9]+)\](.*?)\]/g, '<font style="color:#$1">$2</font>')
# [[color:red] Текст]
.replace(/\[\[color:([a-zA-Z0-9]+)\](.*?)\]/g, '<span class="$1">$2</span>')
ind: (text) ->
text
# <<<reestr
.replace(/<<<\#?\:?([a-zA-Z0-9\-\.\/\?\_]+)\n?/g, '<div class="well well-small"><a id="anchor-$1"></a>')
# <<<
.replace(/<<<\n?/g, '<div class="well well-small">')
# >>>
.replace(/>>>\n?/g, '</div>')
anchor: (text) ->
text
# [anchor:reestr] -> <a id="anchor-reestr"></a> Якорь
.replace(/\[anchor:([a-zA-Z0-9\-\.\/\?\%\#\_]+)\]\n?/g, '<a id="anchor-$1"></a>')
weather: (text) ->
# [gismeteo]
text.replace(/\[gismeteo\]\n?/g, '<iframe src="' + @options.gismeteo.url + '" width="96%" height="160" scrolling="no" marginheight="0" marginwidth="0" frameborder="0"></iframe> ')
spoiler: (text) ->
text
# <<[button primary Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[b(tn|utton)[\s]+(primary|info|success|warning|danger|inverse|link)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="btn btn-$2 spoiler-caption spoiler-close">'+
'<span class="caret"></span> $3</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
# <<[button Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[b(tn|utton)[\s]+([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="btn spoiler-caption spoiler-close">'+
'<span class="caret"></span> $2</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
# <<[Заголовок спойлера]
# текст спойлера
# >>
.replace(/<<\[([\s0-9a-zA-Zа-яА-Я\_\.\/\-\?\!\*\#\'\"\<\>\=\,\;\:\(\)\№\«\»]+)\]\n?/g,'<div class="spoiler">'+
'<a href="#spoiler" class="spoiler-caption spoiler-close">'+
'$1</a><p>'+
'<div class="hide spoiler-body spoiler-close"><pre>')
.replace(/>>\n?/g,'</pre></div></p></div>')
header: (text) ->
text
# <[
# Заголовок с нижним подчеркиванием
# ]>
.replace(/<\[\n?/g,'<div class="page-header">')
.replace(/\]>\n?/g,'</div>')
spaces: (text) ->
text
.replace(/^\n/, "")
.replace(/\n\n/g, "<br><br>")
.replace(/>\n?/g, '>')
.replace(/<pre><br>/g, '<pre>')
.replace(/\n/g, "<br>")
noevent: (text) ->
text
# <a href="#">Ссылка</a> -> <a href="#" data-noevent="true">Ссылка</a>
.replace(/(href="#")/g,'$1 data-noevent="true"')
|
[
{
"context": "://chartbeat.com/docs/api/explore\n# \n# Author:\n# Drew Delianides\n\nmodule.exports = (robot) ->\n robot.respond /cha",
"end": 567,
"score": 0.9998688697814941,
"start": 552,
"tag": "NAME",
"value": "Drew Delianides"
}
] | src/scripts/chartbeat.coffee | Reelhouse/hubot-scripts | 2 | # Description:
# Display number of concurrent vistors to the specified site.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_CHARTBEAT_SITE
# HUBOT_CHARTBEAT_API_KEY <use global key for access to all sites>
#
# Commands:
# hubot chart me - Returns active concurrent vistors from the default site specified.
# hubot chart me <host> - Returns active concurrent vistors from the site specified.
#
# Notes:
# How to find these settings:
# Log into chartbeat then browse to
# http://chartbeat.com/docs/api/explore
#
# Author:
# Drew Delianides
module.exports = (robot) ->
robot.respond /chart( me)? (.*)/i, (msg) ->
if (!process.env.HUBOT_CHARTBEAT_SITE && msg.match[2] == 'me')
msg.send "You need to set a default site"
return
site = if (msg.match[2] == 'me') then process.env.HUBOT_CHARTBEAT_SITE else msg.match[2]
apiKey = process.env.HUBOT_CHARTBEAT_API_KEY
msg.http("http://api.chartbeat.com/live/quickstats/v3/?apikey=#{apiKey}&host=#{site}")
.get() (err, res, body) ->
unless res.statusCode is 200
msg.send "There was a problem with Chartbeat. Do you have access to this domain?"
return
response = JSON.parse(body)
people = response.people || []
if (people < 1)
msg.send "It doesn't appear that #{site} has any visitors right now"
return
pluralize = if (people == 1) then "person" else "people"
msg.send "I see #{people} #{pluralize} on #{site} right now!"
| 13559 | # Description:
# Display number of concurrent vistors to the specified site.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_CHARTBEAT_SITE
# HUBOT_CHARTBEAT_API_KEY <use global key for access to all sites>
#
# Commands:
# hubot chart me - Returns active concurrent vistors from the default site specified.
# hubot chart me <host> - Returns active concurrent vistors from the site specified.
#
# Notes:
# How to find these settings:
# Log into chartbeat then browse to
# http://chartbeat.com/docs/api/explore
#
# Author:
# <NAME>
module.exports = (robot) ->
robot.respond /chart( me)? (.*)/i, (msg) ->
if (!process.env.HUBOT_CHARTBEAT_SITE && msg.match[2] == 'me')
msg.send "You need to set a default site"
return
site = if (msg.match[2] == 'me') then process.env.HUBOT_CHARTBEAT_SITE else msg.match[2]
apiKey = process.env.HUBOT_CHARTBEAT_API_KEY
msg.http("http://api.chartbeat.com/live/quickstats/v3/?apikey=#{apiKey}&host=#{site}")
.get() (err, res, body) ->
unless res.statusCode is 200
msg.send "There was a problem with Chartbeat. Do you have access to this domain?"
return
response = JSON.parse(body)
people = response.people || []
if (people < 1)
msg.send "It doesn't appear that #{site} has any visitors right now"
return
pluralize = if (people == 1) then "person" else "people"
msg.send "I see #{people} #{pluralize} on #{site} right now!"
| true | # Description:
# Display number of concurrent vistors to the specified site.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_CHARTBEAT_SITE
# HUBOT_CHARTBEAT_API_KEY <use global key for access to all sites>
#
# Commands:
# hubot chart me - Returns active concurrent vistors from the default site specified.
# hubot chart me <host> - Returns active concurrent vistors from the site specified.
#
# Notes:
# How to find these settings:
# Log into chartbeat then browse to
# http://chartbeat.com/docs/api/explore
#
# Author:
# PI:NAME:<NAME>END_PI
module.exports = (robot) ->
robot.respond /chart( me)? (.*)/i, (msg) ->
if (!process.env.HUBOT_CHARTBEAT_SITE && msg.match[2] == 'me')
msg.send "You need to set a default site"
return
site = if (msg.match[2] == 'me') then process.env.HUBOT_CHARTBEAT_SITE else msg.match[2]
apiKey = process.env.HUBOT_CHARTBEAT_API_KEY
msg.http("http://api.chartbeat.com/live/quickstats/v3/?apikey=#{apiKey}&host=#{site}")
.get() (err, res, body) ->
unless res.statusCode is 200
msg.send "There was a problem with Chartbeat. Do you have access to this domain?"
return
response = JSON.parse(body)
people = response.people || []
if (people < 1)
msg.send "It doesn't appear that #{site} has any visitors right now"
return
pluralize = if (people == 1) then "person" else "people"
msg.send "I see #{people} #{pluralize} on #{site} right now!"
|
[
{
"context": "comment: \"Ada -- chris@cjack.com. Feel free to modify, distribute, be happy. Share",
"end": 32,
"score": 0.9999151825904846,
"start": 17,
"tag": "EMAIL",
"value": "chris@cjack.com"
},
{
"context": "y.\"\nfileTypes: [\n \"ada\"\n \"adb\"\n \"ads\"\n]\nname: \"Ada\"\n... | grammars/ada.cson | Synntix/atom-language-ada | 0 | comment: "Ada -- chris@cjack.com. Feel free to modify, distribute, be happy. Share and enjoy."
fileTypes: [
"ada"
"adb"
"ads"
]
name: "Ada"
patterns: [
{
match: "\=>|\\b(?i:(abort|abs|abstract|accept|access|aliased|all|and|array|at|body|case|constant|declare|delay|delta|digits|do|else|elsif|end case|end if|end loop|end record|entry|exception|exit|for|generic|goto|if|in|interface|is|limited|loop|mod|new|not|null|of|or|others|out|overriding|pragma|private|protected|raise|range|record|rem|renames|requeue|return|reverse|select|separate|some|subtype|synchronized|tagged|task|terminate|then|type|until|use|when|while|with|xor))\\b"
name: "keyword.other.ada"
}
{
captures:
"1":
name: "storage.type.function.ada"
"2":
name: "entity.name.function.ada"
match: "\\b(?i:(function|procedure))\\b\\s+(\\w+(\\.\\w+)?|\"(?:\\+|-|=|\\*|/)\")"
name: "meta.function.ada"
}
{
captures:
"1":
name: "storage.type.package.ada"
"2":
name: "keyword.other.body.ada"
"3":
name: "entity.name.type.package.ada"
match: "\\b(?i:(package)(?:\\b\\s+(body))?)\\b\\s+(\\w+(\\.\\w+)*|\"(?:\\+|-|=|\\*|/)\")"
name: "meta.function.ada"
}
{
captures:
"1":
name: "storage.type.function.ada"
"2":
name: "entity.name.function.ada"
match: "\\b(?i:(end))\\b\\s+(\\w+(\\.\\w+)*|\"(\\+|-|=|\\*|/)\")\\s?;"
name: "meta.function.ada"
}
{
captures:
"1":
name: "keyword.control.import.ada"
"2":
name: "string.unquoted.import.ada"
match: "(^|[\\r\\n])((?i:((limited[ \\t]*)?(private[ \\t]*)?with))[ \\t]+(\\w+(\\.\\w+)*);[ \\t]*)+"
name: "meta.function.ada"
}
{
match: "\\b(?i:(begin|end|package))\\b"
name: "storage.type.function.ada"
}
{
match: "\\b(?i:(boolean|string|natural|integer|positive|float))\\b"
name: "storage.type.primitive.ada"
}
{
match: "\\b(?i:([0-9](_?[0-9])*((#[0-9a-f](_?[0-9a-f])*#((e(\\+|-)?[0-9](_?[0-9])*\\b)|\\B))|((\\.[0-9](_?[0-9])*)?(e(\\+|-)?[0-9](_?[0-9])*)?\\b))))"
name: "constant.numeric.ada"
}
{
match: "\\b(?i:true|false)"
name: "constant.language.ada"
}
{
match: "\\b(?i:Lire|Ecrire|ecrire_ligne|a_la_ligne|image)"
name: "entity.name.function.ada"
}
{
match: "(:\=|\/\=|\=|<\=|>\=|<|>)"
name: "keyword.other.ada"
}
{
#match: "(;|\\.|\\(|\\)|,|:)"
match: "(;|\\.|,|:)"
name: "keyword.other.unit.ada"
}
{
begin: "\""
beginCaptures:
"1":
name: "punctuation.definition.string.begin.ada"
end: "\""
endCaptures:
"1":
name: "punctuation.definition.string.end.ada"
name: "string.quoted.double.ada"
patterns: [
{
match: "\\n"
name: "invalid.illegal.lf-in-string.ada"
}
]
}
{
begin: "(^[ \\t]+)?(?=--)"
beginCaptures:
"1":
name: "punctuation.whitespace.comment.leading.ada"
end: "(?!\\G)"
patterns: [
{
begin: "--"
beginCaptures:
"0":
name: "punctuation.definition.comment.ada"
end: "\\n"
name: "comment.line.double-dash.ada"
}
]
}
]
scopeName: "source.ada"
| 40884 | comment: "Ada -- <EMAIL>. Feel free to modify, distribute, be happy. Share and enjoy."
fileTypes: [
"ada"
"adb"
"ads"
]
name: "<NAME>"
patterns: [
{
match: "\=>|\\b(?i:(abort|abs|abstract|accept|access|aliased|all|and|array|at|body|case|constant|declare|delay|delta|digits|do|else|elsif|end case|end if|end loop|end record|entry|exception|exit|for|generic|goto|if|in|interface|is|limited|loop|mod|new|not|null|of|or|others|out|overriding|pragma|private|protected|raise|range|record|rem|renames|requeue|return|reverse|select|separate|some|subtype|synchronized|tagged|task|terminate|then|type|until|use|when|while|with|xor))\\b"
name: "keyword.other.ada"
}
{
captures:
"1":
name: "storage.type.function.ada"
"2":
name: "entity.name.function.ada"
match: "\\b(?i:(function|procedure))\\b\\s+(\\w+(\\.\\w+)?|\"(?:\\+|-|=|\\*|/)\")"
name: "meta.function.ada"
}
{
captures:
"1":
name: "storage.type.package.ada"
"2":
name: "keyword.other.body.ada"
"3":
name: "entity.name.type.package.ada"
match: "\\b(?i:(package)(?:\\b\\s+(body))?)\\b\\s+(\\w+(\\.\\w+)*|\"(?:\\+|-|=|\\*|/)\")"
name: "meta.function.ada"
}
{
captures:
"1":
name: "storage.type.function.ada"
"2":
name: "entity.name.function.ada"
match: "\\b(?i:(end))\\b\\s+(\\w+(\\.\\w+)*|\"(\\+|-|=|\\*|/)\")\\s?;"
name: "meta.function.ada"
}
{
captures:
"1":
name: "keyword.control.import.ada"
"2":
name: "string.unquoted.import.ada"
match: "(^|[\\r\\n])((?i:((limited[ \\t]*)?(private[ \\t]*)?with))[ \\t]+(\\w+(\\.\\w+)*);[ \\t]*)+"
name: "meta.function.ada"
}
{
match: "\\b(?i:(begin|end|package))\\b"
name: "storage.type.function.ada"
}
{
match: "\\b(?i:(boolean|string|natural|integer|positive|float))\\b"
name: "storage.type.primitive.ada"
}
{
match: "\\b(?i:([0-9](_?[0-9])*((#[0-9a-f](_?[0-9a-f])*#((e(\\+|-)?[0-9](_?[0-9])*\\b)|\\B))|((\\.[0-9](_?[0-9])*)?(e(\\+|-)?[0-9](_?[0-9])*)?\\b))))"
name: "constant.numeric.ada"
}
{
match: "\\b(?i:true|false)"
name: "constant.language.ada"
}
{
match: "\\b(?i:Lire|Ecrire|ecrire_ligne|a_la_ligne|image)"
name: "entity.name.function.ada"
}
{
match: "(:\=|\/\=|\=|<\=|>\=|<|>)"
name: "keyword.other.ada"
}
{
#match: "(;|\\.|\\(|\\)|,|:)"
match: "(;|\\.|,|:)"
name: "keyword.other.unit.ada"
}
{
begin: "\""
beginCaptures:
"1":
name: "punctuation.definition.string.begin.ada"
end: "\""
endCaptures:
"1":
name: "punctuation.definition.string.end.ada"
name: "string.quoted.double.ada"
patterns: [
{
match: "\\n"
name: "invalid.illegal.lf-in-string.ada"
}
]
}
{
begin: "(^[ \\t]+)?(?=--)"
beginCaptures:
"1":
name: "punctuation.whitespace.comment.leading.ada"
end: "(?!\\G)"
patterns: [
{
begin: "--"
beginCaptures:
"0":
name: "punctuation.definition.comment.ada"
end: "\\n"
name: "comment.line.double-dash.ada"
}
]
}
]
scopeName: "source.ada"
| true | comment: "Ada -- PI:EMAIL:<EMAIL>END_PI. Feel free to modify, distribute, be happy. Share and enjoy."
fileTypes: [
"ada"
"adb"
"ads"
]
name: "PI:NAME:<NAME>END_PI"
patterns: [
{
match: "\=>|\\b(?i:(abort|abs|abstract|accept|access|aliased|all|and|array|at|body|case|constant|declare|delay|delta|digits|do|else|elsif|end case|end if|end loop|end record|entry|exception|exit|for|generic|goto|if|in|interface|is|limited|loop|mod|new|not|null|of|or|others|out|overriding|pragma|private|protected|raise|range|record|rem|renames|requeue|return|reverse|select|separate|some|subtype|synchronized|tagged|task|terminate|then|type|until|use|when|while|with|xor))\\b"
name: "keyword.other.ada"
}
{
captures:
"1":
name: "storage.type.function.ada"
"2":
name: "entity.name.function.ada"
match: "\\b(?i:(function|procedure))\\b\\s+(\\w+(\\.\\w+)?|\"(?:\\+|-|=|\\*|/)\")"
name: "meta.function.ada"
}
{
captures:
"1":
name: "storage.type.package.ada"
"2":
name: "keyword.other.body.ada"
"3":
name: "entity.name.type.package.ada"
match: "\\b(?i:(package)(?:\\b\\s+(body))?)\\b\\s+(\\w+(\\.\\w+)*|\"(?:\\+|-|=|\\*|/)\")"
name: "meta.function.ada"
}
{
captures:
"1":
name: "storage.type.function.ada"
"2":
name: "entity.name.function.ada"
match: "\\b(?i:(end))\\b\\s+(\\w+(\\.\\w+)*|\"(\\+|-|=|\\*|/)\")\\s?;"
name: "meta.function.ada"
}
{
captures:
"1":
name: "keyword.control.import.ada"
"2":
name: "string.unquoted.import.ada"
match: "(^|[\\r\\n])((?i:((limited[ \\t]*)?(private[ \\t]*)?with))[ \\t]+(\\w+(\\.\\w+)*);[ \\t]*)+"
name: "meta.function.ada"
}
{
match: "\\b(?i:(begin|end|package))\\b"
name: "storage.type.function.ada"
}
{
match: "\\b(?i:(boolean|string|natural|integer|positive|float))\\b"
name: "storage.type.primitive.ada"
}
{
match: "\\b(?i:([0-9](_?[0-9])*((#[0-9a-f](_?[0-9a-f])*#((e(\\+|-)?[0-9](_?[0-9])*\\b)|\\B))|((\\.[0-9](_?[0-9])*)?(e(\\+|-)?[0-9](_?[0-9])*)?\\b))))"
name: "constant.numeric.ada"
}
{
match: "\\b(?i:true|false)"
name: "constant.language.ada"
}
{
match: "\\b(?i:Lire|Ecrire|ecrire_ligne|a_la_ligne|image)"
name: "entity.name.function.ada"
}
{
match: "(:\=|\/\=|\=|<\=|>\=|<|>)"
name: "keyword.other.ada"
}
{
#match: "(;|\\.|\\(|\\)|,|:)"
match: "(;|\\.|,|:)"
name: "keyword.other.unit.ada"
}
{
begin: "\""
beginCaptures:
"1":
name: "punctuation.definition.string.begin.ada"
end: "\""
endCaptures:
"1":
name: "punctuation.definition.string.end.ada"
name: "string.quoted.double.ada"
patterns: [
{
match: "\\n"
name: "invalid.illegal.lf-in-string.ada"
}
]
}
{
begin: "(^[ \\t]+)?(?=--)"
beginCaptures:
"1":
name: "punctuation.whitespace.comment.leading.ada"
end: "(?!\\G)"
patterns: [
{
begin: "--"
beginCaptures:
"0":
name: "punctuation.definition.comment.ada"
end: "\\n"
name: "comment.line.double-dash.ada"
}
]
}
]
scopeName: "source.ada"
|
[
{
"context": "key: 'code'\npatterns: [\n {\n # begin: '(`+)(?!$)'\n # e",
"end": 10,
"score": 0.9959285855293274,
"start": 6,
"tag": "KEY",
"value": "code"
}
] | grammars/repositories/inlines/code.cson | doc22940/language-markdown | 138 | key: 'code'
patterns: [
{
# begin: '(`+)(?!$)'
# end: '(?<!`)(\\1)(?!`)'
# match: '(?<!`)(`+)[^`]+(\\1)(?!`)'
match: '(?<!`)(`+)(?!`).+?(?<!`)(\\1)(?!`)'
name: 'code.raw.markup.md'
captures:
1: name: 'punctuation.md'
2: name: 'punctuation.md'
}
]
| 139143 | key: '<KEY>'
patterns: [
{
# begin: '(`+)(?!$)'
# end: '(?<!`)(\\1)(?!`)'
# match: '(?<!`)(`+)[^`]+(\\1)(?!`)'
match: '(?<!`)(`+)(?!`).+?(?<!`)(\\1)(?!`)'
name: 'code.raw.markup.md'
captures:
1: name: 'punctuation.md'
2: name: 'punctuation.md'
}
]
| true | key: 'PI:KEY:<KEY>END_PI'
patterns: [
{
# begin: '(`+)(?!$)'
# end: '(?<!`)(\\1)(?!`)'
# match: '(?<!`)(`+)[^`]+(\\1)(?!`)'
match: '(?<!`)(`+)(?!`).+?(?<!`)(\\1)(?!`)'
name: 'code.raw.markup.md'
captures:
1: name: 'punctuation.md'
2: name: 'punctuation.md'
}
]
|
[
{
"context": "a, list=[], options={} )->\n\tkey = options.key or \"id\"\n\tprepend = options.prepend or false\n\tsafeSeparat",
"end": 202,
"score": 0.9906394481658936,
"start": 200,
"tag": "KEY",
"value": "id"
}
] | _src/lib/main.coffee | mpneuried/sortbylist | 2 | # # Sortbylist
#
# ### Exports: *Function*
#
# Small helper to sort a collection by a given list of id's
#
#export this class
module.exports = ( data, list=[], options={} )->
key = options.key or "id"
prepend = options.prepend or false
safeSeparator = options.safeSeparator or ":|:|:"
# no list provided, so return original
if not list?.length
return data
# on empty data return an empty array
if not data?.length
return []
# create an index
index = for el in data
el[key].toString()
# copy the index to ba able to detect the rest
indexCheck = index.join( safeSeparator ).split( safeSeparator )
# do the sorting
res = []
for _l in list
_idx = index.indexOf( _l )
_idxCheck = indexCheck.indexOf( _l )
if _idx >= 0 and _idxCheck >= 0
indexCheck.splice( _idxCheck, 1 )
res.push data[_idx]
# if indexCheck is empty all data elements where added
if not indexCheck.length
return res
_rest = []
for _l in indexCheck
_idx = index.indexOf( _l.toString() )
if _idx >= 0
_rest.push data[_idx]
if prepend
return _rest.concat( res )
else
return [].concat( res, _rest ) | 43862 | # # Sortbylist
#
# ### Exports: *Function*
#
# Small helper to sort a collection by a given list of id's
#
#export this class
module.exports = ( data, list=[], options={} )->
key = options.key or "<KEY>"
prepend = options.prepend or false
safeSeparator = options.safeSeparator or ":|:|:"
# no list provided, so return original
if not list?.length
return data
# on empty data return an empty array
if not data?.length
return []
# create an index
index = for el in data
el[key].toString()
# copy the index to ba able to detect the rest
indexCheck = index.join( safeSeparator ).split( safeSeparator )
# do the sorting
res = []
for _l in list
_idx = index.indexOf( _l )
_idxCheck = indexCheck.indexOf( _l )
if _idx >= 0 and _idxCheck >= 0
indexCheck.splice( _idxCheck, 1 )
res.push data[_idx]
# if indexCheck is empty all data elements where added
if not indexCheck.length
return res
_rest = []
for _l in indexCheck
_idx = index.indexOf( _l.toString() )
if _idx >= 0
_rest.push data[_idx]
if prepend
return _rest.concat( res )
else
return [].concat( res, _rest ) | true | # # Sortbylist
#
# ### Exports: *Function*
#
# Small helper to sort a collection by a given list of id's
#
#export this class
module.exports = ( data, list=[], options={} )->
key = options.key or "PI:KEY:<KEY>END_PI"
prepend = options.prepend or false
safeSeparator = options.safeSeparator or ":|:|:"
# no list provided, so return original
if not list?.length
return data
# on empty data return an empty array
if not data?.length
return []
# create an index
index = for el in data
el[key].toString()
# copy the index to ba able to detect the rest
indexCheck = index.join( safeSeparator ).split( safeSeparator )
# do the sorting
res = []
for _l in list
_idx = index.indexOf( _l )
_idxCheck = indexCheck.indexOf( _l )
if _idx >= 0 and _idxCheck >= 0
indexCheck.splice( _idxCheck, 1 )
res.push data[_idx]
# if indexCheck is empty all data elements where added
if not indexCheck.length
return res
_rest = []
for _l in indexCheck
_idx = index.indexOf( _l.toString() )
if _idx >= 0
_rest.push data[_idx]
if prepend
return _rest.concat( res )
else
return [].concat( res, _rest ) |
[
{
"context": ")\n\nUser.remove {}, ->\n new User({\n username: \"sylvain\"\n nickname: \"Obélix\"\n email: \"bigsylvain@gm",
"end": 843,
"score": 0.9997220635414124,
"start": 836,
"tag": "USERNAME",
"value": "sylvain"
},
{
"context": "new User({\n username: \"sylvain\"\n... | backend/populate.coffee | fasterthanlime/agora2 | 0 | sys = require('sys')
sha1 = require('sha1')
mongoose = require('mongoose')
schemas = require('./schemas')
# Add a few categories
Category = mongoose.model('Category')
User = mongoose.model('User')
Category.remove {}, ->
new Category({
slug: 'philo',
title: 'Philosophico-théoriques',
description: 'Débats, réflexions, partages d\'idées... sur tous les sujets profonds que le monde peut contenir.'
}).save()
new Category({
slug: 'fufus',
title: 'Le clan des fufus',
description: 'Discussions sérieuses ou rigolotes sur tout ce qui concerne le clan des Fufus !'
}).save()
new Category({
slug: 'delirium',
title: 'Délirium',
description: 'Pour parler de tout et de rien, et même de n\'importe quoi ! Rigolades bienvenues.'
}).save()
User.remove {}, ->
new User({
username: "sylvain"
nickname: "Obélix"
email: "bigsylvain@gmail.com"
joindate: Date.now()
posts: 0
avatar: "/stylesheets/avatar1.png"
slogan: "Pardieu, c'est un inculte!"
sha1: sha1("sylvain")
}).save()
new User({
username: "bluesky"
nickname: "Loth"
email: "amos@official.fm"
joindate: Date.now()
posts: 0
avatar: "/stylesheets/avatar2.png"
slogan: "Montjoie! Saint-Denis!"
sha1: sha1("bluesky")
}).save()
sys.puts('Done populating!')
| 43156 | sys = require('sys')
sha1 = require('sha1')
mongoose = require('mongoose')
schemas = require('./schemas')
# Add a few categories
Category = mongoose.model('Category')
User = mongoose.model('User')
Category.remove {}, ->
new Category({
slug: 'philo',
title: 'Philosophico-théoriques',
description: 'Débats, réflexions, partages d\'idées... sur tous les sujets profonds que le monde peut contenir.'
}).save()
new Category({
slug: 'fufus',
title: 'Le clan des fufus',
description: 'Discussions sérieuses ou rigolotes sur tout ce qui concerne le clan des Fufus !'
}).save()
new Category({
slug: 'delirium',
title: 'Délirium',
description: 'Pour parler de tout et de rien, et même de n\'importe quoi ! Rigolades bienvenues.'
}).save()
User.remove {}, ->
new User({
username: "sylvain"
nickname: "Obélix"
email: "<EMAIL>"
joindate: Date.now()
posts: 0
avatar: "/stylesheets/avatar1.png"
slogan: "P<NAME>, c'est un inculte!"
sha1: sha1("sylvain")
}).save()
new User({
username: "bluesky"
nickname: "Loth"
email: "<EMAIL>"
joindate: Date.now()
posts: 0
avatar: "/stylesheets/avatar2.png"
slogan: "Montjoie! Saint-Denis!"
sha1: sha1("bluesky")
}).save()
sys.puts('Done populating!')
| true | sys = require('sys')
sha1 = require('sha1')
mongoose = require('mongoose')
schemas = require('./schemas')
# Add a few categories
Category = mongoose.model('Category')
User = mongoose.model('User')
Category.remove {}, ->
new Category({
slug: 'philo',
title: 'Philosophico-théoriques',
description: 'Débats, réflexions, partages d\'idées... sur tous les sujets profonds que le monde peut contenir.'
}).save()
new Category({
slug: 'fufus',
title: 'Le clan des fufus',
description: 'Discussions sérieuses ou rigolotes sur tout ce qui concerne le clan des Fufus !'
}).save()
new Category({
slug: 'delirium',
title: 'Délirium',
description: 'Pour parler de tout et de rien, et même de n\'importe quoi ! Rigolades bienvenues.'
}).save()
User.remove {}, ->
new User({
username: "sylvain"
nickname: "Obélix"
email: "PI:EMAIL:<EMAIL>END_PI"
joindate: Date.now()
posts: 0
avatar: "/stylesheets/avatar1.png"
slogan: "PPI:NAME:<NAME>END_PI, c'est un inculte!"
sha1: sha1("sylvain")
}).save()
new User({
username: "bluesky"
nickname: "Loth"
email: "PI:EMAIL:<EMAIL>END_PI"
joindate: Date.now()
posts: 0
avatar: "/stylesheets/avatar2.png"
slogan: "Montjoie! Saint-Denis!"
sha1: sha1("bluesky")
}).save()
sys.puts('Done populating!')
|
[
{
"context": "stry.register [], ({metadata}) ->\n key: \"root value, depth #{metadata.depth}\"\n {key} = await nikit",
"end": 258,
"score": 0.6839759349822998,
"start": 253,
"tag": "KEY",
"value": "value"
},
{
"context": " {key} = await nikita()\n key.should.eql 'root va... | packages/engine/test/options/depth.coffee | DanielJohnHarty/node-nikita | 1 |
nikita = require '../../src'
registry = require '../../src/registry'
register = require '../../src/register'
describe 'options `depth`', ->
it 'start at depth 0 with registered action', ->
registry.register [], ({metadata}) ->
key: "root value, depth #{metadata.depth}"
{key} = await nikita()
key.should.eql 'root value, depth 0'
registry.unregister [], register['']
it 'start at depth 0 with action argument', ->
{key} = await nikita ({metadata}) ->
key: "root value, depth #{metadata.depth}"
key.should.eql 'root value, depth 0'
| 12319 |
nikita = require '../../src'
registry = require '../../src/registry'
register = require '../../src/register'
describe 'options `depth`', ->
it 'start at depth 0 with registered action', ->
registry.register [], ({metadata}) ->
key: "root <KEY>, depth #{metadata.depth}"
{key} = await nikita()
key.should.eql 'root <KEY>, depth 0'
registry.unregister [], register['']
it 'start at depth 0 with action argument', ->
{key} = await nikita ({metadata}) ->
key: "root <KEY>, depth #{metadata.depth}"
key.should.eql 'root <KEY>, depth 0'
| true |
nikita = require '../../src'
registry = require '../../src/registry'
register = require '../../src/register'
describe 'options `depth`', ->
it 'start at depth 0 with registered action', ->
registry.register [], ({metadata}) ->
key: "root PI:KEY:<KEY>END_PI, depth #{metadata.depth}"
{key} = await nikita()
key.should.eql 'root PI:KEY:<KEY>END_PI, depth 0'
registry.unregister [], register['']
it 'start at depth 0 with action argument', ->
{key} = await nikita ({metadata}) ->
key: "root PI:KEY:<KEY>END_PI, depth #{metadata.depth}"
key.should.eql 'root PI:KEY:<KEY>END_PI, depth 0'
|
[
{
"context": "sList.add('collapsible1')\n button.textContent = name\n headContainer.appendChild button\n contentC",
"end": 2137,
"score": 0.9748855233192444,
"start": 2133,
"tag": "NAME",
"value": "name"
}
] | lib/gitlab-repository-view.coffee | vanboom/gitlab-manager | 2 | {CompositeDisposable} = require 'atom'
log = require './log'
opn = require 'opn'
class GitlabRepositoryView extends HTMLElement
init: (@gitlab) =>
@classList.add('gitlab-repository')
@currentProject = null
@tooltips = []
@successOnce = false
@subscriptions = new CompositeDisposable
@deleted = false
@loading()
getURI: () => 'atom://gitlab-manager/lib/gitlab-repository-view.coffee'
getDefaultLocation: () => 'right'
getTitle: () => 'Gitlab tasks'
getSuccessOnce: =>
return @successOnce
serialize: ->
deserializer: 'gitlab-manager/tobiasGitlabRepository'
getElement: () ->
return this.element
deactivate: =>
@deleted = true
@successOnce = false
@subscriptions.dispose()
@disposeTooltips()
loading: =>
@removeAllChildren()
status = document.createElement('div')
status.classList.add('inline-block')
icon = document.createElement('span')
icon.classList.add('icon', 'icon-gitlab')
status.classList.add("general-view")
message = document.createElement('div')
message.textContent = 'Currently there is no information about MR/issues available.'
message.classList.add("floating")
status.appendChild icon
status.appendChild message
@appendChild(status)
recreateView: =>
@successOnce = true
@removeAllChildren()
@appendChild(@createCollapsibleHead("Merge requests assigned to you:", (contentContainer) => @addMergeRequestInformation contentContainer ))
@appendChild(@createCollapsibleHead("Merge requests for you to approve:", (contentContainer) => @addMergeRequestApprover contentContainer ))
@appendChild(@createCollapsibleHead("Issues assigned to you:", (contentContainer) => @addIssuesSelfInformation contentContainer ))
createCollapsibleHead: (name, contentFunction) =>
mainContainer = document.createElement('div')
mainContainer.classList.add('main-container')
headContainer = document.createElement('div')
headContainer.classList.add('head-container')
button = document.createElement('button')
button.classList.add('collapsible1')
button.textContent = name
headContainer.appendChild button
contentContainer = document.createElement('div')
contentContainer.classList.add('content-collapsible')
mainContainer.appendChild headContainer
mainContainer.appendChild contentContainer
retry = document.createElement('div')
retry.classList.add('floating-right')
icon = document.createElement('span')
icon.classList.add('icon', 'gitlab-retry' )
retry.appendChild icon
headContainer.appendChild retry
button.onclick = =>
button.classList.toggle 'active'
if contentContainer.style.maxHeight
contentContainer.style.maxHeight = null
else
contentFunction contentContainer
retry.onclick = =>
contentContainer.style.maxHeight = null
contentFunction contentContainer
return mainContainer
addMergeRequestInformation: (contentContainer) =>
mergeObject = @gitlab.retrieveMergeRequestsSelf().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open merge request assigned to you.'
contentContainer.appendChild notExisting
else
result.forEach((mergeRequest) =>
mrContainer = document.createElement('div')
mrContainer.textContent = "#{mergeRequest.title}"
mrContainer.classList.add('clickable-link')
mrContainer.onclick = =>
opn(mergeRequest.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild mrContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve merge request assigned to you.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
addMergeRequestApprover: (contentContainer) =>
mergeObject = @gitlab.retrieveMergeRequestsApprover().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open merge for you to approve.'
contentContainer.appendChild notExisting
else
result.forEach((mergeRequest) =>
mrContainer = document.createElement('div')
mrContainer.textContent = "#{mergeRequest.title}"
mrContainer.classList.add('clickable-link')
mrContainer.onclick = =>
opn(mergeRequest.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild mrContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve merge request assigned to you for approval.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
addIssuesSelfInformation: (contentContainer) =>
mergeObject = @gitlab.retrieveIssuesSelf().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open issue assigned to you.'
contentContainer.appendChild notExisting
else
result.forEach((responseObject) =>
issContainer = document.createElement('div')
issContainer.textContent = "#{responseObject.title}"
issContainer.classList.add('clickable-link')
issContainer.onclick = =>
opn(responseObject.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild issContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve open issues assigned to you.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
disposeTooltips: =>
@tooltips.forEach((tooltip) => tooltip.dispose())
@tooltips = []
removeAllChildrenObjects: (container) =>
if container.children.length > 0
while container.hasChildNodes()
log "currentChildren", container.children[0]
container.removeChild container.children[0]
removeAllChildren: =>
if @children.length > 0
while @hasChildNodes()
log "currentChildren", @children[0]
@removeChild @children[0]
module.exports = document.registerElement 'gitlab-repository',
prototype: GitlabRepositoryView.prototype, extends: 'div'
| 28595 | {CompositeDisposable} = require 'atom'
log = require './log'
opn = require 'opn'
class GitlabRepositoryView extends HTMLElement
init: (@gitlab) =>
@classList.add('gitlab-repository')
@currentProject = null
@tooltips = []
@successOnce = false
@subscriptions = new CompositeDisposable
@deleted = false
@loading()
getURI: () => 'atom://gitlab-manager/lib/gitlab-repository-view.coffee'
getDefaultLocation: () => 'right'
getTitle: () => 'Gitlab tasks'
getSuccessOnce: =>
return @successOnce
serialize: ->
deserializer: 'gitlab-manager/tobiasGitlabRepository'
getElement: () ->
return this.element
deactivate: =>
@deleted = true
@successOnce = false
@subscriptions.dispose()
@disposeTooltips()
loading: =>
@removeAllChildren()
status = document.createElement('div')
status.classList.add('inline-block')
icon = document.createElement('span')
icon.classList.add('icon', 'icon-gitlab')
status.classList.add("general-view")
message = document.createElement('div')
message.textContent = 'Currently there is no information about MR/issues available.'
message.classList.add("floating")
status.appendChild icon
status.appendChild message
@appendChild(status)
recreateView: =>
@successOnce = true
@removeAllChildren()
@appendChild(@createCollapsibleHead("Merge requests assigned to you:", (contentContainer) => @addMergeRequestInformation contentContainer ))
@appendChild(@createCollapsibleHead("Merge requests for you to approve:", (contentContainer) => @addMergeRequestApprover contentContainer ))
@appendChild(@createCollapsibleHead("Issues assigned to you:", (contentContainer) => @addIssuesSelfInformation contentContainer ))
createCollapsibleHead: (name, contentFunction) =>
mainContainer = document.createElement('div')
mainContainer.classList.add('main-container')
headContainer = document.createElement('div')
headContainer.classList.add('head-container')
button = document.createElement('button')
button.classList.add('collapsible1')
button.textContent = <NAME>
headContainer.appendChild button
contentContainer = document.createElement('div')
contentContainer.classList.add('content-collapsible')
mainContainer.appendChild headContainer
mainContainer.appendChild contentContainer
retry = document.createElement('div')
retry.classList.add('floating-right')
icon = document.createElement('span')
icon.classList.add('icon', 'gitlab-retry' )
retry.appendChild icon
headContainer.appendChild retry
button.onclick = =>
button.classList.toggle 'active'
if contentContainer.style.maxHeight
contentContainer.style.maxHeight = null
else
contentFunction contentContainer
retry.onclick = =>
contentContainer.style.maxHeight = null
contentFunction contentContainer
return mainContainer
addMergeRequestInformation: (contentContainer) =>
mergeObject = @gitlab.retrieveMergeRequestsSelf().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open merge request assigned to you.'
contentContainer.appendChild notExisting
else
result.forEach((mergeRequest) =>
mrContainer = document.createElement('div')
mrContainer.textContent = "#{mergeRequest.title}"
mrContainer.classList.add('clickable-link')
mrContainer.onclick = =>
opn(mergeRequest.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild mrContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve merge request assigned to you.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
addMergeRequestApprover: (contentContainer) =>
mergeObject = @gitlab.retrieveMergeRequestsApprover().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open merge for you to approve.'
contentContainer.appendChild notExisting
else
result.forEach((mergeRequest) =>
mrContainer = document.createElement('div')
mrContainer.textContent = "#{mergeRequest.title}"
mrContainer.classList.add('clickable-link')
mrContainer.onclick = =>
opn(mergeRequest.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild mrContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve merge request assigned to you for approval.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
addIssuesSelfInformation: (contentContainer) =>
mergeObject = @gitlab.retrieveIssuesSelf().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open issue assigned to you.'
contentContainer.appendChild notExisting
else
result.forEach((responseObject) =>
issContainer = document.createElement('div')
issContainer.textContent = "#{responseObject.title}"
issContainer.classList.add('clickable-link')
issContainer.onclick = =>
opn(responseObject.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild issContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve open issues assigned to you.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
disposeTooltips: =>
@tooltips.forEach((tooltip) => tooltip.dispose())
@tooltips = []
removeAllChildrenObjects: (container) =>
if container.children.length > 0
while container.hasChildNodes()
log "currentChildren", container.children[0]
container.removeChild container.children[0]
removeAllChildren: =>
if @children.length > 0
while @hasChildNodes()
log "currentChildren", @children[0]
@removeChild @children[0]
module.exports = document.registerElement 'gitlab-repository',
prototype: GitlabRepositoryView.prototype, extends: 'div'
| true | {CompositeDisposable} = require 'atom'
log = require './log'
opn = require 'opn'
class GitlabRepositoryView extends HTMLElement
init: (@gitlab) =>
@classList.add('gitlab-repository')
@currentProject = null
@tooltips = []
@successOnce = false
@subscriptions = new CompositeDisposable
@deleted = false
@loading()
getURI: () => 'atom://gitlab-manager/lib/gitlab-repository-view.coffee'
getDefaultLocation: () => 'right'
getTitle: () => 'Gitlab tasks'
getSuccessOnce: =>
return @successOnce
serialize: ->
deserializer: 'gitlab-manager/tobiasGitlabRepository'
getElement: () ->
return this.element
deactivate: =>
@deleted = true
@successOnce = false
@subscriptions.dispose()
@disposeTooltips()
loading: =>
@removeAllChildren()
status = document.createElement('div')
status.classList.add('inline-block')
icon = document.createElement('span')
icon.classList.add('icon', 'icon-gitlab')
status.classList.add("general-view")
message = document.createElement('div')
message.textContent = 'Currently there is no information about MR/issues available.'
message.classList.add("floating")
status.appendChild icon
status.appendChild message
@appendChild(status)
recreateView: =>
@successOnce = true
@removeAllChildren()
@appendChild(@createCollapsibleHead("Merge requests assigned to you:", (contentContainer) => @addMergeRequestInformation contentContainer ))
@appendChild(@createCollapsibleHead("Merge requests for you to approve:", (contentContainer) => @addMergeRequestApprover contentContainer ))
@appendChild(@createCollapsibleHead("Issues assigned to you:", (contentContainer) => @addIssuesSelfInformation contentContainer ))
createCollapsibleHead: (name, contentFunction) =>
mainContainer = document.createElement('div')
mainContainer.classList.add('main-container')
headContainer = document.createElement('div')
headContainer.classList.add('head-container')
button = document.createElement('button')
button.classList.add('collapsible1')
button.textContent = PI:NAME:<NAME>END_PI
headContainer.appendChild button
contentContainer = document.createElement('div')
contentContainer.classList.add('content-collapsible')
mainContainer.appendChild headContainer
mainContainer.appendChild contentContainer
retry = document.createElement('div')
retry.classList.add('floating-right')
icon = document.createElement('span')
icon.classList.add('icon', 'gitlab-retry' )
retry.appendChild icon
headContainer.appendChild retry
button.onclick = =>
button.classList.toggle 'active'
if contentContainer.style.maxHeight
contentContainer.style.maxHeight = null
else
contentFunction contentContainer
retry.onclick = =>
contentContainer.style.maxHeight = null
contentFunction contentContainer
return mainContainer
addMergeRequestInformation: (contentContainer) =>
mergeObject = @gitlab.retrieveMergeRequestsSelf().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open merge request assigned to you.'
contentContainer.appendChild notExisting
else
result.forEach((mergeRequest) =>
mrContainer = document.createElement('div')
mrContainer.textContent = "#{mergeRequest.title}"
mrContainer.classList.add('clickable-link')
mrContainer.onclick = =>
opn(mergeRequest.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild mrContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve merge request assigned to you.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
addMergeRequestApprover: (contentContainer) =>
mergeObject = @gitlab.retrieveMergeRequestsApprover().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open merge for you to approve.'
contentContainer.appendChild notExisting
else
result.forEach((mergeRequest) =>
mrContainer = document.createElement('div')
mrContainer.textContent = "#{mergeRequest.title}"
mrContainer.classList.add('clickable-link')
mrContainer.onclick = =>
opn(mergeRequest.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild mrContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve merge request assigned to you for approval.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
addIssuesSelfInformation: (contentContainer) =>
mergeObject = @gitlab.retrieveIssuesSelf().then (result) =>
@removeAllChildrenObjects(contentContainer)
if result.length == 0
notExisting = document.createElement('div')
notExisting.textContent = 'Currently there is no open issue assigned to you.'
contentContainer.appendChild notExisting
else
result.forEach((responseObject) =>
issContainer = document.createElement('div')
issContainer.textContent = "#{responseObject.title}"
issContainer.classList.add('clickable-link')
issContainer.onclick = =>
opn(responseObject.web_url).catch (error) ->
atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
console.error error
contentContainer.appendChild issContainer
)
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
.catch((error) =>
@removeAllChildrenObjects(contentContainer)
console.error "couldn't fullfill promise", error
notExisting = document.createElement('div')
notExisting.textContent = 'Could not retrieve open issues assigned to you.'
contentContainer.appendChild notExisting
contentContainer.style.maxHeight = contentContainer.scrollHeight + 'px'
)
disposeTooltips: =>
@tooltips.forEach((tooltip) => tooltip.dispose())
@tooltips = []
removeAllChildrenObjects: (container) =>
if container.children.length > 0
while container.hasChildNodes()
log "currentChildren", container.children[0]
container.removeChild container.children[0]
removeAllChildren: =>
if @children.length > 0
while @hasChildNodes()
log "currentChildren", @children[0]
@removeChild @children[0]
module.exports = document.registerElement 'gitlab-repository',
prototype: GitlabRepositoryView.prototype, extends: 'div'
|
[
{
"context": "\"\n and: \"et\"\n back: \"retour\"\n changePassword: \"Modifier le mot de passe\"\n choosePassword: \"Choisir le mot de pa",
"end": 173,
"score": 0.7598887085914612,
"start": 158,
"tag": "PASSWORD",
"value": "Modifier le mot"
},
{
"context": "rd: \"Modifier le mot ... | t9n/fr_CA.coffee | softwarerero/meteor-accounts-t9n | 80 | #Language: Canadian French
#Translators: 2 Associés
fr_CA =
t9Name: 'Français (Canada)'
add: "Ajouter"
and: "et"
back: "retour"
changePassword: "Modifier le mot de passe"
choosePassword: "Choisir le mot de passe"
clickAgree: "En cliquant sur « S'enregistrer », vous acceptez nos"
configure: "Configurer"
createAccount: "Créer un compte"
currentPassword: "Mot de passe actuel"
dontHaveAnAccount: "Vous n'avez pas de compte?"
email: "Courriel"
emailAddress: "Adresse courriel"
emailResetLink: "Envoyer un courriel de réinitialisation"
forgotPassword: "Mot de passe oublié?"
ifYouAlreadyHaveAnAccount: "Si vous avez déjà un compte"
newPassword: "Nouveau mot de passe"
newPasswordAgain: "Confirmer le nouveau mot de passe"
optional: "Facultatif"
OR: "OU"
password: "Mot de passe"
passwordAgain: "Confirmer le mot de passe"
privacyPolicy: "Politique de confidentialité"
remove: "Supprimer"
resetYourPassword: "Reinitialiser votre mot de passe"
setPassword: "Saisir le mot de passe"
sign: "Inscrivez-vous"
signIn: "Ouvrir une session"
signin: "ouvrir une session"
signOut: "Quitter"
signUp: "Inscrivez-vous"
signupCode: "Code d'inscription"
signUpWithYourEmailAddress: "S'inscrire avec une adresse courriel"
terms: "Conditions d'utilisation"
updateYourPassword: "Mettre à jour le mot de passe"
username: "Nom d'utilisateur"
usernameOrEmail: "Nom d'utilisateur ou adresse courriel"
with: "avec"
"Verification email lost?": "Vous n'avez pas reçu de courriel de vérification?"
"Send again": "Envoyer à nouveau"
"Send the verification email again": "Renvoyer le courriel de vérification"
"Send email again": "Renvoyer le courriel"
"Minimum required length: 6": "Veuillez saisir au moins 6 caractères"
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nouveau courriel vous a été envoyé. Si vous ne le recevez pas sous peu, vérifiez votre dossier destiné aux courriels indésirables.",
"Required Field" : "Ce champ est obligatoire"
"Successful Registration! Please check your email and follow the instructions.": "Votre compte a été créé! Vous recevrez sous peu un courriel de confirmation et la marche à suivre pour valider votre inscription."
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nouvel e-mail vous a été envoyé. Si l'e-mail n'apparaît pas dans votre boîte de réception, vérifiez bien votre dossier spam."
"Already verified": "Déjà vérifié"
"At least 1 digit, 1 lowercase and 1 uppercase": "Au moins 1 chiffre, 1 minuscule et 1 majuscule"
"Invalid email": "Email invalide"
"Required Field": "Champs requis"
info:
emailSent: "Courriel envoyé"
emailVerified: "Adresse courriel verifiée"
passwordChanged: "Mot de passe modifié"
passwordReset: "Mot de passe réinitialisé"
error:
emailRequired: "Une adresse courriel est requise."
minChar: "Votre mot de passe doit contenir au moins 7 caractères."
pwdsDontMatch: "Les mots de passe saisis ne correspondent pas"
pwOneDigit: "Votre mot de passe doit contenir au moins un chiffre."
pwOneLetter: "Votre mot de passe doit contenir au moins une lettre."
signInRequired: "Vous devez ouvrir une session pour continuer."
signupCodeIncorrect: "Le code d'inscription est incorrect."
signupCodeRequired: "Un code d'inscription est requis."
usernameIsEmail: "Le nom d'utilisateur ne peut être identique à l'adresse courriel."
usernameRequired: "Un nom d'utilisateur est requis."
accounts:
#---- accounts-base
#"@" + domain + " email requis":
#"A login handler should return a result or undefined": "Un gestionnaire d'authentification doit retourner un résultat ou la valeur 'undefined'"
"Email already exists.": "L'adresse courriel existe déjà."
"Email doesn't match the criteria.": "L'adresse courriel semble incorrectement formatée."
"Invalid login token": "Jeton d'authentification invalide"
"Login forbidden": "Votre identifiant ou votre mot de passe est incorrect"
#"Service " + options.service + " already configured": "Le service " + options.service + " est déjà configuré"
"Service unknown": "Service inconnu"
"Unrecognized options for login request": "Options inconnues pour la requête d'authentification"
"User validation failed": "Échec de la validation de l'utilisateur"
"Username already exists.": "Nom d'utilisateur déjà utilisé."
"You are not logged in.": "Vous n'êtes pas connecté."
"You've been logged out by the server. Please log in again.": "Vous avez été déconnecté par le serveur. Veuillez vous reconnecter."
"Your session has expired. Please log in again.": "Votre session a expiré. Veuillez vous reconnecter."
#---- accounts-oauth
"No matching login attempt found": "Aucune tentative d'authentification ne correspond"
#---- accounts-password-client
"Password is old. Please reset your password.": "Votre mot de passe est périmé. Veuillez le modifier."
#---- accounts-password
"Incorrect password": "Mot de passe incorrect"
"Invalid email": "Adresse courriel invalide"
"Must be logged in": "Vous devez être connecté"
"Need to set a username or email": "Vous devez préciser un nom d'utilisateur ou une adresse courriel"
"old password format": "Ancien format de mot de passe"
"Password may not be empty": "Le mot de passe ne peut être vide"
"Signups forbidden": "Vous ne pouvez pas créer de compte"
"Token expired": "Jeton expiré"
"Token has invalid email address": "Le jeton contient une adresse courriel invalide"
"User has no password set": "L'utilisateur n'a pas de mot de passe"
"User not found": "Utilisateur inconnu"
"Verify email link expired": "Lien de vérification de courriel expiré"
"Please verify your email first. Check the email and follow the link!": "Votre courriel n'a pas encore été vérifié. Veuillez cliquer le lien que nous vous avons envoyé."
"Verify email link is for unknown address": "Le lien de vérification de courriel réfère à une adresse inconnue"
#---- match
"Match failed": "La correspondance a échoué"
#---- Misc...
"Unknown error": "Erreur inconnue"
T9n?.map "fr_CA", fr_CA
module?.exports = fr_CA | 64707 | #Language: Canadian French
#Translators: 2 Associés
fr_CA =
t9Name: 'Français (Canada)'
add: "Ajouter"
and: "et"
back: "retour"
changePassword: "<PASSWORD> de passe"
choosePassword: "<PASSWORD>"
clickAgree: "En cliquant sur « S'enregistrer », vous acceptez nos"
configure: "Configurer"
createAccount: "Créer un compte"
currentPassword: "<PASSWORD>"
dontHaveAnAccount: "Vous n'avez pas de compte?"
email: "Cour<NAME>"
emailAddress: "Adresse courriel"
emailResetLink: "Envoyer un courriel de réinitialisation"
forgotPassword: "<PASSWORD>?"
ifYouAlreadyHaveAnAccount: "Si vous avez déjà un compte"
newPassword: "<PASSWORD>"
newPasswordAgain: "<PASSWORD> de passe"
optional: "Facultatif"
OR: "OU"
password: "<PASSWORD>"
passwordAgain: "<PASSWORD>"
privacyPolicy: "Politique de confidentialité"
remove: "Supprimer"
resetYourPassword: "<PASSWORD>"
setPassword: "<PASSWORD> passe"
sign: "Inscrivez-vous"
signIn: "Ouvrir une session"
signin: "ouvrir une session"
signOut: "Quitter"
signUp: "Inscrivez-vous"
signupCode: "Code d'inscription"
signUpWithYourEmailAddress: "S'inscrire avec une adresse courriel"
terms: "Conditions d'utilisation"
updateYourPassword: "<PASSWORD> de passe"
username: "Nom d'utilisateur"
usernameOrEmail: "Nom d'utilisateur ou adresse courriel"
with: "avec"
"Verification email lost?": "Vous n'avez pas reçu de courriel de vérification?"
"Send again": "Envoyer à nouveau"
"Send the verification email again": "Renvoyer le courriel de vérification"
"Send email again": "Renvoyer le courriel"
"Minimum required length: 6": "Veuillez saisir au moins 6 caractères"
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nouveau courriel vous a été envoyé. Si vous ne le recevez pas sous peu, vérifiez votre dossier destiné aux courriels indésirables.",
"Required Field" : "Ce champ est obligatoire"
"Successful Registration! Please check your email and follow the instructions.": "Votre compte a été créé! Vous recevrez sous peu un courriel de confirmation et la marche à suivre pour valider votre inscription."
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nouvel e-mail vous a été envoyé. Si l'e-mail n'apparaît pas dans votre boîte de réception, vérifiez bien votre dossier spam."
"Already verified": "Déjà vérifié"
"At least 1 digit, 1 lowercase and 1 uppercase": "Au moins 1 chiffre, 1 minuscule et 1 majuscule"
"Invalid email": "Email invalide"
"Required Field": "Champs requis"
info:
emailSent: "Courriel envoyé"
emailVerified: "Adresse courriel verifiée"
passwordChanged: "<PASSWORD>"
passwordReset: "<PASSWORD>"
error:
emailRequired: "Une adresse courriel est requise."
minChar: "Votre mot de passe doit contenir au moins 7 caractères."
pwdsDontMatch: "Les mots de passe saisis ne correspondent pas"
pwOneDigit: "Votre mot de passe doit contenir au moins un chiffre."
pwOneLetter: "Votre mot de passe doit contenir au moins une lettre."
signInRequired: "Vous devez ouvrir une session pour continuer."
signupCodeIncorrect: "Le code d'inscription est incorrect."
signupCodeRequired: "Un code d'inscription est requis."
usernameIsEmail: "Le nom d'utilisateur ne peut être identique à l'adresse courriel."
usernameRequired: "Un nom d'utilisateur est requis."
accounts:
#---- accounts-base
#"@" + domain + " email requis":
#"A login handler should return a result or undefined": "Un gestionnaire d'authentification doit retourner un résultat ou la valeur 'undefined'"
"Email already exists.": "L'adresse courriel existe déjà."
"Email doesn't match the criteria.": "L'adresse courriel semble incorrectement formatée."
"Invalid login token": "Jeton d'authentification invalide"
"Login forbidden": "Votre identifiant ou votre mot de passe est incorrect"
#"Service " + options.service + " already configured": "Le service " + options.service + " est déjà configuré"
"Service unknown": "Service inconnu"
"Unrecognized options for login request": "Options inconnues pour la requête d'authentification"
"User validation failed": "Échec de la validation de l'utilisateur"
"Username already exists.": "Nom d'utilisateur déjà utilisé."
"You are not logged in.": "Vous n'êtes pas connecté."
"You've been logged out by the server. Please log in again.": "Vous avez été déconnecté par le serveur. Veuillez vous reconnecter."
"Your session has expired. Please log in again.": "Votre session a expiré. Veuillez vous reconnecter."
#---- accounts-oauth
"No matching login attempt found": "Aucune tentative d'authentification ne correspond"
#---- accounts-password-client
"Password is old. Please reset your password.": "Votre mot de passe est périmé. Veuillez le modifier."
#---- accounts-password
"Incorrect password": "Mot de passe incorrect"
"Invalid email": "Adresse courriel invalide"
"Must be logged in": "Vous devez être connecté"
"Need to set a username or email": "Vous devez préciser un nom d'utilisateur ou une adresse courriel"
"old password format": "Ancien format de mot de passe"
"Password may not be empty": "Le mot de passe ne peut être vide"
"Signups forbidden": "Vous ne pouvez pas créer de compte"
"Token expired": "Jeton expiré"
"Token has invalid email address": "Le jeton contient une adresse courriel invalide"
"User has no password set": "L'utilisateur n'a pas de mot de passe"
"User not found": "Utilisateur inconnu"
"Verify email link expired": "Lien de vérification de courriel expiré"
"Please verify your email first. Check the email and follow the link!": "Votre courriel n'a pas encore été vérifié. Veuillez cliquer le lien que nous vous avons envoyé."
"Verify email link is for unknown address": "Le lien de vérification de courriel réfère à une adresse inconnue"
#---- match
"Match failed": "La correspondance a échoué"
#---- Misc...
"Unknown error": "Erreur inconnue"
T9n?.map "fr_CA", fr_CA
module?.exports = fr_CA | true | #Language: Canadian French
#Translators: 2 Associés
fr_CA =
t9Name: 'Français (Canada)'
add: "Ajouter"
and: "et"
back: "retour"
changePassword: "PI:PASSWORD:<PASSWORD>END_PI de passe"
choosePassword: "PI:PASSWORD:<PASSWORD>END_PI"
clickAgree: "En cliquant sur « S'enregistrer », vous acceptez nos"
configure: "Configurer"
createAccount: "Créer un compte"
currentPassword: "PI:PASSWORD:<PASSWORD>END_PI"
dontHaveAnAccount: "Vous n'avez pas de compte?"
email: "CourPI:NAME:<NAME>END_PI"
emailAddress: "Adresse courriel"
emailResetLink: "Envoyer un courriel de réinitialisation"
forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI?"
ifYouAlreadyHaveAnAccount: "Si vous avez déjà un compte"
newPassword: "PI:PASSWORD:<PASSWORD>END_PI"
newPasswordAgain: "PI:PASSWORD:<PASSWORD>END_PI de passe"
optional: "Facultatif"
OR: "OU"
password: "PI:PASSWORD:<PASSWORD>END_PI"
passwordAgain: "PI:PASSWORD:<PASSWORD>END_PI"
privacyPolicy: "Politique de confidentialité"
remove: "Supprimer"
resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI"
setPassword: "PI:PASSWORD:<PASSWORD>END_PI passe"
sign: "Inscrivez-vous"
signIn: "Ouvrir une session"
signin: "ouvrir une session"
signOut: "Quitter"
signUp: "Inscrivez-vous"
signupCode: "Code d'inscription"
signUpWithYourEmailAddress: "S'inscrire avec une adresse courriel"
terms: "Conditions d'utilisation"
updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI de passe"
username: "Nom d'utilisateur"
usernameOrEmail: "Nom d'utilisateur ou adresse courriel"
with: "avec"
"Verification email lost?": "Vous n'avez pas reçu de courriel de vérification?"
"Send again": "Envoyer à nouveau"
"Send the verification email again": "Renvoyer le courriel de vérification"
"Send email again": "Renvoyer le courriel"
"Minimum required length: 6": "Veuillez saisir au moins 6 caractères"
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nouveau courriel vous a été envoyé. Si vous ne le recevez pas sous peu, vérifiez votre dossier destiné aux courriels indésirables.",
"Required Field" : "Ce champ est obligatoire"
"Successful Registration! Please check your email and follow the instructions.": "Votre compte a été créé! Vous recevrez sous peu un courriel de confirmation et la marche à suivre pour valider votre inscription."
"A new email has been sent to you. If the email doesn't show up in your inbox, be sure to check your spam folder.": "Un nouvel e-mail vous a été envoyé. Si l'e-mail n'apparaît pas dans votre boîte de réception, vérifiez bien votre dossier spam."
"Already verified": "Déjà vérifié"
"At least 1 digit, 1 lowercase and 1 uppercase": "Au moins 1 chiffre, 1 minuscule et 1 majuscule"
"Invalid email": "Email invalide"
"Required Field": "Champs requis"
info:
emailSent: "Courriel envoyé"
emailVerified: "Adresse courriel verifiée"
passwordChanged: "PI:PASSWORD:<PASSWORD>END_PI"
passwordReset: "PI:PASSWORD:<PASSWORD>END_PI"
error:
emailRequired: "Une adresse courriel est requise."
minChar: "Votre mot de passe doit contenir au moins 7 caractères."
pwdsDontMatch: "Les mots de passe saisis ne correspondent pas"
pwOneDigit: "Votre mot de passe doit contenir au moins un chiffre."
pwOneLetter: "Votre mot de passe doit contenir au moins une lettre."
signInRequired: "Vous devez ouvrir une session pour continuer."
signupCodeIncorrect: "Le code d'inscription est incorrect."
signupCodeRequired: "Un code d'inscription est requis."
usernameIsEmail: "Le nom d'utilisateur ne peut être identique à l'adresse courriel."
usernameRequired: "Un nom d'utilisateur est requis."
accounts:
#---- accounts-base
#"@" + domain + " email requis":
#"A login handler should return a result or undefined": "Un gestionnaire d'authentification doit retourner un résultat ou la valeur 'undefined'"
"Email already exists.": "L'adresse courriel existe déjà."
"Email doesn't match the criteria.": "L'adresse courriel semble incorrectement formatée."
"Invalid login token": "Jeton d'authentification invalide"
"Login forbidden": "Votre identifiant ou votre mot de passe est incorrect"
#"Service " + options.service + " already configured": "Le service " + options.service + " est déjà configuré"
"Service unknown": "Service inconnu"
"Unrecognized options for login request": "Options inconnues pour la requête d'authentification"
"User validation failed": "Échec de la validation de l'utilisateur"
"Username already exists.": "Nom d'utilisateur déjà utilisé."
"You are not logged in.": "Vous n'êtes pas connecté."
"You've been logged out by the server. Please log in again.": "Vous avez été déconnecté par le serveur. Veuillez vous reconnecter."
"Your session has expired. Please log in again.": "Votre session a expiré. Veuillez vous reconnecter."
#---- accounts-oauth
"No matching login attempt found": "Aucune tentative d'authentification ne correspond"
#---- accounts-password-client
"Password is old. Please reset your password.": "Votre mot de passe est périmé. Veuillez le modifier."
#---- accounts-password
"Incorrect password": "Mot de passe incorrect"
"Invalid email": "Adresse courriel invalide"
"Must be logged in": "Vous devez être connecté"
"Need to set a username or email": "Vous devez préciser un nom d'utilisateur ou une adresse courriel"
"old password format": "Ancien format de mot de passe"
"Password may not be empty": "Le mot de passe ne peut être vide"
"Signups forbidden": "Vous ne pouvez pas créer de compte"
"Token expired": "Jeton expiré"
"Token has invalid email address": "Le jeton contient une adresse courriel invalide"
"User has no password set": "L'utilisateur n'a pas de mot de passe"
"User not found": "Utilisateur inconnu"
"Verify email link expired": "Lien de vérification de courriel expiré"
"Please verify your email first. Check the email and follow the link!": "Votre courriel n'a pas encore été vérifié. Veuillez cliquer le lien que nous vous avons envoyé."
"Verify email link is for unknown address": "Le lien de vérification de courriel réfère à une adresse inconnue"
#---- match
"Match failed": "La correspondance a échoué"
#---- Misc...
"Unknown error": "Erreur inconnue"
T9n?.map "fr_CA", fr_CA
module?.exports = fr_CA |
[
{
"context": "iv>\"\n $scope.activityData =\n displayKey: 'name'\n source: util.substringMatcher(DataAdapter.",
"end": 2365,
"score": 0.877029538154602,
"start": 2361,
"tag": "USERNAME",
"value": "name"
},
{
"context": "000)\n Log.warn conf\n\n\n class Auto\n\n na... | src/coffee/controllers/timerCtrl.coffee | Chanshi712/RedmineTimeTracker | 73 | timeTracker.controller 'TimerCtrl', ($scope, $timeout, Redmine, Project, Ticket, DataAdapter, Message, State, Resource, Option, Log, PluginManager, Const) ->
# comment charactor max
COMMENT_MAX = 255
# mode switching animation time [ms]
SWITCHING_TIME = 250
# check result
CHECK = OK: 0, CANCEL: 1, NG: -1
# time picker's base time
BASE_TIME = new Date("1970/01/01 00:00:00")
# represents 24 hours in minutes
H24 = 1440
# represents 1 minutes
ONE_MINUTE = 1
# Application state
$scope.state = State
# Application data
$scope.data = DataAdapter
# comment objects
$scope.comment = { text: "", maxLength: COMMENT_MAX, remain: COMMENT_MAX }
# ticked time
$scope.time = { min: 0 }
# time for time-picker
$scope.picker = { manualTime: BASE_TIME }
# Count down time for Pomodoro mode
$scope.countDownSec = 25 * 60 # sec
# typeahead options
$scope.typeaheadOptions = { highlight: true, minLength: 0 }
# jquery-timepicker options
$scope.timePickerOptions = null
# keyword which inputted on search form.
$scope.word = null
# mode state objects
auto = pomodoro = manual = null
# Application options
options = Option.getOptions()
###
Initialize.
###
init = () ->
initializeSearchform()
initializePicker(options.stepTime)
auto = new Auto()
pomodoro = new Pomodoro()
manual = new Manual()
$scope.mode = auto
$scope.word = DataAdapter.searchKeyword
Option.onChanged('stepTime', initializePicker)
###
Initialize search form.
###
initializeSearchform = () ->
$scope.ticketData =
displayKey: (ticket) -> ticket.id + " " + ticket.text
source: util.substringMatcher(DataAdapter.tasks, ['text', 'id', 'project.name'])
templates:
suggestion: (n) ->
if n.type is Const.TASK_TYPE.ISSUE
return "<div class='numbered-label'>
<span class='numbered-label__number'>#{n.id}</span>
<span class='numbered-label__label'>#{n.text}</span>
</div>"
else
return "<div class='numbered-label select-issues__project'>
<span class='numbered-label__number'>#{n.id}</span>
<span class='numbered-label__label'>#{n.text}</span>
</div>"
$scope.activityData =
displayKey: 'name'
source: util.substringMatcher(DataAdapter.activities, ['name', 'id'])
templates:
suggestion: (n) -> "<div class='list'><div class='list-item'>
<span class='list-item__name'>#{n.name}</span>
<span class='list-item__description list-item__id'>#{n.id}</span>
</div></div>"
###
Initialize time picker options.
###
initializePicker = (newStep) ->
if newStep is 60
minTime = '01:00'
else
minTime = '00:' + newStep
$scope.timePickerOptions =
step: newStep,
minTime: minTime
timeFormat: 'H:i',
show2400: true
###
change post mode.
if tracking, restore tracked time.
###
$scope.changeMode = (direction) ->
restoreSelected()
$scope.mode.onNextMode(direction)
$scope.mode.onChanged()
###
Workaround for restore selected state on switching view.
###
restoreSelected = () ->
return if not DataAdapter.searchKeyword.task
tmpTask = DataAdapter.searchKeyword.task
tmpActivity = DataAdapter.searchKeyword.activity
$timeout () ->
DataAdapter.searchKeyword.task = tmpTask
DataAdapter.searchKeyword.activity = tmpActivity
, SWITCHING_TIME / 2
###
Start or End Time tracking
###
$scope.clickSubmitButton = () ->
$scope.mode.onSubmitClick()
###
on timer stopped, send time entry.
###
$scope.$on 'timer-stopped', (e, time) ->
$scope.mode.onTimerStopped(time)
###
on timer ticked, update title.
###
$scope.$on 'timer-tick', (e, time) ->
if (not State.isAutoTracking) and (not State.isPomodoring)
return
$scope.time.min = Math.floor(time.millis / (60000))
###
send time entry.
###
postEntry = (minutes) ->
hours = Math.floor(minutes / 60 * 100) / 100 # 0.00
postParam = { hours: hours , comment: $scope.comment.text }
PluginManager.notify(PluginManager.events.SEND_TIME_ENTRY, postParam, DataAdapter.selectedTask, $scope.mode.name)
total = DataAdapter.selectedTask.total + postParam.hours
DataAdapter.selectedTask.total = Math.floor(total * 100) / 100
conf =
id: DataAdapter.selectedTask.id
hours: postParam.hours
comment: postParam.comment
activityId: DataAdapter.selectedActivity.id
type: DataAdapter.selectedTask.type
url = DataAdapter.selectedTask.url
account = DataAdapter.getAccount(url)
Redmine.get(account).submitTime(conf, submitSuccess, submitError(conf))
Message.toast Resource.string("msgSubmitTimeEntry", [DataAdapter.selectedTask.text, util.formatMinutes(minutes)])
###
check time entry before starting track.
###
preCheck = () ->
if not DataAdapter.selectedTask
Message.toast Resource.string("msgSelectTicket"), 2000
return CHECK.NG
if not DataAdapter.selectedActivity
Message.toast Resource.string("msgSelectActivity"), 2000
return CHECK.NG
return CHECK.OK
###
check time entry.
###
checkEntry = (min) ->
return if preCheck() isnt CHECK.OK
if $scope.comment.remain < 0
Message.toast Resource.string("msgCommentTooLong"), 2000
return CHECK.NG
if min < ONE_MINUTE
Message.toast Resource.string("msgShortTime"), 2000
return CHECK.CANCEL
return CHECK.OK
###
show success message.
###
submitSuccess = (msg, status) ->
if msg?.time_entry?.id?
PluginManager.notify(PluginManager.events.SENDED_TIME_ENTRY, msg.time_entry, status, DataAdapter.selectedTask, $scope.mode.name)
Message.toast Resource.string("msgSubmitTimeSuccess")
else
submitError(msg, status)
###
show failed message.
###
submitError = (conf) -> (msg, status) ->
PluginManager.notify(PluginManager.events.SENDED_TIME_ENTRY, msg, status, DataAdapter.selectedTask, $scope.mode.name)
Message.toast(Resource.string("msgSubmitTimeFail") + Resource.string("status", status), 3000)
Log.warn conf
class Auto
name: "auto"
trackedTime: {}
onChanged: () =>
if State.isAutoTracking
$timeout () => # wait for complete switching
$scope.$broadcast 'timer-start', new Date() - @trackedTime.millis
, SWITCHING_TIME
onNextMode: (direction) =>
if State.isAutoTracking
$scope.$broadcast 'timer-stop'
if direction > 0
$scope.mode = manual
else
$scope.mode = pomodoro
onSubmitClick: () =>
return if preCheck() isnt CHECK.OK
if State.isAutoTracking
State.isAutoTracking = false
State.title = Resource.string("extName")
checkResult = checkEntry($scope.time.min)
if checkResult is CHECK.CANCEL
$scope.$broadcast 'timer-clear'
else if checkResult is CHECK.OK
$scope.$broadcast 'timer-stop'
else
State.isAutoTracking = true
State.title = "Tracking..."
$scope.$broadcast 'timer-start'
onTimerStopped: (time) =>
if State.isAutoTracking # store temporary
@trackedTime = time
else
postEntry(time.days * 60 * 24 + time.hours * 60 + time.minutes)
class Pomodoro
name: "pomodoro"
trackedTime: {}
onChanged: () =>
if State.isPomodoring
$timeout () => # wait for complete switching
$scope.countDownSec = @trackedTime.millis / 1000
$scope.$broadcast 'timer-start', $scope.countDownSec
, SWITCHING_TIME
onNextMode: (direction) =>
if State.isPomodoring
$scope.$broadcast 'timer-stop'
if direction > 0
$scope.mode = auto
else
$scope.mode = manual
onSubmitClick: () =>
return if preCheck() isnt CHECK.OK
if State.isPomodoring
State.isPomodoring = false
State.title = Resource.string("extName")
checkResult = checkEntry(($scope.countDownSec / 60) - ($scope.time.min + 1))
if checkResult is CHECK.CANCEL
$scope.$broadcast 'timer-clear'
else if checkResult is CHECK.OK
$scope.$broadcast 'timer-stop'
else
State.isPomodoring = true
State.title = "Pomodoro..."
$scope.countDownSec = options.pomodoroTime * 60 # sec
$scope.$broadcast 'timer-start', $scope.countDownSec
onTimerStopped: (time) =>
if State.isPomodoring and (time.millis > 0) # store temporary
@trackedTime = time
else
State.isPomodoring = false
State.title = Resource.string("extName")
postEntry(Math.round(($scope.countDownSec / 60) - Math.round(time.millis / 1000 / 60)))
class Manual
name: "manual"
trackedTime: {}
onChanged: () =>
initializePicker(options.stepTime)
onNextMode: (direction) =>
if direction > 0
$scope.mode = pomodoro
else
$scope.mode = auto
onSubmitClick: () =>
diffMillis = $scope.picker.manualTime - BASE_TIME
min = (diffMillis / 1000 / 60)
if (min >= H24) and (min % H24 is 0) # max 24 hrs
min = H24
else
min = min % H24
checkResult = checkEntry(min)
return if checkResult isnt CHECK.OK
postEntry(min)
onTimerStopped: (time) =>
# nothing to do
###
Start Initialize.
###
init()
| 132418 | timeTracker.controller 'TimerCtrl', ($scope, $timeout, Redmine, Project, Ticket, DataAdapter, Message, State, Resource, Option, Log, PluginManager, Const) ->
# comment charactor max
COMMENT_MAX = 255
# mode switching animation time [ms]
SWITCHING_TIME = 250
# check result
CHECK = OK: 0, CANCEL: 1, NG: -1
# time picker's base time
BASE_TIME = new Date("1970/01/01 00:00:00")
# represents 24 hours in minutes
H24 = 1440
# represents 1 minutes
ONE_MINUTE = 1
# Application state
$scope.state = State
# Application data
$scope.data = DataAdapter
# comment objects
$scope.comment = { text: "", maxLength: COMMENT_MAX, remain: COMMENT_MAX }
# ticked time
$scope.time = { min: 0 }
# time for time-picker
$scope.picker = { manualTime: BASE_TIME }
# Count down time for Pomodoro mode
$scope.countDownSec = 25 * 60 # sec
# typeahead options
$scope.typeaheadOptions = { highlight: true, minLength: 0 }
# jquery-timepicker options
$scope.timePickerOptions = null
# keyword which inputted on search form.
$scope.word = null
# mode state objects
auto = pomodoro = manual = null
# Application options
options = Option.getOptions()
###
Initialize.
###
init = () ->
initializeSearchform()
initializePicker(options.stepTime)
auto = new Auto()
pomodoro = new Pomodoro()
manual = new Manual()
$scope.mode = auto
$scope.word = DataAdapter.searchKeyword
Option.onChanged('stepTime', initializePicker)
###
Initialize search form.
###
initializeSearchform = () ->
$scope.ticketData =
displayKey: (ticket) -> ticket.id + " " + ticket.text
source: util.substringMatcher(DataAdapter.tasks, ['text', 'id', 'project.name'])
templates:
suggestion: (n) ->
if n.type is Const.TASK_TYPE.ISSUE
return "<div class='numbered-label'>
<span class='numbered-label__number'>#{n.id}</span>
<span class='numbered-label__label'>#{n.text}</span>
</div>"
else
return "<div class='numbered-label select-issues__project'>
<span class='numbered-label__number'>#{n.id}</span>
<span class='numbered-label__label'>#{n.text}</span>
</div>"
$scope.activityData =
displayKey: 'name'
source: util.substringMatcher(DataAdapter.activities, ['name', 'id'])
templates:
suggestion: (n) -> "<div class='list'><div class='list-item'>
<span class='list-item__name'>#{n.name}</span>
<span class='list-item__description list-item__id'>#{n.id}</span>
</div></div>"
###
Initialize time picker options.
###
initializePicker = (newStep) ->
if newStep is 60
minTime = '01:00'
else
minTime = '00:' + newStep
$scope.timePickerOptions =
step: newStep,
minTime: minTime
timeFormat: 'H:i',
show2400: true
###
change post mode.
if tracking, restore tracked time.
###
$scope.changeMode = (direction) ->
restoreSelected()
$scope.mode.onNextMode(direction)
$scope.mode.onChanged()
###
Workaround for restore selected state on switching view.
###
restoreSelected = () ->
return if not DataAdapter.searchKeyword.task
tmpTask = DataAdapter.searchKeyword.task
tmpActivity = DataAdapter.searchKeyword.activity
$timeout () ->
DataAdapter.searchKeyword.task = tmpTask
DataAdapter.searchKeyword.activity = tmpActivity
, SWITCHING_TIME / 2
###
Start or End Time tracking
###
$scope.clickSubmitButton = () ->
$scope.mode.onSubmitClick()
###
on timer stopped, send time entry.
###
$scope.$on 'timer-stopped', (e, time) ->
$scope.mode.onTimerStopped(time)
###
on timer ticked, update title.
###
$scope.$on 'timer-tick', (e, time) ->
if (not State.isAutoTracking) and (not State.isPomodoring)
return
$scope.time.min = Math.floor(time.millis / (60000))
###
send time entry.
###
postEntry = (minutes) ->
hours = Math.floor(minutes / 60 * 100) / 100 # 0.00
postParam = { hours: hours , comment: $scope.comment.text }
PluginManager.notify(PluginManager.events.SEND_TIME_ENTRY, postParam, DataAdapter.selectedTask, $scope.mode.name)
total = DataAdapter.selectedTask.total + postParam.hours
DataAdapter.selectedTask.total = Math.floor(total * 100) / 100
conf =
id: DataAdapter.selectedTask.id
hours: postParam.hours
comment: postParam.comment
activityId: DataAdapter.selectedActivity.id
type: DataAdapter.selectedTask.type
url = DataAdapter.selectedTask.url
account = DataAdapter.getAccount(url)
Redmine.get(account).submitTime(conf, submitSuccess, submitError(conf))
Message.toast Resource.string("msgSubmitTimeEntry", [DataAdapter.selectedTask.text, util.formatMinutes(minutes)])
###
check time entry before starting track.
###
preCheck = () ->
if not DataAdapter.selectedTask
Message.toast Resource.string("msgSelectTicket"), 2000
return CHECK.NG
if not DataAdapter.selectedActivity
Message.toast Resource.string("msgSelectActivity"), 2000
return CHECK.NG
return CHECK.OK
###
check time entry.
###
checkEntry = (min) ->
return if preCheck() isnt CHECK.OK
if $scope.comment.remain < 0
Message.toast Resource.string("msgCommentTooLong"), 2000
return CHECK.NG
if min < ONE_MINUTE
Message.toast Resource.string("msgShortTime"), 2000
return CHECK.CANCEL
return CHECK.OK
###
show success message.
###
submitSuccess = (msg, status) ->
if msg?.time_entry?.id?
PluginManager.notify(PluginManager.events.SENDED_TIME_ENTRY, msg.time_entry, status, DataAdapter.selectedTask, $scope.mode.name)
Message.toast Resource.string("msgSubmitTimeSuccess")
else
submitError(msg, status)
###
show failed message.
###
submitError = (conf) -> (msg, status) ->
PluginManager.notify(PluginManager.events.SENDED_TIME_ENTRY, msg, status, DataAdapter.selectedTask, $scope.mode.name)
Message.toast(Resource.string("msgSubmitTimeFail") + Resource.string("status", status), 3000)
Log.warn conf
class Auto
name: "<NAME>"
trackedTime: {}
onChanged: () =>
if State.isAutoTracking
$timeout () => # wait for complete switching
$scope.$broadcast 'timer-start', new Date() - @trackedTime.millis
, SWITCHING_TIME
onNextMode: (direction) =>
if State.isAutoTracking
$scope.$broadcast 'timer-stop'
if direction > 0
$scope.mode = manual
else
$scope.mode = pomodoro
onSubmitClick: () =>
return if preCheck() isnt CHECK.OK
if State.isAutoTracking
State.isAutoTracking = false
State.title = Resource.string("extName")
checkResult = checkEntry($scope.time.min)
if checkResult is CHECK.CANCEL
$scope.$broadcast 'timer-clear'
else if checkResult is CHECK.OK
$scope.$broadcast 'timer-stop'
else
State.isAutoTracking = true
State.title = "Tracking..."
$scope.$broadcast 'timer-start'
onTimerStopped: (time) =>
if State.isAutoTracking # store temporary
@trackedTime = time
else
postEntry(time.days * 60 * 24 + time.hours * 60 + time.minutes)
class Pomodoro
name: "<NAME>"
trackedTime: {}
onChanged: () =>
if State.isPomodoring
$timeout () => # wait for complete switching
$scope.countDownSec = @trackedTime.millis / 1000
$scope.$broadcast 'timer-start', $scope.countDownSec
, SWITCHING_TIME
onNextMode: (direction) =>
if State.isPomodoring
$scope.$broadcast 'timer-stop'
if direction > 0
$scope.mode = auto
else
$scope.mode = manual
onSubmitClick: () =>
return if preCheck() isnt CHECK.OK
if State.isPomodoring
State.isPomodoring = false
State.title = Resource.string("extName")
checkResult = checkEntry(($scope.countDownSec / 60) - ($scope.time.min + 1))
if checkResult is CHECK.CANCEL
$scope.$broadcast 'timer-clear'
else if checkResult is CHECK.OK
$scope.$broadcast 'timer-stop'
else
State.isPomodoring = true
State.title = "Pomodoro..."
$scope.countDownSec = options.pomodoroTime * 60 # sec
$scope.$broadcast 'timer-start', $scope.countDownSec
onTimerStopped: (time) =>
if State.isPomodoring and (time.millis > 0) # store temporary
@trackedTime = time
else
State.isPomodoring = false
State.title = Resource.string("extName")
postEntry(Math.round(($scope.countDownSec / 60) - Math.round(time.millis / 1000 / 60)))
class Manual
name: "manual"
trackedTime: {}
onChanged: () =>
initializePicker(options.stepTime)
onNextMode: (direction) =>
if direction > 0
$scope.mode = pomodoro
else
$scope.mode = auto
onSubmitClick: () =>
diffMillis = $scope.picker.manualTime - BASE_TIME
min = (diffMillis / 1000 / 60)
if (min >= H24) and (min % H24 is 0) # max 24 hrs
min = H24
else
min = min % H24
checkResult = checkEntry(min)
return if checkResult isnt CHECK.OK
postEntry(min)
onTimerStopped: (time) =>
# nothing to do
###
Start Initialize.
###
init()
| true | timeTracker.controller 'TimerCtrl', ($scope, $timeout, Redmine, Project, Ticket, DataAdapter, Message, State, Resource, Option, Log, PluginManager, Const) ->
# comment charactor max
COMMENT_MAX = 255
# mode switching animation time [ms]
SWITCHING_TIME = 250
# check result
CHECK = OK: 0, CANCEL: 1, NG: -1
# time picker's base time
BASE_TIME = new Date("1970/01/01 00:00:00")
# represents 24 hours in minutes
H24 = 1440
# represents 1 minutes
ONE_MINUTE = 1
# Application state
$scope.state = State
# Application data
$scope.data = DataAdapter
# comment objects
$scope.comment = { text: "", maxLength: COMMENT_MAX, remain: COMMENT_MAX }
# ticked time
$scope.time = { min: 0 }
# time for time-picker
$scope.picker = { manualTime: BASE_TIME }
# Count down time for Pomodoro mode
$scope.countDownSec = 25 * 60 # sec
# typeahead options
$scope.typeaheadOptions = { highlight: true, minLength: 0 }
# jquery-timepicker options
$scope.timePickerOptions = null
# keyword which inputted on search form.
$scope.word = null
# mode state objects
auto = pomodoro = manual = null
# Application options
options = Option.getOptions()
###
Initialize.
###
init = () ->
initializeSearchform()
initializePicker(options.stepTime)
auto = new Auto()
pomodoro = new Pomodoro()
manual = new Manual()
$scope.mode = auto
$scope.word = DataAdapter.searchKeyword
Option.onChanged('stepTime', initializePicker)
###
Initialize search form.
###
initializeSearchform = () ->
$scope.ticketData =
displayKey: (ticket) -> ticket.id + " " + ticket.text
source: util.substringMatcher(DataAdapter.tasks, ['text', 'id', 'project.name'])
templates:
suggestion: (n) ->
if n.type is Const.TASK_TYPE.ISSUE
return "<div class='numbered-label'>
<span class='numbered-label__number'>#{n.id}</span>
<span class='numbered-label__label'>#{n.text}</span>
</div>"
else
return "<div class='numbered-label select-issues__project'>
<span class='numbered-label__number'>#{n.id}</span>
<span class='numbered-label__label'>#{n.text}</span>
</div>"
$scope.activityData =
displayKey: 'name'
source: util.substringMatcher(DataAdapter.activities, ['name', 'id'])
templates:
suggestion: (n) -> "<div class='list'><div class='list-item'>
<span class='list-item__name'>#{n.name}</span>
<span class='list-item__description list-item__id'>#{n.id}</span>
</div></div>"
###
Initialize time picker options.
###
initializePicker = (newStep) ->
if newStep is 60
minTime = '01:00'
else
minTime = '00:' + newStep
$scope.timePickerOptions =
step: newStep,
minTime: minTime
timeFormat: 'H:i',
show2400: true
###
change post mode.
if tracking, restore tracked time.
###
$scope.changeMode = (direction) ->
restoreSelected()
$scope.mode.onNextMode(direction)
$scope.mode.onChanged()
###
Workaround for restore selected state on switching view.
###
restoreSelected = () ->
return if not DataAdapter.searchKeyword.task
tmpTask = DataAdapter.searchKeyword.task
tmpActivity = DataAdapter.searchKeyword.activity
$timeout () ->
DataAdapter.searchKeyword.task = tmpTask
DataAdapter.searchKeyword.activity = tmpActivity
, SWITCHING_TIME / 2
###
Start or End Time tracking
###
$scope.clickSubmitButton = () ->
$scope.mode.onSubmitClick()
###
on timer stopped, send time entry.
###
$scope.$on 'timer-stopped', (e, time) ->
$scope.mode.onTimerStopped(time)
###
on timer ticked, update title.
###
$scope.$on 'timer-tick', (e, time) ->
if (not State.isAutoTracking) and (not State.isPomodoring)
return
$scope.time.min = Math.floor(time.millis / (60000))
###
send time entry.
###
postEntry = (minutes) ->
hours = Math.floor(minutes / 60 * 100) / 100 # 0.00
postParam = { hours: hours , comment: $scope.comment.text }
PluginManager.notify(PluginManager.events.SEND_TIME_ENTRY, postParam, DataAdapter.selectedTask, $scope.mode.name)
total = DataAdapter.selectedTask.total + postParam.hours
DataAdapter.selectedTask.total = Math.floor(total * 100) / 100
conf =
id: DataAdapter.selectedTask.id
hours: postParam.hours
comment: postParam.comment
activityId: DataAdapter.selectedActivity.id
type: DataAdapter.selectedTask.type
url = DataAdapter.selectedTask.url
account = DataAdapter.getAccount(url)
Redmine.get(account).submitTime(conf, submitSuccess, submitError(conf))
Message.toast Resource.string("msgSubmitTimeEntry", [DataAdapter.selectedTask.text, util.formatMinutes(minutes)])
###
check time entry before starting track.
###
preCheck = () ->
if not DataAdapter.selectedTask
Message.toast Resource.string("msgSelectTicket"), 2000
return CHECK.NG
if not DataAdapter.selectedActivity
Message.toast Resource.string("msgSelectActivity"), 2000
return CHECK.NG
return CHECK.OK
###
check time entry.
###
checkEntry = (min) ->
return if preCheck() isnt CHECK.OK
if $scope.comment.remain < 0
Message.toast Resource.string("msgCommentTooLong"), 2000
return CHECK.NG
if min < ONE_MINUTE
Message.toast Resource.string("msgShortTime"), 2000
return CHECK.CANCEL
return CHECK.OK
###
show success message.
###
submitSuccess = (msg, status) ->
if msg?.time_entry?.id?
PluginManager.notify(PluginManager.events.SENDED_TIME_ENTRY, msg.time_entry, status, DataAdapter.selectedTask, $scope.mode.name)
Message.toast Resource.string("msgSubmitTimeSuccess")
else
submitError(msg, status)
###
show failed message.
###
submitError = (conf) -> (msg, status) ->
PluginManager.notify(PluginManager.events.SENDED_TIME_ENTRY, msg, status, DataAdapter.selectedTask, $scope.mode.name)
Message.toast(Resource.string("msgSubmitTimeFail") + Resource.string("status", status), 3000)
Log.warn conf
class Auto
name: "PI:NAME:<NAME>END_PI"
trackedTime: {}
onChanged: () =>
if State.isAutoTracking
$timeout () => # wait for complete switching
$scope.$broadcast 'timer-start', new Date() - @trackedTime.millis
, SWITCHING_TIME
onNextMode: (direction) =>
if State.isAutoTracking
$scope.$broadcast 'timer-stop'
if direction > 0
$scope.mode = manual
else
$scope.mode = pomodoro
onSubmitClick: () =>
return if preCheck() isnt CHECK.OK
if State.isAutoTracking
State.isAutoTracking = false
State.title = Resource.string("extName")
checkResult = checkEntry($scope.time.min)
if checkResult is CHECK.CANCEL
$scope.$broadcast 'timer-clear'
else if checkResult is CHECK.OK
$scope.$broadcast 'timer-stop'
else
State.isAutoTracking = true
State.title = "Tracking..."
$scope.$broadcast 'timer-start'
onTimerStopped: (time) =>
if State.isAutoTracking # store temporary
@trackedTime = time
else
postEntry(time.days * 60 * 24 + time.hours * 60 + time.minutes)
class Pomodoro
name: "PI:NAME:<NAME>END_PI"
trackedTime: {}
onChanged: () =>
if State.isPomodoring
$timeout () => # wait for complete switching
$scope.countDownSec = @trackedTime.millis / 1000
$scope.$broadcast 'timer-start', $scope.countDownSec
, SWITCHING_TIME
onNextMode: (direction) =>
if State.isPomodoring
$scope.$broadcast 'timer-stop'
if direction > 0
$scope.mode = auto
else
$scope.mode = manual
onSubmitClick: () =>
return if preCheck() isnt CHECK.OK
if State.isPomodoring
State.isPomodoring = false
State.title = Resource.string("extName")
checkResult = checkEntry(($scope.countDownSec / 60) - ($scope.time.min + 1))
if checkResult is CHECK.CANCEL
$scope.$broadcast 'timer-clear'
else if checkResult is CHECK.OK
$scope.$broadcast 'timer-stop'
else
State.isPomodoring = true
State.title = "Pomodoro..."
$scope.countDownSec = options.pomodoroTime * 60 # sec
$scope.$broadcast 'timer-start', $scope.countDownSec
onTimerStopped: (time) =>
if State.isPomodoring and (time.millis > 0) # store temporary
@trackedTime = time
else
State.isPomodoring = false
State.title = Resource.string("extName")
postEntry(Math.round(($scope.countDownSec / 60) - Math.round(time.millis / 1000 / 60)))
class Manual
name: "manual"
trackedTime: {}
onChanged: () =>
initializePicker(options.stepTime)
onNextMode: (direction) =>
if direction > 0
$scope.mode = pomodoro
else
$scope.mode = auto
onSubmitClick: () =>
diffMillis = $scope.picker.manualTime - BASE_TIME
min = (diffMillis / 1000 / 60)
if (min >= H24) and (min % H24 is 0) # max 24 hrs
min = H24
else
min = min % H24
checkResult = checkEntry(min)
return if checkResult isnt CHECK.OK
postEntry(min)
onTimerStopped: (time) =>
# nothing to do
###
Start Initialize.
###
init()
|
[
{
"context": " }\n See\n %a{ href: 'https://github.com/helixbass/animate-backgrounds#for-animejs' }^ installation/",
"end": 2459,
"score": 0.9945560097694397,
"start": 2450,
"tag": "USERNAME",
"value": "helixbass"
},
{
"context": "_index is changed_args.length - 1\n ... | app/javascript/gradients/components/AnimationEditor.coffee | helixbass/mamagata | 0 | import {connect} from 'react-redux'
import {css as has} from 'glamor'
import {contains} from 'underscore.string'
import deep_equal from 'deep-equal'
import get_mixin_args from '../selectors/get_mixin_args'
import get_animation_state from '../selectors/get_animation_state'
import get_animation_steps from '../selectors/get_animation_steps'
import get_current_mixin from '../selectors/get_current_mixin'
import get_loop from '../selectors/get_loop'
import get_animation_js from '../selectors/get_animation_js'
import dashed_to_label from '../helpers/dashed_to_label'
import _int from '../helpers/_int'
import extended from '../helpers/extended'
import ArgField from './ArgField'
import {Segment, Button, Accordion, Tab, Form, Checkbox, Dropdown, Input, Icon, Message} from 'semantic-ui-react'
{TextArea, Field} = Form
{Group} = Button
import Collapse from 'react-css-collapse'
import {play_animation, pause_animation, reset_animation, add_animation_step, set_animation_step_shorthand, update_step_arg, delete_step_arg, delete_step, reorder_step, toggle_step_preview, update_step, toggle_animation_step, update_loop as _update_loop} from '../actions'
import find from 'lodash/find'
import fromPairs from 'lodash/fromPairs'
import defer from 'lodash/defer'
AnimationEditor = ({animation_state, play, pause, reset, add_step, animation, handle_seek}) ->
.animation-editor
%Tab{
panes: [
{
menuItem:
icon: 'edit'
content: 'Edit'
key: 'edit'
render: ->
%Tab.Pane
%Controls{ animation_state, play, pause, reset, animation, handle_seek }
%Steps{ add_step }
}
{
menuItem:
icon: 'share'
content: 'Export JS'
key: 'export'
render: ->
%Tab.Pane
%ExportJs
}
]
}
export default AnimationEditor = connect(
(state) ->
animation_state: get_animation_state state
(dispatch) ->
play: ->
dispatch do play_animation
pause: ->
dispatch do pause_animation
reset: ->
dispatch do reset_animation
add_step: ->
dispatch do add_animation_step
) AnimationEditor
ExportJs = ({animation_js}) ->
%div
%pre.(has
whiteSpace: 'pre-wrap'
)= animation_js
%Message.(has
maxWidth: 350
){
warning: yes
size: 'tiny'
}
See
%a{ href: 'https://github.com/helixbass/animate-backgrounds#for-animejs' }^ installation/usage instructions
for how to load the
hook-enabled version
of AnimeJS (<a href='http://npm.im/animejs-hooks'><code>animejs-hooks</code></a>)
and the <a href='http://npm.im/animate-backgrounds'><code>animate-backgrounds</code></a> hooks
ExportJs = connect(
(state) ->
animation_js: get_animation_js state
) ExportJs
Controls = ({animation_state, play, pause, reset, animation, handle_seek}) ->
%Segment{ vertical: yes }
%div
%Group
%ResetButton{ animation_state, reset }
%PlayButton{ animation_state, play, pause }
%Progress{ animation, onChange: handle_seek, disabled: 'disabled' is animation_state }
%LoopControl
LoopControl = ({update_loop, _loop}) ->
.(has marginLeft: 10, marginTop: 2)
%Checkbox{
label: 'Loop?'
onChange: ->
update_loop
loop: not _loop
count: 4
checked: !! _loop
}
= if _loop
{count} = _loop
%Input.(has
width: 40
marginLeft: 5
){
label:
basic: yes
content: 'x'
labelPosition: 'right'
value: count
onChange: ({target: {value: count}}) ->
update_loop {
loop: yes
count
}
}
LoopControl = connect(
(state) ->
_loop: get_loop state
(dispatch) ->
update_loop: ({loop: _loop, count}) ->
dispatch _update_loop(
loop:
if _loop
{count}
else off
)
) LoopControl
class Progress extends React.Component
constructor: (props) ->
super props
@state =
progress: 0
componentWillReceiveProps: ({animation}) ->
{progress = 0} = animation ? {}
@setState {progress} unless progress is @state.progress
animation?.update ?= ({progress}) =>
# # set_progress {progress}
defer => @setState {progress}
render: ->
{onChange, disabled} = @props
{progress} = @state
%input{
type: 'range'
value: progress ? 0
onChange, disabled
}
ResetButton = ({animation_state, reset}) ->
%Button{
icon: 'step backward'
disabled: 'disabled' is animation_state
onClick: reset
}
PlayButton = ({animation_state, play, pause}) ->
%Button{
style: marginRight: 5
icon:
switch animation_state
when 'playing' then 'pause'
else 'play'
disabled: 'disabled' is animation_state
active: 'playing' is animation_state
onClick:
switch animation_state
when 'playing' then pause
else play
}
Steps = ({add_step}) ->
%Segment.(has position: 'relative'){ vertical: yes }
%Button.(has
position: 'absolute'
top: 5
right: 1
zIndex: 10
){
icon: 'plus'
size: 'tiny'
content: 'Add step'
onClick: add_step
}
%AnimationSteps
running_class = has
backgroundColor: 'rgba(0, 255, 0, 0.3)'
AnimationSteps = ({steps, toggle_step}) ->
%Accordion.animation-steps{
exclusive: no
panels:
for step, step_index in steps
{active=yes, running=no} = step
{
title:
%span.(
has
transition: 'all .2s'
"#{running_class}": running
) Step {step_index + 1}
content:
%Collapse.(has
transition: 'height 150ms ease-out'
){ isOpen: active }
%AnimationStep{ step, step_index, steps }
active
key: "#{step_index}"
}
onTitleClick: (event, step_index) ->
toggle_step {step_index}
}
AnimationSteps = connect(
(state) ->
steps: get_animation_steps state
(dispatch) ->
toggle_step: ({step_index}) ->
dispatch toggle_animation_step {step_index}
) AnimationSteps
easing_options = [
'linear'
'easeInQuad'
'easeInCubic'
'easeInQuart'
'easeInQuint'
'easeInSine'
'easeInExpo'
'easeInCirc'
'easeInBack'
'easeInElastic'
'easeOutQuad'
'easeOutCubic'
'easeOutQuart'
'easeOutQuint'
'easeOutSine'
'easeOutExpo'
'easeOutCirc'
'easeOutBack'
'easeOutElastic'
'easeInOutQuad'
'easeInOutCubic'
'easeInOutQuart'
'easeInOutQuint'
'easeInOutSine'
'easeInOutExpo'
'easeInOutCirc'
'easeInOutBack'
'easeInOutElastic'
].map (easing) ->
key: easing
value: easing
text: easing
class AnimationStep extends React.Component
constructor: (props) ->
super props
@state =
sorting: no
toggle_sorting: =>
{sorting} = @state
@setState sorting: not sorting
handle_reorder: (event) =>
{handle_reorder} = @props
handle_reorder event
@setState sorting: no
render: ->
{step, step_index, set_duration, set_easing, set_elasticity, toggle_preview, handle_delete, steps, set_offset, set_offset_direction} = @props
{duration, easing, preview, elasticity, offset, offset_from} = step
{sorting} = @state
.animation-step
%Icon{
name: 'window close outline'
link: yes
fitted: yes
onClick: handle_delete
style: float: 'right'
}
= %Icon{
name: 'sort'
link: yes
fitted: yes
onClick: @toggle_sorting
style:
float: 'right'
marginRight: 7
} if steps.length > 1
%Checkbox.(has
fontSize: '.85rem !important'
){
label: 'Preview?'
onChange: toggle_preview
checked: preview
}
= %Sorting{ step_index, steps, @handle_reorder } if sorting
%StepForm{ set_duration, duration, set_easing, easing, easing_options, set_elasticity, elasticity, offset, offset_from, set_offset, set_offset_direction, step_index }
%Changes{ step, step_index }
AnimationStep = connect(
null
(dispatch, {step_index, step}) ->
set_offset: ({target: {value: offset}}) ->
dispatch update_step {
step_index
offset:
offset * if step.offset < 0 then -1 else 1
}
set_offset_direction: (event, {value: multiplier}) ->
dispatch update_step {
step_index
offset:
Math.abs(step.offset) * _int multiplier
}
set_duration: ({target: {value: duration}}) ->
dispatch update_step {step_index, duration}
set_easing: (event, {value: easing}) ->
dispatch update_step {step_index, easing}
set_elasticity: ({target: {value: elasticity}}) ->
dispatch update_step {step_index, elasticity}
toggle_preview: ->
dispatch toggle_step_preview {step_index}
handle_delete: ->
return unless window.confirm 'Delete step?'
dispatch delete_step {step_index}
handle_reorder: ({target: {value: before_step_index}}) ->
dispatch reorder_step {step_index, before_step_index}
) AnimationStep
class StepTabs extends React.Component
shouldComponentUpdate: (nextProps) ->
{step: {changed_args} = {}} = @props # TODO: this'll have to be updated once other tab has exported JS
# TODO: use deep equal helper?
return yes if nextProps.step?.changed_args?.length isnt changed_args?.length
return no unless changed_args
for changed_arg, index in changed_args
next_changed_arg = nextProps.step.changed_args[index]
return yes if changed_arg.name isnt next_changed_arg.name
return yes if changed_arg.value isnt next_changed_arg.value
no
render: ->
{step, step_index} = @props
%Tab{
panes: [
{
menuItem: 'Changes'
render: ->
%Tab.Pane
%Changes{ step, step_index }
}
{
menuItem: 'Shorthand'
render: ->
%Tab.Pane
%Shorthand{ step, step_index }
}
]
}
class StepForm extends React.Component
shouldComponentUpdate: (nextProps) ->
return yes for prop in ['duration', 'easing', 'elasticity', 'offset'] when @props[prop] isnt nextProps[prop]
no
render: ->
{set_duration, duration, set_easing, easing, easing_options, set_elasticity, elasticity, step_index, offset, offset_from, set_offset, set_offset_direction} = @props
%Form.step-form.(has
marginTop: '.5rem'
marginBottom: '.8rem'
){ size: 'tiny' }
%Duration{ duration, set_duration }
= %StartOffset{ offset, offset_from, set_offset, set_offset_direction } if step_index > 0
%Easing{ easing, set_easing, easing_options }
= %Elasticity{ elasticity, set_elasticity } if contains easing, 'Elastic'
Elasticity = ({elasticity, set_elasticity}) ->
%Field{ inline: yes }
%label Elasticity
%Input{
onChange: set_elasticity
value: elasticity
style: width: '70px'
}
Easing = ({easing, set_easing, easing_options}) ->
%Field{ inline: yes }
%label Easing
%Dropdown.tiny{
onChange: set_easing
value: easing
options: easing_options
scrolling: yes
upward: yes
}
class StartOffset extends React.Component
constructor: (props) ->
super props
@state =
editing: no
toggle_editing: =>
{editing} = @state
@setState editing: not editing
render: ->
{offset, offset_from, set_offset, set_offset_direction} = @props
{editing} = @state
%Field{ inline: yes }
%label Start
= if editing
%span
%Input{
onChange: set_offset
value: Math.abs offset
style: width: '55px'
}^
ms
%Dropdown.tiny.(has
margin: '0 3px'
){
value:
if offset < 0
-1
else
1
options: [
text: 'before'
value: -1
,
text: 'after'
value: 1
]
onChange: set_offset_direction
}^
%span
the previous step ends
else
%Dropdown.tiny{
onClick: @toggle_editing
text:
"#{
unless offset
'when'
else
"#{offset}ms #{
if offset > 0
'after'
else
'before'
}"
} the previous step #{
if offset_from is 'prev_end'
'ends'
else
'starts'
}"
}
Duration = ({duration, set_duration}) ->
%Field{ inline: yes }
%label Duration
%Input{
label:
basic: yes
content: 'ms'
labelPosition: 'right'
onChange: set_duration
value: duration
style: width: '70px'
}
Sorting = ({step_index, steps, handle_reorder}) ->
%select{
value: ''
onChange: handle_reorder
}
%option{ value: '' } Move to:
= for step, _step_index in steps when _step_index isnt step_index and _step_index isnt step_index + 1
%option{ value: _step_index, key: _step_index }
Before Step {_step_index + 1}
= unless step_index is steps.length - 1
%option{ value: 'last' } Last
class Changes extends React.Component
# handle_select_param: ({target: {value}}) =>
handle_select_param: (event, {value}) =>
{add_animated_param} = @props
add_animated_param name: value
shouldComponentUpdate: (nextProps) ->
return yes unless @props.step_index is nextProps.step_index
return yes unless deep_equal @props.start_args, nextProps.start_args
return yes unless deep_equal @props.step?.changed_args, nextProps.step?.changed_args
no
render: ->
{step, step_index, start_args} = @props
%Form{ size: 'tiny' }
%Field
%Dropdown.icon.tiny{
button: yes
labeled: yes
scrolling: yes
upward: yes
icon: 'plus'
text: 'Add animated param'
options: [
(for {name, value, type} in start_args when type isnt 'boolean'
text: dashed_to_label name
value: name
)...
text: 'Background position'
value: 'background_position'
]
onChange: @handle_select_param
value: ''
}
%ChangedArgs{ step, step_index }
Changes = connect(
(state) ->
start_args: do ->
args = get_mixin_args state
{params} = get_current_mixin state
args.map (arg) ->
{name} = arg
extended arg,
type:
find(
params
{name}
).type
(dispatch, {step_index}) ->
add_animated_param: ({name}) ->
dispatch update_step_arg {step_index, name}
) Changes
class ChangedArgs extends React.Component
constructor: (props) ->
super props
@state =
auto_open_last: no
componentWillReceiveProps: ({step: {changed_args}}) ->
auto_open_last = changed_args.length > @props.step.changed_args.length
@setState {auto_open_last} if @state.auto_open_last isnt auto_open_last
render: ->
{step: {changed_args}, step_index} = @props
{auto_open_last} = @state
.changed_args
= %ChangedArg{
arg, step_index
auto_open: auto_open_last and arg_index is changed_args.length - 1
key: arg.name
} for arg, arg_index in changed_args
ChangedArg = connect(
(state, {arg: {name}}) ->
param:
find(
get_current_mixin(state).params
{name}
)
(dispatch, {step_index, arg: {name}}) ->
onChange: (value) ->
dispatch update_step_arg {step_index, name, value}
onDelete: ->
# return unless window.confirm 'Remove ?'
dispatch delete_step_arg {step_index, name}
) ArgField
Shorthand = ({step, step_index, set_shorthand}) ->
%Form
%TextArea{
rows: 8
onChange: ({target: {value}}) ->
set_shorthand value
}
Shorthand = connect(
null
(dispatch, {step_index}) ->
set_shorthand: (shorthand) ->
dispatch set_animation_step_shorthand {
shorthand, step_index
}
) Shorthand
| 172816 | import {connect} from 'react-redux'
import {css as has} from 'glamor'
import {contains} from 'underscore.string'
import deep_equal from 'deep-equal'
import get_mixin_args from '../selectors/get_mixin_args'
import get_animation_state from '../selectors/get_animation_state'
import get_animation_steps from '../selectors/get_animation_steps'
import get_current_mixin from '../selectors/get_current_mixin'
import get_loop from '../selectors/get_loop'
import get_animation_js from '../selectors/get_animation_js'
import dashed_to_label from '../helpers/dashed_to_label'
import _int from '../helpers/_int'
import extended from '../helpers/extended'
import ArgField from './ArgField'
import {Segment, Button, Accordion, Tab, Form, Checkbox, Dropdown, Input, Icon, Message} from 'semantic-ui-react'
{TextArea, Field} = Form
{Group} = Button
import Collapse from 'react-css-collapse'
import {play_animation, pause_animation, reset_animation, add_animation_step, set_animation_step_shorthand, update_step_arg, delete_step_arg, delete_step, reorder_step, toggle_step_preview, update_step, toggle_animation_step, update_loop as _update_loop} from '../actions'
import find from 'lodash/find'
import fromPairs from 'lodash/fromPairs'
import defer from 'lodash/defer'
AnimationEditor = ({animation_state, play, pause, reset, add_step, animation, handle_seek}) ->
.animation-editor
%Tab{
panes: [
{
menuItem:
icon: 'edit'
content: 'Edit'
key: 'edit'
render: ->
%Tab.Pane
%Controls{ animation_state, play, pause, reset, animation, handle_seek }
%Steps{ add_step }
}
{
menuItem:
icon: 'share'
content: 'Export JS'
key: 'export'
render: ->
%Tab.Pane
%ExportJs
}
]
}
export default AnimationEditor = connect(
(state) ->
animation_state: get_animation_state state
(dispatch) ->
play: ->
dispatch do play_animation
pause: ->
dispatch do pause_animation
reset: ->
dispatch do reset_animation
add_step: ->
dispatch do add_animation_step
) AnimationEditor
ExportJs = ({animation_js}) ->
%div
%pre.(has
whiteSpace: 'pre-wrap'
)= animation_js
%Message.(has
maxWidth: 350
){
warning: yes
size: 'tiny'
}
See
%a{ href: 'https://github.com/helixbass/animate-backgrounds#for-animejs' }^ installation/usage instructions
for how to load the
hook-enabled version
of AnimeJS (<a href='http://npm.im/animejs-hooks'><code>animejs-hooks</code></a>)
and the <a href='http://npm.im/animate-backgrounds'><code>animate-backgrounds</code></a> hooks
ExportJs = connect(
(state) ->
animation_js: get_animation_js state
) ExportJs
Controls = ({animation_state, play, pause, reset, animation, handle_seek}) ->
%Segment{ vertical: yes }
%div
%Group
%ResetButton{ animation_state, reset }
%PlayButton{ animation_state, play, pause }
%Progress{ animation, onChange: handle_seek, disabled: 'disabled' is animation_state }
%LoopControl
LoopControl = ({update_loop, _loop}) ->
.(has marginLeft: 10, marginTop: 2)
%Checkbox{
label: 'Loop?'
onChange: ->
update_loop
loop: not _loop
count: 4
checked: !! _loop
}
= if _loop
{count} = _loop
%Input.(has
width: 40
marginLeft: 5
){
label:
basic: yes
content: 'x'
labelPosition: 'right'
value: count
onChange: ({target: {value: count}}) ->
update_loop {
loop: yes
count
}
}
LoopControl = connect(
(state) ->
_loop: get_loop state
(dispatch) ->
update_loop: ({loop: _loop, count}) ->
dispatch _update_loop(
loop:
if _loop
{count}
else off
)
) LoopControl
class Progress extends React.Component
constructor: (props) ->
super props
@state =
progress: 0
componentWillReceiveProps: ({animation}) ->
{progress = 0} = animation ? {}
@setState {progress} unless progress is @state.progress
animation?.update ?= ({progress}) =>
# # set_progress {progress}
defer => @setState {progress}
render: ->
{onChange, disabled} = @props
{progress} = @state
%input{
type: 'range'
value: progress ? 0
onChange, disabled
}
ResetButton = ({animation_state, reset}) ->
%Button{
icon: 'step backward'
disabled: 'disabled' is animation_state
onClick: reset
}
PlayButton = ({animation_state, play, pause}) ->
%Button{
style: marginRight: 5
icon:
switch animation_state
when 'playing' then 'pause'
else 'play'
disabled: 'disabled' is animation_state
active: 'playing' is animation_state
onClick:
switch animation_state
when 'playing' then pause
else play
}
Steps = ({add_step}) ->
%Segment.(has position: 'relative'){ vertical: yes }
%Button.(has
position: 'absolute'
top: 5
right: 1
zIndex: 10
){
icon: 'plus'
size: 'tiny'
content: 'Add step'
onClick: add_step
}
%AnimationSteps
running_class = has
backgroundColor: 'rgba(0, 255, 0, 0.3)'
AnimationSteps = ({steps, toggle_step}) ->
%Accordion.animation-steps{
exclusive: no
panels:
for step, step_index in steps
{active=yes, running=no} = step
{
title:
%span.(
has
transition: 'all .2s'
"#{running_class}": running
) Step {step_index + 1}
content:
%Collapse.(has
transition: 'height 150ms ease-out'
){ isOpen: active }
%AnimationStep{ step, step_index, steps }
active
key: "#{step_index}"
}
onTitleClick: (event, step_index) ->
toggle_step {step_index}
}
AnimationSteps = connect(
(state) ->
steps: get_animation_steps state
(dispatch) ->
toggle_step: ({step_index}) ->
dispatch toggle_animation_step {step_index}
) AnimationSteps
easing_options = [
'linear'
'easeInQuad'
'easeInCubic'
'easeInQuart'
'easeInQuint'
'easeInSine'
'easeInExpo'
'easeInCirc'
'easeInBack'
'easeInElastic'
'easeOutQuad'
'easeOutCubic'
'easeOutQuart'
'easeOutQuint'
'easeOutSine'
'easeOutExpo'
'easeOutCirc'
'easeOutBack'
'easeOutElastic'
'easeInOutQuad'
'easeInOutCubic'
'easeInOutQuart'
'easeInOutQuint'
'easeInOutSine'
'easeInOutExpo'
'easeInOutCirc'
'easeInOutBack'
'easeInOutElastic'
].map (easing) ->
key: easing
value: easing
text: easing
class AnimationStep extends React.Component
constructor: (props) ->
super props
@state =
sorting: no
toggle_sorting: =>
{sorting} = @state
@setState sorting: not sorting
handle_reorder: (event) =>
{handle_reorder} = @props
handle_reorder event
@setState sorting: no
render: ->
{step, step_index, set_duration, set_easing, set_elasticity, toggle_preview, handle_delete, steps, set_offset, set_offset_direction} = @props
{duration, easing, preview, elasticity, offset, offset_from} = step
{sorting} = @state
.animation-step
%Icon{
name: 'window close outline'
link: yes
fitted: yes
onClick: handle_delete
style: float: 'right'
}
= %Icon{
name: 'sort'
link: yes
fitted: yes
onClick: @toggle_sorting
style:
float: 'right'
marginRight: 7
} if steps.length > 1
%Checkbox.(has
fontSize: '.85rem !important'
){
label: 'Preview?'
onChange: toggle_preview
checked: preview
}
= %Sorting{ step_index, steps, @handle_reorder } if sorting
%StepForm{ set_duration, duration, set_easing, easing, easing_options, set_elasticity, elasticity, offset, offset_from, set_offset, set_offset_direction, step_index }
%Changes{ step, step_index }
AnimationStep = connect(
null
(dispatch, {step_index, step}) ->
set_offset: ({target: {value: offset}}) ->
dispatch update_step {
step_index
offset:
offset * if step.offset < 0 then -1 else 1
}
set_offset_direction: (event, {value: multiplier}) ->
dispatch update_step {
step_index
offset:
Math.abs(step.offset) * _int multiplier
}
set_duration: ({target: {value: duration}}) ->
dispatch update_step {step_index, duration}
set_easing: (event, {value: easing}) ->
dispatch update_step {step_index, easing}
set_elasticity: ({target: {value: elasticity}}) ->
dispatch update_step {step_index, elasticity}
toggle_preview: ->
dispatch toggle_step_preview {step_index}
handle_delete: ->
return unless window.confirm 'Delete step?'
dispatch delete_step {step_index}
handle_reorder: ({target: {value: before_step_index}}) ->
dispatch reorder_step {step_index, before_step_index}
) AnimationStep
class StepTabs extends React.Component
shouldComponentUpdate: (nextProps) ->
{step: {changed_args} = {}} = @props # TODO: this'll have to be updated once other tab has exported JS
# TODO: use deep equal helper?
return yes if nextProps.step?.changed_args?.length isnt changed_args?.length
return no unless changed_args
for changed_arg, index in changed_args
next_changed_arg = nextProps.step.changed_args[index]
return yes if changed_arg.name isnt next_changed_arg.name
return yes if changed_arg.value isnt next_changed_arg.value
no
render: ->
{step, step_index} = @props
%Tab{
panes: [
{
menuItem: 'Changes'
render: ->
%Tab.Pane
%Changes{ step, step_index }
}
{
menuItem: 'Shorthand'
render: ->
%Tab.Pane
%Shorthand{ step, step_index }
}
]
}
class StepForm extends React.Component
shouldComponentUpdate: (nextProps) ->
return yes for prop in ['duration', 'easing', 'elasticity', 'offset'] when @props[prop] isnt nextProps[prop]
no
render: ->
{set_duration, duration, set_easing, easing, easing_options, set_elasticity, elasticity, step_index, offset, offset_from, set_offset, set_offset_direction} = @props
%Form.step-form.(has
marginTop: '.5rem'
marginBottom: '.8rem'
){ size: 'tiny' }
%Duration{ duration, set_duration }
= %StartOffset{ offset, offset_from, set_offset, set_offset_direction } if step_index > 0
%Easing{ easing, set_easing, easing_options }
= %Elasticity{ elasticity, set_elasticity } if contains easing, 'Elastic'
Elasticity = ({elasticity, set_elasticity}) ->
%Field{ inline: yes }
%label Elasticity
%Input{
onChange: set_elasticity
value: elasticity
style: width: '70px'
}
Easing = ({easing, set_easing, easing_options}) ->
%Field{ inline: yes }
%label Easing
%Dropdown.tiny{
onChange: set_easing
value: easing
options: easing_options
scrolling: yes
upward: yes
}
class StartOffset extends React.Component
constructor: (props) ->
super props
@state =
editing: no
toggle_editing: =>
{editing} = @state
@setState editing: not editing
render: ->
{offset, offset_from, set_offset, set_offset_direction} = @props
{editing} = @state
%Field{ inline: yes }
%label Start
= if editing
%span
%Input{
onChange: set_offset
value: Math.abs offset
style: width: '55px'
}^
ms
%Dropdown.tiny.(has
margin: '0 3px'
){
value:
if offset < 0
-1
else
1
options: [
text: 'before'
value: -1
,
text: 'after'
value: 1
]
onChange: set_offset_direction
}^
%span
the previous step ends
else
%Dropdown.tiny{
onClick: @toggle_editing
text:
"#{
unless offset
'when'
else
"#{offset}ms #{
if offset > 0
'after'
else
'before'
}"
} the previous step #{
if offset_from is 'prev_end'
'ends'
else
'starts'
}"
}
Duration = ({duration, set_duration}) ->
%Field{ inline: yes }
%label Duration
%Input{
label:
basic: yes
content: 'ms'
labelPosition: 'right'
onChange: set_duration
value: duration
style: width: '70px'
}
Sorting = ({step_index, steps, handle_reorder}) ->
%select{
value: ''
onChange: handle_reorder
}
%option{ value: '' } Move to:
= for step, _step_index in steps when _step_index isnt step_index and _step_index isnt step_index + 1
%option{ value: _step_index, key: _step_index }
Before Step {_step_index + 1}
= unless step_index is steps.length - 1
%option{ value: 'last' } Last
class Changes extends React.Component
# handle_select_param: ({target: {value}}) =>
handle_select_param: (event, {value}) =>
{add_animated_param} = @props
add_animated_param name: value
shouldComponentUpdate: (nextProps) ->
return yes unless @props.step_index is nextProps.step_index
return yes unless deep_equal @props.start_args, nextProps.start_args
return yes unless deep_equal @props.step?.changed_args, nextProps.step?.changed_args
no
render: ->
{step, step_index, start_args} = @props
%Form{ size: 'tiny' }
%Field
%Dropdown.icon.tiny{
button: yes
labeled: yes
scrolling: yes
upward: yes
icon: 'plus'
text: 'Add animated param'
options: [
(for {name, value, type} in start_args when type isnt 'boolean'
text: dashed_to_label name
value: name
)...
text: 'Background position'
value: 'background_position'
]
onChange: @handle_select_param
value: ''
}
%ChangedArgs{ step, step_index }
Changes = connect(
(state) ->
start_args: do ->
args = get_mixin_args state
{params} = get_current_mixin state
args.map (arg) ->
{name} = arg
extended arg,
type:
find(
params
{name}
).type
(dispatch, {step_index}) ->
add_animated_param: ({name}) ->
dispatch update_step_arg {step_index, name}
) Changes
class ChangedArgs extends React.Component
constructor: (props) ->
super props
@state =
auto_open_last: no
componentWillReceiveProps: ({step: {changed_args}}) ->
auto_open_last = changed_args.length > @props.step.changed_args.length
@setState {auto_open_last} if @state.auto_open_last isnt auto_open_last
render: ->
{step: {changed_args}, step_index} = @props
{auto_open_last} = @state
.changed_args
= %ChangedArg{
arg, step_index
auto_open: auto_open_last and arg_index is changed_args.length - 1
key: arg.<KEY>
} for arg, arg_index in changed_args
ChangedArg = connect(
(state, {arg: {name}}) ->
param:
find(
get_current_mixin(state).params
{name}
)
(dispatch, {step_index, arg: {name}}) ->
onChange: (value) ->
dispatch update_step_arg {step_index, name, value}
onDelete: ->
# return unless window.confirm 'Remove ?'
dispatch delete_step_arg {step_index, name}
) ArgField
Shorthand = ({step, step_index, set_shorthand}) ->
%Form
%TextArea{
rows: 8
onChange: ({target: {value}}) ->
set_shorthand value
}
Shorthand = connect(
null
(dispatch, {step_index}) ->
set_shorthand: (shorthand) ->
dispatch set_animation_step_shorthand {
shorthand, step_index
}
) Shorthand
| true | import {connect} from 'react-redux'
import {css as has} from 'glamor'
import {contains} from 'underscore.string'
import deep_equal from 'deep-equal'
import get_mixin_args from '../selectors/get_mixin_args'
import get_animation_state from '../selectors/get_animation_state'
import get_animation_steps from '../selectors/get_animation_steps'
import get_current_mixin from '../selectors/get_current_mixin'
import get_loop from '../selectors/get_loop'
import get_animation_js from '../selectors/get_animation_js'
import dashed_to_label from '../helpers/dashed_to_label'
import _int from '../helpers/_int'
import extended from '../helpers/extended'
import ArgField from './ArgField'
import {Segment, Button, Accordion, Tab, Form, Checkbox, Dropdown, Input, Icon, Message} from 'semantic-ui-react'
{TextArea, Field} = Form
{Group} = Button
import Collapse from 'react-css-collapse'
import {play_animation, pause_animation, reset_animation, add_animation_step, set_animation_step_shorthand, update_step_arg, delete_step_arg, delete_step, reorder_step, toggle_step_preview, update_step, toggle_animation_step, update_loop as _update_loop} from '../actions'
import find from 'lodash/find'
import fromPairs from 'lodash/fromPairs'
import defer from 'lodash/defer'
AnimationEditor = ({animation_state, play, pause, reset, add_step, animation, handle_seek}) ->
.animation-editor
%Tab{
panes: [
{
menuItem:
icon: 'edit'
content: 'Edit'
key: 'edit'
render: ->
%Tab.Pane
%Controls{ animation_state, play, pause, reset, animation, handle_seek }
%Steps{ add_step }
}
{
menuItem:
icon: 'share'
content: 'Export JS'
key: 'export'
render: ->
%Tab.Pane
%ExportJs
}
]
}
export default AnimationEditor = connect(
(state) ->
animation_state: get_animation_state state
(dispatch) ->
play: ->
dispatch do play_animation
pause: ->
dispatch do pause_animation
reset: ->
dispatch do reset_animation
add_step: ->
dispatch do add_animation_step
) AnimationEditor
ExportJs = ({animation_js}) ->
%div
%pre.(has
whiteSpace: 'pre-wrap'
)= animation_js
%Message.(has
maxWidth: 350
){
warning: yes
size: 'tiny'
}
See
%a{ href: 'https://github.com/helixbass/animate-backgrounds#for-animejs' }^ installation/usage instructions
for how to load the
hook-enabled version
of AnimeJS (<a href='http://npm.im/animejs-hooks'><code>animejs-hooks</code></a>)
and the <a href='http://npm.im/animate-backgrounds'><code>animate-backgrounds</code></a> hooks
ExportJs = connect(
(state) ->
animation_js: get_animation_js state
) ExportJs
Controls = ({animation_state, play, pause, reset, animation, handle_seek}) ->
%Segment{ vertical: yes }
%div
%Group
%ResetButton{ animation_state, reset }
%PlayButton{ animation_state, play, pause }
%Progress{ animation, onChange: handle_seek, disabled: 'disabled' is animation_state }
%LoopControl
LoopControl = ({update_loop, _loop}) ->
.(has marginLeft: 10, marginTop: 2)
%Checkbox{
label: 'Loop?'
onChange: ->
update_loop
loop: not _loop
count: 4
checked: !! _loop
}
= if _loop
{count} = _loop
%Input.(has
width: 40
marginLeft: 5
){
label:
basic: yes
content: 'x'
labelPosition: 'right'
value: count
onChange: ({target: {value: count}}) ->
update_loop {
loop: yes
count
}
}
LoopControl = connect(
(state) ->
_loop: get_loop state
(dispatch) ->
update_loop: ({loop: _loop, count}) ->
dispatch _update_loop(
loop:
if _loop
{count}
else off
)
) LoopControl
class Progress extends React.Component
constructor: (props) ->
super props
@state =
progress: 0
componentWillReceiveProps: ({animation}) ->
{progress = 0} = animation ? {}
@setState {progress} unless progress is @state.progress
animation?.update ?= ({progress}) =>
# # set_progress {progress}
defer => @setState {progress}
render: ->
{onChange, disabled} = @props
{progress} = @state
%input{
type: 'range'
value: progress ? 0
onChange, disabled
}
ResetButton = ({animation_state, reset}) ->
%Button{
icon: 'step backward'
disabled: 'disabled' is animation_state
onClick: reset
}
PlayButton = ({animation_state, play, pause}) ->
%Button{
style: marginRight: 5
icon:
switch animation_state
when 'playing' then 'pause'
else 'play'
disabled: 'disabled' is animation_state
active: 'playing' is animation_state
onClick:
switch animation_state
when 'playing' then pause
else play
}
Steps = ({add_step}) ->
%Segment.(has position: 'relative'){ vertical: yes }
%Button.(has
position: 'absolute'
top: 5
right: 1
zIndex: 10
){
icon: 'plus'
size: 'tiny'
content: 'Add step'
onClick: add_step
}
%AnimationSteps
running_class = has
backgroundColor: 'rgba(0, 255, 0, 0.3)'
AnimationSteps = ({steps, toggle_step}) ->
%Accordion.animation-steps{
exclusive: no
panels:
for step, step_index in steps
{active=yes, running=no} = step
{
title:
%span.(
has
transition: 'all .2s'
"#{running_class}": running
) Step {step_index + 1}
content:
%Collapse.(has
transition: 'height 150ms ease-out'
){ isOpen: active }
%AnimationStep{ step, step_index, steps }
active
key: "#{step_index}"
}
onTitleClick: (event, step_index) ->
toggle_step {step_index}
}
AnimationSteps = connect(
(state) ->
steps: get_animation_steps state
(dispatch) ->
toggle_step: ({step_index}) ->
dispatch toggle_animation_step {step_index}
) AnimationSteps
easing_options = [
'linear'
'easeInQuad'
'easeInCubic'
'easeInQuart'
'easeInQuint'
'easeInSine'
'easeInExpo'
'easeInCirc'
'easeInBack'
'easeInElastic'
'easeOutQuad'
'easeOutCubic'
'easeOutQuart'
'easeOutQuint'
'easeOutSine'
'easeOutExpo'
'easeOutCirc'
'easeOutBack'
'easeOutElastic'
'easeInOutQuad'
'easeInOutCubic'
'easeInOutQuart'
'easeInOutQuint'
'easeInOutSine'
'easeInOutExpo'
'easeInOutCirc'
'easeInOutBack'
'easeInOutElastic'
].map (easing) ->
key: easing
value: easing
text: easing
class AnimationStep extends React.Component
constructor: (props) ->
super props
@state =
sorting: no
toggle_sorting: =>
{sorting} = @state
@setState sorting: not sorting
handle_reorder: (event) =>
{handle_reorder} = @props
handle_reorder event
@setState sorting: no
render: ->
{step, step_index, set_duration, set_easing, set_elasticity, toggle_preview, handle_delete, steps, set_offset, set_offset_direction} = @props
{duration, easing, preview, elasticity, offset, offset_from} = step
{sorting} = @state
.animation-step
%Icon{
name: 'window close outline'
link: yes
fitted: yes
onClick: handle_delete
style: float: 'right'
}
= %Icon{
name: 'sort'
link: yes
fitted: yes
onClick: @toggle_sorting
style:
float: 'right'
marginRight: 7
} if steps.length > 1
%Checkbox.(has
fontSize: '.85rem !important'
){
label: 'Preview?'
onChange: toggle_preview
checked: preview
}
= %Sorting{ step_index, steps, @handle_reorder } if sorting
%StepForm{ set_duration, duration, set_easing, easing, easing_options, set_elasticity, elasticity, offset, offset_from, set_offset, set_offset_direction, step_index }
%Changes{ step, step_index }
AnimationStep = connect(
null
(dispatch, {step_index, step}) ->
set_offset: ({target: {value: offset}}) ->
dispatch update_step {
step_index
offset:
offset * if step.offset < 0 then -1 else 1
}
set_offset_direction: (event, {value: multiplier}) ->
dispatch update_step {
step_index
offset:
Math.abs(step.offset) * _int multiplier
}
set_duration: ({target: {value: duration}}) ->
dispatch update_step {step_index, duration}
set_easing: (event, {value: easing}) ->
dispatch update_step {step_index, easing}
set_elasticity: ({target: {value: elasticity}}) ->
dispatch update_step {step_index, elasticity}
toggle_preview: ->
dispatch toggle_step_preview {step_index}
handle_delete: ->
return unless window.confirm 'Delete step?'
dispatch delete_step {step_index}
handle_reorder: ({target: {value: before_step_index}}) ->
dispatch reorder_step {step_index, before_step_index}
) AnimationStep
class StepTabs extends React.Component
shouldComponentUpdate: (nextProps) ->
{step: {changed_args} = {}} = @props # TODO: this'll have to be updated once other tab has exported JS
# TODO: use deep equal helper?
return yes if nextProps.step?.changed_args?.length isnt changed_args?.length
return no unless changed_args
for changed_arg, index in changed_args
next_changed_arg = nextProps.step.changed_args[index]
return yes if changed_arg.name isnt next_changed_arg.name
return yes if changed_arg.value isnt next_changed_arg.value
no
render: ->
{step, step_index} = @props
%Tab{
panes: [
{
menuItem: 'Changes'
render: ->
%Tab.Pane
%Changes{ step, step_index }
}
{
menuItem: 'Shorthand'
render: ->
%Tab.Pane
%Shorthand{ step, step_index }
}
]
}
class StepForm extends React.Component
shouldComponentUpdate: (nextProps) ->
return yes for prop in ['duration', 'easing', 'elasticity', 'offset'] when @props[prop] isnt nextProps[prop]
no
render: ->
{set_duration, duration, set_easing, easing, easing_options, set_elasticity, elasticity, step_index, offset, offset_from, set_offset, set_offset_direction} = @props
%Form.step-form.(has
marginTop: '.5rem'
marginBottom: '.8rem'
){ size: 'tiny' }
%Duration{ duration, set_duration }
= %StartOffset{ offset, offset_from, set_offset, set_offset_direction } if step_index > 0
%Easing{ easing, set_easing, easing_options }
= %Elasticity{ elasticity, set_elasticity } if contains easing, 'Elastic'
Elasticity = ({elasticity, set_elasticity}) ->
%Field{ inline: yes }
%label Elasticity
%Input{
onChange: set_elasticity
value: elasticity
style: width: '70px'
}
Easing = ({easing, set_easing, easing_options}) ->
%Field{ inline: yes }
%label Easing
%Dropdown.tiny{
onChange: set_easing
value: easing
options: easing_options
scrolling: yes
upward: yes
}
class StartOffset extends React.Component
constructor: (props) ->
super props
@state =
editing: no
toggle_editing: =>
{editing} = @state
@setState editing: not editing
render: ->
{offset, offset_from, set_offset, set_offset_direction} = @props
{editing} = @state
%Field{ inline: yes }
%label Start
= if editing
%span
%Input{
onChange: set_offset
value: Math.abs offset
style: width: '55px'
}^
ms
%Dropdown.tiny.(has
margin: '0 3px'
){
value:
if offset < 0
-1
else
1
options: [
text: 'before'
value: -1
,
text: 'after'
value: 1
]
onChange: set_offset_direction
}^
%span
the previous step ends
else
%Dropdown.tiny{
onClick: @toggle_editing
text:
"#{
unless offset
'when'
else
"#{offset}ms #{
if offset > 0
'after'
else
'before'
}"
} the previous step #{
if offset_from is 'prev_end'
'ends'
else
'starts'
}"
}
Duration = ({duration, set_duration}) ->
%Field{ inline: yes }
%label Duration
%Input{
label:
basic: yes
content: 'ms'
labelPosition: 'right'
onChange: set_duration
value: duration
style: width: '70px'
}
Sorting = ({step_index, steps, handle_reorder}) ->
%select{
value: ''
onChange: handle_reorder
}
%option{ value: '' } Move to:
= for step, _step_index in steps when _step_index isnt step_index and _step_index isnt step_index + 1
%option{ value: _step_index, key: _step_index }
Before Step {_step_index + 1}
= unless step_index is steps.length - 1
%option{ value: 'last' } Last
class Changes extends React.Component
# handle_select_param: ({target: {value}}) =>
handle_select_param: (event, {value}) =>
{add_animated_param} = @props
add_animated_param name: value
shouldComponentUpdate: (nextProps) ->
return yes unless @props.step_index is nextProps.step_index
return yes unless deep_equal @props.start_args, nextProps.start_args
return yes unless deep_equal @props.step?.changed_args, nextProps.step?.changed_args
no
render: ->
{step, step_index, start_args} = @props
%Form{ size: 'tiny' }
%Field
%Dropdown.icon.tiny{
button: yes
labeled: yes
scrolling: yes
upward: yes
icon: 'plus'
text: 'Add animated param'
options: [
(for {name, value, type} in start_args when type isnt 'boolean'
text: dashed_to_label name
value: name
)...
text: 'Background position'
value: 'background_position'
]
onChange: @handle_select_param
value: ''
}
%ChangedArgs{ step, step_index }
Changes = connect(
(state) ->
start_args: do ->
args = get_mixin_args state
{params} = get_current_mixin state
args.map (arg) ->
{name} = arg
extended arg,
type:
find(
params
{name}
).type
(dispatch, {step_index}) ->
add_animated_param: ({name}) ->
dispatch update_step_arg {step_index, name}
) Changes
class ChangedArgs extends React.Component
constructor: (props) ->
super props
@state =
auto_open_last: no
componentWillReceiveProps: ({step: {changed_args}}) ->
auto_open_last = changed_args.length > @props.step.changed_args.length
@setState {auto_open_last} if @state.auto_open_last isnt auto_open_last
render: ->
{step: {changed_args}, step_index} = @props
{auto_open_last} = @state
.changed_args
= %ChangedArg{
arg, step_index
auto_open: auto_open_last and arg_index is changed_args.length - 1
key: arg.PI:KEY:<KEY>END_PI
} for arg, arg_index in changed_args
ChangedArg = connect(
(state, {arg: {name}}) ->
param:
find(
get_current_mixin(state).params
{name}
)
(dispatch, {step_index, arg: {name}}) ->
onChange: (value) ->
dispatch update_step_arg {step_index, name, value}
onDelete: ->
# return unless window.confirm 'Remove ?'
dispatch delete_step_arg {step_index, name}
) ArgField
Shorthand = ({step, step_index, set_shorthand}) ->
%Form
%TextArea{
rows: 8
onChange: ({target: {value}}) ->
set_shorthand value
}
Shorthand = connect(
null
(dispatch, {step_index}) ->
set_shorthand: (shorthand) ->
dispatch set_animation_step_shorthand {
shorthand, step_index
}
) Shorthand
|
[
{
"context": ".public_dev_key)\n\n res = Create( { user_name: \"cli_2_test\", marketing: { name: \"CLI Testing Procedures\" }, ",
"end": 369,
"score": 0.9995580911636353,
"start": 359,
"tag": "USERNAME",
"value": "cli_2_test"
},
{
"context": "ting: { name: \"CLI Testing Procedures... | tests/integration/action_profile_spec.coffee | 3vot/3vot-cli | 0 | Create = require("../../app/actions/profile_create")
should = require("should")
nock = require("nock")
Path = require("path");
describe '3VOT Profile', ->
#nock.recorder.rec();
it 'should create a profile', (donefn) ->
@timeout(20000)
console.log("executing setup with key " + process.env.public_dev_key)
res = Create( { user_name: "cli_2_test", marketing: { name: "CLI Testing Procedures" }, email: "rr@rr.com" } )
res.fail (error) =>
okError = "Error: duplicate key value violates unique constraint \"profile_user_name_found\"";
if JSON.parse(error).message == okError
console.log("Warning: Profile Already Created")
return donefn()
return error.should.equal("");
res.then (profile) ->
process.env.public_dev_key = profile.security.public_dev_key
donefn()
it 'should update a profile', (donefn) ->
@timeout(20000)
console.log("executing setup with key " + process.env.public_dev_key)
res = Update( { user_name: "cli_2_test")
res.fail (error) =>
return error.should.equal("");
res.then (profile) ->
process.env.public_dev_key = profile.security.public_dev_key
donefn() | 64173 | Create = require("../../app/actions/profile_create")
should = require("should")
nock = require("nock")
Path = require("path");
describe '3VOT Profile', ->
#nock.recorder.rec();
it 'should create a profile', (donefn) ->
@timeout(20000)
console.log("executing setup with key " + process.env.public_dev_key)
res = Create( { user_name: "cli_2_test", marketing: { name: "CLI Testing Procedures" }, email: "<EMAIL>" } )
res.fail (error) =>
okError = "Error: duplicate key value violates unique constraint \"profile_user_name_found\"";
if JSON.parse(error).message == okError
console.log("Warning: Profile Already Created")
return donefn()
return error.should.equal("");
res.then (profile) ->
process.env.public_dev_key = profile.security.public_dev_key
donefn()
it 'should update a profile', (donefn) ->
@timeout(20000)
console.log("executing setup with key " + process.env.public_dev_key)
res = Update( { user_name: "cli_2_test")
res.fail (error) =>
return error.should.equal("");
res.then (profile) ->
process.env.public_dev_key = profile.security.public_dev_key
donefn() | true | Create = require("../../app/actions/profile_create")
should = require("should")
nock = require("nock")
Path = require("path");
describe '3VOT Profile', ->
#nock.recorder.rec();
it 'should create a profile', (donefn) ->
@timeout(20000)
console.log("executing setup with key " + process.env.public_dev_key)
res = Create( { user_name: "cli_2_test", marketing: { name: "CLI Testing Procedures" }, email: "PI:EMAIL:<EMAIL>END_PI" } )
res.fail (error) =>
okError = "Error: duplicate key value violates unique constraint \"profile_user_name_found\"";
if JSON.parse(error).message == okError
console.log("Warning: Profile Already Created")
return donefn()
return error.should.equal("");
res.then (profile) ->
process.env.public_dev_key = profile.security.public_dev_key
donefn()
it 'should update a profile', (donefn) ->
@timeout(20000)
console.log("executing setup with key " + process.env.public_dev_key)
res = Update( { user_name: "cli_2_test")
res.fail (error) =>
return error.should.equal("");
res.then (profile) ->
process.env.public_dev_key = profile.security.public_dev_key
donefn() |
[
{
"context": "\n uid: 42, country: 'US', display_name: 'John P. User')\n contentType = 'application/json'\n if",
"end": 3097,
"score": 0.9995976090431213,
"start": 3085,
"tag": "NAME",
"value": "John P. User"
}
] | test/src/helpers/web_file_server.coffee | noamraph/datastore-js | 64 | express = require 'express'
fs = require 'fs'
http = require 'http'
https = require 'https'
# express.js app server for the Web files and XHR tests.
class WebFileServer
# Starts up a HTTP server.
constructor: (options = {}) ->
@port = options.port or 8911
@noSsl = !!options.noSsl
@protocol = if @noSsl then 'http' else 'https'
@createApp()
# The root URL for XHR tests.
testOrigin: ->
"#{@protocol}://localhost:#{@port}"
# The URL that should be used to start the tests.
testUrl: ->
"#{@protocol}://localhost:#{@port}/test/html/browser_test.html"
# The URL that should be used to open the debugging environment.
consoleUrl: ->
"#{@protocol}://localhost:#{@port}/test/html/browser_console.html"
# The self-signed certificate used by this server.
certificate: ->
return null unless @useHttps
keyMaterial = fs.readFileSync 'test/ssl/cert.pem', 'utf8'
certIndex = keyMaterial.indexOf '-----BEGIN CERTIFICATE-----'
keyMaterial.substring certIndex
# The server code.
createApp: ->
@app = express()
## Middleware.
# CORS headers.
@app.use (request, response, next) ->
response.header 'Access-Control-Allow-Origin', '*'
response.header 'Access-Control-Allow-Methods', 'DELETE,GET,POST,PUT'
response.header 'Access-Control-Allow-Headers',
'Content-Type, Authorization'
response.header 'Access-Control-Expose-Headers', 'x-dropbox-metadata'
next()
# Disable HTTP caching, for IE.
@app.use (request, response, next) ->
response.header 'Cache-Control', 'no-cache'
# For IE. Invalid dates should be parsed as "already expired".
response.header 'Expires', '-1'
next()
@app.use @app.router
@app.use express.static(fs.realpathSync(__dirname + '/../../../'),
{ hidden: true })
## Routes
# Ends the tests.
@app.get '/diediedie', (request, response) =>
if 'failed' of request.query
failed = parseInt request.query['failed']
else
failed = 1
total = parseInt request.query['total'] || 0
passed = total - failed
exitCode = if failed == 0 then 0 else 1
console.log "#{passed} passed, #{failed} failed"
response.header 'Content-Type', 'image/png'
response.header 'Content-Length', '0'
response.end ''
unless 'NO_EXIT' of process.env
@server.close()
process.exit exitCode
# Simulate receiving an OAuth 2 access token.
@app.post '/form_encoded', (request, response) ->
body = 'access_token=test%20token&token_type=Bearer'
contentType = 'application/x-www-form-urlencoded'
if charset = request.param('charset')
contentType += "; charset=#{charset}"
response.header 'Content-Type', contentType
response.header 'Content-Length', body.length.toString()
response.end body
# Simulate receiving user info.
@app.post '/json_encoded', (request, response) ->
body = JSON.stringify(
uid: 42, country: 'US', display_name: 'John P. User')
contentType = 'application/json'
if charset = request.param('charset')
contentType += "; charset=#{charset}"
response.header 'Content-Type', contentType
response.header 'Content-Length', body.length.toString()
response.end body
# Simulate reading a file.
@app.get '/dropbox_file', (request, response) ->
# Test Authorize and error handling.
if request.get('Authorization') != 'Bearer mock00token'
body = JSON.stringify error: 'invalid access token'
response.status 401
# NOTE: the API server uses text/javascript instead of application/json
response.header 'Content-Type', 'text/javascript'
response.header 'Content-Length', body.length
response.end body
return
# Test metadata parsing.
metadata = JSON.stringify(
size: '1KB', is_dir: false, path: '/test_path.txt', root: 'dropbox')
body = 'Test file contents'
response.header 'Content-Type', 'text/plain'
response.header 'X-Dropbox-Metadata', metadata
response.header 'Content-Length', body.length
response.end body
# Simulate metadata bugs.
@app.get '/dropbox_file_bug/:bug_id', (request, response) ->
metadata = JSON.stringify(
size: '1KB', is_dir: false, path: '/test_path.txt', root: 'dropbox')
body = 'Test file contents'
response.header 'Content-Type', 'text/plain'
switch request.params.bug_id
when '2x'
response.header 'X-Dropbox-Metadata', "#{metadata}, #{metadata}"
when 'txt'
response.header 'X-Dropbox-Metadata', 'no json here'
response.end body
## Server creation.
if @noSsl
@server = http.createServer @app
else
options = key: fs.readFileSync('test/ssl/cert.pem')
options.cert = options.key
@server = https.createServer options, @app
@server.listen @port
module.exports = WebFileServer
| 174312 | express = require 'express'
fs = require 'fs'
http = require 'http'
https = require 'https'
# express.js app server for the Web files and XHR tests.
class WebFileServer
# Starts up a HTTP server.
constructor: (options = {}) ->
@port = options.port or 8911
@noSsl = !!options.noSsl
@protocol = if @noSsl then 'http' else 'https'
@createApp()
# The root URL for XHR tests.
testOrigin: ->
"#{@protocol}://localhost:#{@port}"
# The URL that should be used to start the tests.
testUrl: ->
"#{@protocol}://localhost:#{@port}/test/html/browser_test.html"
# The URL that should be used to open the debugging environment.
consoleUrl: ->
"#{@protocol}://localhost:#{@port}/test/html/browser_console.html"
# The self-signed certificate used by this server.
certificate: ->
return null unless @useHttps
keyMaterial = fs.readFileSync 'test/ssl/cert.pem', 'utf8'
certIndex = keyMaterial.indexOf '-----BEGIN CERTIFICATE-----'
keyMaterial.substring certIndex
# The server code.
createApp: ->
@app = express()
## Middleware.
# CORS headers.
@app.use (request, response, next) ->
response.header 'Access-Control-Allow-Origin', '*'
response.header 'Access-Control-Allow-Methods', 'DELETE,GET,POST,PUT'
response.header 'Access-Control-Allow-Headers',
'Content-Type, Authorization'
response.header 'Access-Control-Expose-Headers', 'x-dropbox-metadata'
next()
# Disable HTTP caching, for IE.
@app.use (request, response, next) ->
response.header 'Cache-Control', 'no-cache'
# For IE. Invalid dates should be parsed as "already expired".
response.header 'Expires', '-1'
next()
@app.use @app.router
@app.use express.static(fs.realpathSync(__dirname + '/../../../'),
{ hidden: true })
## Routes
# Ends the tests.
@app.get '/diediedie', (request, response) =>
if 'failed' of request.query
failed = parseInt request.query['failed']
else
failed = 1
total = parseInt request.query['total'] || 0
passed = total - failed
exitCode = if failed == 0 then 0 else 1
console.log "#{passed} passed, #{failed} failed"
response.header 'Content-Type', 'image/png'
response.header 'Content-Length', '0'
response.end ''
unless 'NO_EXIT' of process.env
@server.close()
process.exit exitCode
# Simulate receiving an OAuth 2 access token.
@app.post '/form_encoded', (request, response) ->
body = 'access_token=test%20token&token_type=Bearer'
contentType = 'application/x-www-form-urlencoded'
if charset = request.param('charset')
contentType += "; charset=#{charset}"
response.header 'Content-Type', contentType
response.header 'Content-Length', body.length.toString()
response.end body
# Simulate receiving user info.
@app.post '/json_encoded', (request, response) ->
body = JSON.stringify(
uid: 42, country: 'US', display_name: '<NAME>')
contentType = 'application/json'
if charset = request.param('charset')
contentType += "; charset=#{charset}"
response.header 'Content-Type', contentType
response.header 'Content-Length', body.length.toString()
response.end body
# Simulate reading a file.
@app.get '/dropbox_file', (request, response) ->
# Test Authorize and error handling.
if request.get('Authorization') != 'Bearer mock00token'
body = JSON.stringify error: 'invalid access token'
response.status 401
# NOTE: the API server uses text/javascript instead of application/json
response.header 'Content-Type', 'text/javascript'
response.header 'Content-Length', body.length
response.end body
return
# Test metadata parsing.
metadata = JSON.stringify(
size: '1KB', is_dir: false, path: '/test_path.txt', root: 'dropbox')
body = 'Test file contents'
response.header 'Content-Type', 'text/plain'
response.header 'X-Dropbox-Metadata', metadata
response.header 'Content-Length', body.length
response.end body
# Simulate metadata bugs.
@app.get '/dropbox_file_bug/:bug_id', (request, response) ->
metadata = JSON.stringify(
size: '1KB', is_dir: false, path: '/test_path.txt', root: 'dropbox')
body = 'Test file contents'
response.header 'Content-Type', 'text/plain'
switch request.params.bug_id
when '2x'
response.header 'X-Dropbox-Metadata', "#{metadata}, #{metadata}"
when 'txt'
response.header 'X-Dropbox-Metadata', 'no json here'
response.end body
## Server creation.
if @noSsl
@server = http.createServer @app
else
options = key: fs.readFileSync('test/ssl/cert.pem')
options.cert = options.key
@server = https.createServer options, @app
@server.listen @port
module.exports = WebFileServer
| true | express = require 'express'
fs = require 'fs'
http = require 'http'
https = require 'https'
# express.js app server for the Web files and XHR tests.
class WebFileServer
# Starts up a HTTP server.
constructor: (options = {}) ->
@port = options.port or 8911
@noSsl = !!options.noSsl
@protocol = if @noSsl then 'http' else 'https'
@createApp()
# The root URL for XHR tests.
testOrigin: ->
"#{@protocol}://localhost:#{@port}"
# The URL that should be used to start the tests.
testUrl: ->
"#{@protocol}://localhost:#{@port}/test/html/browser_test.html"
# The URL that should be used to open the debugging environment.
consoleUrl: ->
"#{@protocol}://localhost:#{@port}/test/html/browser_console.html"
# The self-signed certificate used by this server.
certificate: ->
return null unless @useHttps
keyMaterial = fs.readFileSync 'test/ssl/cert.pem', 'utf8'
certIndex = keyMaterial.indexOf '-----BEGIN CERTIFICATE-----'
keyMaterial.substring certIndex
# The server code.
createApp: ->
@app = express()
## Middleware.
# CORS headers.
@app.use (request, response, next) ->
response.header 'Access-Control-Allow-Origin', '*'
response.header 'Access-Control-Allow-Methods', 'DELETE,GET,POST,PUT'
response.header 'Access-Control-Allow-Headers',
'Content-Type, Authorization'
response.header 'Access-Control-Expose-Headers', 'x-dropbox-metadata'
next()
# Disable HTTP caching, for IE.
@app.use (request, response, next) ->
response.header 'Cache-Control', 'no-cache'
# For IE. Invalid dates should be parsed as "already expired".
response.header 'Expires', '-1'
next()
@app.use @app.router
@app.use express.static(fs.realpathSync(__dirname + '/../../../'),
{ hidden: true })
## Routes
# Ends the tests.
@app.get '/diediedie', (request, response) =>
if 'failed' of request.query
failed = parseInt request.query['failed']
else
failed = 1
total = parseInt request.query['total'] || 0
passed = total - failed
exitCode = if failed == 0 then 0 else 1
console.log "#{passed} passed, #{failed} failed"
response.header 'Content-Type', 'image/png'
response.header 'Content-Length', '0'
response.end ''
unless 'NO_EXIT' of process.env
@server.close()
process.exit exitCode
# Simulate receiving an OAuth 2 access token.
@app.post '/form_encoded', (request, response) ->
body = 'access_token=test%20token&token_type=Bearer'
contentType = 'application/x-www-form-urlencoded'
if charset = request.param('charset')
contentType += "; charset=#{charset}"
response.header 'Content-Type', contentType
response.header 'Content-Length', body.length.toString()
response.end body
# Simulate receiving user info.
@app.post '/json_encoded', (request, response) ->
body = JSON.stringify(
uid: 42, country: 'US', display_name: 'PI:NAME:<NAME>END_PI')
contentType = 'application/json'
if charset = request.param('charset')
contentType += "; charset=#{charset}"
response.header 'Content-Type', contentType
response.header 'Content-Length', body.length.toString()
response.end body
# Simulate reading a file.
@app.get '/dropbox_file', (request, response) ->
# Test Authorize and error handling.
if request.get('Authorization') != 'Bearer mock00token'
body = JSON.stringify error: 'invalid access token'
response.status 401
# NOTE: the API server uses text/javascript instead of application/json
response.header 'Content-Type', 'text/javascript'
response.header 'Content-Length', body.length
response.end body
return
# Test metadata parsing.
metadata = JSON.stringify(
size: '1KB', is_dir: false, path: '/test_path.txt', root: 'dropbox')
body = 'Test file contents'
response.header 'Content-Type', 'text/plain'
response.header 'X-Dropbox-Metadata', metadata
response.header 'Content-Length', body.length
response.end body
# Simulate metadata bugs.
@app.get '/dropbox_file_bug/:bug_id', (request, response) ->
metadata = JSON.stringify(
size: '1KB', is_dir: false, path: '/test_path.txt', root: 'dropbox')
body = 'Test file contents'
response.header 'Content-Type', 'text/plain'
switch request.params.bug_id
when '2x'
response.header 'X-Dropbox-Metadata', "#{metadata}, #{metadata}"
when 'txt'
response.header 'X-Dropbox-Metadata', 'no json here'
response.end body
## Server creation.
if @noSsl
@server = http.createServer @app
else
options = key: fs.readFileSync('test/ssl/cert.pem')
options.cert = options.key
@server = https.createServer options, @app
@server.listen @port
module.exports = WebFileServer
|
[
{
"context": "###\n# MIT LICENSE\n# Copyright (c) 2011 Devon Govett\n# \n# Permission is hereby granted, free of charge",
"end": 51,
"score": 0.9998533129692078,
"start": 39,
"tag": "NAME",
"value": "Devon Govett"
},
{
"context": " index = text.indexOf(0)\n key = S... | node_modules/png-js/png.coffee | fahamk/writersblock | 8 | ###
# MIT LICENSE
# Copyright (c) 2011 Devon Govett
#
# 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.
###
class PNG
@load: (url, canvas, callback) ->
callback = canvas if typeof canvas is 'function'
xhr = new XMLHttpRequest
xhr.open("GET", url, true)
xhr.responseType = "arraybuffer"
xhr.onload = =>
data = new Uint8Array(xhr.response or xhr.mozResponseArrayBuffer)
png = new PNG(data)
png.render(canvas) if typeof canvas?.getContext is 'function'
callback?(png)
xhr.send(null)
APNG_DISPOSE_OP_NONE = 0
APNG_DISPOSE_OP_BACKGROUND = 1
APNG_DISPOSE_OP_PREVIOUS = 2
APNG_BLEND_OP_SOURCE = 0
APNG_BLEND_OP_OVER = 1
constructor: (@data) ->
@pos = 8 # Skip the default header
@palette = []
@imgData = []
@transparency = {}
@animation = null
@text = {}
frame = null
loop
chunkSize = @readUInt32()
section = (String.fromCharCode @data[@pos++] for i in [0...4]).join('')
switch section
when 'IHDR'
# we can grab interesting values from here (like width, height, etc)
@width = @readUInt32()
@height = @readUInt32()
@bits = @data[@pos++]
@colorType = @data[@pos++]
@compressionMethod = @data[@pos++]
@filterMethod = @data[@pos++]
@interlaceMethod = @data[@pos++]
when 'acTL'
# we have an animated PNG
@animation =
numFrames: @readUInt32()
numPlays: @readUInt32() or Infinity
frames: []
when 'PLTE'
@palette = @read(chunkSize)
when 'fcTL'
@animation.frames.push(frame) if frame
@pos += 4 # skip sequence number
frame =
width: @readUInt32()
height: @readUInt32()
xOffset: @readUInt32()
yOffset: @readUInt32()
delayNum = @readUInt16()
delayDen = @readUInt16() or 100
frame.delay = 1000 * delayNum / delayDen
frame.disposeOp = @data[@pos++]
frame.blendOp = @data[@pos++]
frame.data = []
when 'IDAT', 'fdAT'
if section is 'fdAT'
@pos += 4 # skip sequence number
chunkSize -= 4
data = frame?.data or @imgData
for i in [0...chunkSize]
data.push @data[@pos++]
when 'tRNS'
# This chunk can only occur once and it must occur after the
# PLTE chunk and before the IDAT chunk.
@transparency = {}
switch @colorType
when 3
# Indexed color, RGB. Each byte in this chunk is an alpha for
# the palette index in the PLTE ("palette") chunk up until the
# last non-opaque entry. Set up an array, stretching over all
# palette entries which will be 0 (opaque) or 1 (transparent).
@transparency.indexed = @read(chunkSize)
short = 255 - @transparency.indexed.length
if short > 0
@transparency.indexed.push 255 for i in [0...short]
when 0
# Greyscale. Corresponding to entries in the PLTE chunk.
# Grey is two bytes, range 0 .. (2 ^ bit-depth) - 1
@transparency.grayscale = @read(chunkSize)[0]
when 2
# True color with proper alpha channel.
@transparency.rgb = @read(chunkSize)
when 'tEXt'
text = @read(chunkSize)
index = text.indexOf(0)
key = String.fromCharCode text.slice(0, index)...
@text[key] = String.fromCharCode text.slice(index + 1)...
when 'IEND'
@animation.frames.push(frame) if frame
# we've got everything we need!
@colors = switch @colorType
when 0, 3, 4 then 1
when 2, 6 then 3
@hasAlphaChannel = @colorType in [4, 6]
colors = @colors + if @hasAlphaChannel then 1 else 0
@pixelBitlength = @bits * colors
@colorSpace = switch @colors
when 1 then 'DeviceGray'
when 3 then 'DeviceRGB'
@imgData = new Uint8Array @imgData
return
else
# unknown (or unimportant) section, skip it
@pos += chunkSize
@pos += 4 # Skip the CRC
if @pos > @data.length
throw new Error "Incomplete or corrupt PNG file"
return
read: (bytes) ->
(@data[@pos++] for i in [0...bytes])
readUInt32: ->
b1 = @data[@pos++] << 24
b2 = @data[@pos++] << 16
b3 = @data[@pos++] << 8
b4 = @data[@pos++]
b1 | b2 | b3 | b4
readUInt16: ->
b1 = @data[@pos++] << 8
b2 = @data[@pos++]
b1 | b2
decodePixels: (data = @imgData) ->
return new Uint8Array(0) if data.length is 0
data = new FlateStream(data)
data = data.getBytes()
pixelBytes = @pixelBitlength / 8
scanlineLength = pixelBytes * @width
pixels = new Uint8Array(scanlineLength * @height)
length = data.length
row = 0
pos = 0
c = 0
while pos < length
switch data[pos++]
when 0 # None
for i in [0...scanlineLength] by 1
pixels[c++] = data[pos++]
when 1 # Sub
for i in [0...scanlineLength] by 1
byte = data[pos++]
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
pixels[c++] = (byte + left) % 256
when 2 # Up
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (upper + byte) % 256
when 3 # Average
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256
when 4 # Paeth
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
if row is 0
upper = upperLeft = 0
else
upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)]
p = left + upper - upperLeft
pa = Math.abs(p - left)
pb = Math.abs(p - upper)
pc = Math.abs(p - upperLeft)
if pa <= pb and pa <= pc
paeth = left
else if pb <= pc
paeth = upper
else
paeth = upperLeft
pixels[c++] = (byte + paeth) % 256
else
throw new Error "Invalid filter algorithm: " + data[pos - 1]
row++
return pixels
decodePalette: ->
palette = @palette
transparency = @transparency.indexed or []
ret = new Uint8Array((transparency.length or 0) + palette.length)
pos = 0
length = palette.length
c = 0
for i in [0...palette.length] by 3
ret[pos++] = palette[i]
ret[pos++] = palette[i + 1]
ret[pos++] = palette[i + 2]
ret[pos++] = transparency[c++] ? 255
return ret
copyToImageData: (imageData, pixels) ->
colors = @colors
palette = null
alpha = @hasAlphaChannel
if @palette.length
palette = @_decodedPalette ?= @decodePalette()
colors = 4
alpha = true
data = imageData.data
length = data.length
input = palette or pixels
i = j = 0
if colors is 1
while i < length
k = if palette then pixels[i / 4] * 4 else j
v = input[k++]
data[i++] = v
data[i++] = v
data[i++] = v
data[i++] = if alpha then input[k++] else 255
j = k
else
while i < length
k = if palette then pixels[i / 4] * 4 else j
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = if alpha then input[k++] else 255
j = k
return
decode: ->
ret = new Uint8Array(@width * @height * 4)
@copyToImageData ret, @decodePixels()
return ret
scratchCanvas = document.createElement 'canvas'
scratchCtx = scratchCanvas.getContext '2d'
makeImage = (imageData) ->
scratchCtx.width = imageData.width
scratchCtx.height = imageData.height
scratchCtx.clearRect(0, 0, imageData.width, imageData.height)
scratchCtx.putImageData(imageData, 0, 0)
img = new Image
img.src = scratchCanvas.toDataURL()
return img
decodeFrames: (ctx) ->
return unless @animation
for frame, i in @animation.frames
imageData = ctx.createImageData(frame.width, frame.height)
pixels = @decodePixels(new Uint8Array(frame.data))
@copyToImageData(imageData, pixels)
frame.imageData = imageData
frame.image = makeImage(imageData)
renderFrame: (ctx, number) ->
frames = @animation.frames
frame = frames[number]
prev = frames[number - 1]
# if we're on the first frame, clear the canvas
if number is 0
ctx.clearRect(0, 0, @width, @height)
# check the previous frame's dispose operation
if prev?.disposeOp is APNG_DISPOSE_OP_BACKGROUND
ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height)
else if prev?.disposeOp is APNG_DISPOSE_OP_PREVIOUS
ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset)
# APNG_BLEND_OP_SOURCE overwrites the previous data
if frame.blendOp is APNG_BLEND_OP_SOURCE
ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height)
# draw the current frame
ctx.drawImage(frame.image, frame.xOffset, frame.yOffset)
animate: (ctx) ->
frameNumber = 0
{numFrames, frames, numPlays} = @animation
do doFrame = =>
f = frameNumber++ % numFrames
frame = frames[f]
@renderFrame(ctx, f)
if numFrames > 1 and frameNumber / numFrames < numPlays
@animation._timeout = setTimeout(doFrame, frame.delay)
stopAnimation: ->
clearTimeout @animation?._timeout
render: (canvas) ->
# if this canvas was displaying another image before,
# stop the animation on it
if canvas._png
canvas._png.stopAnimation()
canvas._png = this
canvas.width = @width
canvas.height = @height
ctx = canvas.getContext "2d"
if @animation
@decodeFrames(ctx)
@animate(ctx)
else
data = ctx.createImageData @width, @height
@copyToImageData data, @decodePixels()
ctx.putImageData data, 0, 0
window.PNG = PNG | 193160 | ###
# MIT LICENSE
# Copyright (c) 2011 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
# to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
###
class PNG
@load: (url, canvas, callback) ->
callback = canvas if typeof canvas is 'function'
xhr = new XMLHttpRequest
xhr.open("GET", url, true)
xhr.responseType = "arraybuffer"
xhr.onload = =>
data = new Uint8Array(xhr.response or xhr.mozResponseArrayBuffer)
png = new PNG(data)
png.render(canvas) if typeof canvas?.getContext is 'function'
callback?(png)
xhr.send(null)
APNG_DISPOSE_OP_NONE = 0
APNG_DISPOSE_OP_BACKGROUND = 1
APNG_DISPOSE_OP_PREVIOUS = 2
APNG_BLEND_OP_SOURCE = 0
APNG_BLEND_OP_OVER = 1
constructor: (@data) ->
@pos = 8 # Skip the default header
@palette = []
@imgData = []
@transparency = {}
@animation = null
@text = {}
frame = null
loop
chunkSize = @readUInt32()
section = (String.fromCharCode @data[@pos++] for i in [0...4]).join('')
switch section
when 'IHDR'
# we can grab interesting values from here (like width, height, etc)
@width = @readUInt32()
@height = @readUInt32()
@bits = @data[@pos++]
@colorType = @data[@pos++]
@compressionMethod = @data[@pos++]
@filterMethod = @data[@pos++]
@interlaceMethod = @data[@pos++]
when 'acTL'
# we have an animated PNG
@animation =
numFrames: @readUInt32()
numPlays: @readUInt32() or Infinity
frames: []
when 'PLTE'
@palette = @read(chunkSize)
when 'fcTL'
@animation.frames.push(frame) if frame
@pos += 4 # skip sequence number
frame =
width: @readUInt32()
height: @readUInt32()
xOffset: @readUInt32()
yOffset: @readUInt32()
delayNum = @readUInt16()
delayDen = @readUInt16() or 100
frame.delay = 1000 * delayNum / delayDen
frame.disposeOp = @data[@pos++]
frame.blendOp = @data[@pos++]
frame.data = []
when 'IDAT', 'fdAT'
if section is 'fdAT'
@pos += 4 # skip sequence number
chunkSize -= 4
data = frame?.data or @imgData
for i in [0...chunkSize]
data.push @data[@pos++]
when 'tRNS'
# This chunk can only occur once and it must occur after the
# PLTE chunk and before the IDAT chunk.
@transparency = {}
switch @colorType
when 3
# Indexed color, RGB. Each byte in this chunk is an alpha for
# the palette index in the PLTE ("palette") chunk up until the
# last non-opaque entry. Set up an array, stretching over all
# palette entries which will be 0 (opaque) or 1 (transparent).
@transparency.indexed = @read(chunkSize)
short = 255 - @transparency.indexed.length
if short > 0
@transparency.indexed.push 255 for i in [0...short]
when 0
# Greyscale. Corresponding to entries in the PLTE chunk.
# Grey is two bytes, range 0 .. (2 ^ bit-depth) - 1
@transparency.grayscale = @read(chunkSize)[0]
when 2
# True color with proper alpha channel.
@transparency.rgb = @read(chunkSize)
when 'tEXt'
text = @read(chunkSize)
index = text.indexOf(0)
key = <KEY>.<KEY>CharCode text.slice(0, index)...
@text[key] = String.fromCharCode text.slice(index + 1)...
when 'IEND'
@animation.frames.push(frame) if frame
# we've got everything we need!
@colors = switch @colorType
when 0, 3, 4 then 1
when 2, 6 then 3
@hasAlphaChannel = @colorType in [4, 6]
colors = @colors + if @hasAlphaChannel then 1 else 0
@pixelBitlength = @bits * colors
@colorSpace = switch @colors
when 1 then 'DeviceGray'
when 3 then 'DeviceRGB'
@imgData = new Uint8Array @imgData
return
else
# unknown (or unimportant) section, skip it
@pos += chunkSize
@pos += 4 # Skip the CRC
if @pos > @data.length
throw new Error "Incomplete or corrupt PNG file"
return
read: (bytes) ->
(@data[@pos++] for i in [0...bytes])
readUInt32: ->
b1 = @data[@pos++] << 24
b2 = @data[@pos++] << 16
b3 = @data[@pos++] << 8
b4 = @data[@pos++]
b1 | b2 | b3 | b4
readUInt16: ->
b1 = @data[@pos++] << 8
b2 = @data[@pos++]
b1 | b2
decodePixels: (data = @imgData) ->
return new Uint8Array(0) if data.length is 0
data = new FlateStream(data)
data = data.getBytes()
pixelBytes = @pixelBitlength / 8
scanlineLength = pixelBytes * @width
pixels = new Uint8Array(scanlineLength * @height)
length = data.length
row = 0
pos = 0
c = 0
while pos < length
switch data[pos++]
when 0 # None
for i in [0...scanlineLength] by 1
pixels[c++] = data[pos++]
when 1 # Sub
for i in [0...scanlineLength] by 1
byte = data[pos++]
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
pixels[c++] = (byte + left) % 256
when 2 # Up
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (upper + byte) % 256
when 3 # Average
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256
when 4 # Paeth
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
if row is 0
upper = upperLeft = 0
else
upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)]
p = left + upper - upperLeft
pa = Math.abs(p - left)
pb = Math.abs(p - upper)
pc = Math.abs(p - upperLeft)
if pa <= pb and pa <= pc
paeth = left
else if pb <= pc
paeth = upper
else
paeth = upperLeft
pixels[c++] = (byte + paeth) % 256
else
throw new Error "Invalid filter algorithm: " + data[pos - 1]
row++
return pixels
decodePalette: ->
palette = @palette
transparency = @transparency.indexed or []
ret = new Uint8Array((transparency.length or 0) + palette.length)
pos = 0
length = palette.length
c = 0
for i in [0...palette.length] by 3
ret[pos++] = palette[i]
ret[pos++] = palette[i + 1]
ret[pos++] = palette[i + 2]
ret[pos++] = transparency[c++] ? 255
return ret
copyToImageData: (imageData, pixels) ->
colors = @colors
palette = null
alpha = @hasAlphaChannel
if @palette.length
palette = @_decodedPalette ?= @decodePalette()
colors = 4
alpha = true
data = imageData.data
length = data.length
input = palette or pixels
i = j = 0
if colors is 1
while i < length
k = if palette then pixels[i / 4] * 4 else j
v = input[k++]
data[i++] = v
data[i++] = v
data[i++] = v
data[i++] = if alpha then input[k++] else 255
j = k
else
while i < length
k = if palette then pixels[i / 4] * 4 else j
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = if alpha then input[k++] else 255
j = k
return
decode: ->
ret = new Uint8Array(@width * @height * 4)
@copyToImageData ret, @decodePixels()
return ret
scratchCanvas = document.createElement 'canvas'
scratchCtx = scratchCanvas.getContext '2d'
makeImage = (imageData) ->
scratchCtx.width = imageData.width
scratchCtx.height = imageData.height
scratchCtx.clearRect(0, 0, imageData.width, imageData.height)
scratchCtx.putImageData(imageData, 0, 0)
img = new Image
img.src = scratchCanvas.toDataURL()
return img
decodeFrames: (ctx) ->
return unless @animation
for frame, i in @animation.frames
imageData = ctx.createImageData(frame.width, frame.height)
pixels = @decodePixels(new Uint8Array(frame.data))
@copyToImageData(imageData, pixels)
frame.imageData = imageData
frame.image = makeImage(imageData)
renderFrame: (ctx, number) ->
frames = @animation.frames
frame = frames[number]
prev = frames[number - 1]
# if we're on the first frame, clear the canvas
if number is 0
ctx.clearRect(0, 0, @width, @height)
# check the previous frame's dispose operation
if prev?.disposeOp is APNG_DISPOSE_OP_BACKGROUND
ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height)
else if prev?.disposeOp is APNG_DISPOSE_OP_PREVIOUS
ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset)
# APNG_BLEND_OP_SOURCE overwrites the previous data
if frame.blendOp is APNG_BLEND_OP_SOURCE
ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height)
# draw the current frame
ctx.drawImage(frame.image, frame.xOffset, frame.yOffset)
animate: (ctx) ->
frameNumber = 0
{numFrames, frames, numPlays} = @animation
do doFrame = =>
f = frameNumber++ % numFrames
frame = frames[f]
@renderFrame(ctx, f)
if numFrames > 1 and frameNumber / numFrames < numPlays
@animation._timeout = setTimeout(doFrame, frame.delay)
stopAnimation: ->
clearTimeout @animation?._timeout
render: (canvas) ->
# if this canvas was displaying another image before,
# stop the animation on it
if canvas._png
canvas._png.stopAnimation()
canvas._png = this
canvas.width = @width
canvas.height = @height
ctx = canvas.getContext "2d"
if @animation
@decodeFrames(ctx)
@animate(ctx)
else
data = ctx.createImageData @width, @height
@copyToImageData data, @decodePixels()
ctx.putImageData data, 0, 0
window.PNG = PNG | true | ###
# MIT LICENSE
# Copyright (c) 2011 PI:NAME:<NAME>END_PI
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
# to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
###
class PNG
@load: (url, canvas, callback) ->
callback = canvas if typeof canvas is 'function'
xhr = new XMLHttpRequest
xhr.open("GET", url, true)
xhr.responseType = "arraybuffer"
xhr.onload = =>
data = new Uint8Array(xhr.response or xhr.mozResponseArrayBuffer)
png = new PNG(data)
png.render(canvas) if typeof canvas?.getContext is 'function'
callback?(png)
xhr.send(null)
APNG_DISPOSE_OP_NONE = 0
APNG_DISPOSE_OP_BACKGROUND = 1
APNG_DISPOSE_OP_PREVIOUS = 2
APNG_BLEND_OP_SOURCE = 0
APNG_BLEND_OP_OVER = 1
constructor: (@data) ->
@pos = 8 # Skip the default header
@palette = []
@imgData = []
@transparency = {}
@animation = null
@text = {}
frame = null
loop
chunkSize = @readUInt32()
section = (String.fromCharCode @data[@pos++] for i in [0...4]).join('')
switch section
when 'IHDR'
# we can grab interesting values from here (like width, height, etc)
@width = @readUInt32()
@height = @readUInt32()
@bits = @data[@pos++]
@colorType = @data[@pos++]
@compressionMethod = @data[@pos++]
@filterMethod = @data[@pos++]
@interlaceMethod = @data[@pos++]
when 'acTL'
# we have an animated PNG
@animation =
numFrames: @readUInt32()
numPlays: @readUInt32() or Infinity
frames: []
when 'PLTE'
@palette = @read(chunkSize)
when 'fcTL'
@animation.frames.push(frame) if frame
@pos += 4 # skip sequence number
frame =
width: @readUInt32()
height: @readUInt32()
xOffset: @readUInt32()
yOffset: @readUInt32()
delayNum = @readUInt16()
delayDen = @readUInt16() or 100
frame.delay = 1000 * delayNum / delayDen
frame.disposeOp = @data[@pos++]
frame.blendOp = @data[@pos++]
frame.data = []
when 'IDAT', 'fdAT'
if section is 'fdAT'
@pos += 4 # skip sequence number
chunkSize -= 4
data = frame?.data or @imgData
for i in [0...chunkSize]
data.push @data[@pos++]
when 'tRNS'
# This chunk can only occur once and it must occur after the
# PLTE chunk and before the IDAT chunk.
@transparency = {}
switch @colorType
when 3
# Indexed color, RGB. Each byte in this chunk is an alpha for
# the palette index in the PLTE ("palette") chunk up until the
# last non-opaque entry. Set up an array, stretching over all
# palette entries which will be 0 (opaque) or 1 (transparent).
@transparency.indexed = @read(chunkSize)
short = 255 - @transparency.indexed.length
if short > 0
@transparency.indexed.push 255 for i in [0...short]
when 0
# Greyscale. Corresponding to entries in the PLTE chunk.
# Grey is two bytes, range 0 .. (2 ^ bit-depth) - 1
@transparency.grayscale = @read(chunkSize)[0]
when 2
# True color with proper alpha channel.
@transparency.rgb = @read(chunkSize)
when 'tEXt'
text = @read(chunkSize)
index = text.indexOf(0)
key = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PICharCode text.slice(0, index)...
@text[key] = String.fromCharCode text.slice(index + 1)...
when 'IEND'
@animation.frames.push(frame) if frame
# we've got everything we need!
@colors = switch @colorType
when 0, 3, 4 then 1
when 2, 6 then 3
@hasAlphaChannel = @colorType in [4, 6]
colors = @colors + if @hasAlphaChannel then 1 else 0
@pixelBitlength = @bits * colors
@colorSpace = switch @colors
when 1 then 'DeviceGray'
when 3 then 'DeviceRGB'
@imgData = new Uint8Array @imgData
return
else
# unknown (or unimportant) section, skip it
@pos += chunkSize
@pos += 4 # Skip the CRC
if @pos > @data.length
throw new Error "Incomplete or corrupt PNG file"
return
read: (bytes) ->
(@data[@pos++] for i in [0...bytes])
readUInt32: ->
b1 = @data[@pos++] << 24
b2 = @data[@pos++] << 16
b3 = @data[@pos++] << 8
b4 = @data[@pos++]
b1 | b2 | b3 | b4
readUInt16: ->
b1 = @data[@pos++] << 8
b2 = @data[@pos++]
b1 | b2
decodePixels: (data = @imgData) ->
return new Uint8Array(0) if data.length is 0
data = new FlateStream(data)
data = data.getBytes()
pixelBytes = @pixelBitlength / 8
scanlineLength = pixelBytes * @width
pixels = new Uint8Array(scanlineLength * @height)
length = data.length
row = 0
pos = 0
c = 0
while pos < length
switch data[pos++]
when 0 # None
for i in [0...scanlineLength] by 1
pixels[c++] = data[pos++]
when 1 # Sub
for i in [0...scanlineLength] by 1
byte = data[pos++]
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
pixels[c++] = (byte + left) % 256
when 2 # Up
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (upper + byte) % 256
when 3 # Average
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256
when 4 # Paeth
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
if row is 0
upper = upperLeft = 0
else
upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)]
p = left + upper - upperLeft
pa = Math.abs(p - left)
pb = Math.abs(p - upper)
pc = Math.abs(p - upperLeft)
if pa <= pb and pa <= pc
paeth = left
else if pb <= pc
paeth = upper
else
paeth = upperLeft
pixels[c++] = (byte + paeth) % 256
else
throw new Error "Invalid filter algorithm: " + data[pos - 1]
row++
return pixels
decodePalette: ->
palette = @palette
transparency = @transparency.indexed or []
ret = new Uint8Array((transparency.length or 0) + palette.length)
pos = 0
length = palette.length
c = 0
for i in [0...palette.length] by 3
ret[pos++] = palette[i]
ret[pos++] = palette[i + 1]
ret[pos++] = palette[i + 2]
ret[pos++] = transparency[c++] ? 255
return ret
copyToImageData: (imageData, pixels) ->
colors = @colors
palette = null
alpha = @hasAlphaChannel
if @palette.length
palette = @_decodedPalette ?= @decodePalette()
colors = 4
alpha = true
data = imageData.data
length = data.length
input = palette or pixels
i = j = 0
if colors is 1
while i < length
k = if palette then pixels[i / 4] * 4 else j
v = input[k++]
data[i++] = v
data[i++] = v
data[i++] = v
data[i++] = if alpha then input[k++] else 255
j = k
else
while i < length
k = if palette then pixels[i / 4] * 4 else j
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = if alpha then input[k++] else 255
j = k
return
decode: ->
ret = new Uint8Array(@width * @height * 4)
@copyToImageData ret, @decodePixels()
return ret
scratchCanvas = document.createElement 'canvas'
scratchCtx = scratchCanvas.getContext '2d'
makeImage = (imageData) ->
scratchCtx.width = imageData.width
scratchCtx.height = imageData.height
scratchCtx.clearRect(0, 0, imageData.width, imageData.height)
scratchCtx.putImageData(imageData, 0, 0)
img = new Image
img.src = scratchCanvas.toDataURL()
return img
decodeFrames: (ctx) ->
return unless @animation
for frame, i in @animation.frames
imageData = ctx.createImageData(frame.width, frame.height)
pixels = @decodePixels(new Uint8Array(frame.data))
@copyToImageData(imageData, pixels)
frame.imageData = imageData
frame.image = makeImage(imageData)
renderFrame: (ctx, number) ->
frames = @animation.frames
frame = frames[number]
prev = frames[number - 1]
# if we're on the first frame, clear the canvas
if number is 0
ctx.clearRect(0, 0, @width, @height)
# check the previous frame's dispose operation
if prev?.disposeOp is APNG_DISPOSE_OP_BACKGROUND
ctx.clearRect(prev.xOffset, prev.yOffset, prev.width, prev.height)
else if prev?.disposeOp is APNG_DISPOSE_OP_PREVIOUS
ctx.putImageData(prev.imageData, prev.xOffset, prev.yOffset)
# APNG_BLEND_OP_SOURCE overwrites the previous data
if frame.blendOp is APNG_BLEND_OP_SOURCE
ctx.clearRect(frame.xOffset, frame.yOffset, frame.width, frame.height)
# draw the current frame
ctx.drawImage(frame.image, frame.xOffset, frame.yOffset)
animate: (ctx) ->
frameNumber = 0
{numFrames, frames, numPlays} = @animation
do doFrame = =>
f = frameNumber++ % numFrames
frame = frames[f]
@renderFrame(ctx, f)
if numFrames > 1 and frameNumber / numFrames < numPlays
@animation._timeout = setTimeout(doFrame, frame.delay)
stopAnimation: ->
clearTimeout @animation?._timeout
render: (canvas) ->
# if this canvas was displaying another image before,
# stop the animation on it
if canvas._png
canvas._png.stopAnimation()
canvas._png = this
canvas.width = @width
canvas.height = @height
ctx = canvas.getContext "2d"
if @animation
@decodeFrames(ctx)
@animate(ctx)
else
data = ctx.createImageData @width, @height
@copyToImageData data, @decodePixels()
ctx.putImageData data, 0, 0
window.PNG = PNG |
[
{
"context": "for the reaction permissions\n# https://github.com/ongoworks/reaction#rolespermissions-system\n# use: {{hasPerm",
"end": 4622,
"score": 0.9994480609893799,
"start": 4613,
"tag": "USERNAME",
"value": "ongoworks"
},
{
"context": "ptions.hash\n\t\t\tunless key is 'enabled'... | app/client/helpers/spacebars.coffee | chrisdamba/offer-market | 1 | ###
#
# Reaction Spacebars helpers
# See: http://docs.meteor.com/#/full/template_registerhelper
#
###
#
# monthOptions
# returns momentjs months formatted for autoform
#
Template.registerHelper "monthOptions", () ->
monthOptions = [{value: "", label: "Choose month"}]
months = moment.months()
for month, index in months
monthOptions.push value: index + 1, label: month
return monthOptions
#
# yearOptions
# returns array of years, formatted for autoform
#
Template.registerHelper "yearOptions", () ->
yearOptions = [{ value: "", label: "Choose year" }]
year = new Date().getFullYear()
for x in [1...9] by 1
yearOptions.push { value: year , label: year}
year++
return yearOptions
#
# timezoneOptions
# returns array of momentjs timezones formatted for autoform
#
Template.registerHelper "timezoneOptions", () ->
timezoneOptions = [{value: "", label: "Choose timezone"}]
timezones = moment.tz.names()
for timezone, index in timezones
timezoneOptions.push value: timezone, label: timezone
return timezoneOptions
#
# gets current cart billing address / payment name
#
Template.registerHelper "cartPayerName", ->
Cart.findOne()?.payment?.address?.fullName
###
# return shop /locale specific formatted price
# also accepts a range formatted with " - "
###
Template.registerHelper "formatPrice", (price) ->
localeDep.depend() # create dependency on localeDep
try
prices = price.split(' - ')
for actualPrice in prices
originalPrice = actualPrice
#TODO Add user services for conversions
if OfferMarket.Locale?.currency?.exchangeRate then actualPrice = actualPrice * OfferMarket.Locale?.currency?.exchangeRate.Rate
formattedPrice = accounting.formatMoney actualPrice, OfferMarket.Locale.currency
price = price.replace(originalPrice, formattedPrice)
catch
if OfferMarket.Locale?.currency?.exchangeRate then price = price * OfferMarket.Locale?.currency?.exchangeRate.Rate
price = accounting.formatMoney price, OfferMarket.Locale?.currency
return price
#
# return path for route
#
Template.registerHelper "pathForSEO", (path, params) ->
if this[params]
return "/"+ path + "/" + this[params]
else
return Router.path path,this
#
# displayName
#
# params user - optional a user object defaults to current user
# returns string user name
#
Template.registerHelper "displayName", (user) ->
userSub = Meteor.subscribe "UserProfile", user?._id || Meteor.userId()
userId = user?._id || Meteor.userId()
if userSub.ready()
user = Meteor.users.findOne(userId) unless user
# every social channel is different
# legacy profile name
if user and user.profile and user.profile.name
return user.profile.name
# meteor user name
else if user and user.username
return user.username
# service names
if user and user.services
username = switch
when user.services.twitter then user.services.twitter.name
when user.services.facebook then user.services.facebook.name
when user.services.instagram then user.services.instagram.name
when user.services.pinterest then user.services.pinterest.name
else "Guest"
#
# general helper user name handling
# TODO: needs additional validation all use cases
# returns first word in profile name
#
Template.registerHelper "fName", (user) ->
userSub = Meteor.subscribe "UserProfile", user?._id || Meteor.userId()
if userSub.ready()
user = Meteor.users.findOne() unless user
# every social channel is different
# legacy profile name
if user and user.profile and user.profile.name
return user.profile.name.split(" ")[0]
else if user and user.username
return user.username.name.split(" ")[0]
# service names
if user and user.services
username = switch
when user.services.twitter then user.services.twitter.first_name
when user.services.facebook then user.services.facebook.first_name
when user.services.instagram then user.services.instagram.first_name
when user.services.pinterest then user.services.pinterest.first_name
else "Guest"
#
# decamelSpace
#
Template.registerHelper "camelToSpace", (str) ->
downCamel = str.replace(/\W+/g, "-").replace /([a-z\d])([A-Z])/g, "$1 $2"
return downCamel.toLowerCase()
#
# upperCase or lowerCase string
#
Template.registerHelper "toLowerCase", (str) ->
return str.toLowerCase()
Template.registerHelper "toUpperCase", (str) ->
return str.toUpperCase()
Template.registerHelper "capitalize", (str) ->
return str.charAt(0).toUpperCase() + str.slice(1)
#
# camelCase string
#
Template.registerHelper "toCamelCase", (str) ->
return str.toCamelCase()
###
# Methods for the reaction permissions
# https://github.com/ongoworks/reaction#rolespermissions-system
# use: {{hasPermissions admin userId}}
###
Template.registerHelper "hasPermission", (permissions, userId) ->
check permissions, Match.OneOf(String, Object)
if typeof(userId) is 'object' then userId = Meteor.userId()
return OfferMarket.hasPermission permissions, userId
Template.registerHelper "hasOwnerAccess", ->
OfferMarket.hasOwnerAccess()
Template.registerHelper "hasAdminAccess", ->
OfferMarket.hasAdminAccess()
Template.registerHelper "hasDashboardAccess", ->
return OfferMarket.hasDashboardAccess()
Template.registerHelper "allowGuestCheckout", ->
packageRegistry = OfferMarket.Collections.Packages.findOne shopId: OfferMarket.getShopId(), name: 'core'
allowGuest = packageRegistry?.settings?.public?.allowGuestCheckout || false
return allowGuest
###
# activeRouteClass
# return "active" if current path
###
Template.registerHelper "activeRouteClass", ->
args = Array::slice.call(arguments, 0)
args.pop()
active = _.any(args, (name) ->
location.pathname is Router.path(name)
)
return active and "active"
###
# siteName()
# return site name
###
Template.registerHelper "siteName", ->
return Shops.findOne()?.name
###
# methods to return cart calculated values
# cartCount, cartSubTotal, cartShipping, cartTaxes, cartTotal
# are calculated by a transformation on the collection
# and are available to use in template as cart.xxx
# in template: {{cart.cartCount}}
# in code: OfferMarket.Collections.Cart.findOne().cartTotal()
###
Template.registerHelper "cart", () ->
# return true if there is an issue with the user's cart and we should display the warning icon
showCartIconWarning: ->
if @.showLowInventoryWarning()
return true
return false
# return true if any item in the user's cart has a low inventory warning
showLowInventoryWarning: ->
storedCart = Cart.findOne()
if storedCart?.items
for item in storedCart?.items
if item.variants?.inventoryPolicy and item.variants?.lowInventoryWarningThreshold
if (item.variants?.inventoryQuantity <= item.variants.lowInventoryWarningThreshold)
return true
return false
# return true if item variant has a low inventory warning
showItemLowInventoryWarning: (variant) ->
if variant?.inventoryPolicy and variant?.lowInventoryWarningThreshold
if (variant?.inventoryQuantity <= variant.lowInventoryWarningThreshold)
return true
return false
###
# General helpers for template functionality
###
###
# conditional template helpers
# example: {{#if condition status "eq" ../value}}
###
Template.registerHelper "condition", (v1, operator, v2, options) ->
switch operator
when "==", "eq"
v1 is v2
when "!=", "neq"
v1 isnt v2
when "===", "ideq"
v1 is v2
when "!==", "nideq"
v1 isnt v2
when "&&", "and"
v1 and v2
when "||", "or"
v1 or v2
when "<", "lt"
v1 < v2
when "<=", "lte"
v1 <= v2
when ">", "gt"
v1 > v2
when ">=", "gte"
v1 >= v2
else
throw "Undefined operator \"" + operator + "\""
Template.registerHelper "orElse", (v1, v2) ->
return v1 || v2
Template.registerHelper "key_value", (context, options) ->
result = []
_.each context, (value, key, list) ->
result.push
key: key
value: value
return result
###
# Convert new line (\n\r) to <br>
# from http://phpjs.org/functions/nl2br:480
###
Template.registerHelper "nl2br", (text) ->
nl2br = (text + "").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1" + "<br>" + "$2")
new Spacebars.SafeString(nl2br)
###
# format an ISO date using Moment.js
# http://momentjs.com/
# moment syntax example: moment(Date("2011-07-18T15:50:52")).format("MMMM YYYY")
# usage: {{dateFormat creation_date format="MMMM YYYY"}}
###
Template.registerHelper "dateFormat", (context, block) ->
if window.moment
f = block.hash.format or "MMM DD, YYYY hh:mm:ss A"
return moment(context).format(f) #had to remove Date(context)
else
return context # moment plugin not available. return data as is.
return
###
# general helper for plurization of strings
# returns string with 's' concatenated if n = 1
# TODO: adapt to, and use i18n
###
Template.registerHelper "pluralize", (n, thing) ->
# fairly stupid pluralizer
if n is 1
"1 " + thing
else
n + " " + thing + "s"
###
# general helper to return 'active' when on current path
# returns string\
# handlebars: {{active 'route'}}
###
#Determine if current link should be active
Template.registerHelper "active", (path) ->
# Get the current path for URL
current = Router.current()
routeName = current and current.route.getName()
if routeName is path
return "active"
else
return ""
###
# general helper to return 'active' when on current path
# returns string
# handlebars: {{navLink 'projectsList' 'icon-edit'}}
###
Template.registerHelper "navLink", (page, icon) ->
ret = "<li "
ret += "class='active'" if Meteor.Router.page() is page
ret += "><a href='" + Meteor.Router.namedRoutes[page].path + "'><i class='" + icon + " icon-fixed-width'></i></a></li>"
return new Spacebars.SafeString(ret)
###
#
# reactionApps
#
# provides="<where matching registry provides is this >"
# enabled=true <false for disabled packages>
# context= true filter templates to current route
#
# returns matching package registry objects
#
# TODO:
# - reintroduce a dependency context
# - introduce position,zones #148
# - is it better to get all packages once and filter in code
# and possibly have some cache benefits down the road,
# or to retrieve what is requested and gain the advantage of priviledged,
# unnecessary data not retrieved with the cost of additional requests.
# - context filter should be considered experimental
#
###
Template.registerHelper "reactionApps", (options) ->
packageSubscription = Meteor.subscribe "Packages"
if packageSubscription.ready()
unless options.hash.shopId then options.hash.shopId = OfferMarket.getShopId()
reactionApps = []
filter = {}
registryFilter = {}
# any registry property, name, enabled can be used as filter
for key, value of options.hash
unless key is 'enabled' or key is 'name' or key is 'shopId'
filter['registry.' + key] = value #for query
registryFilter[key] = value #for registry filter
else
filter[key] = value #handle top level filters
# we only need these fields (filtered for user, all available to admin)
fields =
'enabled': 1
'registry': 1
'name': 1
# fetch filtered package
reactionPackages = OfferMarket.Collections.Packages.find(filter, fields).fetch()
# really, this shouldn't ever happen
unless reactionPackages then throw new Error("Packages not loaded.")
# filter packages
# this isn't as elegant as one could wish, review, refactor?
# filter name and enabled as the package level filter
if filter.name and filter.enabled
packages = (pkg for pkg in reactionPackages when pkg.name is filter.name and pkg.enabled is filter.enabled)
else if filter.name
packages = (pkg for pkg in reactionPackages when pkg.name is filter.name)
else if filter.enabled
packages = (pkg for pkg in reactionPackages when pkg.enabled is filter.enabled)
else
packages = (pkg for pkg in reactionPackages)
# filter and reduce, format registry objects
# checks to see that all registry filters are applied to the registry objects
# and pushes to reactionApps
for app in packages
for registry in app.registry
match = 0
for key, value of registryFilter
if registry[key] is value
match += 1
if match is Object.keys(registryFilter).length
registry.name = app.name
# skip false registry entries, even if pkg is enabled
unless registry.enabled is false
registry.enabled = registry.enabled || app.enabled
registry.packageId = app._id
reactionApps.push registry
#
# TODO: add group by provides, sort by cycle, enabled
#
# make sure they are unique,
# add priority for default sort
reactionApps = _.uniq(reactionApps)
for app, index in reactionApps
reactionApps[index].priority = index unless app.priority
# need to sort after?
return reactionApps
| 113914 | ###
#
# Reaction Spacebars helpers
# See: http://docs.meteor.com/#/full/template_registerhelper
#
###
#
# monthOptions
# returns momentjs months formatted for autoform
#
Template.registerHelper "monthOptions", () ->
monthOptions = [{value: "", label: "Choose month"}]
months = moment.months()
for month, index in months
monthOptions.push value: index + 1, label: month
return monthOptions
#
# yearOptions
# returns array of years, formatted for autoform
#
Template.registerHelper "yearOptions", () ->
yearOptions = [{ value: "", label: "Choose year" }]
year = new Date().getFullYear()
for x in [1...9] by 1
yearOptions.push { value: year , label: year}
year++
return yearOptions
#
# timezoneOptions
# returns array of momentjs timezones formatted for autoform
#
Template.registerHelper "timezoneOptions", () ->
timezoneOptions = [{value: "", label: "Choose timezone"}]
timezones = moment.tz.names()
for timezone, index in timezones
timezoneOptions.push value: timezone, label: timezone
return timezoneOptions
#
# gets current cart billing address / payment name
#
Template.registerHelper "cartPayerName", ->
Cart.findOne()?.payment?.address?.fullName
###
# return shop /locale specific formatted price
# also accepts a range formatted with " - "
###
Template.registerHelper "formatPrice", (price) ->
localeDep.depend() # create dependency on localeDep
try
prices = price.split(' - ')
for actualPrice in prices
originalPrice = actualPrice
#TODO Add user services for conversions
if OfferMarket.Locale?.currency?.exchangeRate then actualPrice = actualPrice * OfferMarket.Locale?.currency?.exchangeRate.Rate
formattedPrice = accounting.formatMoney actualPrice, OfferMarket.Locale.currency
price = price.replace(originalPrice, formattedPrice)
catch
if OfferMarket.Locale?.currency?.exchangeRate then price = price * OfferMarket.Locale?.currency?.exchangeRate.Rate
price = accounting.formatMoney price, OfferMarket.Locale?.currency
return price
#
# return path for route
#
Template.registerHelper "pathForSEO", (path, params) ->
if this[params]
return "/"+ path + "/" + this[params]
else
return Router.path path,this
#
# displayName
#
# params user - optional a user object defaults to current user
# returns string user name
#
Template.registerHelper "displayName", (user) ->
userSub = Meteor.subscribe "UserProfile", user?._id || Meteor.userId()
userId = user?._id || Meteor.userId()
if userSub.ready()
user = Meteor.users.findOne(userId) unless user
# every social channel is different
# legacy profile name
if user and user.profile and user.profile.name
return user.profile.name
# meteor user name
else if user and user.username
return user.username
# service names
if user and user.services
username = switch
when user.services.twitter then user.services.twitter.name
when user.services.facebook then user.services.facebook.name
when user.services.instagram then user.services.instagram.name
when user.services.pinterest then user.services.pinterest.name
else "Guest"
#
# general helper user name handling
# TODO: needs additional validation all use cases
# returns first word in profile name
#
Template.registerHelper "fName", (user) ->
userSub = Meteor.subscribe "UserProfile", user?._id || Meteor.userId()
if userSub.ready()
user = Meteor.users.findOne() unless user
# every social channel is different
# legacy profile name
if user and user.profile and user.profile.name
return user.profile.name.split(" ")[0]
else if user and user.username
return user.username.name.split(" ")[0]
# service names
if user and user.services
username = switch
when user.services.twitter then user.services.twitter.first_name
when user.services.facebook then user.services.facebook.first_name
when user.services.instagram then user.services.instagram.first_name
when user.services.pinterest then user.services.pinterest.first_name
else "Guest"
#
# decamelSpace
#
Template.registerHelper "camelToSpace", (str) ->
downCamel = str.replace(/\W+/g, "-").replace /([a-z\d])([A-Z])/g, "$1 $2"
return downCamel.toLowerCase()
#
# upperCase or lowerCase string
#
Template.registerHelper "toLowerCase", (str) ->
return str.toLowerCase()
Template.registerHelper "toUpperCase", (str) ->
return str.toUpperCase()
Template.registerHelper "capitalize", (str) ->
return str.charAt(0).toUpperCase() + str.slice(1)
#
# camelCase string
#
Template.registerHelper "toCamelCase", (str) ->
return str.toCamelCase()
###
# Methods for the reaction permissions
# https://github.com/ongoworks/reaction#rolespermissions-system
# use: {{hasPermissions admin userId}}
###
Template.registerHelper "hasPermission", (permissions, userId) ->
check permissions, Match.OneOf(String, Object)
if typeof(userId) is 'object' then userId = Meteor.userId()
return OfferMarket.hasPermission permissions, userId
Template.registerHelper "hasOwnerAccess", ->
OfferMarket.hasOwnerAccess()
Template.registerHelper "hasAdminAccess", ->
OfferMarket.hasAdminAccess()
Template.registerHelper "hasDashboardAccess", ->
return OfferMarket.hasDashboardAccess()
Template.registerHelper "allowGuestCheckout", ->
packageRegistry = OfferMarket.Collections.Packages.findOne shopId: OfferMarket.getShopId(), name: 'core'
allowGuest = packageRegistry?.settings?.public?.allowGuestCheckout || false
return allowGuest
###
# activeRouteClass
# return "active" if current path
###
Template.registerHelper "activeRouteClass", ->
args = Array::slice.call(arguments, 0)
args.pop()
active = _.any(args, (name) ->
location.pathname is Router.path(name)
)
return active and "active"
###
# siteName()
# return site name
###
Template.registerHelper "siteName", ->
return Shops.findOne()?.name
###
# methods to return cart calculated values
# cartCount, cartSubTotal, cartShipping, cartTaxes, cartTotal
# are calculated by a transformation on the collection
# and are available to use in template as cart.xxx
# in template: {{cart.cartCount}}
# in code: OfferMarket.Collections.Cart.findOne().cartTotal()
###
Template.registerHelper "cart", () ->
# return true if there is an issue with the user's cart and we should display the warning icon
showCartIconWarning: ->
if @.showLowInventoryWarning()
return true
return false
# return true if any item in the user's cart has a low inventory warning
showLowInventoryWarning: ->
storedCart = Cart.findOne()
if storedCart?.items
for item in storedCart?.items
if item.variants?.inventoryPolicy and item.variants?.lowInventoryWarningThreshold
if (item.variants?.inventoryQuantity <= item.variants.lowInventoryWarningThreshold)
return true
return false
# return true if item variant has a low inventory warning
showItemLowInventoryWarning: (variant) ->
if variant?.inventoryPolicy and variant?.lowInventoryWarningThreshold
if (variant?.inventoryQuantity <= variant.lowInventoryWarningThreshold)
return true
return false
###
# General helpers for template functionality
###
###
# conditional template helpers
# example: {{#if condition status "eq" ../value}}
###
Template.registerHelper "condition", (v1, operator, v2, options) ->
switch operator
when "==", "eq"
v1 is v2
when "!=", "neq"
v1 isnt v2
when "===", "ideq"
v1 is v2
when "!==", "nideq"
v1 isnt v2
when "&&", "and"
v1 and v2
when "||", "or"
v1 or v2
when "<", "lt"
v1 < v2
when "<=", "lte"
v1 <= v2
when ">", "gt"
v1 > v2
when ">=", "gte"
v1 >= v2
else
throw "Undefined operator \"" + operator + "\""
Template.registerHelper "orElse", (v1, v2) ->
return v1 || v2
Template.registerHelper "key_value", (context, options) ->
result = []
_.each context, (value, key, list) ->
result.push
key: key
value: value
return result
###
# Convert new line (\n\r) to <br>
# from http://phpjs.org/functions/nl2br:480
###
Template.registerHelper "nl2br", (text) ->
nl2br = (text + "").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1" + "<br>" + "$2")
new Spacebars.SafeString(nl2br)
###
# format an ISO date using Moment.js
# http://momentjs.com/
# moment syntax example: moment(Date("2011-07-18T15:50:52")).format("MMMM YYYY")
# usage: {{dateFormat creation_date format="MMMM YYYY"}}
###
Template.registerHelper "dateFormat", (context, block) ->
if window.moment
f = block.hash.format or "MMM DD, YYYY hh:mm:ss A"
return moment(context).format(f) #had to remove Date(context)
else
return context # moment plugin not available. return data as is.
return
###
# general helper for plurization of strings
# returns string with 's' concatenated if n = 1
# TODO: adapt to, and use i18n
###
Template.registerHelper "pluralize", (n, thing) ->
# fairly stupid pluralizer
if n is 1
"1 " + thing
else
n + " " + thing + "s"
###
# general helper to return 'active' when on current path
# returns string\
# handlebars: {{active 'route'}}
###
#Determine if current link should be active
Template.registerHelper "active", (path) ->
# Get the current path for URL
current = Router.current()
routeName = current and current.route.getName()
if routeName is path
return "active"
else
return ""
###
# general helper to return 'active' when on current path
# returns string
# handlebars: {{navLink 'projectsList' 'icon-edit'}}
###
Template.registerHelper "navLink", (page, icon) ->
ret = "<li "
ret += "class='active'" if Meteor.Router.page() is page
ret += "><a href='" + Meteor.Router.namedRoutes[page].path + "'><i class='" + icon + " icon-fixed-width'></i></a></li>"
return new Spacebars.SafeString(ret)
###
#
# reactionApps
#
# provides="<where matching registry provides is this >"
# enabled=true <false for disabled packages>
# context= true filter templates to current route
#
# returns matching package registry objects
#
# TODO:
# - reintroduce a dependency context
# - introduce position,zones #148
# - is it better to get all packages once and filter in code
# and possibly have some cache benefits down the road,
# or to retrieve what is requested and gain the advantage of priviledged,
# unnecessary data not retrieved with the cost of additional requests.
# - context filter should be considered experimental
#
###
Template.registerHelper "reactionApps", (options) ->
packageSubscription = Meteor.subscribe "Packages"
if packageSubscription.ready()
unless options.hash.shopId then options.hash.shopId = OfferMarket.getShopId()
reactionApps = []
filter = {}
registryFilter = {}
# any registry property, name, enabled can be used as filter
for key, value of options.hash
unless key is 'enabled' or key is '<KEY>' or key is '<KEY>'
filter['registry.' + key] = value #for query
registryFilter[key] = value #for registry filter
else
filter[key] = value #handle top level filters
# we only need these fields (filtered for user, all available to admin)
fields =
'enabled': 1
'registry': 1
'name': 1
# fetch filtered package
reactionPackages = OfferMarket.Collections.Packages.find(filter, fields).fetch()
# really, this shouldn't ever happen
unless reactionPackages then throw new Error("Packages not loaded.")
# filter packages
# this isn't as elegant as one could wish, review, refactor?
# filter name and enabled as the package level filter
if filter.name and filter.enabled
packages = (pkg for pkg in reactionPackages when pkg.name is filter.name and pkg.enabled is filter.enabled)
else if filter.name
packages = (pkg for pkg in reactionPackages when pkg.name is filter.name)
else if filter.enabled
packages = (pkg for pkg in reactionPackages when pkg.enabled is filter.enabled)
else
packages = (pkg for pkg in reactionPackages)
# filter and reduce, format registry objects
# checks to see that all registry filters are applied to the registry objects
# and pushes to reactionApps
for app in packages
for registry in app.registry
match = 0
for key, value of registryFilter
if registry[key] is value
match += 1
if match is Object.keys(registryFilter).length
registry.name = app.name
# skip false registry entries, even if pkg is enabled
unless registry.enabled is false
registry.enabled = registry.enabled || app.enabled
registry.packageId = app._id
reactionApps.push registry
#
# TODO: add group by provides, sort by cycle, enabled
#
# make sure they are unique,
# add priority for default sort
reactionApps = _.uniq(reactionApps)
for app, index in reactionApps
reactionApps[index].priority = index unless app.priority
# need to sort after?
return reactionApps
| true | ###
#
# Reaction Spacebars helpers
# See: http://docs.meteor.com/#/full/template_registerhelper
#
###
#
# monthOptions
# returns momentjs months formatted for autoform
#
Template.registerHelper "monthOptions", () ->
monthOptions = [{value: "", label: "Choose month"}]
months = moment.months()
for month, index in months
monthOptions.push value: index + 1, label: month
return monthOptions
#
# yearOptions
# returns array of years, formatted for autoform
#
Template.registerHelper "yearOptions", () ->
yearOptions = [{ value: "", label: "Choose year" }]
year = new Date().getFullYear()
for x in [1...9] by 1
yearOptions.push { value: year , label: year}
year++
return yearOptions
#
# timezoneOptions
# returns array of momentjs timezones formatted for autoform
#
Template.registerHelper "timezoneOptions", () ->
timezoneOptions = [{value: "", label: "Choose timezone"}]
timezones = moment.tz.names()
for timezone, index in timezones
timezoneOptions.push value: timezone, label: timezone
return timezoneOptions
#
# gets current cart billing address / payment name
#
Template.registerHelper "cartPayerName", ->
Cart.findOne()?.payment?.address?.fullName
###
# return shop /locale specific formatted price
# also accepts a range formatted with " - "
###
Template.registerHelper "formatPrice", (price) ->
localeDep.depend() # create dependency on localeDep
try
prices = price.split(' - ')
for actualPrice in prices
originalPrice = actualPrice
#TODO Add user services for conversions
if OfferMarket.Locale?.currency?.exchangeRate then actualPrice = actualPrice * OfferMarket.Locale?.currency?.exchangeRate.Rate
formattedPrice = accounting.formatMoney actualPrice, OfferMarket.Locale.currency
price = price.replace(originalPrice, formattedPrice)
catch
if OfferMarket.Locale?.currency?.exchangeRate then price = price * OfferMarket.Locale?.currency?.exchangeRate.Rate
price = accounting.formatMoney price, OfferMarket.Locale?.currency
return price
#
# return path for route
#
Template.registerHelper "pathForSEO", (path, params) ->
if this[params]
return "/"+ path + "/" + this[params]
else
return Router.path path,this
#
# displayName
#
# params user - optional a user object defaults to current user
# returns string user name
#
Template.registerHelper "displayName", (user) ->
userSub = Meteor.subscribe "UserProfile", user?._id || Meteor.userId()
userId = user?._id || Meteor.userId()
if userSub.ready()
user = Meteor.users.findOne(userId) unless user
# every social channel is different
# legacy profile name
if user and user.profile and user.profile.name
return user.profile.name
# meteor user name
else if user and user.username
return user.username
# service names
if user and user.services
username = switch
when user.services.twitter then user.services.twitter.name
when user.services.facebook then user.services.facebook.name
when user.services.instagram then user.services.instagram.name
when user.services.pinterest then user.services.pinterest.name
else "Guest"
#
# general helper user name handling
# TODO: needs additional validation all use cases
# returns first word in profile name
#
Template.registerHelper "fName", (user) ->
userSub = Meteor.subscribe "UserProfile", user?._id || Meteor.userId()
if userSub.ready()
user = Meteor.users.findOne() unless user
# every social channel is different
# legacy profile name
if user and user.profile and user.profile.name
return user.profile.name.split(" ")[0]
else if user and user.username
return user.username.name.split(" ")[0]
# service names
if user and user.services
username = switch
when user.services.twitter then user.services.twitter.first_name
when user.services.facebook then user.services.facebook.first_name
when user.services.instagram then user.services.instagram.first_name
when user.services.pinterest then user.services.pinterest.first_name
else "Guest"
#
# decamelSpace
#
Template.registerHelper "camelToSpace", (str) ->
downCamel = str.replace(/\W+/g, "-").replace /([a-z\d])([A-Z])/g, "$1 $2"
return downCamel.toLowerCase()
#
# upperCase or lowerCase string
#
Template.registerHelper "toLowerCase", (str) ->
return str.toLowerCase()
Template.registerHelper "toUpperCase", (str) ->
return str.toUpperCase()
Template.registerHelper "capitalize", (str) ->
return str.charAt(0).toUpperCase() + str.slice(1)
#
# camelCase string
#
Template.registerHelper "toCamelCase", (str) ->
return str.toCamelCase()
###
# Methods for the reaction permissions
# https://github.com/ongoworks/reaction#rolespermissions-system
# use: {{hasPermissions admin userId}}
###
Template.registerHelper "hasPermission", (permissions, userId) ->
check permissions, Match.OneOf(String, Object)
if typeof(userId) is 'object' then userId = Meteor.userId()
return OfferMarket.hasPermission permissions, userId
Template.registerHelper "hasOwnerAccess", ->
OfferMarket.hasOwnerAccess()
Template.registerHelper "hasAdminAccess", ->
OfferMarket.hasAdminAccess()
Template.registerHelper "hasDashboardAccess", ->
return OfferMarket.hasDashboardAccess()
Template.registerHelper "allowGuestCheckout", ->
packageRegistry = OfferMarket.Collections.Packages.findOne shopId: OfferMarket.getShopId(), name: 'core'
allowGuest = packageRegistry?.settings?.public?.allowGuestCheckout || false
return allowGuest
###
# activeRouteClass
# return "active" if current path
###
Template.registerHelper "activeRouteClass", ->
args = Array::slice.call(arguments, 0)
args.pop()
active = _.any(args, (name) ->
location.pathname is Router.path(name)
)
return active and "active"
###
# siteName()
# return site name
###
Template.registerHelper "siteName", ->
return Shops.findOne()?.name
###
# methods to return cart calculated values
# cartCount, cartSubTotal, cartShipping, cartTaxes, cartTotal
# are calculated by a transformation on the collection
# and are available to use in template as cart.xxx
# in template: {{cart.cartCount}}
# in code: OfferMarket.Collections.Cart.findOne().cartTotal()
###
Template.registerHelper "cart", () ->
# return true if there is an issue with the user's cart and we should display the warning icon
showCartIconWarning: ->
if @.showLowInventoryWarning()
return true
return false
# return true if any item in the user's cart has a low inventory warning
showLowInventoryWarning: ->
storedCart = Cart.findOne()
if storedCart?.items
for item in storedCart?.items
if item.variants?.inventoryPolicy and item.variants?.lowInventoryWarningThreshold
if (item.variants?.inventoryQuantity <= item.variants.lowInventoryWarningThreshold)
return true
return false
# return true if item variant has a low inventory warning
showItemLowInventoryWarning: (variant) ->
if variant?.inventoryPolicy and variant?.lowInventoryWarningThreshold
if (variant?.inventoryQuantity <= variant.lowInventoryWarningThreshold)
return true
return false
###
# General helpers for template functionality
###
###
# conditional template helpers
# example: {{#if condition status "eq" ../value}}
###
Template.registerHelper "condition", (v1, operator, v2, options) ->
switch operator
when "==", "eq"
v1 is v2
when "!=", "neq"
v1 isnt v2
when "===", "ideq"
v1 is v2
when "!==", "nideq"
v1 isnt v2
when "&&", "and"
v1 and v2
when "||", "or"
v1 or v2
when "<", "lt"
v1 < v2
when "<=", "lte"
v1 <= v2
when ">", "gt"
v1 > v2
when ">=", "gte"
v1 >= v2
else
throw "Undefined operator \"" + operator + "\""
Template.registerHelper "orElse", (v1, v2) ->
return v1 || v2
Template.registerHelper "key_value", (context, options) ->
result = []
_.each context, (value, key, list) ->
result.push
key: key
value: value
return result
###
# Convert new line (\n\r) to <br>
# from http://phpjs.org/functions/nl2br:480
###
Template.registerHelper "nl2br", (text) ->
nl2br = (text + "").replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, "$1" + "<br>" + "$2")
new Spacebars.SafeString(nl2br)
###
# format an ISO date using Moment.js
# http://momentjs.com/
# moment syntax example: moment(Date("2011-07-18T15:50:52")).format("MMMM YYYY")
# usage: {{dateFormat creation_date format="MMMM YYYY"}}
###
Template.registerHelper "dateFormat", (context, block) ->
if window.moment
f = block.hash.format or "MMM DD, YYYY hh:mm:ss A"
return moment(context).format(f) #had to remove Date(context)
else
return context # moment plugin not available. return data as is.
return
###
# general helper for plurization of strings
# returns string with 's' concatenated if n = 1
# TODO: adapt to, and use i18n
###
Template.registerHelper "pluralize", (n, thing) ->
# fairly stupid pluralizer
if n is 1
"1 " + thing
else
n + " " + thing + "s"
###
# general helper to return 'active' when on current path
# returns string\
# handlebars: {{active 'route'}}
###
#Determine if current link should be active
Template.registerHelper "active", (path) ->
# Get the current path for URL
current = Router.current()
routeName = current and current.route.getName()
if routeName is path
return "active"
else
return ""
###
# general helper to return 'active' when on current path
# returns string
# handlebars: {{navLink 'projectsList' 'icon-edit'}}
###
Template.registerHelper "navLink", (page, icon) ->
ret = "<li "
ret += "class='active'" if Meteor.Router.page() is page
ret += "><a href='" + Meteor.Router.namedRoutes[page].path + "'><i class='" + icon + " icon-fixed-width'></i></a></li>"
return new Spacebars.SafeString(ret)
###
#
# reactionApps
#
# provides="<where matching registry provides is this >"
# enabled=true <false for disabled packages>
# context= true filter templates to current route
#
# returns matching package registry objects
#
# TODO:
# - reintroduce a dependency context
# - introduce position,zones #148
# - is it better to get all packages once and filter in code
# and possibly have some cache benefits down the road,
# or to retrieve what is requested and gain the advantage of priviledged,
# unnecessary data not retrieved with the cost of additional requests.
# - context filter should be considered experimental
#
###
Template.registerHelper "reactionApps", (options) ->
packageSubscription = Meteor.subscribe "Packages"
if packageSubscription.ready()
unless options.hash.shopId then options.hash.shopId = OfferMarket.getShopId()
reactionApps = []
filter = {}
registryFilter = {}
# any registry property, name, enabled can be used as filter
for key, value of options.hash
unless key is 'enabled' or key is 'PI:KEY:<KEY>END_PI' or key is 'PI:KEY:<KEY>END_PI'
filter['registry.' + key] = value #for query
registryFilter[key] = value #for registry filter
else
filter[key] = value #handle top level filters
# we only need these fields (filtered for user, all available to admin)
fields =
'enabled': 1
'registry': 1
'name': 1
# fetch filtered package
reactionPackages = OfferMarket.Collections.Packages.find(filter, fields).fetch()
# really, this shouldn't ever happen
unless reactionPackages then throw new Error("Packages not loaded.")
# filter packages
# this isn't as elegant as one could wish, review, refactor?
# filter name and enabled as the package level filter
if filter.name and filter.enabled
packages = (pkg for pkg in reactionPackages when pkg.name is filter.name and pkg.enabled is filter.enabled)
else if filter.name
packages = (pkg for pkg in reactionPackages when pkg.name is filter.name)
else if filter.enabled
packages = (pkg for pkg in reactionPackages when pkg.enabled is filter.enabled)
else
packages = (pkg for pkg in reactionPackages)
# filter and reduce, format registry objects
# checks to see that all registry filters are applied to the registry objects
# and pushes to reactionApps
for app in packages
for registry in app.registry
match = 0
for key, value of registryFilter
if registry[key] is value
match += 1
if match is Object.keys(registryFilter).length
registry.name = app.name
# skip false registry entries, even if pkg is enabled
unless registry.enabled is false
registry.enabled = registry.enabled || app.enabled
registry.packageId = app._id
reactionApps.push registry
#
# TODO: add group by provides, sort by cycle, enabled
#
# make sure they are unique,
# add priority for default sort
reactionApps = _.uniq(reactionApps)
for app, index in reactionApps
reactionApps[index].priority = index unless app.priority
# need to sort after?
return reactionApps
|
[
{
"context": "nstructor: ->\n\nclass @IrcGatewayApp\n fullname = \"Irc Gateway\"\n description = \"Irc Gateway to freenode\"\n @ico",
"end": 816,
"score": 0.9373502135276794,
"start": 805,
"tag": "NAME",
"value": "Irc Gateway"
},
{
"context": "eenode\"\n @icon = \"qwebircsmall.pn... | app/assets/javascripts/ircgatewayapp.js.coffee | CoffeeDesktop/coffeedesktop-rails | 0 | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require localstorage
#= require usecase
#= require glue
#= require gui
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
class Glue extends @GlueClass
class Gui extends @GuiClass
createWindow: (title=false,id=false) =>
rand=UUIDjs.randomUI48()
id=UUIDjs.randomUI48() if !id #if undefined just throw sth random
title = "You ARE LAZY" if !title #if undefined set sth stupid
divid = rand+"-"+id
$.newWindow({id:divid,title:title,type:"iframe", width:647, height:400})
$.updateWindowContent(divid,'<iframe src="http://webchat.freenode.net?channels=CoffeeDesktop&uio=d4" width="647" height="400"></iframe>');
constructor: ->
class @IrcGatewayApp
fullname = "Irc Gateway"
description = "Irc Gateway to freenode"
@icon = "qwebircsmall.png"
@fullname = fullname
@description = description
constructor: (id, params)->
@id = id
@fullname = fullname
@description = description
@fullname = "Irc Gateway"
@description = "Irc Gateway to freenode"
useCase = new UseCase()
gui = new Gui()
localStorage = new LocalStorage("CoffeeDesktop")
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, gui, localStorage,this)
# ^ this this is this ugly this
useCase.start()
window.CoffeeDesktop.appAdd('irc',@IrcGatewayApp) | 154993 | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require localstorage
#= require usecase
#= require glue
#= require gui
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
class Glue extends @GlueClass
class Gui extends @GuiClass
createWindow: (title=false,id=false) =>
rand=UUIDjs.randomUI48()
id=UUIDjs.randomUI48() if !id #if undefined just throw sth random
title = "You ARE LAZY" if !title #if undefined set sth stupid
divid = rand+"-"+id
$.newWindow({id:divid,title:title,type:"iframe", width:647, height:400})
$.updateWindowContent(divid,'<iframe src="http://webchat.freenode.net?channels=CoffeeDesktop&uio=d4" width="647" height="400"></iframe>');
constructor: ->
class @IrcGatewayApp
fullname = "<NAME>"
description = "Irc Gateway to freenode"
@icon = "qwebircsmall.png"
@fullname = <NAME>
@description = description
constructor: (id, params)->
@id = id
@fullname = <NAME>
@description = description
@fullname = "<NAME>"
@description = "Irc Gateway to freenode"
useCase = new UseCase()
gui = new Gui()
localStorage = new LocalStorage("CoffeeDesktop")
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, gui, localStorage,this)
# ^ this this is this ugly this
useCase.start()
window.CoffeeDesktop.appAdd('irc',@IrcGatewayApp) | true | #Warning: This code contains ugly this
#Warning: You have been warned about this
#= require localstorage
#= require usecase
#= require glue
#= require gui
class LocalStorage extends @LocalStorageClass
class UseCase extends @UseCaseClass
class Glue extends @GlueClass
class Gui extends @GuiClass
createWindow: (title=false,id=false) =>
rand=UUIDjs.randomUI48()
id=UUIDjs.randomUI48() if !id #if undefined just throw sth random
title = "You ARE LAZY" if !title #if undefined set sth stupid
divid = rand+"-"+id
$.newWindow({id:divid,title:title,type:"iframe", width:647, height:400})
$.updateWindowContent(divid,'<iframe src="http://webchat.freenode.net?channels=CoffeeDesktop&uio=d4" width="647" height="400"></iframe>');
constructor: ->
class @IrcGatewayApp
fullname = "PI:NAME:<NAME>END_PI"
description = "Irc Gateway to freenode"
@icon = "qwebircsmall.png"
@fullname = PI:NAME:<NAME>END_PI
@description = description
constructor: (id, params)->
@id = id
@fullname = PI:NAME:<NAME>END_PI
@description = description
@fullname = "PI:NAME:<NAME>END_PI"
@description = "Irc Gateway to freenode"
useCase = new UseCase()
gui = new Gui()
localStorage = new LocalStorage("CoffeeDesktop")
#probably this under this line is temporary this because this isnt on the path of truth
glue = new Glue(useCase, gui, localStorage,this)
# ^ this this is this ugly this
useCase.start()
window.CoffeeDesktop.appAdd('irc',@IrcGatewayApp) |
[
{
"context": "mparisons\nshow '--- String comparisons ---'\nshow 'Aardvark' < 'Zoroaster'\nshow 'Itchy' != 'Scratchy'\n\n# Logi",
"end": 1526,
"score": 0.6957703828811646,
"start": 1518,
"tag": "NAME",
"value": "Aardvark"
}
] | src-no-solutions/02-BasicCoffeeScript.coffee | autotelicum/Smooth-CoffeeScript | 66 | require './prelude'
# Number formats
show '--- Number formats ---'
show 144
show 144.toString 2
show 9.81
show 2.998e8
# Rounding errors
show '--- Rounding errors ---'
p = 1/3
show 6*p is 2
show p+p+p+p+p+p is 2
show 2-1e-15 < p+p+p+p+p+p < 2+1e-15
# Rounding errors accumulate in loops
i = 0
i++ for angle in [0...2*Math.PI] by 1/3*Math.PI
show i # Gives 7 iterations and not 6
# Arithmetic operators
show '--- Arithmetic operators ---'
show 100 + 4 * 11
show (100 + 4) * 11
show 115 * 4 - 4 + 88 / 2
show 314 % 100
show 10 % 3
show 144 % 12
# String types
show '--- String types ---'
show 'Patch my boat with chewing gum.'
show 'The programmer pondered: "0x2b or not 0x2b"'
show "Aha! It's 43 if I'm not a bit off"
show "2 + 2 is equal to #{2 + 2}"
show 'Imagine if this was a
very long line of text'
show '''First comes A
then comes B'''
show """ 1
+ 1
--- # " The next line confuses docco
#{1 + 1}"""
# Escape characters
show '--- Escape characters ---'
show 'This is the first line\nAnd this is the second'
show 'A newline character is written like \"\\n\".'
show 'con' + 'cat' + 'e' + 'nate'
# String description of a type
show '--- String description of a type ---'
show typeof 4.5
# Unary minus
show '--- Unary minus ---'
show -(10 - 2)
# Booleans
show '--- Booleans ---'
show 3 > 2
show 3 < 2
# Chained comparisons
show '--- Chained comparisons ---'
show 100 < 115 < 200
show 100 < 315 < 200
# String comparisons
show '--- String comparisons ---'
show 'Aardvark' < 'Zoroaster'
show 'Itchy' != 'Scratchy'
# Logical operators
show '--- Logical operators ---'
show true and false
show true or false
show !true
show not false
# Exercise 1
show '--- Exercise 1 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Useless program
show '--- Useless program ---'
1; !false
show 'Nothing was intentionally output'
# Variables
show '--- Variables ---'
caught = 5 * 5
show caught
show caught + 1
caught = 4 * 4
show caught
# Tentacles
show '--- Tentacles ---'
luigiDebt = 140
luigiDebt = luigiDebt - 35
show luigiDebt
# Environment
show '--- Environment ---'
# To show the environment, use: show global or show window
show 'Also, your hair is on fire.'
# Function invocation
show '--- Function invocation ---'
show Math.max 2, 4
show 100 + Math.max 7, 4
show Math.max(7, 4) + 100
show Math.max(7, 4 + 100)
show Math.max 7, 4 + 100
# Explore the environment - Try this in the REPL
# show process
# show console
# show _
# show show
# Questions
show '--- Questions ---'
# chain is required here to wait for the answer
confirm 'Shall we, then?', (answer) -> show answer; chain1()
chain1 = ->
prompt 'Tell us everything you know.', '...',
(answer) -> show 'So you know: ' + answer; chain2()
chain2 = ->
prompt 'Pick a number', '', (answer) ->
theNumber = Number answer
show 'Your number is the square root of ' +
(theNumber * theNumber)
chain3()
chain3 = ->
# While loops
show '--- While loops ---'
show 0
show 2
show 4
show 6
show 8
show 10
show 12
currentNumber = 0
while currentNumber <= 12
show currentNumber
currentNumber = currentNumber + 2
counter = 0
while counter <= 12 then counter = counter + 2
# Exercise 2
show '--- Exercise 2 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Exercise 3
show '--- Exercise 3 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Sneak peek at Functional solutions
show '--- Sneak peek at Functional solutions ---'
show _.reduce [1..10], ((x) -> 2*x), 1
_.reduce [1..10], ((s) -> show s += '#'), ''
# For loops
show '--- For loops ---'
show 'For on one line'
for number in [0..12] by 2 then show number
show 'For with indented body'
for number in [0..12] by 2
show number
show 'For with prepended body'
show number for number in [0..12] by 2
show 'For collecting results'
numbers = (number for number in [0..12] by 2)
show numbers
# Comments
show '--- Comments ---'
# The variable counter, which is about to be defined,
# is going to start with a value of 0, which is zero.
counter = 0
# Now, we are going to loop, hold on to your hat.
while counter < 100 # counter is less than one hundred
###
Every time we loop, we INCREMENT the value of counter
Seriously, we just add one to it.
###
counter++
# And then, we are done.
# Exercise 4
show '--- Exercise 4 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Conditionals
show '--- Conditionals ---'
for counter in [0..20]
if counter % 3 == 0 and counter % 4 == 0
show counter
for counter in [0..20]
if counter % 4 == 0
show counter
if counter % 4 != 0
show '(' + counter + ')'
for counter in [0..20]
if counter % 4 == 0
show counter
else
show '(' + counter + ')'
for counter in [0..20]
if counter > 15
show counter + '**'
else if counter > 10
show counter + '*'
else
show counter
# Exercise 5
show '--- Exercise 5 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
chain4 = ->
# If variation
show '--- If variation ---'
fun = on
show 'The show is on!' unless fun is off
# Loop variations
show '--- Loop variations ---'
current = 20
loop
if current % 7 == 0
break
current++
show current
current = 20
current++ until current % 7 == 0
show current
# Exercise 6
show '--- Exercise 6 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Undefined variable
show '--- Undefined variable ---'
show mysteryVariable
mysteryVariable = 'nothing'
show console.log 'I am a side effect.'
# Existential operator
show '--- Existential operator ---'
show iam ? undefined
iam ?= 'I want to be'
show iam
iam ?= 'I am already'
show iam if iam?
# Type conversions
show '--- Type conversions ---'
show false == 0
show '' == 0
show '5' == 5
# String type conversions
show '--- String type conversions ---'
show 'Apollo' + 5
show null + 'ify'
show '5' * 5
show 'strawberry' * 5
show Number('5') * 5
# NaN
show '--- NaN ---'
show NaN == NaN
# Boolean type conversions
show '--- Boolean type conversions ---'
prompt 'What is your name?', '',
(input) ->
show 'Well hello ' + (input || 'dear')
chain5()
chain5 = ->
# Short circuit operators
show '--- Short circuit operators ---'
false || show 'I am happening!'
true || show 'Not me.'
# Exit from the chain of inputs
process.exit()
| 137781 | require './prelude'
# Number formats
show '--- Number formats ---'
show 144
show 144.toString 2
show 9.81
show 2.998e8
# Rounding errors
show '--- Rounding errors ---'
p = 1/3
show 6*p is 2
show p+p+p+p+p+p is 2
show 2-1e-15 < p+p+p+p+p+p < 2+1e-15
# Rounding errors accumulate in loops
i = 0
i++ for angle in [0...2*Math.PI] by 1/3*Math.PI
show i # Gives 7 iterations and not 6
# Arithmetic operators
show '--- Arithmetic operators ---'
show 100 + 4 * 11
show (100 + 4) * 11
show 115 * 4 - 4 + 88 / 2
show 314 % 100
show 10 % 3
show 144 % 12
# String types
show '--- String types ---'
show 'Patch my boat with chewing gum.'
show 'The programmer pondered: "0x2b or not 0x2b"'
show "Aha! It's 43 if I'm not a bit off"
show "2 + 2 is equal to #{2 + 2}"
show 'Imagine if this was a
very long line of text'
show '''First comes A
then comes B'''
show """ 1
+ 1
--- # " The next line confuses docco
#{1 + 1}"""
# Escape characters
show '--- Escape characters ---'
show 'This is the first line\nAnd this is the second'
show 'A newline character is written like \"\\n\".'
show 'con' + 'cat' + 'e' + 'nate'
# String description of a type
show '--- String description of a type ---'
show typeof 4.5
# Unary minus
show '--- Unary minus ---'
show -(10 - 2)
# Booleans
show '--- Booleans ---'
show 3 > 2
show 3 < 2
# Chained comparisons
show '--- Chained comparisons ---'
show 100 < 115 < 200
show 100 < 315 < 200
# String comparisons
show '--- String comparisons ---'
show '<NAME>' < 'Zoroaster'
show 'Itchy' != 'Scratchy'
# Logical operators
show '--- Logical operators ---'
show true and false
show true or false
show !true
show not false
# Exercise 1
show '--- Exercise 1 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Useless program
show '--- Useless program ---'
1; !false
show 'Nothing was intentionally output'
# Variables
show '--- Variables ---'
caught = 5 * 5
show caught
show caught + 1
caught = 4 * 4
show caught
# Tentacles
show '--- Tentacles ---'
luigiDebt = 140
luigiDebt = luigiDebt - 35
show luigiDebt
# Environment
show '--- Environment ---'
# To show the environment, use: show global or show window
show 'Also, your hair is on fire.'
# Function invocation
show '--- Function invocation ---'
show Math.max 2, 4
show 100 + Math.max 7, 4
show Math.max(7, 4) + 100
show Math.max(7, 4 + 100)
show Math.max 7, 4 + 100
# Explore the environment - Try this in the REPL
# show process
# show console
# show _
# show show
# Questions
show '--- Questions ---'
# chain is required here to wait for the answer
confirm 'Shall we, then?', (answer) -> show answer; chain1()
chain1 = ->
prompt 'Tell us everything you know.', '...',
(answer) -> show 'So you know: ' + answer; chain2()
chain2 = ->
prompt 'Pick a number', '', (answer) ->
theNumber = Number answer
show 'Your number is the square root of ' +
(theNumber * theNumber)
chain3()
chain3 = ->
# While loops
show '--- While loops ---'
show 0
show 2
show 4
show 6
show 8
show 10
show 12
currentNumber = 0
while currentNumber <= 12
show currentNumber
currentNumber = currentNumber + 2
counter = 0
while counter <= 12 then counter = counter + 2
# Exercise 2
show '--- Exercise 2 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Exercise 3
show '--- Exercise 3 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Sneak peek at Functional solutions
show '--- Sneak peek at Functional solutions ---'
show _.reduce [1..10], ((x) -> 2*x), 1
_.reduce [1..10], ((s) -> show s += '#'), ''
# For loops
show '--- For loops ---'
show 'For on one line'
for number in [0..12] by 2 then show number
show 'For with indented body'
for number in [0..12] by 2
show number
show 'For with prepended body'
show number for number in [0..12] by 2
show 'For collecting results'
numbers = (number for number in [0..12] by 2)
show numbers
# Comments
show '--- Comments ---'
# The variable counter, which is about to be defined,
# is going to start with a value of 0, which is zero.
counter = 0
# Now, we are going to loop, hold on to your hat.
while counter < 100 # counter is less than one hundred
###
Every time we loop, we INCREMENT the value of counter
Seriously, we just add one to it.
###
counter++
# And then, we are done.
# Exercise 4
show '--- Exercise 4 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Conditionals
show '--- Conditionals ---'
for counter in [0..20]
if counter % 3 == 0 and counter % 4 == 0
show counter
for counter in [0..20]
if counter % 4 == 0
show counter
if counter % 4 != 0
show '(' + counter + ')'
for counter in [0..20]
if counter % 4 == 0
show counter
else
show '(' + counter + ')'
for counter in [0..20]
if counter > 15
show counter + '**'
else if counter > 10
show counter + '*'
else
show counter
# Exercise 5
show '--- Exercise 5 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
chain4 = ->
# If variation
show '--- If variation ---'
fun = on
show 'The show is on!' unless fun is off
# Loop variations
show '--- Loop variations ---'
current = 20
loop
if current % 7 == 0
break
current++
show current
current = 20
current++ until current % 7 == 0
show current
# Exercise 6
show '--- Exercise 6 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Undefined variable
show '--- Undefined variable ---'
show mysteryVariable
mysteryVariable = 'nothing'
show console.log 'I am a side effect.'
# Existential operator
show '--- Existential operator ---'
show iam ? undefined
iam ?= 'I want to be'
show iam
iam ?= 'I am already'
show iam if iam?
# Type conversions
show '--- Type conversions ---'
show false == 0
show '' == 0
show '5' == 5
# String type conversions
show '--- String type conversions ---'
show 'Apollo' + 5
show null + 'ify'
show '5' * 5
show 'strawberry' * 5
show Number('5') * 5
# NaN
show '--- NaN ---'
show NaN == NaN
# Boolean type conversions
show '--- Boolean type conversions ---'
prompt 'What is your name?', '',
(input) ->
show 'Well hello ' + (input || 'dear')
chain5()
chain5 = ->
# Short circuit operators
show '--- Short circuit operators ---'
false || show 'I am happening!'
true || show 'Not me.'
# Exit from the chain of inputs
process.exit()
| true | require './prelude'
# Number formats
show '--- Number formats ---'
show 144
show 144.toString 2
show 9.81
show 2.998e8
# Rounding errors
show '--- Rounding errors ---'
p = 1/3
show 6*p is 2
show p+p+p+p+p+p is 2
show 2-1e-15 < p+p+p+p+p+p < 2+1e-15
# Rounding errors accumulate in loops
i = 0
i++ for angle in [0...2*Math.PI] by 1/3*Math.PI
show i # Gives 7 iterations and not 6
# Arithmetic operators
show '--- Arithmetic operators ---'
show 100 + 4 * 11
show (100 + 4) * 11
show 115 * 4 - 4 + 88 / 2
show 314 % 100
show 10 % 3
show 144 % 12
# String types
show '--- String types ---'
show 'Patch my boat with chewing gum.'
show 'The programmer pondered: "0x2b or not 0x2b"'
show "Aha! It's 43 if I'm not a bit off"
show "2 + 2 is equal to #{2 + 2}"
show 'Imagine if this was a
very long line of text'
show '''First comes A
then comes B'''
show """ 1
+ 1
--- # " The next line confuses docco
#{1 + 1}"""
# Escape characters
show '--- Escape characters ---'
show 'This is the first line\nAnd this is the second'
show 'A newline character is written like \"\\n\".'
show 'con' + 'cat' + 'e' + 'nate'
# String description of a type
show '--- String description of a type ---'
show typeof 4.5
# Unary minus
show '--- Unary minus ---'
show -(10 - 2)
# Booleans
show '--- Booleans ---'
show 3 > 2
show 3 < 2
# Chained comparisons
show '--- Chained comparisons ---'
show 100 < 115 < 200
show 100 < 315 < 200
# String comparisons
show '--- String comparisons ---'
show 'PI:NAME:<NAME>END_PI' < 'Zoroaster'
show 'Itchy' != 'Scratchy'
# Logical operators
show '--- Logical operators ---'
show true and false
show true or false
show !true
show not false
# Exercise 1
show '--- Exercise 1 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Useless program
show '--- Useless program ---'
1; !false
show 'Nothing was intentionally output'
# Variables
show '--- Variables ---'
caught = 5 * 5
show caught
show caught + 1
caught = 4 * 4
show caught
# Tentacles
show '--- Tentacles ---'
luigiDebt = 140
luigiDebt = luigiDebt - 35
show luigiDebt
# Environment
show '--- Environment ---'
# To show the environment, use: show global or show window
show 'Also, your hair is on fire.'
# Function invocation
show '--- Function invocation ---'
show Math.max 2, 4
show 100 + Math.max 7, 4
show Math.max(7, 4) + 100
show Math.max(7, 4 + 100)
show Math.max 7, 4 + 100
# Explore the environment - Try this in the REPL
# show process
# show console
# show _
# show show
# Questions
show '--- Questions ---'
# chain is required here to wait for the answer
confirm 'Shall we, then?', (answer) -> show answer; chain1()
chain1 = ->
prompt 'Tell us everything you know.', '...',
(answer) -> show 'So you know: ' + answer; chain2()
chain2 = ->
prompt 'Pick a number', '', (answer) ->
theNumber = Number answer
show 'Your number is the square root of ' +
(theNumber * theNumber)
chain3()
chain3 = ->
# While loops
show '--- While loops ---'
show 0
show 2
show 4
show 6
show 8
show 10
show 12
currentNumber = 0
while currentNumber <= 12
show currentNumber
currentNumber = currentNumber + 2
counter = 0
while counter <= 12 then counter = counter + 2
# Exercise 2
show '--- Exercise 2 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Exercise 3
show '--- Exercise 3 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Sneak peek at Functional solutions
show '--- Sneak peek at Functional solutions ---'
show _.reduce [1..10], ((x) -> 2*x), 1
_.reduce [1..10], ((s) -> show s += '#'), ''
# For loops
show '--- For loops ---'
show 'For on one line'
for number in [0..12] by 2 then show number
show 'For with indented body'
for number in [0..12] by 2
show number
show 'For with prepended body'
show number for number in [0..12] by 2
show 'For collecting results'
numbers = (number for number in [0..12] by 2)
show numbers
# Comments
show '--- Comments ---'
# The variable counter, which is about to be defined,
# is going to start with a value of 0, which is zero.
counter = 0
# Now, we are going to loop, hold on to your hat.
while counter < 100 # counter is less than one hundred
###
Every time we loop, we INCREMENT the value of counter
Seriously, we just add one to it.
###
counter++
# And then, we are done.
# Exercise 4
show '--- Exercise 4 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Conditionals
show '--- Conditionals ---'
for counter in [0..20]
if counter % 3 == 0 and counter % 4 == 0
show counter
for counter in [0..20]
if counter % 4 == 0
show counter
if counter % 4 != 0
show '(' + counter + ')'
for counter in [0..20]
if counter % 4 == 0
show counter
else
show '(' + counter + ')'
for counter in [0..20]
if counter > 15
show counter + '**'
else if counter > 10
show counter + '*'
else
show counter
# Exercise 5
show '--- Exercise 5 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
chain4 = ->
# If variation
show '--- If variation ---'
fun = on
show 'The show is on!' unless fun is off
# Loop variations
show '--- Loop variations ---'
current = 20
loop
if current % 7 == 0
break
current++
show current
current = 20
current++ until current % 7 == 0
show current
# Exercise 6
show '--- Exercise 6 ---'
process.exit() # Replace this line with your solution
show '--- End of Exercise ---'
# Undefined variable
show '--- Undefined variable ---'
show mysteryVariable
mysteryVariable = 'nothing'
show console.log 'I am a side effect.'
# Existential operator
show '--- Existential operator ---'
show iam ? undefined
iam ?= 'I want to be'
show iam
iam ?= 'I am already'
show iam if iam?
# Type conversions
show '--- Type conversions ---'
show false == 0
show '' == 0
show '5' == 5
# String type conversions
show '--- String type conversions ---'
show 'Apollo' + 5
show null + 'ify'
show '5' * 5
show 'strawberry' * 5
show Number('5') * 5
# NaN
show '--- NaN ---'
show NaN == NaN
# Boolean type conversions
show '--- Boolean type conversions ---'
prompt 'What is your name?', '',
(input) ->
show 'Well hello ' + (input || 'dear')
chain5()
chain5 = ->
# Short circuit operators
show '--- Short circuit operators ---'
false || show 'I am happening!'
true || show 'Not me.'
# Exit from the chain of inputs
process.exit()
|
[
{
"context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L",
"end": 35,
"score": 0.9998763203620911,
"start": 21,
"tag": "NAME",
"value": "JeongHoon Byun"
},
{
"context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.o... | test/parser/ruby-parser.test.coffee | uppalapatisujitha/CodingConventionofCommitHistory | 421 | # Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/ruby-parser'
describe 'ruby-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'a = 1;', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check space indent #4', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\ta = 1;', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\ta = 1;', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t a = 1; ', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \ta = 1;', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'a = 1;', {}
convention.indent.tab.should.equal 0
describe 'linelength >', ->
it 'line length is 80 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #3', ->
convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 0
it 'line length is 120 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #3', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char120.should.equal 0
it 'line length is 150 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {}
convention.linelength.char150.should.equal 1
describe 'whitespace >', ->
it 'one whitespace #1', ->
convention = parser.whitespace 'sum = 1 + 2', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #2', ->
convention = parser.whitespace 'a, b = 1, 2', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #3', ->
convention = parser.whitespace "1 > 2 ? true : false; puts 'Hi'", {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #4', ->
convention = parser.whitespace "[1, 2, 3].each { |e| puts e }", {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #5', ->
convention = parser.whitespace '[1, 2, 3].each {|e| puts e }', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #6', ->
convention = parser.whitespace 'sum = 1+2', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #7', ->
convention = parser.whitespace 'sum = "1+2"', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #8', ->
convention = parser.whitespace 'a, b = 1,2', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #9', ->
convention = parser.whitespace 'a, b = 1, 2;', {}
convention.whitespace.spaces.should.equal 1
it 'no whitespace #1', ->
convention = parser.whitespace 'sum = 1 +2', {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #2', ->
convention = parser.whitespace 'a,b = 1, 2', {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #3', ->
convention = parser.whitespace "1>2 ? true : false;puts 'Hi'", {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #4', ->
convention = parser.whitespace "[1, 2, 3].each {|e| puts e}", {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #5', ->
convention = parser.whitespace 'sum = 1 + 2', {}
convention.whitespace.nospace.should.equal 0
it 'no whitespace #6', ->
convention = parser.whitespace 'a, b = 1, 2;c', {}
convention.whitespace.nospace.should.equal 1
describe 'asignDefaultValue >', ->
it 'use spaces #1', ->
convention = parser.asignDefaultValue 'def some_method(arg1 = :default)', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #2', ->
convention = parser.asignDefaultValue ' def some_method(arg2 = nil)', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #3', ->
convention = parser.asignDefaultValue 'def some_method( arg3 = [] )', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #4', ->
convention = parser.asignDefaultValue 'def some_method(arg1 = :default, arg2 = nil, arg3 = [])', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #5', ->
convention = parser.asignDefaultValue 'def some_method(arg3)', {}
convention.asignDefaultValue.space.should.equal 0
it 'use spaces #6', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default)', {}
convention.asignDefaultValue.space.should.equal 0
it 'no spaces #1', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default)', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #2', ->
convention = parser.asignDefaultValue ' def some_method(arg2=nil)', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #3', ->
convention = parser.asignDefaultValue 'def some_method( arg3=[] )', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #4', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default, arg2=nil, arg3=[])', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #5', ->
convention = parser.asignDefaultValue 'def some_method( arg3 = [] )', {}
convention.asignDefaultValue.nospace.should.equal 0
it 'no spaces #6', ->
convention = parser.asignDefaultValue 'def some_method(arg3)', {}
convention.asignDefaultValue.nospace.should.equal 0
describe 'numericLiteral >', ->
it 'use underscore #1', ->
convention = parser.numericLiteral 'num = 1_000_000', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #2', ->
convention = parser.numericLiteral 'num = 7_473', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #3', ->
convention = parser.numericLiteral 'num = 34_000_000', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #4', ->
convention = parser.numericLiteral 'str = "404_094"', {}
convention.numericLiteral.underscore.should.equal 0
it 'use underscore #5', ->
convention = parser.numericLiteral 'num = 438958', {}
convention.numericLiteral.underscore.should.equal 0
it 'use underscore #6', ->
convention = parser.numericLiteral 'num = 958', {}
convention.numericLiteral.underscore.should.equal 0
it 'use no underscore #1', ->
convention = parser.numericLiteral 'num = 1000000', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #2', ->
convention = parser.numericLiteral 'num = 438958', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #3', ->
convention = parser.numericLiteral 'num = 584058', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #4', ->
convention = parser.numericLiteral 'num = 504', {}
convention.numericLiteral.nounderscore.should.equal 0
it 'use no underscore #5', ->
convention = parser.numericLiteral 'str = "404094"', {}
convention.numericLiteral.nounderscore.should.equal 0
it 'use no underscore #6', ->
convention = parser.numericLiteral 'num = 584_058', {}
convention.numericLiteral.nounderscore.should.equal 0
describe 'defNoArgs >', ->
it 'omit parenthenes #1', ->
convention = parser.defNoArgs ' def some_method', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #2', ->
convention = parser.defNoArgs ' def some_method # comment', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #3', ->
convention = parser.defNoArgs ' def some_method # comment()', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #4', ->
convention = parser.defNoArgs ' def some_method()', {}
convention.defNoArgs.omit.should.equal 0
it 'omit parenthenes #5', ->
convention = parser.defNoArgs ' def some_method arg1, arg2', {}
convention.defNoArgs.omit.should.equal 0
it 'omit parenthenes #6', ->
convention = parser.defNoArgs ' def some_method arg1', {}
convention.defNoArgs.omit.should.equal 0
it 'use parenthenes #1', ->
convention = parser.defNoArgs ' def some_method()', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #2', ->
convention = parser.defNoArgs ' def some_method ()', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #3', ->
convention = parser.defNoArgs ' def some_method ( )', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #4', ->
convention = parser.defNoArgs ' def some_method # comment()', {}
convention.defNoArgs.use.should.equal 0
it 'use parenthenes #5', ->
convention = parser.defNoArgs ' def some_method(arg)', {}
convention.defNoArgs.use.should.equal 0
describe 'defArgs >', ->
it 'omit parenthenes #1', ->
convention = parser.defArgs ' def some_method arg1, arg2', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #1', ->
convention = parser.defArgs ' def some_method arg1', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #3', ->
convention = parser.defArgs ' def some_method arg1, arg2 # fjeofjeo( arg1, arg2)', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #4', ->
convention = parser.defArgs 'def some_method()', {}
convention.defArgs.omit.should.equal 0
it 'omit parenthenes #5', ->
convention = parser.defArgs 'def some_method(arg1, arg2)', {}
convention.defArgs.omit.should.equal 0
it 'omit parenthenes #6', ->
convention = parser.defArgs 'def some_method', {}
convention.defArgs.omit.should.equal 0
it 'use parenthenes #1', ->
convention = parser.defArgs ' def some_method( arg1, arg2)', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #2', ->
convention = parser.defArgs ' def some_method ( arg1 )', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #3', ->
convention = parser.defArgs ' def some_method ( arg1, arg2 )', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #4', ->
convention = parser.defArgs 'def some_method arg1, arg2', {}
convention.defArgs.use.should.equal 0
it 'use parenthenes #5', ->
convention = parser.defArgs 'def some_method()', {}
convention.defArgs.use.should.equal 0
it 'use parenthenes #6', ->
convention = parser.defArgs 'def update_requirements(features, group_overrides, init_git_url=nil, user_env_vars=nil)', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #7', ->
convention = parser.defArgs 'def some_method', {}
convention.defArgs.use.should.equal 0
| 1610 | # Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/ruby-parser'
describe 'ruby-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'a = 1;', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check space indent #4', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\ta = 1;', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\ta = 1;', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t a = 1; ', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \ta = 1;', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'a = 1;', {}
convention.indent.tab.should.equal 0
describe 'linelength >', ->
it 'line length is 80 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #3', ->
convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 0
it 'line length is 120 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #3', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char120.should.equal 0
it 'line length is 150 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {}
convention.linelength.char150.should.equal 1
describe 'whitespace >', ->
it 'one whitespace #1', ->
convention = parser.whitespace 'sum = 1 + 2', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #2', ->
convention = parser.whitespace 'a, b = 1, 2', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #3', ->
convention = parser.whitespace "1 > 2 ? true : false; puts 'Hi'", {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #4', ->
convention = parser.whitespace "[1, 2, 3].each { |e| puts e }", {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #5', ->
convention = parser.whitespace '[1, 2, 3].each {|e| puts e }', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #6', ->
convention = parser.whitespace 'sum = 1+2', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #7', ->
convention = parser.whitespace 'sum = "1+2"', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #8', ->
convention = parser.whitespace 'a, b = 1,2', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #9', ->
convention = parser.whitespace 'a, b = 1, 2;', {}
convention.whitespace.spaces.should.equal 1
it 'no whitespace #1', ->
convention = parser.whitespace 'sum = 1 +2', {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #2', ->
convention = parser.whitespace 'a,b = 1, 2', {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #3', ->
convention = parser.whitespace "1>2 ? true : false;puts 'Hi'", {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #4', ->
convention = parser.whitespace "[1, 2, 3].each {|e| puts e}", {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #5', ->
convention = parser.whitespace 'sum = 1 + 2', {}
convention.whitespace.nospace.should.equal 0
it 'no whitespace #6', ->
convention = parser.whitespace 'a, b = 1, 2;c', {}
convention.whitespace.nospace.should.equal 1
describe 'asignDefaultValue >', ->
it 'use spaces #1', ->
convention = parser.asignDefaultValue 'def some_method(arg1 = :default)', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #2', ->
convention = parser.asignDefaultValue ' def some_method(arg2 = nil)', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #3', ->
convention = parser.asignDefaultValue 'def some_method( arg3 = [] )', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #4', ->
convention = parser.asignDefaultValue 'def some_method(arg1 = :default, arg2 = nil, arg3 = [])', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #5', ->
convention = parser.asignDefaultValue 'def some_method(arg3)', {}
convention.asignDefaultValue.space.should.equal 0
it 'use spaces #6', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default)', {}
convention.asignDefaultValue.space.should.equal 0
it 'no spaces #1', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default)', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #2', ->
convention = parser.asignDefaultValue ' def some_method(arg2=nil)', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #3', ->
convention = parser.asignDefaultValue 'def some_method( arg3=[] )', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #4', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default, arg2=nil, arg3=[])', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #5', ->
convention = parser.asignDefaultValue 'def some_method( arg3 = [] )', {}
convention.asignDefaultValue.nospace.should.equal 0
it 'no spaces #6', ->
convention = parser.asignDefaultValue 'def some_method(arg3)', {}
convention.asignDefaultValue.nospace.should.equal 0
describe 'numericLiteral >', ->
it 'use underscore #1', ->
convention = parser.numericLiteral 'num = 1_000_000', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #2', ->
convention = parser.numericLiteral 'num = 7_473', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #3', ->
convention = parser.numericLiteral 'num = 34_000_000', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #4', ->
convention = parser.numericLiteral 'str = "404_094"', {}
convention.numericLiteral.underscore.should.equal 0
it 'use underscore #5', ->
convention = parser.numericLiteral 'num = 438958', {}
convention.numericLiteral.underscore.should.equal 0
it 'use underscore #6', ->
convention = parser.numericLiteral 'num = 958', {}
convention.numericLiteral.underscore.should.equal 0
it 'use no underscore #1', ->
convention = parser.numericLiteral 'num = 1000000', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #2', ->
convention = parser.numericLiteral 'num = 438958', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #3', ->
convention = parser.numericLiteral 'num = 584058', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #4', ->
convention = parser.numericLiteral 'num = 504', {}
convention.numericLiteral.nounderscore.should.equal 0
it 'use no underscore #5', ->
convention = parser.numericLiteral 'str = "404094"', {}
convention.numericLiteral.nounderscore.should.equal 0
it 'use no underscore #6', ->
convention = parser.numericLiteral 'num = 584_058', {}
convention.numericLiteral.nounderscore.should.equal 0
describe 'defNoArgs >', ->
it 'omit parenthenes #1', ->
convention = parser.defNoArgs ' def some_method', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #2', ->
convention = parser.defNoArgs ' def some_method # comment', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #3', ->
convention = parser.defNoArgs ' def some_method # comment()', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #4', ->
convention = parser.defNoArgs ' def some_method()', {}
convention.defNoArgs.omit.should.equal 0
it 'omit parenthenes #5', ->
convention = parser.defNoArgs ' def some_method arg1, arg2', {}
convention.defNoArgs.omit.should.equal 0
it 'omit parenthenes #6', ->
convention = parser.defNoArgs ' def some_method arg1', {}
convention.defNoArgs.omit.should.equal 0
it 'use parenthenes #1', ->
convention = parser.defNoArgs ' def some_method()', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #2', ->
convention = parser.defNoArgs ' def some_method ()', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #3', ->
convention = parser.defNoArgs ' def some_method ( )', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #4', ->
convention = parser.defNoArgs ' def some_method # comment()', {}
convention.defNoArgs.use.should.equal 0
it 'use parenthenes #5', ->
convention = parser.defNoArgs ' def some_method(arg)', {}
convention.defNoArgs.use.should.equal 0
describe 'defArgs >', ->
it 'omit parenthenes #1', ->
convention = parser.defArgs ' def some_method arg1, arg2', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #1', ->
convention = parser.defArgs ' def some_method arg1', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #3', ->
convention = parser.defArgs ' def some_method arg1, arg2 # fjeofjeo( arg1, arg2)', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #4', ->
convention = parser.defArgs 'def some_method()', {}
convention.defArgs.omit.should.equal 0
it 'omit parenthenes #5', ->
convention = parser.defArgs 'def some_method(arg1, arg2)', {}
convention.defArgs.omit.should.equal 0
it 'omit parenthenes #6', ->
convention = parser.defArgs 'def some_method', {}
convention.defArgs.omit.should.equal 0
it 'use parenthenes #1', ->
convention = parser.defArgs ' def some_method( arg1, arg2)', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #2', ->
convention = parser.defArgs ' def some_method ( arg1 )', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #3', ->
convention = parser.defArgs ' def some_method ( arg1, arg2 )', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #4', ->
convention = parser.defArgs 'def some_method arg1, arg2', {}
convention.defArgs.use.should.equal 0
it 'use parenthenes #5', ->
convention = parser.defArgs 'def some_method()', {}
convention.defArgs.use.should.equal 0
it 'use parenthenes #6', ->
convention = parser.defArgs 'def update_requirements(features, group_overrides, init_git_url=nil, user_env_vars=nil)', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #7', ->
convention = parser.defArgs 'def some_method', {}
convention.defArgs.use.should.equal 0
| true | # Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/ruby-parser'
describe 'ruby-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'a = 1;', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check space indent #4', ->
convention = parser.indent ' a = 1;', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\ta = 1;', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\ta = 1;', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t a = 1; ', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \ta = 1;', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'a = 1;', {}
convention.indent.tab.should.equal 0
describe 'linelength >', ->
it 'line length is 80 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #3', ->
convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 0
it 'line length is 120 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #3', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char120.should.equal 0
it 'line length is 150 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {}
convention.linelength.char150.should.equal 1
describe 'whitespace >', ->
it 'one whitespace #1', ->
convention = parser.whitespace 'sum = 1 + 2', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #2', ->
convention = parser.whitespace 'a, b = 1, 2', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #3', ->
convention = parser.whitespace "1 > 2 ? true : false; puts 'Hi'", {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #4', ->
convention = parser.whitespace "[1, 2, 3].each { |e| puts e }", {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #5', ->
convention = parser.whitespace '[1, 2, 3].each {|e| puts e }', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #6', ->
convention = parser.whitespace 'sum = 1+2', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #7', ->
convention = parser.whitespace 'sum = "1+2"', {}
convention.whitespace.spaces.should.equal 1
it 'one whitespace #8', ->
convention = parser.whitespace 'a, b = 1,2', {}
convention.whitespace.spaces.should.equal 0
it 'one whitespace #9', ->
convention = parser.whitespace 'a, b = 1, 2;', {}
convention.whitespace.spaces.should.equal 1
it 'no whitespace #1', ->
convention = parser.whitespace 'sum = 1 +2', {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #2', ->
convention = parser.whitespace 'a,b = 1, 2', {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #3', ->
convention = parser.whitespace "1>2 ? true : false;puts 'Hi'", {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #4', ->
convention = parser.whitespace "[1, 2, 3].each {|e| puts e}", {}
convention.whitespace.nospace.should.equal 1
it 'no whitespace #5', ->
convention = parser.whitespace 'sum = 1 + 2', {}
convention.whitespace.nospace.should.equal 0
it 'no whitespace #6', ->
convention = parser.whitespace 'a, b = 1, 2;c', {}
convention.whitespace.nospace.should.equal 1
describe 'asignDefaultValue >', ->
it 'use spaces #1', ->
convention = parser.asignDefaultValue 'def some_method(arg1 = :default)', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #2', ->
convention = parser.asignDefaultValue ' def some_method(arg2 = nil)', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #3', ->
convention = parser.asignDefaultValue 'def some_method( arg3 = [] )', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #4', ->
convention = parser.asignDefaultValue 'def some_method(arg1 = :default, arg2 = nil, arg3 = [])', {}
convention.asignDefaultValue.space.should.equal 1
it 'use spaces #5', ->
convention = parser.asignDefaultValue 'def some_method(arg3)', {}
convention.asignDefaultValue.space.should.equal 0
it 'use spaces #6', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default)', {}
convention.asignDefaultValue.space.should.equal 0
it 'no spaces #1', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default)', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #2', ->
convention = parser.asignDefaultValue ' def some_method(arg2=nil)', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #3', ->
convention = parser.asignDefaultValue 'def some_method( arg3=[] )', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #4', ->
convention = parser.asignDefaultValue 'def some_method(arg1=:default, arg2=nil, arg3=[])', {}
convention.asignDefaultValue.nospace.should.equal 1
it 'no spaces #5', ->
convention = parser.asignDefaultValue 'def some_method( arg3 = [] )', {}
convention.asignDefaultValue.nospace.should.equal 0
it 'no spaces #6', ->
convention = parser.asignDefaultValue 'def some_method(arg3)', {}
convention.asignDefaultValue.nospace.should.equal 0
describe 'numericLiteral >', ->
it 'use underscore #1', ->
convention = parser.numericLiteral 'num = 1_000_000', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #2', ->
convention = parser.numericLiteral 'num = 7_473', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #3', ->
convention = parser.numericLiteral 'num = 34_000_000', {}
convention.numericLiteral.underscore.should.equal 1
it 'use underscore #4', ->
convention = parser.numericLiteral 'str = "404_094"', {}
convention.numericLiteral.underscore.should.equal 0
it 'use underscore #5', ->
convention = parser.numericLiteral 'num = 438958', {}
convention.numericLiteral.underscore.should.equal 0
it 'use underscore #6', ->
convention = parser.numericLiteral 'num = 958', {}
convention.numericLiteral.underscore.should.equal 0
it 'use no underscore #1', ->
convention = parser.numericLiteral 'num = 1000000', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #2', ->
convention = parser.numericLiteral 'num = 438958', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #3', ->
convention = parser.numericLiteral 'num = 584058', {}
convention.numericLiteral.nounderscore.should.equal 1
it 'use no underscore #4', ->
convention = parser.numericLiteral 'num = 504', {}
convention.numericLiteral.nounderscore.should.equal 0
it 'use no underscore #5', ->
convention = parser.numericLiteral 'str = "404094"', {}
convention.numericLiteral.nounderscore.should.equal 0
it 'use no underscore #6', ->
convention = parser.numericLiteral 'num = 584_058', {}
convention.numericLiteral.nounderscore.should.equal 0
describe 'defNoArgs >', ->
it 'omit parenthenes #1', ->
convention = parser.defNoArgs ' def some_method', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #2', ->
convention = parser.defNoArgs ' def some_method # comment', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #3', ->
convention = parser.defNoArgs ' def some_method # comment()', {}
convention.defNoArgs.omit.should.equal 1
it 'omit parenthenes #4', ->
convention = parser.defNoArgs ' def some_method()', {}
convention.defNoArgs.omit.should.equal 0
it 'omit parenthenes #5', ->
convention = parser.defNoArgs ' def some_method arg1, arg2', {}
convention.defNoArgs.omit.should.equal 0
it 'omit parenthenes #6', ->
convention = parser.defNoArgs ' def some_method arg1', {}
convention.defNoArgs.omit.should.equal 0
it 'use parenthenes #1', ->
convention = parser.defNoArgs ' def some_method()', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #2', ->
convention = parser.defNoArgs ' def some_method ()', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #3', ->
convention = parser.defNoArgs ' def some_method ( )', {}
convention.defNoArgs.use.should.equal 1
it 'use parenthenes #4', ->
convention = parser.defNoArgs ' def some_method # comment()', {}
convention.defNoArgs.use.should.equal 0
it 'use parenthenes #5', ->
convention = parser.defNoArgs ' def some_method(arg)', {}
convention.defNoArgs.use.should.equal 0
describe 'defArgs >', ->
it 'omit parenthenes #1', ->
convention = parser.defArgs ' def some_method arg1, arg2', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #1', ->
convention = parser.defArgs ' def some_method arg1', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #3', ->
convention = parser.defArgs ' def some_method arg1, arg2 # fjeofjeo( arg1, arg2)', {}
convention.defArgs.omit.should.equal 1
it 'omit parenthenes #4', ->
convention = parser.defArgs 'def some_method()', {}
convention.defArgs.omit.should.equal 0
it 'omit parenthenes #5', ->
convention = parser.defArgs 'def some_method(arg1, arg2)', {}
convention.defArgs.omit.should.equal 0
it 'omit parenthenes #6', ->
convention = parser.defArgs 'def some_method', {}
convention.defArgs.omit.should.equal 0
it 'use parenthenes #1', ->
convention = parser.defArgs ' def some_method( arg1, arg2)', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #2', ->
convention = parser.defArgs ' def some_method ( arg1 )', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #3', ->
convention = parser.defArgs ' def some_method ( arg1, arg2 )', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #4', ->
convention = parser.defArgs 'def some_method arg1, arg2', {}
convention.defArgs.use.should.equal 0
it 'use parenthenes #5', ->
convention = parser.defArgs 'def some_method()', {}
convention.defArgs.use.should.equal 0
it 'use parenthenes #6', ->
convention = parser.defArgs 'def update_requirements(features, group_overrides, init_git_url=nil, user_env_vars=nil)', {}
convention.defArgs.use.should.equal 1
it 'use parenthenes #7', ->
convention = parser.defArgs 'def some_method', {}
convention.defArgs.use.should.equal 0
|
[
{
"context": "name)->\n\n speak:->\n console.log \"hi my name is #{@name}\"\n\n run:->\n \"console.log fast running\"\n",
"end": 79,
"score": 0.49313825368881226,
"start": 79,
"tag": "NAME",
"value": ""
},
{
"context": ")->\n\n speak:->\n console.log \"hi my name is #{@na... | test/Person.coffee | BeastJavaScript/Coffee-Stir | 3 | class Person
constructor:(@name)->
speak:->
console.log "hi my name is #{@name}"
run:->
"console.log fast running"
| 137734 | class Person
constructor:(@name)->
speak:->
console.log "hi my name is<NAME> #{@name}"
run:->
"console.log fast running"
| true | class Person
constructor:(@name)->
speak:->
console.log "hi my name isPI:NAME:<NAME>END_PI #{@name}"
run:->
"console.log fast running"
|
[
{
"context": "@Referral = {}\nReferral.config =\n account: 'meteor-useraccounts'\n email:\n from: 'no-reply@example.com'\n te",
"end": 64,
"score": 0.998959481716156,
"start": 45,
"tag": "USERNAME",
"value": "meteor-useraccounts"
},
{
"context": "ccount: 'meteor-useraccounts'... | server/config.coffee | keryi/meteor-referral | 1 | @Referral = {}
Referral.config =
account: 'meteor-useraccounts'
email:
from: 'no-reply@example.com'
text: ''
product:
name: 'Example'
description: 'Example lets you to hire a cleaner at affordable price easily.'
hostUrl: 'http://www.example.com'
| 20405 | @Referral = {}
Referral.config =
account: 'meteor-useraccounts'
email:
from: '<EMAIL>'
text: ''
product:
name: 'Example'
description: 'Example lets you to hire a cleaner at affordable price easily.'
hostUrl: 'http://www.example.com'
| true | @Referral = {}
Referral.config =
account: 'meteor-useraccounts'
email:
from: 'PI:EMAIL:<EMAIL>END_PI'
text: ''
product:
name: 'Example'
description: 'Example lets you to hire a cleaner at affordable price easily.'
hostUrl: 'http://www.example.com'
|
[
{
"context": "abs: false\n \"exception-reporting\":\n userId: \"641e57f7-71ad-3e89-7424-d0acd1db4782\"\n",
"end": 295,
"score": 0.6046683192253113,
"start": 260,
"tag": "PASSWORD",
"value": "41e57f7-71ad-3e89-7424-d0acd1db4782"
}
] | config.cson | aschneiderman/atom-voice | 0 | "*":
welcome:
showOnStartup: false
core:
themes: [
"one-light-ui"
"one-light-syntax"
]
audioBeep: false
editor:
invisibles: {}
tabLength: 2
softWrap: true
softTabs: false
"exception-reporting":
userId: "641e57f7-71ad-3e89-7424-d0acd1db4782"
| 140438 | "*":
welcome:
showOnStartup: false
core:
themes: [
"one-light-ui"
"one-light-syntax"
]
audioBeep: false
editor:
invisibles: {}
tabLength: 2
softWrap: true
softTabs: false
"exception-reporting":
userId: "6<PASSWORD>"
| true | "*":
welcome:
showOnStartup: false
core:
themes: [
"one-light-ui"
"one-light-syntax"
]
audioBeep: false
editor:
invisibles: {}
tabLength: 2
softWrap: true
softTabs: false
"exception-reporting":
userId: "6PI:PASSWORD:<PASSWORD>END_PI"
|
[
{
"context": "icense CodeCanyon Standard / Extended\n@author Alex Grozav\n@company Pixevil\n@website http://pixevil.com\n",
"end": 361,
"score": 0.9998828768730164,
"start": 350,
"tag": "NAME",
"value": "Alex Grozav"
},
{
"context": " Pixevil\n@website http://pixevil.com\... | public/template/src/resources/js/animus/animus.coffee | georgi-dev/dmr-academy | 0 | ###
oo
.d8888b. 88d888b. dP 88d8b.d8b. dP dP .d8888b.
88' `88 88' `88 88 88'`88'`88 88 88 Y8ooooo.
88. .88 88 88 88 88 88 88 88. .88 88
`88888P8 dP dP dP dP dP dP `88888P' `88888P'
oooooooooooooooooooooooooooooooooooooooooooooooooo
@plugin jQuery
@license CodeCanyon Standard / Extended
@author Alex Grozav
@company Pixevil
@website http://pixevil.com
@email alex@grozav.com
###
(($, window, document) ->
'use strict'
$.animus = (override) ->
# Animation Model
model = {}
# Animation duration
model.duration = 600
# Model Default State
model.defaults =
opacity: 1
rotationX: 0
rotationY: 0
rotationZ: 0
x: 0
y: 0
z: 0
xPercent: 0
yPercent: 0
scale: 1
scaleX: 1
scaleY: 1
scaleZ: 1
skewX: 0
skewY: 0
easing: "Quad.easeOut"
# List of allowed GSAP parameters
@parameters = [
'scale'
'scaleX'
'scaleY'
'scaleZ'
'x'
'y'
'z'
'skewX'
'skewY'
'rotation'
'rotationX'
'rotationY'
'rotationZ'
'perspective'
'xPercent'
'yPercent'
'shortRotation'
'shortRotationX'
'shortRotationY'
'shortRotationZ'
'transformOrigin'
'svgOrigin'
'transformPerspective'
'directionalRotation'
'parseTransform'
'force3D'
'skewType'
'smoothOrigin'
'boxShadow'
'borderRadius'
'backgroundPosition'
'backgroundSize'
'perspectiveOrigin'
'transformStyle'
'backfaceVisibility'
'userSelect'
'margin'
'padding'
'color'
'clip'
'textShadow'
'autoRound'
'strictUnits'
'border'
'borderWidth'
'float'
'cssFloat'
'styleFloat'
'perspectiveOrigin'
'transformStyle'
'backfaceVisibility'
'userSelect'
'opacity'
'alpha'
'autoAlpha'
'className'
'clearProps'
]
# Override default and final animus animation model
#
@init = ->
$.extend model, override
return
###
Process an animation string of the form "rotate 45, fade in" into
a usable VelocityJS animation object
@var string The animation string to be modified, of the form
move x 300px, fade in, scale up
###
@get = (input) ->
# Animation Object
animation = {}
animation.state = { z: 0 }
animation.duration = model.duration / 1000
animation.timeline = null
if input == '' or !input? or !input
return animation
input = input.split /(\,\s*)/
$.each input, (index, string) =>
i = 0
# Trim input string partial
string = $.trim(string)
# Replace round brackets
if /\(.*\)/.test(string)
string = string.replace(/\s*\(\s*/, ' ').replace(/\s*\)\s*/, ' ')
# Split by space
string = string.split /\s+/
# Remove empty strings
string = $.grep string, (n) ->
n != ""
# Set current working parameter
parameter = string.shift()
# Set current working value
value = string.join ' '
# Check if we have a VelocityJS parameter
if ['duration', 'speed'].indexOf(parameter) != -1
animation.duration = parseFloat(value, 10) / 1000
else if ['ease', 'easing'].indexOf(parameter) != -1
animation.state.ease = value
else if parameter in @parameters
if value? and !/.+(\s+.+)+/.test(value)
if /px/.test value
value = parseFloat value.replace('px', ''), 10
else if /deg/.test value
value = parseFloat value.replace('deg', ''), 10
# Set as float if it isn't a percentage value
if /^[0-9](\.[0-9]+)?$/.test value
value = parseFloat value, 10
# @TODO Add final values
# else
# value = model.finals[parameter]
animation.state[parameter] = value
# Check if we have a VelocityJS redirect
else if parameter of $.animus.presets
animation.state = parameter
return
return animation
###
Set reset state by getting all the animation variables
and setting them to the default values
@param data [State] State which overwrites reset variables
@param data [Object] Element states data in RockSlider
@param deep [Boolean] Generate reset from an array of animations if true
or from a single animation if false
###
@reset = (state, data) ->
###
Check if we need to add the percentage sign to the default state value
###
percentage = (value) ->
if /\%$/.test value
return '%'
else
return ''
reset = {}
$.each data, (anim)->
return if $.type(@state) is 'string'
$.each @state, (key, value) ->
if !(key of reset) and key of model.defaults
reset[key] = model.defaults[key] + percentage(value)
return
return
return $.extend {}, reset, state
# Initialize Animus
@init()
return
# Keeps all Animus presets
$.animus.presets = {}
# Add a new Animus preset
$.animus.register_preset = (name, timeline) ->
$.animus.presets[name] = timeline
return
return
) jQuery, window, document
| 32711 | ###
oo
.d8888b. 88d888b. dP 88d8b.d8b. dP dP .d8888b.
88' `88 88' `88 88 88'`88'`88 88 88 Y8ooooo.
88. .88 88 88 88 88 88 88 88. .88 88
`88888P8 dP dP dP dP dP dP `88888P' `88888P'
oooooooooooooooooooooooooooooooooooooooooooooooooo
@plugin jQuery
@license CodeCanyon Standard / Extended
@author <NAME>
@company Pixevil
@website http://pixevil.com
@email <EMAIL>
###
(($, window, document) ->
'use strict'
$.animus = (override) ->
# Animation Model
model = {}
# Animation duration
model.duration = 600
# Model Default State
model.defaults =
opacity: 1
rotationX: 0
rotationY: 0
rotationZ: 0
x: 0
y: 0
z: 0
xPercent: 0
yPercent: 0
scale: 1
scaleX: 1
scaleY: 1
scaleZ: 1
skewX: 0
skewY: 0
easing: "Quad.easeOut"
# List of allowed GSAP parameters
@parameters = [
'scale'
'scaleX'
'scaleY'
'scaleZ'
'x'
'y'
'z'
'skewX'
'skewY'
'rotation'
'rotationX'
'rotationY'
'rotationZ'
'perspective'
'xPercent'
'yPercent'
'shortRotation'
'shortRotationX'
'shortRotationY'
'shortRotationZ'
'transformOrigin'
'svgOrigin'
'transformPerspective'
'directionalRotation'
'parseTransform'
'force3D'
'skewType'
'smoothOrigin'
'boxShadow'
'borderRadius'
'backgroundPosition'
'backgroundSize'
'perspectiveOrigin'
'transformStyle'
'backfaceVisibility'
'userSelect'
'margin'
'padding'
'color'
'clip'
'textShadow'
'autoRound'
'strictUnits'
'border'
'borderWidth'
'float'
'cssFloat'
'styleFloat'
'perspectiveOrigin'
'transformStyle'
'backfaceVisibility'
'userSelect'
'opacity'
'alpha'
'autoAlpha'
'className'
'clearProps'
]
# Override default and final animus animation model
#
@init = ->
$.extend model, override
return
###
Process an animation string of the form "rotate 45, fade in" into
a usable VelocityJS animation object
@var string The animation string to be modified, of the form
move x 300px, fade in, scale up
###
@get = (input) ->
# Animation Object
animation = {}
animation.state = { z: 0 }
animation.duration = model.duration / 1000
animation.timeline = null
if input == '' or !input? or !input
return animation
input = input.split /(\,\s*)/
$.each input, (index, string) =>
i = 0
# Trim input string partial
string = $.trim(string)
# Replace round brackets
if /\(.*\)/.test(string)
string = string.replace(/\s*\(\s*/, ' ').replace(/\s*\)\s*/, ' ')
# Split by space
string = string.split /\s+/
# Remove empty strings
string = $.grep string, (n) ->
n != ""
# Set current working parameter
parameter = string.shift()
# Set current working value
value = string.join ' '
# Check if we have a VelocityJS parameter
if ['duration', 'speed'].indexOf(parameter) != -1
animation.duration = parseFloat(value, 10) / 1000
else if ['ease', 'easing'].indexOf(parameter) != -1
animation.state.ease = value
else if parameter in @parameters
if value? and !/.+(\s+.+)+/.test(value)
if /px/.test value
value = parseFloat value.replace('px', ''), 10
else if /deg/.test value
value = parseFloat value.replace('deg', ''), 10
# Set as float if it isn't a percentage value
if /^[0-9](\.[0-9]+)?$/.test value
value = parseFloat value, 10
# @TODO Add final values
# else
# value = model.finals[parameter]
animation.state[parameter] = value
# Check if we have a VelocityJS redirect
else if parameter of $.animus.presets
animation.state = parameter
return
return animation
###
Set reset state by getting all the animation variables
and setting them to the default values
@param data [State] State which overwrites reset variables
@param data [Object] Element states data in RockSlider
@param deep [Boolean] Generate reset from an array of animations if true
or from a single animation if false
###
@reset = (state, data) ->
###
Check if we need to add the percentage sign to the default state value
###
percentage = (value) ->
if /\%$/.test value
return '%'
else
return ''
reset = {}
$.each data, (anim)->
return if $.type(@state) is 'string'
$.each @state, (key, value) ->
if !(key of reset) and key of model.defaults
reset[key] = model.defaults[key] + percentage(value)
return
return
return $.extend {}, reset, state
# Initialize Animus
@init()
return
# Keeps all Animus presets
$.animus.presets = {}
# Add a new Animus preset
$.animus.register_preset = (name, timeline) ->
$.animus.presets[name] = timeline
return
return
) jQuery, window, document
| true | ###
oo
.d8888b. 88d888b. dP 88d8b.d8b. dP dP .d8888b.
88' `88 88' `88 88 88'`88'`88 88 88 Y8ooooo.
88. .88 88 88 88 88 88 88 88. .88 88
`88888P8 dP dP dP dP dP dP `88888P' `88888P'
oooooooooooooooooooooooooooooooooooooooooooooooooo
@plugin jQuery
@license CodeCanyon Standard / Extended
@author PI:NAME:<NAME>END_PI
@company Pixevil
@website http://pixevil.com
@email PI:EMAIL:<EMAIL>END_PI
###
(($, window, document) ->
'use strict'
$.animus = (override) ->
# Animation Model
model = {}
# Animation duration
model.duration = 600
# Model Default State
model.defaults =
opacity: 1
rotationX: 0
rotationY: 0
rotationZ: 0
x: 0
y: 0
z: 0
xPercent: 0
yPercent: 0
scale: 1
scaleX: 1
scaleY: 1
scaleZ: 1
skewX: 0
skewY: 0
easing: "Quad.easeOut"
# List of allowed GSAP parameters
@parameters = [
'scale'
'scaleX'
'scaleY'
'scaleZ'
'x'
'y'
'z'
'skewX'
'skewY'
'rotation'
'rotationX'
'rotationY'
'rotationZ'
'perspective'
'xPercent'
'yPercent'
'shortRotation'
'shortRotationX'
'shortRotationY'
'shortRotationZ'
'transformOrigin'
'svgOrigin'
'transformPerspective'
'directionalRotation'
'parseTransform'
'force3D'
'skewType'
'smoothOrigin'
'boxShadow'
'borderRadius'
'backgroundPosition'
'backgroundSize'
'perspectiveOrigin'
'transformStyle'
'backfaceVisibility'
'userSelect'
'margin'
'padding'
'color'
'clip'
'textShadow'
'autoRound'
'strictUnits'
'border'
'borderWidth'
'float'
'cssFloat'
'styleFloat'
'perspectiveOrigin'
'transformStyle'
'backfaceVisibility'
'userSelect'
'opacity'
'alpha'
'autoAlpha'
'className'
'clearProps'
]
# Override default and final animus animation model
#
@init = ->
$.extend model, override
return
###
Process an animation string of the form "rotate 45, fade in" into
a usable VelocityJS animation object
@var string The animation string to be modified, of the form
move x 300px, fade in, scale up
###
@get = (input) ->
# Animation Object
animation = {}
animation.state = { z: 0 }
animation.duration = model.duration / 1000
animation.timeline = null
if input == '' or !input? or !input
return animation
input = input.split /(\,\s*)/
$.each input, (index, string) =>
i = 0
# Trim input string partial
string = $.trim(string)
# Replace round brackets
if /\(.*\)/.test(string)
string = string.replace(/\s*\(\s*/, ' ').replace(/\s*\)\s*/, ' ')
# Split by space
string = string.split /\s+/
# Remove empty strings
string = $.grep string, (n) ->
n != ""
# Set current working parameter
parameter = string.shift()
# Set current working value
value = string.join ' '
# Check if we have a VelocityJS parameter
if ['duration', 'speed'].indexOf(parameter) != -1
animation.duration = parseFloat(value, 10) / 1000
else if ['ease', 'easing'].indexOf(parameter) != -1
animation.state.ease = value
else if parameter in @parameters
if value? and !/.+(\s+.+)+/.test(value)
if /px/.test value
value = parseFloat value.replace('px', ''), 10
else if /deg/.test value
value = parseFloat value.replace('deg', ''), 10
# Set as float if it isn't a percentage value
if /^[0-9](\.[0-9]+)?$/.test value
value = parseFloat value, 10
# @TODO Add final values
# else
# value = model.finals[parameter]
animation.state[parameter] = value
# Check if we have a VelocityJS redirect
else if parameter of $.animus.presets
animation.state = parameter
return
return animation
###
Set reset state by getting all the animation variables
and setting them to the default values
@param data [State] State which overwrites reset variables
@param data [Object] Element states data in RockSlider
@param deep [Boolean] Generate reset from an array of animations if true
or from a single animation if false
###
@reset = (state, data) ->
###
Check if we need to add the percentage sign to the default state value
###
percentage = (value) ->
if /\%$/.test value
return '%'
else
return ''
reset = {}
$.each data, (anim)->
return if $.type(@state) is 'string'
$.each @state, (key, value) ->
if !(key of reset) and key of model.defaults
reset[key] = model.defaults[key] + percentage(value)
return
return
return $.extend {}, reset, state
# Initialize Animus
@init()
return
# Keeps all Animus presets
$.animus.presets = {}
# Add a new Animus preset
$.animus.register_preset = (name, timeline) ->
$.animus.presets[name] = timeline
return
return
) jQuery, window, document
|
[
{
"context": "rom User\n\nSet of bot commands\n1. create sonar user test1\n2. delete sonar user test1\n3. create sonar projec",
"end": 942,
"score": 0.9627575874328613,
"start": 937,
"tag": "USERNAME",
"value": "test1"
},
{
"context": "ds\n1. create sonar user test1\n2. delete sonar ... | scripts/sonar/scripts-msteams/Sonar.coffee | CognizantOneDevOps/OnBot | 4 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Coffee script used for:
1. Creation and Deletion of Project/User
2. Grant and Revoke Permissions from User
Set of bot commands
1. create sonar user test1
2. delete sonar user test1
3. create sonar project testproj
4. delete sonar project testproj
5. grant sonar user access for user test1 to project testproj
Environment variables to set:
1. SONAR_URL
2. SONAR_USER_ID
3. SONAR_PASSWORD
4. HUBOT_NAME
###
#Load Dependencies
eindex = require('./index')
request = require('request')
readjson = require ('./readjson.js');
create_project = require('./create_project.js');
delete_project = require('./delete_project.js');
create_user = require('./create_user.js');
delete_user = require('./delete_user.js');
grant_user = require('./grant_user.js');
revoke_user = require('./revoke_user.js');
list_project = require('./list_project.js');
list_user = require('./list_user.js');
generate_id = require('./mongoConnt');
#Required Environment Variables
sonar_url = process.env.SONAR_URL
sonar_user_id = process.env.SONAR_USER_ID
sonar_password = process.env.SONAR_PASSWORD
botname = process.env.HUBOT_NAME
pod_ip = process.env.MY_POD_IP
post = (recipient, data) ->
optons = {method: "POST", url: recipient, json: data}
request.post optons, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /help/i, (msg) ->
msg.send '<br>1) create sonar project <<*project-id*>><br>2) list sonar projects<br>3) list sonar users<br>4) delete sonar user <<*user-id*>><br>5) create sonar user <<*user-id*>><br>6) delete sonar project <<*project-id*>><br>7) grant sonar <<*permission-name*>> <<*userid*>> <<*projectid*>><br>8) revoke sonar <<*permission-name*>> <<*userid*>> <<*projectid*>><br>9) getMetrics <<*projectname*>>'
robot.respond /create sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonarcreateproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonarcreateproject.admin,podIp:process.env.MY_POD_IP,projectid:projectid,"callback_id": 'sonarcreateproject',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for create sonar project","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to create a sonar project '+payload.projectid+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonarcreateproject.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Sonar project created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send (stderr)
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar create project "+request.body.projectid+", requested by "+request.body.username+"\n"
# Approved Message send to the user chat room
projectid = request.body.projectid;
# Call from create_project file for project creation
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
dt.text='Sonar project created with ID : '.concat(projectid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
# Send data to elastic search for wall notification
message = 'create sonar project '+ projectid;
actionmsg = 'Sonar project created'
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
# Error and Exception handled
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar create project "+request.body.projectid+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /list sonar projects/i, (msg) ->
projectid = msg.match[1]
# Call from list_project file to list available project
list_project.list_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /list sonar users/i, (msg) ->
projectid = msg.match[1]
# Call from list_user file to list available users
list_user.list_user sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
# Exception and Error Handled
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /delete sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonardeleteuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonardeleteuser.admin,podIp:process.env.MY_POD_IP,userids:userids,"callback_id": 'sonardeleteuser',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar delete user","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to delete a sonar user '+payload.userids+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonardeleteuser.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData stdout),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar delete user "+request.body.userids+", requested by "+request.body.username+"\n"
userids = request.body.userids;
# Call from delete_user file to delete user
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'User deleted with ID : '.concat(userids);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'delete sonar user '+ userids;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt.title=request.body.approver+" rejected sonar delete user "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
# Creation of users
robot.respond /create sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonarcreateuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonarcreateuser.admin,podIp:process.env.MY_POD_IP,userids:userids,"callback_id": 'sonarcreateuser',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar create user","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to create a sonar user '+payload.userids+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonarcreateuser.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar user created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar create user "+request.body.userids+", requested by "+request.body.username+"\n"
userids = request.body.userids;
# Call from create_user file to create user
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text= 'User created with ID and password: '.concat(userids);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
message = 'create sonar user '+ userids;
actionmsg = 'Sonar user created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar create user "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /delete sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonardeleteproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonardeleteproject.admin,podIp:process.env.MY_POD_IP,projectid:projectid,"callback_id": 'sonardeleteproject',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar delete project","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to delete sonar project '+payload.projectid+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonardeleteproject.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar delete project "+request.body.projectid+", requested by "+request.body.username+"\n"
projectid = request.body.projectid;
# Call from delete_project file for the deletion of project
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Sonar project deleted with id : '.concat(projectid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'delete sonar project '+ projectid;
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.title=sdterr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar delete project "+request.body.projectid+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /grant sonar (.*)/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.grantsonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.grantsonar.admin,podIp:process.env.MY_POD_IP,projid:projid,userids:userids,perm:perm,"callback_id": 'grantsonar',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for grant sonar permission","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to grant sonar '+payload.projid+' '+payload.userids+' '+payload.perm+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.grantsonar.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.grantsonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions granted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/grantsonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar Grant Permission project "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from grant_user file to grant permission to the user for particular project
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'grant sonar '+ perm;
actionmsg = 'Permissions granted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text= stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar Grant Permission project "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /revoke sonar (.*)/i, (msg) ->
message = "Sonar permissions revoked"
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.revokesonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.revokesonar.admin,podIp:process.env.MY_POD_IP,projid:projid,userids:userids,perm:perm,"callback_id": 'revokesonar',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for revoke sonar permission","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to revoke sonar '+payload.projid+' '+payload.userids+' '+payload.perm+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.revokesonar.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.revokesonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions revoked';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/revokesonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar revoke permission "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from revoke_user file to revoke permission from the user for particular project
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'revoke sonar '+ perm;
actionmsg = 'Permissions revoked';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
#Rejection Handled
else
dt.title=request.body.approver+" rejected sonar revoke permission "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /getMetrics (.*)/i, (msg) ->
project = msg.match[1]
request.get sonar_url+'api/projects', (error, response, body) ->
if error
console.log error
dt = "Error! Please check logs."
msg.send dt
setTimeout (->eindex.passData dt),1000
else
body=JSON.parse(body)
console.log(project)
for i in [0... body.length]
console.log(body[i].k)
if body[i].nm == project
url = sonar_url+'api/measures/component?componentKey='+body[i].k+'&metricKeys=ncloc,sqale_index,duplicated_lines_density,coverage,bugs,code_smells,vulnerabilities'
break
if url == undefined
dt = "Project not found"
msg.send dt
setTimeout (->eindex.passData dt),1000
else
console.log(url)
options = {
url: url,
method: 'GET',
auth: {username: sonar_user_id, password: sonar_password}
}
request.get options, (error, response, body) ->
if error
msg.send error
setTimeout (->eindex.passData error),1000
else
dt = ''
body = JSON.parse(body)
if body.errors
for i in [0... body.errors.length]
msg.send body.errors[i].msg
else
for i in [0... body.component.measures.length]
if body.component.measures[i].metric == 'bugs'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'code_smells'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'coverage'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'duplicated_lines_density'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'ncloc'
dt += " Lines of Code: "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'sqale_index'
dt += " Technical Debt :" +body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'vulnerabilities'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
msg.send dt
setTimeout (->eindex.passData dt),1000
| 105052 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Coffee script used for:
1. Creation and Deletion of Project/User
2. Grant and Revoke Permissions from User
Set of bot commands
1. create sonar user test1
2. delete sonar user test1
3. create sonar project testproj
4. delete sonar project testproj
5. grant sonar user access for user test1 to project testproj
Environment variables to set:
1. SONAR_URL
2. SONAR_USER_ID
3. SONAR_PASSWORD
4. HUBOT_NAME
###
#Load Dependencies
eindex = require('./index')
request = require('request')
readjson = require ('./readjson.js');
create_project = require('./create_project.js');
delete_project = require('./delete_project.js');
create_user = require('./create_user.js');
delete_user = require('./delete_user.js');
grant_user = require('./grant_user.js');
revoke_user = require('./revoke_user.js');
list_project = require('./list_project.js');
list_user = require('./list_user.js');
generate_id = require('./mongoConnt');
#Required Environment Variables
sonar_url = process.env.SONAR_URL
sonar_user_id = process.env.SONAR_USER_ID
sonar_password = process.env.SONAR_PASSWORD
botname = process.env.HUBOT_NAME
pod_ip = process.env.MY_POD_IP
post = (recipient, data) ->
optons = {method: "POST", url: recipient, json: data}
request.post optons, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /help/i, (msg) ->
msg.send '<br>1) create sonar project <<*project-id*>><br>2) list sonar projects<br>3) list sonar users<br>4) delete sonar user <<*user-id*>><br>5) create sonar user <<*user-id*>><br>6) delete sonar project <<*project-id*>><br>7) grant sonar <<*permission-name*>> <<*userid*>> <<*projectid*>><br>8) revoke sonar <<*permission-name*>> <<*userid*>> <<*projectid*>><br>9) getMetrics <<*projectname*>>'
robot.respond /create sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonarcreateproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonarcreateproject.admin,podIp:process.env.MY_POD_IP,projectid:projectid,"callback_id": 'sonarcreateproject',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for create sonar project","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to create a sonar project '+payload.projectid+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonarcreateproject.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Sonar project created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send (stderr)
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar create project "+request.body.projectid+", requested by "+request.body.username+"\n"
# Approved Message send to the user chat room
projectid = request.body.projectid;
# Call from create_project file for project creation
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
dt.text='Sonar project created with ID : '.concat(projectid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
# Send data to elastic search for wall notification
message = 'create sonar project '+ projectid;
actionmsg = 'Sonar project created'
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
# Error and Exception handled
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar create project "+request.body.projectid+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /list sonar projects/i, (msg) ->
projectid = msg.match[1]
# Call from list_project file to list available project
list_project.list_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /list sonar users/i, (msg) ->
projectid = msg.match[1]
# Call from list_user file to list available users
list_user.list_user sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
# Exception and Error Handled
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /delete sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonardeleteuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonardeleteuser.admin,podIp:process.env.MY_POD_IP,userids:userids,"callback_id": 'sonardeleteuser',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar delete user","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to delete a sonar user '+payload.userids+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonardeleteuser.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData stdout),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar delete user "+request.body.userids+", requested by "+request.body.username+"\n"
userids = request.body.userids;
# Call from delete_user file to delete user
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'User deleted with ID : '.concat(userids);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'delete sonar user '+ userids;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt.title=request.body.approver+" rejected sonar delete user "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
# Creation of users
robot.respond /create sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonarcreateuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonarcreateuser.admin,podIp:process.env.MY_POD_IP,userids:userids,"callback_id": 'sonarcreateuser',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar create user","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to create a sonar user '+payload.userids+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonarcreateuser.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar user created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar create user "+request.body.userids+", requested by "+request.body.username+"\n"
userids = request.body.userids;
# Call from create_user file to create user
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text= 'User created with ID and password: '.concat(userids);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
message = 'create sonar user '+ userids;
actionmsg = 'Sonar user created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar create user "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /delete sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonardeleteproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonardeleteproject.admin,podIp:process.env.MY_POD_IP,projectid:projectid,"callback_id": 'sonardeleteproject',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar delete project","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to delete sonar project '+payload.projectid+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonardeleteproject.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar delete project "+request.body.projectid+", requested by "+request.body.username+"\n"
projectid = request.body.projectid;
# Call from delete_project file for the deletion of project
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Sonar project deleted with id : '.concat(projectid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'delete sonar project '+ projectid;
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.title=sdterr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar delete project "+request.body.projectid+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /grant sonar (.*)/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.grantsonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.grantsonar.admin,podIp:process.env.MY_POD_IP,projid:projid,userids:userids,perm:perm,"callback_id": 'grantsonar',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for grant sonar permission","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to grant sonar '+payload.projid+' '+payload.userids+' '+payload.perm+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.grantsonar.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.grantsonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions granted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/grantsonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar Grant Permission project "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from grant_user file to grant permission to the user for particular project
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'grant sonar '+ perm;
actionmsg = 'Permissions granted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text= stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar Grant Permission project "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /revoke sonar (.*)/i, (msg) ->
message = "Sonar permissions revoked"
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.revokesonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.revokesonar.admin,podIp:process.env.MY_POD_IP,projid:projid,userids:userids,perm:perm,"callback_id": 'revokesonar',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for revoke sonar permission","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to revoke sonar '+payload.projid+' '+payload.userids+' '+payload.perm+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.revokesonar.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.revokesonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions revoked';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/revokesonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar revoke permission "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from revoke_user file to revoke permission from the user for particular project
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'revoke sonar '+ perm;
actionmsg = 'Permissions revoked';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
#Rejection Handled
else
dt.title=request.body.approver+" rejected sonar revoke permission "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /getMetrics (.*)/i, (msg) ->
project = msg.match[1]
request.get sonar_url+'api/projects', (error, response, body) ->
if error
console.log error
dt = "Error! Please check logs."
msg.send dt
setTimeout (->eindex.passData dt),1000
else
body=JSON.parse(body)
console.log(project)
for i in [0... body.length]
console.log(body[i].k)
if body[i].nm == project
url = sonar_url+'api/measures/component?componentKey='+body[i].k+'&metricKeys=<KEY>,sqale_index,duplicated_lines_density,coverage,bugs,code_smells,vulnerabilities'
break
if url == undefined
dt = "Project not found"
msg.send dt
setTimeout (->eindex.passData dt),1000
else
console.log(url)
options = {
url: url,
method: 'GET',
auth: {username: sonar_user_id, password: <PASSWORD>}
}
request.get options, (error, response, body) ->
if error
msg.send error
setTimeout (->eindex.passData error),1000
else
dt = ''
body = JSON.parse(body)
if body.errors
for i in [0... body.errors.length]
msg.send body.errors[i].msg
else
for i in [0... body.component.measures.length]
if body.component.measures[i].metric == 'bugs'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'code_smells'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'coverage'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'duplicated_lines_density'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'ncloc'
dt += " Lines of Code: "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'sqale_index'
dt += " Technical Debt :" +body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'vulnerabilities'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
msg.send dt
setTimeout (->eindex.passData dt),1000
| true | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
###
Coffee script used for:
1. Creation and Deletion of Project/User
2. Grant and Revoke Permissions from User
Set of bot commands
1. create sonar user test1
2. delete sonar user test1
3. create sonar project testproj
4. delete sonar project testproj
5. grant sonar user access for user test1 to project testproj
Environment variables to set:
1. SONAR_URL
2. SONAR_USER_ID
3. SONAR_PASSWORD
4. HUBOT_NAME
###
#Load Dependencies
eindex = require('./index')
request = require('request')
readjson = require ('./readjson.js');
create_project = require('./create_project.js');
delete_project = require('./delete_project.js');
create_user = require('./create_user.js');
delete_user = require('./delete_user.js');
grant_user = require('./grant_user.js');
revoke_user = require('./revoke_user.js');
list_project = require('./list_project.js');
list_user = require('./list_user.js');
generate_id = require('./mongoConnt');
#Required Environment Variables
sonar_url = process.env.SONAR_URL
sonar_user_id = process.env.SONAR_USER_ID
sonar_password = process.env.SONAR_PASSWORD
botname = process.env.HUBOT_NAME
pod_ip = process.env.MY_POD_IP
post = (recipient, data) ->
optons = {method: "POST", url: recipient, json: data}
request.post optons, (error, response, body) ->
console.log body
module.exports = (robot) ->
robot.respond /help/i, (msg) ->
msg.send '<br>1) create sonar project <<*project-id*>><br>2) list sonar projects<br>3) list sonar users<br>4) delete sonar user <<*user-id*>><br>5) create sonar user <<*user-id*>><br>6) delete sonar project <<*project-id*>><br>7) grant sonar <<*permission-name*>> <<*userid*>> <<*projectid*>><br>8) revoke sonar <<*permission-name*>> <<*userid*>> <<*projectid*>><br>9) getMetrics <<*projectname*>>'
robot.respond /create sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonarcreateproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonarcreateproject.admin,podIp:process.env.MY_POD_IP,projectid:projectid,"callback_id": 'sonarcreateproject',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for create sonar project","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to create a sonar project '+payload.projectid+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonarcreateproject.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project created with ID : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data for wall notification and call from file hubot-elasticsearch-logger/index.js
actionmsg = 'Sonar project created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send (stderr)
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar create project "+request.body.projectid+", requested by "+request.body.username+"\n"
# Approved Message send to the user chat room
projectid = request.body.projectid;
# Call from create_project file for project creation
create_project.create_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
dt.text='Sonar project created with ID : '.concat(projectid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
robot.messageRoom data_http.userid, dt;
# Send data to elastic search for wall notification
message = 'create sonar project '+ projectid;
actionmsg = 'Sonar project created'
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
# Error and Exception handled
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar create project "+request.body.projectid+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /list sonar projects/i, (msg) ->
projectid = msg.match[1]
# Call from list_project file to list available project
list_project.list_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /list sonar users/i, (msg) ->
projectid = msg.match[1]
# Call from list_user file to list available users
list_user.list_user sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout
# Send data to elastic search for logs
setTimeout (->eindex.passData stdout),1000
msg.send stdout;
# Exception and Error Handled
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
robot.respond /delete sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
#Action Flow with workflow flag
if stdout.sonardeleteuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonardeleteuser.admin,podIp:process.env.MY_POD_IP,userids:userids,"callback_id": 'sonardeleteuser',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar delete user","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to delete a sonar user '+payload.userids+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonardeleteuser.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User deleted with ID : '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData stdout),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar delete user "+request.body.userids+", requested by "+request.body.username+"\n"
userids = request.body.userids;
# Call from delete_user file to delete user
delete_user.delete_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'User deleted with ID : '.concat(userids);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'delete sonar user '+ userids;
actionmsg = 'Sonar user deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
robot.messageRoom data_http.userid, error;
else
dt.title=request.body.approver+" rejected sonar delete user "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
# Creation of users
robot.respond /create sonar user (.*)/i, (msg) ->
message = msg.match[0]
userids = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonarcreateuser.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonarcreateuser.admin,podIp:process.env.MY_POD_IP,userids:userids,"callback_id": 'sonarcreateuser',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar create user","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to create a sonar user '+payload.userids+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonarcreateuser.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonarcreateuser.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'User created with ID and password: '.concat(userids);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar user created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonarcreateuser', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar create user "+request.body.userids+", requested by "+request.body.username+"\n"
userids = request.body.userids;
# Call from create_user file to create user
create_user.create_user sonar_url, sonar_user_id, sonar_password, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text= 'User created with ID and password: '.concat(userids);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
message = 'create sonar user '+ userids;
actionmsg = 'Sonar user created';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar create user "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /delete sonar project (.*)/i, (msg) ->
message = msg.match[0]
projectid = msg.match[1]
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.sonardeleteproject.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.sonardeleteproject.admin,podIp:process.env.MY_POD_IP,projectid:projectid,"callback_id": 'sonardeleteproject',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for sonar delete project","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to delete sonar project '+payload.projectid+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.sonardeleteproject.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.sonardeleteproject.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Sonar project deleted with id : '.concat(projectid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/sonardeleteproject', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar delete project "+request.body.projectid+", requested by "+request.body.username+"\n"
projectid = request.body.projectid;
# Call from delete_project file for the deletion of project
delete_project.delete_project sonar_url, sonar_user_id, sonar_password, projectid, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Sonar project deleted with id : '.concat(projectid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'delete sonar project '+ projectid;
actionmsg = 'Sonar project deleted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.title=sdterr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar delete project "+request.body.projectid+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /grant sonar (.*)/i, (msg) ->
message = msg.match[0]
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.grantsonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.grantsonar.admin,podIp:process.env.MY_POD_IP,projid:projid,userids:userids,perm:perm,"callback_id": 'grantsonar',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for grant sonar permission","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to grant sonar '+payload.projid+' '+payload.userids+' '+payload.perm+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.grantsonar.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.grantsonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions granted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/grantsonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar Grant Permission project "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from grant_user file to grant permission to the user for particular project
grant_user.grant_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Granted permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'grant sonar '+ perm;
actionmsg = 'Permissions granted';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text= stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
else
dt.title=request.body.approver+" rejected sonar Grant Permission project "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /revoke sonar (.*)/i, (msg) ->
message = "Sonar permissions revoked"
split_string = msg.match[1].split " ", 3
perm = split_string[0].trim()
userids = split_string[1].trim()
projid = split_string[2].trim()
user = msg.message.user.name
readjson.readworkflow_coffee (error,stdout,stderr) ->
if stdout.revokesonar.workflowflag == true
#Generate Random Ticket Number
generate_id.getNextSequence (err,id) ->
tckid=id
payload={botname:process.env.HUBOT_NAME,username:msg.message.user.name,userid:process.env.CURRENT_CHANNEL,approver:stdout.revokesonar.admin,podIp:process.env.MY_POD_IP,projid:projid,userids:userids,perm:perm,"callback_id": 'revokesonar',msg:msg.toString()}
data = {"type": "MessageCard","context": "http://schema.org/extensions","summary": "Request for revoke sonar permission","themeColor": "81CAF7","sections":[{"startGroup": true,"title": "**Approval Required!**","activityTitle": 'user '+payload.username+' requested to revoke sonar '+payload.projid+' '+payload.userids+' '+payload.perm+'\n',"facts": []},{"potentialAction": [{"@type": "HttpPOST","name": "Approve","target": process.env.APPROVAL_APP_URL+"/Approve","body": "{\"tckid\": \""+tckid+"\" }", "bodyContentType":"application/x-www-form-urlencoded"},{"@type": "HttpPOST","name": "Deny","target": process.env.APPROVAL_APP_URL+"/Rejected","body": "{\"tckid\": \""+tckid+"\" }","bodyContentType":"application/x-www-form-urlencoded"}]}]}
#Post attachment to ms teams
post stdout.revokesonar.adminid, data
msg.send 'Your request is waiting for approval by '+stdout.revokesonar.admin
dataToInsert = {ticketid: tckid, payload: payload, "status":"","approvedby":""}
#Insert into Mongo with Payload
generate_id.add_in_mongo dataToInsert
#Casual workflow
else
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
finalmsg = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
# Send data to elastic search for logs
setTimeout (->eindex.passData finalmsg),1000
msg.send finalmsg;
# Send data to elastic search for wall notification
actionmsg = 'Permissions revoked';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
setTimeout (->eindex.passData stderr),1000
msg.send stderr;
else if error
setTimeout (->eindex.passData error),1000
msg.send error;
#Approval Workflow
robot.router.post '/revokesonar', (request, response) ->
data_http = if request.body.payload? then JSON.parse request.body.payload else request.body
dt = {"text":" ","title":" "}
console.log(data_http)
if data_http.action == "Approve"
dt.title=request.body.approver+" approved sonar revoke permission "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
projid = request.body.projid;
userids = request.body.userids;
perm = request.body.perm;
# Call from revoke_user file to revoke permission from the user for particular project
revoke_user.revoke_user sonar_url, sonar_user_id, sonar_password, perm, projid, userids, (error, stdout, stderr) ->
if stdout == ''
dt.text = 'Revoked permission : '.concat(perm).concat(' for user : ').concat(userids).concat(' for project : ').concat(projid);
post data_http.userid, dt
# Send data to elastic search for logs
setTimeout (->eindex.passData dt),1000
# Send data to elastic search for wall notification
message = 'revoke sonar '+ perm;
actionmsg = 'Permissions revoked';
statusmsg = 'Success';
eindex.wallData botname, message, actionmsg, statusmsg;
else if stderr
dt.text=stderr
post data_http.userid, dt
setTimeout (->eindex.passData stderr),1000
else if error
dt.text=error
post data_http.userid, dt
setTimeout (->eindex.passData error),1000
#Rejection Handled
else
dt.title=request.body.approver+" rejected sonar revoke permission "+request.body.perm+" "+request.body.projid+" "+request.body.userids+", requested by "+request.body.username+"\n"
post data_http.userid, dt
setTimeout (->eindex.passData dt),1000
robot.respond /getMetrics (.*)/i, (msg) ->
project = msg.match[1]
request.get sonar_url+'api/projects', (error, response, body) ->
if error
console.log error
dt = "Error! Please check logs."
msg.send dt
setTimeout (->eindex.passData dt),1000
else
body=JSON.parse(body)
console.log(project)
for i in [0... body.length]
console.log(body[i].k)
if body[i].nm == project
url = sonar_url+'api/measures/component?componentKey='+body[i].k+'&metricKeys=PI:KEY:<KEY>END_PI,sqale_index,duplicated_lines_density,coverage,bugs,code_smells,vulnerabilities'
break
if url == undefined
dt = "Project not found"
msg.send dt
setTimeout (->eindex.passData dt),1000
else
console.log(url)
options = {
url: url,
method: 'GET',
auth: {username: sonar_user_id, password: PI:PASSWORD:<PASSWORD>END_PI}
}
request.get options, (error, response, body) ->
if error
msg.send error
setTimeout (->eindex.passData error),1000
else
dt = ''
body = JSON.parse(body)
if body.errors
for i in [0... body.errors.length]
msg.send body.errors[i].msg
else
for i in [0... body.component.measures.length]
if body.component.measures[i].metric == 'bugs'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'code_smells'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'coverage'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'duplicated_lines_density'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'ncloc'
dt += " Lines of Code: "+body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'sqale_index'
dt += " Technical Debt :" +body.component.measures[i].value+"<br>"
else if body.component.measures[i].metric == 'vulnerabilities'
dt += ' '+body.component.measures[i].metric+": "+body.component.measures[i].value+"<br>"
msg.send dt
setTimeout (->eindex.passData dt),1000
|
[
{
"context": " strings or objects\n # data = [{'name': 'Joe', }, {'name': 'Henry'}, ...]\n typeahead.",
"end": 539,
"score": 0.9997761249542236,
"start": 536,
"tag": "NAME",
"value": "Joe"
},
{
"context": "\n # data = [{'name': 'Joe', }, {'name': 'Henry'}, ... | app/assets/test.coffee | deepakr199/elasticsearch | 0 | # This example does an AJAX lookup and is in CoffeeScript
$('.typeahead').typeahead(
# source can be a function
source: (typeahead, query) ->
# this function receives the typeahead object and the query string
$.ajax(
url: "/lookup/?q="+query
# i'm binding the function here using CoffeeScript syntactic sugar,
# you can use for example Underscore's bind function instead.
success: (data) =>
# data must be a list of either strings or objects
# data = [{'name': 'Joe', }, {'name': 'Henry'}, ...]
typeahead.process(data)
)
# if we return objects to typeahead.process we must specify the property
# that typeahead uses to look up the display value
property: "name"
) | 153083 | # This example does an AJAX lookup and is in CoffeeScript
$('.typeahead').typeahead(
# source can be a function
source: (typeahead, query) ->
# this function receives the typeahead object and the query string
$.ajax(
url: "/lookup/?q="+query
# i'm binding the function here using CoffeeScript syntactic sugar,
# you can use for example Underscore's bind function instead.
success: (data) =>
# data must be a list of either strings or objects
# data = [{'name': '<NAME>', }, {'name': '<NAME>'}, ...]
typeahead.process(data)
)
# if we return objects to typeahead.process we must specify the property
# that typeahead uses to look up the display value
property: "name"
) | true | # This example does an AJAX lookup and is in CoffeeScript
$('.typeahead').typeahead(
# source can be a function
source: (typeahead, query) ->
# this function receives the typeahead object and the query string
$.ajax(
url: "/lookup/?q="+query
# i'm binding the function here using CoffeeScript syntactic sugar,
# you can use for example Underscore's bind function instead.
success: (data) =>
# data must be a list of either strings or objects
# data = [{'name': 'PI:NAME:<NAME>END_PI', }, {'name': 'PI:NAME:<NAME>END_PI'}, ...]
typeahead.process(data)
)
# if we return objects to typeahead.process we must specify the property
# that typeahead uses to look up the display value
property: "name"
) |
[
{
"context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>\n\nroot = exports ? ",
"end": 36,
"score": 0.9998892545700073,
"start": 18,
"tag": "NAME",
"value": "Christopher Joakim"
},
{
"context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.c... | m26-js/src/m26_distance.coffee | cjoakim/oss | 0 | # Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>
root = exports ? this
class Distance
constructor: (d=0, uom=Constants.UOM_MILES) ->
@d = parseFloat(d)
@d = 0 unless @d
if uom
@u = uom.toString().toLowerCase()
else
@u = Constants.UOM_MILES
unless @u in Constants.UNITS_OF_MEASURE
@u = Constants.UOM_MILES
uom: ->
@u
dist: ->
@d
as_miles: ->
switch @u
when Constants.UOM_MILES then @d
when Constants.UOM_KILOMETERS then @d / Constants.KILOMETERS_PER_MILE
when Constants.UOM_YARDS then @d / Constants.YARDS_PER_MILE
else 0
as_kilometers: ->
switch @u
when Constants.UOM_MILES then @d * Constants.KILOMETERS_PER_MILE
when Constants.UOM_KILOMETERS then @d
when Constants.UOM_YARDS then (@d / Constants.YARDS_PER_MILE) / Constants.MILES_PER_KILOMETER
else 0
as_yards: ->
switch @u
when Constants.UOM_MILES then @d * Constants.YARDS_PER_MILE
when Constants.UOM_KILOMETERS then (@d * Constants.MILES_PER_KILOMETER) * Constants.YARDS_PER_MILE
when Constants.UOM_YARDS then @d
else 0
add: (another_instance) ->
if another_instance
d1 = @as_miles()
d2 = another_instance.as_miles()
new Distance(d1 + d2)
subtract: (another_instance) ->
if another_instance
d1 = @as_miles()
d2 = another_instance.as_miles()
new Distance(d1 - d2)
root.Distance = Distance
| 73823 | # Copyright 2015, <NAME> <<EMAIL>>
root = exports ? this
class Distance
constructor: (d=0, uom=Constants.UOM_MILES) ->
@d = parseFloat(d)
@d = 0 unless @d
if uom
@u = uom.toString().toLowerCase()
else
@u = Constants.UOM_MILES
unless @u in Constants.UNITS_OF_MEASURE
@u = Constants.UOM_MILES
uom: ->
@u
dist: ->
@d
as_miles: ->
switch @u
when Constants.UOM_MILES then @d
when Constants.UOM_KILOMETERS then @d / Constants.KILOMETERS_PER_MILE
when Constants.UOM_YARDS then @d / Constants.YARDS_PER_MILE
else 0
as_kilometers: ->
switch @u
when Constants.UOM_MILES then @d * Constants.KILOMETERS_PER_MILE
when Constants.UOM_KILOMETERS then @d
when Constants.UOM_YARDS then (@d / Constants.YARDS_PER_MILE) / Constants.MILES_PER_KILOMETER
else 0
as_yards: ->
switch @u
when Constants.UOM_MILES then @d * Constants.YARDS_PER_MILE
when Constants.UOM_KILOMETERS then (@d * Constants.MILES_PER_KILOMETER) * Constants.YARDS_PER_MILE
when Constants.UOM_YARDS then @d
else 0
add: (another_instance) ->
if another_instance
d1 = @as_miles()
d2 = another_instance.as_miles()
new Distance(d1 + d2)
subtract: (another_instance) ->
if another_instance
d1 = @as_miles()
d2 = another_instance.as_miles()
new Distance(d1 - d2)
root.Distance = Distance
| true | # Copyright 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
root = exports ? this
class Distance
constructor: (d=0, uom=Constants.UOM_MILES) ->
@d = parseFloat(d)
@d = 0 unless @d
if uom
@u = uom.toString().toLowerCase()
else
@u = Constants.UOM_MILES
unless @u in Constants.UNITS_OF_MEASURE
@u = Constants.UOM_MILES
uom: ->
@u
dist: ->
@d
as_miles: ->
switch @u
when Constants.UOM_MILES then @d
when Constants.UOM_KILOMETERS then @d / Constants.KILOMETERS_PER_MILE
when Constants.UOM_YARDS then @d / Constants.YARDS_PER_MILE
else 0
as_kilometers: ->
switch @u
when Constants.UOM_MILES then @d * Constants.KILOMETERS_PER_MILE
when Constants.UOM_KILOMETERS then @d
when Constants.UOM_YARDS then (@d / Constants.YARDS_PER_MILE) / Constants.MILES_PER_KILOMETER
else 0
as_yards: ->
switch @u
when Constants.UOM_MILES then @d * Constants.YARDS_PER_MILE
when Constants.UOM_KILOMETERS then (@d * Constants.MILES_PER_KILOMETER) * Constants.YARDS_PER_MILE
when Constants.UOM_YARDS then @d
else 0
add: (another_instance) ->
if another_instance
d1 = @as_miles()
d2 = another_instance.as_miles()
new Distance(d1 + d2)
subtract: (another_instance) ->
if another_instance
d1 = @as_miles()
d2 = another_instance.as_miles()
new Distance(d1 - d2)
root.Distance = Distance
|
[
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ",
"end": 38,
"score": 0.9998896718025208,
"start": 25,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright... | public/taiga-front/app/coffee/modules/common/history.coffee | mabotech/maboss | 0 | ###
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com>
#
# 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: modules/common/history.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
debounce = @.taiga.debounce
module = angular.module("taigaCommon")
#############################################################################
## History Directive (Main)
#############################################################################
class HistoryController extends taiga.Controller
@.$inject = ["$scope", "$tgRepo", "$tgResources"]
constructor: (@scope, @repo, @rs) ->
initialize: (type, objectId) ->
@.type = type
@.objectId = objectId
loadHistory: (type, objectId) ->
return @rs.history.get(type, objectId).then (history) =>
for historyResult in history
# If description was modified take only the description_html field
if historyResult.values_diff.description_diff?
historyResult.values_diff.description = historyResult.values_diff.description_diff
delete historyResult.values_diff.description_html
delete historyResult.values_diff.description_diff
@scope.history = history
@scope.comments = _.filter(history, (item) -> item.comment != "")
deleteComment: (type, objectId, activityId) ->
return @rs.history.deleteComment(type, objectId, activityId).then => @.loadHistory(type, objectId)
undeleteComment: (type, objectId, activityId) ->
return @rs.history.undeleteComment(type, objectId, activityId).then => @.loadHistory(type, objectId)
HistoryDirective = ($log, $loading, $qqueue) ->
templateChangeDiff = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<p>
<span><%= diff %></span>
</p>
</div>
</div>
""")
templateChangePoints = _.template("""
<% _.each(points, function(point, name) { %>
<div class="change-entry">
<div class="activity-changed">
<span>US points (<%- name.toLowerCase() %>)</span>
</div>
<div class="activity-fromto">
<p>
<strong> from </strong> <br />
<span><%- point[0] %></span>
</p>
<p>
<strong> to </strong> <br />
<span><%- point[1] %></span>
</p>
</div>
</div>
<% }); %>
""")
templateChangeGeneric = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<p>
<strong> from </strong> <br />
<span><%- from %></span>
</p>
<p>
<strong> to </strong> <br />
<span><%- to %></span>
</p>
</div>
</div>
""")
templateChangeAttachment = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<% _.each(diff, function(change) { %>
<p>
<strong><%- change.name %> from </strong> <br />
<span><%- change.from %></span>
</p>
<p>
<strong><%- change.name %> to </strong> <br />
<span><%- change.to %></span>
</p>
<% }) %>
</div>
</div>
""")
templateDeletedComment = _.template("""
<div class="activity-single comment deleted-comment">
<div>
<span>Comment deleted by <%- deleteCommentUser %> on <%- deleteCommentDate %></span>
<a href="" title="Show comment" class="show-deleted-comment">(Show deleted comment)</a>
<a href="" title="Show comment" class="hide-deleted-comment hidden">(Hide deleted comment)</a>
<div class="comment-body wysiwyg"><%= deleteComment %></div>
</div>
<% if (canRestoreComment) { %>
<a href="" class="comment-restore" data-activity-id="<%- activityId %>">
<span class="icon icon-reload"></span>
<span>Restore comment</span>
</a>
<% } %>
</div>
""")
templateActivity = _.template("""
<div class="activity-single <%- mode %>">
<div class="activity-user">
<a class="avatar" href="" title="<%- userFullName %>">
<img src="<%- avatar %>" alt="<%- userFullName %>">
</a>
</div>
<div class="activity-content">
<div class="activity-username">
<a class="username" href="" title="<%- userFullName %>">
<%- userFullName %>
</a>
<span class="date">
<%- creationDate %>
</span>
</div>
<% if (comment.length > 0) { %>
<% if ((deleteCommentDate || deleteCommentUser)) { %>
<div class="deleted-comment">
<span>Comment deleted by <%- deleteCommentUser %> on <%- deleteCommentDate %></span>
</div>
<% } %>
<div class="comment wysiwyg">
<%= comment %>
</div>
<% if (!deleteCommentDate && mode !== "activity" && canDeleteComment) { %>
<a href="" class="icon icon-delete comment-delete" data-activity-id="<%- activityId %>"></a>
<% } %>
<% } %>
<% if(changes.length > 0) { %>
<div class="changes">
<% if (mode != "activity") { %>
<a class="changes-title" href="" title="Show activity">
<span><%- changesText %></span>
<span class="icon icon-arrow-up"></span>
</a>
<% } %>
<% _.each(changes, function(change) { %>
<%= change %>
<% }) %>
</div>
<% } %>
</div>
</div>
""")
templateBaseEntries = _.template("""
<% if (showMore > 0) { %>
<a href="" title="Show more" class="show-more show-more-comments">
+ Show previous entries (<%- showMore %> more)
</a>
<% } %>
<% _.each(entries, function(entry) { %>
<%= entry %>
<% }) %>
""")
templateBase = _.template("""
<section class="history">
<ul class="history-tabs">
<li>
<a href="#" class="active">
<span class="icon icon-comment"></span>
<span class="tab-title">Comments</span>
</a>
</li>
<li>
<a href="#">
<span class="icon icon-issues"></span>
<span class="tab-title">Activity</span>
</a>
</li>
</ul>
<section class="history-comments">
<div class="comments-list"></div>
<div tg-check-permission="modify_<%- type %>" tg-toggle-comment class="add-comment">
<textarea placeholder="Type a new comment here"
ng-model="<%- ngmodel %>.comment" tg-markitup="tg-markitup">
</textarea>
<% if (mode !== "edit") { %>
<a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help">
<span class="icon icon-help"></span>
<span>Markdown syntax help</span>
</a>
<a href="" title="Comment" class="button button-green save-comment">Comment</a>
<% } %>
</div>
</section>
<section class="history-activity hidden">
<div class="changes-list"></div>
</section>
</section>
""")
link = ($scope, $el, $attrs, $ctrl) ->
# Bootstraping
type = $attrs.type
objectId = null
showAllComments = false
showAllActivity = false
bindOnce $scope, $attrs.ngModel, (model) ->
type = $attrs.type
objectId = model.id
$ctrl.initialize(type, objectId)
$ctrl.loadHistory(type, objectId)
# Helpers
getHumanizedFieldName = (field) ->
humanizedFieldNames = {
# US
assigned_to: "assigned to"
is_closed: "is closed"
finish_date: "finish date"
client_requirement: "client requirement"
team_requirement: "team requirement"
# Task
milestone: "sprint"
user_story: "user story"
is_iocaine: "is iocaine"
# Attachment
is_deprecated: "is deprecated"
} # TODO i18n
return humanizedFieldNames[field] or field
getUserFullName = (userId) ->
return $scope.usersById[userId]?.full_name_display
getUserAvatar = (userId) ->
if $scope.usersById[userId]?
return $scope.usersById[userId].photo
else
return "/images/unnamed.png"
countChanges = (comment) ->
return _.keys(comment.values_diff).length
formatChange = (change) ->
if _.isArray(change)
if change.length == 0
return "nil"
return change.join(", ")
if change == ""
return "nil"
if change == true
return "yes"
if change == false
return "no"
return change
# Render into string (operations without mutability)
renderAttachmentEntry = (value) ->
attachments = _.map value, (changes, type) ->
if type == "new"
return _.map changes, (change) ->
# TODO: i18n
return templateChangeDiff({name: "new attachment", diff: change.filename})
else if type == "deleted"
return _.map changes, (change) ->
# TODO: i18n
return templateChangeDiff({name: "deleted attachment", diff: change.filename})
else
return _.map changes, (change) ->
# TODO: i18n
name = "updated attachment #{change.filename}"
diff = _.map change.changes, (values, name) ->
return {
name: getHumanizedFieldName(name)
from: formatChange(values[0])
to: formatChange(values[1])
}
return templateChangeAttachment({name: name, diff: diff})
return _.flatten(attachments).join("\n")
renderChangeEntry = (field, value) ->
if field == "description"
# TODO: i18n
return templateChangeDiff({name: "description", diff: value[1]})
else if field == "points"
return templateChangePoints({points: value})
else if field == "attachments"
return renderAttachmentEntry(value)
else if field == "assigned_to"
name = getHumanizedFieldName(field)
from = formatChange(value[0] or "Unassigned")
to = formatChange(value[1] or "Unassigned")
return templateChangeGeneric({name:name, from:from, to: to})
else
name = getHumanizedFieldName(field)
from = formatChange(value[0])
to = formatChange(value[1])
return templateChangeGeneric({name:name, from:from, to: to})
renderChangeEntries = (change, join=true) ->
entries = _.map(change.values_diff, (value, field) -> renderChangeEntry(field, value))
if join
return entries.join("\n")
return entries
renderChangesHelperText = (change) ->
size = countChanges(change)
if size == 1
return "Made #{size} change" # TODO: i18n
return "Made #{size} changes" # TODO: i18n
renderComment = (comment) ->
if (comment.delete_comment_date or comment.delete_comment_user)
return templateDeletedComment({
deleteCommentDate: moment(comment.delete_comment_date).format("DD MMM YYYY HH:mm")
deleteCommentUser: comment.delete_comment_user.name
deleteComment: comment.comment_html
activityId: comment.id
canRestoreComment: comment.delete_comment_user.pk == $scope.user.id or $scope.project.my_permissions.indexOf("modify_project") > -1
})
return templateActivity({
avatar: getUserAvatar(comment.user.pk)
userFullName: comment.user.name
creationDate: moment(comment.created_at).format("DD MMM YYYY HH:mm")
comment: comment.comment_html
changesText: renderChangesHelperText(comment)
changes: renderChangeEntries(comment, false)
mode: "comment"
deleteCommentDate: moment(comment.delete_comment_date).format("DD MMM YYYY HH:mm") if comment.delete_comment_date
deleteCommentUser: comment.delete_comment_user.name if comment.delete_comment_user?.name
activityId: comment.id
canDeleteComment: comment.user.pk == $scope.user.id or $scope.project.my_permissions.indexOf("modify_project") > -1
})
renderChange = (change) ->
return templateActivity({
avatar: getUserAvatar(change.user.pk)
userFullName: change.user.name
creationDate: moment(change.created_at).format("DD MMM YYYY HH:mm")
comment: change.comment_html
changes: renderChangeEntries(change, false)
changesText: ""
mode: "activity"
deleteCommentDate: moment(change.delete_comment_date).format("DD MMM YYYY HH:mm") if change.delete_comment_date
deleteCommentUser: change.delete_comment_user.name if change.delete_comment_user?.name
activityId: change.id
})
renderHistory = (entries, totalEntries) ->
if entries.length == totalEntries
showMore = 0
else
showMore = totalEntries - entries.length
return templateBaseEntries({entries: entries, showMore:showMore})
# Render into DOM (operations with dom mutability)
renderComments = ->
comments = $scope.comments or []
totalComments = comments.length
if not showAllComments
comments = _.last(comments, 4)
comments = _.map(comments, (x) -> renderComment(x))
html = renderHistory(comments, totalComments)
$el.find(".comments-list").html(html)
renderActivity = ->
changes = $scope.history or []
totalChanges = changes.length
if not showAllActivity
changes = _.last(changes, 4)
changes = _.map(changes, (x) -> renderChange(x))
html = renderHistory(changes, totalChanges)
$el.find(".changes-list").html(html)
save = $qqueue.bindAdd (target) =>
$scope.$broadcast("markdown-editor:submit")
$el.find(".comment-list").addClass("activeanimation")
onSuccess = ->
$ctrl.loadHistory(type, objectId).finally ->
$loading.finish(target)
onError = ->
$loading.finish(target)
$confirm.notify("error")
model = $scope.$eval($attrs.ngModel)
$loading.start(target)
$ctrl.repo.save(model).then(onSuccess, onError)
# Watchers
$scope.$watch("comments", renderComments)
$scope.$watch("history", renderActivity)
$scope.$on("history:reload", -> $ctrl.loadHistory(type, objectId))
# Events
$el.on "click", ".add-comment a.button-green", debounce 2000, (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
save(target)
$el.on "click", ".show-more", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
if target.parent().is(".changes-list")
showAllActivity = not showAllActivity
renderActivity()
else
showAllComments = not showAllComments
renderComments()
$el.on "click", ".show-deleted-comment", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parents('.activity-single').find('.hide-deleted-comment').show()
target.parents('.activity-single').find('.show-deleted-comment').hide()
target.parents('.activity-single').find('.comment-body').show()
$el.on "click", ".hide-deleted-comment", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parents('.activity-single').find('.hide-deleted-comment').hide()
target.parents('.activity-single').find('.show-deleted-comment').show()
target.parents('.activity-single').find('.comment-body').hide()
$el.on "click", ".changes-title", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parent().find(".change-entry").toggleClass("active")
$el.on "focus", ".add-comment textarea", (event) ->
$(this).addClass('active')
$el.on "click", ".history-tabs li a", (event) ->
$el.find(".history-tabs li a").toggleClass("active")
$el.find(".history section").toggleClass("hidden")
$el.on "click", ".comment-delete", debounce 2000, (event) ->
target = angular.element(event.currentTarget)
activityId = target.data('activity-id')
$ctrl.deleteComment(type, objectId, activityId)
$el.on "click", ".comment-restore", debounce 2000, (event) ->
target = angular.element(event.currentTarget)
activityId = target.data('activity-id')
$ctrl.undeleteComment(type, objectId, activityId)
$scope.$on "$destroy", ->
$el.off()
templateFn = ($el, $attrs) ->
return templateBase({ngmodel: $attrs.ngModel, type: $attrs.type, mode: $attrs.mode})
return {
controller: HistoryController
template: templateFn
restrict: "AE"
link: link
# require: ["ngModel", "tgHistory"]
}
module.directive("tgHistory", ["$log", "$tgLoading", "$tgQqueue", HistoryDirective])
| 48168 | ###
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
# Copyright (C) 2014 <NAME> <<EMAIL>>
#
# 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: modules/common/history.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
debounce = @.taiga.debounce
module = angular.module("taigaCommon")
#############################################################################
## History Directive (Main)
#############################################################################
class HistoryController extends taiga.Controller
@.$inject = ["$scope", "$tgRepo", "$tgResources"]
constructor: (@scope, @repo, @rs) ->
initialize: (type, objectId) ->
@.type = type
@.objectId = objectId
loadHistory: (type, objectId) ->
return @rs.history.get(type, objectId).then (history) =>
for historyResult in history
# If description was modified take only the description_html field
if historyResult.values_diff.description_diff?
historyResult.values_diff.description = historyResult.values_diff.description_diff
delete historyResult.values_diff.description_html
delete historyResult.values_diff.description_diff
@scope.history = history
@scope.comments = _.filter(history, (item) -> item.comment != "")
deleteComment: (type, objectId, activityId) ->
return @rs.history.deleteComment(type, objectId, activityId).then => @.loadHistory(type, objectId)
undeleteComment: (type, objectId, activityId) ->
return @rs.history.undeleteComment(type, objectId, activityId).then => @.loadHistory(type, objectId)
HistoryDirective = ($log, $loading, $qqueue) ->
templateChangeDiff = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<p>
<span><%= diff %></span>
</p>
</div>
</div>
""")
templateChangePoints = _.template("""
<% _.each(points, function(point, name) { %>
<div class="change-entry">
<div class="activity-changed">
<span>US points (<%- name.toLowerCase() %>)</span>
</div>
<div class="activity-fromto">
<p>
<strong> from </strong> <br />
<span><%- point[0] %></span>
</p>
<p>
<strong> to </strong> <br />
<span><%- point[1] %></span>
</p>
</div>
</div>
<% }); %>
""")
templateChangeGeneric = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<p>
<strong> from </strong> <br />
<span><%- from %></span>
</p>
<p>
<strong> to </strong> <br />
<span><%- to %></span>
</p>
</div>
</div>
""")
templateChangeAttachment = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<% _.each(diff, function(change) { %>
<p>
<strong><%- change.name %> from </strong> <br />
<span><%- change.from %></span>
</p>
<p>
<strong><%- change.name %> to </strong> <br />
<span><%- change.to %></span>
</p>
<% }) %>
</div>
</div>
""")
templateDeletedComment = _.template("""
<div class="activity-single comment deleted-comment">
<div>
<span>Comment deleted by <%- deleteCommentUser %> on <%- deleteCommentDate %></span>
<a href="" title="Show comment" class="show-deleted-comment">(Show deleted comment)</a>
<a href="" title="Show comment" class="hide-deleted-comment hidden">(Hide deleted comment)</a>
<div class="comment-body wysiwyg"><%= deleteComment %></div>
</div>
<% if (canRestoreComment) { %>
<a href="" class="comment-restore" data-activity-id="<%- activityId %>">
<span class="icon icon-reload"></span>
<span>Restore comment</span>
</a>
<% } %>
</div>
""")
templateActivity = _.template("""
<div class="activity-single <%- mode %>">
<div class="activity-user">
<a class="avatar" href="" title="<%- userFullName %>">
<img src="<%- avatar %>" alt="<%- userFullName %>">
</a>
</div>
<div class="activity-content">
<div class="activity-username">
<a class="username" href="" title="<%- userFullName %>">
<%- userFullName %>
</a>
<span class="date">
<%- creationDate %>
</span>
</div>
<% if (comment.length > 0) { %>
<% if ((deleteCommentDate || deleteCommentUser)) { %>
<div class="deleted-comment">
<span>Comment deleted by <%- deleteCommentUser %> on <%- deleteCommentDate %></span>
</div>
<% } %>
<div class="comment wysiwyg">
<%= comment %>
</div>
<% if (!deleteCommentDate && mode !== "activity" && canDeleteComment) { %>
<a href="" class="icon icon-delete comment-delete" data-activity-id="<%- activityId %>"></a>
<% } %>
<% } %>
<% if(changes.length > 0) { %>
<div class="changes">
<% if (mode != "activity") { %>
<a class="changes-title" href="" title="Show activity">
<span><%- changesText %></span>
<span class="icon icon-arrow-up"></span>
</a>
<% } %>
<% _.each(changes, function(change) { %>
<%= change %>
<% }) %>
</div>
<% } %>
</div>
</div>
""")
templateBaseEntries = _.template("""
<% if (showMore > 0) { %>
<a href="" title="Show more" class="show-more show-more-comments">
+ Show previous entries (<%- showMore %> more)
</a>
<% } %>
<% _.each(entries, function(entry) { %>
<%= entry %>
<% }) %>
""")
templateBase = _.template("""
<section class="history">
<ul class="history-tabs">
<li>
<a href="#" class="active">
<span class="icon icon-comment"></span>
<span class="tab-title">Comments</span>
</a>
</li>
<li>
<a href="#">
<span class="icon icon-issues"></span>
<span class="tab-title">Activity</span>
</a>
</li>
</ul>
<section class="history-comments">
<div class="comments-list"></div>
<div tg-check-permission="modify_<%- type %>" tg-toggle-comment class="add-comment">
<textarea placeholder="Type a new comment here"
ng-model="<%- ngmodel %>.comment" tg-markitup="tg-markitup">
</textarea>
<% if (mode !== "edit") { %>
<a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help">
<span class="icon icon-help"></span>
<span>Markdown syntax help</span>
</a>
<a href="" title="Comment" class="button button-green save-comment">Comment</a>
<% } %>
</div>
</section>
<section class="history-activity hidden">
<div class="changes-list"></div>
</section>
</section>
""")
link = ($scope, $el, $attrs, $ctrl) ->
# Bootstraping
type = $attrs.type
objectId = null
showAllComments = false
showAllActivity = false
bindOnce $scope, $attrs.ngModel, (model) ->
type = $attrs.type
objectId = model.id
$ctrl.initialize(type, objectId)
$ctrl.loadHistory(type, objectId)
# Helpers
getHumanizedFieldName = (field) ->
humanizedFieldNames = {
# US
assigned_to: "assigned to"
is_closed: "is closed"
finish_date: "finish date"
client_requirement: "client requirement"
team_requirement: "team requirement"
# Task
milestone: "sprint"
user_story: "user story"
is_iocaine: "is iocaine"
# Attachment
is_deprecated: "is deprecated"
} # TODO i18n
return humanizedFieldNames[field] or field
getUserFullName = (userId) ->
return $scope.usersById[userId]?.full_name_display
getUserAvatar = (userId) ->
if $scope.usersById[userId]?
return $scope.usersById[userId].photo
else
return "/images/unnamed.png"
countChanges = (comment) ->
return _.keys(comment.values_diff).length
formatChange = (change) ->
if _.isArray(change)
if change.length == 0
return "nil"
return change.join(", ")
if change == ""
return "nil"
if change == true
return "yes"
if change == false
return "no"
return change
# Render into string (operations without mutability)
renderAttachmentEntry = (value) ->
attachments = _.map value, (changes, type) ->
if type == "new"
return _.map changes, (change) ->
# TODO: i18n
return templateChangeDiff({name: "new attachment", diff: change.filename})
else if type == "deleted"
return _.map changes, (change) ->
# TODO: i18n
return templateChangeDiff({name: "deleted attachment", diff: change.filename})
else
return _.map changes, (change) ->
# TODO: i18n
name = "updated attachment #{change.filename}"
diff = _.map change.changes, (values, name) ->
return {
name: getHumanizedFieldName(name)
from: formatChange(values[0])
to: formatChange(values[1])
}
return templateChangeAttachment({name: name, diff: diff})
return _.flatten(attachments).join("\n")
renderChangeEntry = (field, value) ->
if field == "description"
# TODO: i18n
return templateChangeDiff({name: "description", diff: value[1]})
else if field == "points"
return templateChangePoints({points: value})
else if field == "attachments"
return renderAttachmentEntry(value)
else if field == "assigned_to"
name = getHumanizedFieldName(field)
from = formatChange(value[0] or "Unassigned")
to = formatChange(value[1] or "Unassigned")
return templateChangeGeneric({name:name, from:from, to: to})
else
name = getHumanizedFieldName(field)
from = formatChange(value[0])
to = formatChange(value[1])
return templateChangeGeneric({name:name, from:from, to: to})
renderChangeEntries = (change, join=true) ->
entries = _.map(change.values_diff, (value, field) -> renderChangeEntry(field, value))
if join
return entries.join("\n")
return entries
renderChangesHelperText = (change) ->
size = countChanges(change)
if size == 1
return "Made #{size} change" # TODO: i18n
return "Made #{size} changes" # TODO: i18n
renderComment = (comment) ->
if (comment.delete_comment_date or comment.delete_comment_user)
return templateDeletedComment({
deleteCommentDate: moment(comment.delete_comment_date).format("DD MMM YYYY HH:mm")
deleteCommentUser: comment.delete_comment_user.name
deleteComment: comment.comment_html
activityId: comment.id
canRestoreComment: comment.delete_comment_user.pk == $scope.user.id or $scope.project.my_permissions.indexOf("modify_project") > -1
})
return templateActivity({
avatar: getUserAvatar(comment.user.pk)
userFullName: comment.user.name
creationDate: moment(comment.created_at).format("DD MMM YYYY HH:mm")
comment: comment.comment_html
changesText: renderChangesHelperText(comment)
changes: renderChangeEntries(comment, false)
mode: "comment"
deleteCommentDate: moment(comment.delete_comment_date).format("DD MMM YYYY HH:mm") if comment.delete_comment_date
deleteCommentUser: comment.delete_comment_user.name if comment.delete_comment_user?.name
activityId: comment.id
canDeleteComment: comment.user.pk == $scope.user.id or $scope.project.my_permissions.indexOf("modify_project") > -1
})
renderChange = (change) ->
return templateActivity({
avatar: getUserAvatar(change.user.pk)
userFullName: change.user.name
creationDate: moment(change.created_at).format("DD MMM YYYY HH:mm")
comment: change.comment_html
changes: renderChangeEntries(change, false)
changesText: ""
mode: "activity"
deleteCommentDate: moment(change.delete_comment_date).format("DD MMM YYYY HH:mm") if change.delete_comment_date
deleteCommentUser: change.delete_comment_user.name if change.delete_comment_user?.name
activityId: change.id
})
renderHistory = (entries, totalEntries) ->
if entries.length == totalEntries
showMore = 0
else
showMore = totalEntries - entries.length
return templateBaseEntries({entries: entries, showMore:showMore})
# Render into DOM (operations with dom mutability)
renderComments = ->
comments = $scope.comments or []
totalComments = comments.length
if not showAllComments
comments = _.last(comments, 4)
comments = _.map(comments, (x) -> renderComment(x))
html = renderHistory(comments, totalComments)
$el.find(".comments-list").html(html)
renderActivity = ->
changes = $scope.history or []
totalChanges = changes.length
if not showAllActivity
changes = _.last(changes, 4)
changes = _.map(changes, (x) -> renderChange(x))
html = renderHistory(changes, totalChanges)
$el.find(".changes-list").html(html)
save = $qqueue.bindAdd (target) =>
$scope.$broadcast("markdown-editor:submit")
$el.find(".comment-list").addClass("activeanimation")
onSuccess = ->
$ctrl.loadHistory(type, objectId).finally ->
$loading.finish(target)
onError = ->
$loading.finish(target)
$confirm.notify("error")
model = $scope.$eval($attrs.ngModel)
$loading.start(target)
$ctrl.repo.save(model).then(onSuccess, onError)
# Watchers
$scope.$watch("comments", renderComments)
$scope.$watch("history", renderActivity)
$scope.$on("history:reload", -> $ctrl.loadHistory(type, objectId))
# Events
$el.on "click", ".add-comment a.button-green", debounce 2000, (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
save(target)
$el.on "click", ".show-more", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
if target.parent().is(".changes-list")
showAllActivity = not showAllActivity
renderActivity()
else
showAllComments = not showAllComments
renderComments()
$el.on "click", ".show-deleted-comment", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parents('.activity-single').find('.hide-deleted-comment').show()
target.parents('.activity-single').find('.show-deleted-comment').hide()
target.parents('.activity-single').find('.comment-body').show()
$el.on "click", ".hide-deleted-comment", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parents('.activity-single').find('.hide-deleted-comment').hide()
target.parents('.activity-single').find('.show-deleted-comment').show()
target.parents('.activity-single').find('.comment-body').hide()
$el.on "click", ".changes-title", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parent().find(".change-entry").toggleClass("active")
$el.on "focus", ".add-comment textarea", (event) ->
$(this).addClass('active')
$el.on "click", ".history-tabs li a", (event) ->
$el.find(".history-tabs li a").toggleClass("active")
$el.find(".history section").toggleClass("hidden")
$el.on "click", ".comment-delete", debounce 2000, (event) ->
target = angular.element(event.currentTarget)
activityId = target.data('activity-id')
$ctrl.deleteComment(type, objectId, activityId)
$el.on "click", ".comment-restore", debounce 2000, (event) ->
target = angular.element(event.currentTarget)
activityId = target.data('activity-id')
$ctrl.undeleteComment(type, objectId, activityId)
$scope.$on "$destroy", ->
$el.off()
templateFn = ($el, $attrs) ->
return templateBase({ngmodel: $attrs.ngModel, type: $attrs.type, mode: $attrs.mode})
return {
controller: HistoryController
template: templateFn
restrict: "AE"
link: link
# require: ["ngModel", "tgHistory"]
}
module.directive("tgHistory", ["$log", "$tgLoading", "$tgQqueue", HistoryDirective])
| true | ###
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# 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: modules/common/history.coffee
###
taiga = @.taiga
trim = @.taiga.trim
bindOnce = @.taiga.bindOnce
debounce = @.taiga.debounce
module = angular.module("taigaCommon")
#############################################################################
## History Directive (Main)
#############################################################################
class HistoryController extends taiga.Controller
@.$inject = ["$scope", "$tgRepo", "$tgResources"]
constructor: (@scope, @repo, @rs) ->
initialize: (type, objectId) ->
@.type = type
@.objectId = objectId
loadHistory: (type, objectId) ->
return @rs.history.get(type, objectId).then (history) =>
for historyResult in history
# If description was modified take only the description_html field
if historyResult.values_diff.description_diff?
historyResult.values_diff.description = historyResult.values_diff.description_diff
delete historyResult.values_diff.description_html
delete historyResult.values_diff.description_diff
@scope.history = history
@scope.comments = _.filter(history, (item) -> item.comment != "")
deleteComment: (type, objectId, activityId) ->
return @rs.history.deleteComment(type, objectId, activityId).then => @.loadHistory(type, objectId)
undeleteComment: (type, objectId, activityId) ->
return @rs.history.undeleteComment(type, objectId, activityId).then => @.loadHistory(type, objectId)
HistoryDirective = ($log, $loading, $qqueue) ->
templateChangeDiff = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<p>
<span><%= diff %></span>
</p>
</div>
</div>
""")
templateChangePoints = _.template("""
<% _.each(points, function(point, name) { %>
<div class="change-entry">
<div class="activity-changed">
<span>US points (<%- name.toLowerCase() %>)</span>
</div>
<div class="activity-fromto">
<p>
<strong> from </strong> <br />
<span><%- point[0] %></span>
</p>
<p>
<strong> to </strong> <br />
<span><%- point[1] %></span>
</p>
</div>
</div>
<% }); %>
""")
templateChangeGeneric = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<p>
<strong> from </strong> <br />
<span><%- from %></span>
</p>
<p>
<strong> to </strong> <br />
<span><%- to %></span>
</p>
</div>
</div>
""")
templateChangeAttachment = _.template("""
<div class="change-entry">
<div class="activity-changed">
<span><%- name %></span>
</div>
<div class="activity-fromto">
<% _.each(diff, function(change) { %>
<p>
<strong><%- change.name %> from </strong> <br />
<span><%- change.from %></span>
</p>
<p>
<strong><%- change.name %> to </strong> <br />
<span><%- change.to %></span>
</p>
<% }) %>
</div>
</div>
""")
templateDeletedComment = _.template("""
<div class="activity-single comment deleted-comment">
<div>
<span>Comment deleted by <%- deleteCommentUser %> on <%- deleteCommentDate %></span>
<a href="" title="Show comment" class="show-deleted-comment">(Show deleted comment)</a>
<a href="" title="Show comment" class="hide-deleted-comment hidden">(Hide deleted comment)</a>
<div class="comment-body wysiwyg"><%= deleteComment %></div>
</div>
<% if (canRestoreComment) { %>
<a href="" class="comment-restore" data-activity-id="<%- activityId %>">
<span class="icon icon-reload"></span>
<span>Restore comment</span>
</a>
<% } %>
</div>
""")
templateActivity = _.template("""
<div class="activity-single <%- mode %>">
<div class="activity-user">
<a class="avatar" href="" title="<%- userFullName %>">
<img src="<%- avatar %>" alt="<%- userFullName %>">
</a>
</div>
<div class="activity-content">
<div class="activity-username">
<a class="username" href="" title="<%- userFullName %>">
<%- userFullName %>
</a>
<span class="date">
<%- creationDate %>
</span>
</div>
<% if (comment.length > 0) { %>
<% if ((deleteCommentDate || deleteCommentUser)) { %>
<div class="deleted-comment">
<span>Comment deleted by <%- deleteCommentUser %> on <%- deleteCommentDate %></span>
</div>
<% } %>
<div class="comment wysiwyg">
<%= comment %>
</div>
<% if (!deleteCommentDate && mode !== "activity" && canDeleteComment) { %>
<a href="" class="icon icon-delete comment-delete" data-activity-id="<%- activityId %>"></a>
<% } %>
<% } %>
<% if(changes.length > 0) { %>
<div class="changes">
<% if (mode != "activity") { %>
<a class="changes-title" href="" title="Show activity">
<span><%- changesText %></span>
<span class="icon icon-arrow-up"></span>
</a>
<% } %>
<% _.each(changes, function(change) { %>
<%= change %>
<% }) %>
</div>
<% } %>
</div>
</div>
""")
templateBaseEntries = _.template("""
<% if (showMore > 0) { %>
<a href="" title="Show more" class="show-more show-more-comments">
+ Show previous entries (<%- showMore %> more)
</a>
<% } %>
<% _.each(entries, function(entry) { %>
<%= entry %>
<% }) %>
""")
templateBase = _.template("""
<section class="history">
<ul class="history-tabs">
<li>
<a href="#" class="active">
<span class="icon icon-comment"></span>
<span class="tab-title">Comments</span>
</a>
</li>
<li>
<a href="#">
<span class="icon icon-issues"></span>
<span class="tab-title">Activity</span>
</a>
</li>
</ul>
<section class="history-comments">
<div class="comments-list"></div>
<div tg-check-permission="modify_<%- type %>" tg-toggle-comment class="add-comment">
<textarea placeholder="Type a new comment here"
ng-model="<%- ngmodel %>.comment" tg-markitup="tg-markitup">
</textarea>
<% if (mode !== "edit") { %>
<a class="help-markdown" href="https://taiga.io/support/taiga-markdown-syntax/" target="_blank" title="Mardown syntax help">
<span class="icon icon-help"></span>
<span>Markdown syntax help</span>
</a>
<a href="" title="Comment" class="button button-green save-comment">Comment</a>
<% } %>
</div>
</section>
<section class="history-activity hidden">
<div class="changes-list"></div>
</section>
</section>
""")
link = ($scope, $el, $attrs, $ctrl) ->
# Bootstraping
type = $attrs.type
objectId = null
showAllComments = false
showAllActivity = false
bindOnce $scope, $attrs.ngModel, (model) ->
type = $attrs.type
objectId = model.id
$ctrl.initialize(type, objectId)
$ctrl.loadHistory(type, objectId)
# Helpers
getHumanizedFieldName = (field) ->
humanizedFieldNames = {
# US
assigned_to: "assigned to"
is_closed: "is closed"
finish_date: "finish date"
client_requirement: "client requirement"
team_requirement: "team requirement"
# Task
milestone: "sprint"
user_story: "user story"
is_iocaine: "is iocaine"
# Attachment
is_deprecated: "is deprecated"
} # TODO i18n
return humanizedFieldNames[field] or field
getUserFullName = (userId) ->
return $scope.usersById[userId]?.full_name_display
getUserAvatar = (userId) ->
if $scope.usersById[userId]?
return $scope.usersById[userId].photo
else
return "/images/unnamed.png"
countChanges = (comment) ->
return _.keys(comment.values_diff).length
formatChange = (change) ->
if _.isArray(change)
if change.length == 0
return "nil"
return change.join(", ")
if change == ""
return "nil"
if change == true
return "yes"
if change == false
return "no"
return change
# Render into string (operations without mutability)
renderAttachmentEntry = (value) ->
attachments = _.map value, (changes, type) ->
if type == "new"
return _.map changes, (change) ->
# TODO: i18n
return templateChangeDiff({name: "new attachment", diff: change.filename})
else if type == "deleted"
return _.map changes, (change) ->
# TODO: i18n
return templateChangeDiff({name: "deleted attachment", diff: change.filename})
else
return _.map changes, (change) ->
# TODO: i18n
name = "updated attachment #{change.filename}"
diff = _.map change.changes, (values, name) ->
return {
name: getHumanizedFieldName(name)
from: formatChange(values[0])
to: formatChange(values[1])
}
return templateChangeAttachment({name: name, diff: diff})
return _.flatten(attachments).join("\n")
renderChangeEntry = (field, value) ->
if field == "description"
# TODO: i18n
return templateChangeDiff({name: "description", diff: value[1]})
else if field == "points"
return templateChangePoints({points: value})
else if field == "attachments"
return renderAttachmentEntry(value)
else if field == "assigned_to"
name = getHumanizedFieldName(field)
from = formatChange(value[0] or "Unassigned")
to = formatChange(value[1] or "Unassigned")
return templateChangeGeneric({name:name, from:from, to: to})
else
name = getHumanizedFieldName(field)
from = formatChange(value[0])
to = formatChange(value[1])
return templateChangeGeneric({name:name, from:from, to: to})
renderChangeEntries = (change, join=true) ->
entries = _.map(change.values_diff, (value, field) -> renderChangeEntry(field, value))
if join
return entries.join("\n")
return entries
renderChangesHelperText = (change) ->
size = countChanges(change)
if size == 1
return "Made #{size} change" # TODO: i18n
return "Made #{size} changes" # TODO: i18n
renderComment = (comment) ->
if (comment.delete_comment_date or comment.delete_comment_user)
return templateDeletedComment({
deleteCommentDate: moment(comment.delete_comment_date).format("DD MMM YYYY HH:mm")
deleteCommentUser: comment.delete_comment_user.name
deleteComment: comment.comment_html
activityId: comment.id
canRestoreComment: comment.delete_comment_user.pk == $scope.user.id or $scope.project.my_permissions.indexOf("modify_project") > -1
})
return templateActivity({
avatar: getUserAvatar(comment.user.pk)
userFullName: comment.user.name
creationDate: moment(comment.created_at).format("DD MMM YYYY HH:mm")
comment: comment.comment_html
changesText: renderChangesHelperText(comment)
changes: renderChangeEntries(comment, false)
mode: "comment"
deleteCommentDate: moment(comment.delete_comment_date).format("DD MMM YYYY HH:mm") if comment.delete_comment_date
deleteCommentUser: comment.delete_comment_user.name if comment.delete_comment_user?.name
activityId: comment.id
canDeleteComment: comment.user.pk == $scope.user.id or $scope.project.my_permissions.indexOf("modify_project") > -1
})
renderChange = (change) ->
return templateActivity({
avatar: getUserAvatar(change.user.pk)
userFullName: change.user.name
creationDate: moment(change.created_at).format("DD MMM YYYY HH:mm")
comment: change.comment_html
changes: renderChangeEntries(change, false)
changesText: ""
mode: "activity"
deleteCommentDate: moment(change.delete_comment_date).format("DD MMM YYYY HH:mm") if change.delete_comment_date
deleteCommentUser: change.delete_comment_user.name if change.delete_comment_user?.name
activityId: change.id
})
renderHistory = (entries, totalEntries) ->
if entries.length == totalEntries
showMore = 0
else
showMore = totalEntries - entries.length
return templateBaseEntries({entries: entries, showMore:showMore})
# Render into DOM (operations with dom mutability)
renderComments = ->
comments = $scope.comments or []
totalComments = comments.length
if not showAllComments
comments = _.last(comments, 4)
comments = _.map(comments, (x) -> renderComment(x))
html = renderHistory(comments, totalComments)
$el.find(".comments-list").html(html)
renderActivity = ->
changes = $scope.history or []
totalChanges = changes.length
if not showAllActivity
changes = _.last(changes, 4)
changes = _.map(changes, (x) -> renderChange(x))
html = renderHistory(changes, totalChanges)
$el.find(".changes-list").html(html)
save = $qqueue.bindAdd (target) =>
$scope.$broadcast("markdown-editor:submit")
$el.find(".comment-list").addClass("activeanimation")
onSuccess = ->
$ctrl.loadHistory(type, objectId).finally ->
$loading.finish(target)
onError = ->
$loading.finish(target)
$confirm.notify("error")
model = $scope.$eval($attrs.ngModel)
$loading.start(target)
$ctrl.repo.save(model).then(onSuccess, onError)
# Watchers
$scope.$watch("comments", renderComments)
$scope.$watch("history", renderActivity)
$scope.$on("history:reload", -> $ctrl.loadHistory(type, objectId))
# Events
$el.on "click", ".add-comment a.button-green", debounce 2000, (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
save(target)
$el.on "click", ".show-more", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
if target.parent().is(".changes-list")
showAllActivity = not showAllActivity
renderActivity()
else
showAllComments = not showAllComments
renderComments()
$el.on "click", ".show-deleted-comment", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parents('.activity-single').find('.hide-deleted-comment').show()
target.parents('.activity-single').find('.show-deleted-comment').hide()
target.parents('.activity-single').find('.comment-body').show()
$el.on "click", ".hide-deleted-comment", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parents('.activity-single').find('.hide-deleted-comment').hide()
target.parents('.activity-single').find('.show-deleted-comment').show()
target.parents('.activity-single').find('.comment-body').hide()
$el.on "click", ".changes-title", (event) ->
event.preventDefault()
target = angular.element(event.currentTarget)
target.parent().find(".change-entry").toggleClass("active")
$el.on "focus", ".add-comment textarea", (event) ->
$(this).addClass('active')
$el.on "click", ".history-tabs li a", (event) ->
$el.find(".history-tabs li a").toggleClass("active")
$el.find(".history section").toggleClass("hidden")
$el.on "click", ".comment-delete", debounce 2000, (event) ->
target = angular.element(event.currentTarget)
activityId = target.data('activity-id')
$ctrl.deleteComment(type, objectId, activityId)
$el.on "click", ".comment-restore", debounce 2000, (event) ->
target = angular.element(event.currentTarget)
activityId = target.data('activity-id')
$ctrl.undeleteComment(type, objectId, activityId)
$scope.$on "$destroy", ->
$el.off()
templateFn = ($el, $attrs) ->
return templateBase({ngmodel: $attrs.ngModel, type: $attrs.type, mode: $attrs.mode})
return {
controller: HistoryController
template: templateFn
restrict: "AE"
link: link
# require: ["ngModel", "tgHistory"]
}
module.directive("tgHistory", ["$log", "$tgLoading", "$tgQqueue", HistoryDirective])
|
[
{
"context": " {\n ship: 'X-Wing'\n pilot: 'Luke Skywalker'\n upgrades: [\n 'Lone Wo",
"end": 246,
"score": 0.6460283994674683,
"start": 232,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "e\n common.addShip('#rebel-builde... | tests/test_clone.coffee | CrazyVulcan/xwing | 100 | common = require './common'
common.setup()
casper.test.begin "Copy pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Luke Skywalker'
upgrades: [
'Lone Wolf'
'Proton Torpedoes'
'R5-P9'
'Engine Upgrade'
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
# Unique pilots can't be cloned, but the clone will pick either a generic
# or the cheapest named
.then ->
@log("#rebel-builder #{common.selectorForCloneShip(1)}")
test.assertVisible("#rebel-builder #{common.selectorForCloneShip(1)}", "Unique pilots may be cloned")
# Unique clones to generic
common.cloneShip('#rebel-builder', 1)
common.assertShipTypeIs(test, '#rebel-builder', 3, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 3, 'Rookie Pilot')
# ...but only sends valid upgrades
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Proton Torpedoes')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 3, 2)
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Engine Upgrade')
# Non-uniques
common.cloneShip('#rebel-builder', 2)
common.assertShipTypeIs(test, '#rebel-builder', 4, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 4, 'Red Squadron Pilot')
# Don't clone uniques
common.addUpgrade('#rebel-builder', 2, 2, 'R2-D2')
common.cloneShip('#rebel-builder', 2)
common.assertShipTypeIs(test, '#rebel-builder', 5, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 5, 'Red Squadron Pilot')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 5, 2)
# Handle cloning when a unique would confer an upgrade
common.addShip('#rebel-builder', 'X-Wing', 'Tarn Mison')
common.addUpgrade('#rebel-builder', 6, 2, 'R2-D6')
common.addUpgrade('#rebel-builder', 6, 4, 'Calculation')
common.cloneShip('#rebel-builder', 6)
common.assertShipTypeIs(test, '#rebel-builder', 7, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 7, 'Rookie Pilot')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 7, 2)
test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 7, 4}"
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy A-Wing with Test Pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'A-Wing'
pilot: 'Green Squadron Pilot'
upgrades: [
'Deadeye'
null
'A-Wing Test Pilot'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 44)
common.removeShip('#rebel-builder', 2)
common.addUpgrade('#rebel-builder', 1, 5, 'Squad Leader')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 42)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy B-Wing with B-Wing/E2", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'B-Wing'
pilot: 'Blue Squadron Pilot'
upgrades: [
'Fire-Control System'
null
'Proton Torpedoes'
null
'B-Wing/E2'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 6, 'Targeting Coordinator')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 33 * 2)
common.removeShip('#rebel-builder', 1)
common.addUpgrade('#rebel-builder', 1, 6, 'Nien Nunb')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 59)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy Royal Guard Pilot with Royal Guard TIE", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'TIE Interceptor'
pilot: 'Royal Guard Pilot'
upgrades: [
'Determination'
'Royal Guard TIE'
'Stealth Device'
]
}
])
common.addUpgrade('#empire-builder', 1, 4, 'Hull Upgrade')
common.cloneShip('#empire-builder', 1)
common.assertTotalPoints(test, '#empire-builder', 58)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
casper.test.begin "Copy IG-88", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'Aggressor'
pilot: 'IG-88C'
upgrades: [
'Lone Wolf'
'Advanced Sensors'
'Heavy Laser Cannon'
null
null
null
'IG-2000'
'Autothrusters'
]
}
])
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(2, 1)}")
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(3, 1)}")
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(4, 1)}")
# Clone should do nothing now
common.cloneShip('#scum-builder', 1)
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForShipIndex(5)}")
common.assertTotalPoints(test, '#scum-builder', 194)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
.run ->
test.done()
| 136987 | common = require './common'
common.setup()
casper.test.begin "Copy pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: '<NAME>'
upgrades: [
'Lone Wolf'
'Proton Torpedoes'
'R5-P9'
'Engine Upgrade'
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
# Unique pilots can't be cloned, but the clone will pick either a generic
# or the cheapest named
.then ->
@log("#rebel-builder #{common.selectorForCloneShip(1)}")
test.assertVisible("#rebel-builder #{common.selectorForCloneShip(1)}", "Unique pilots may be cloned")
# Unique clones to generic
common.cloneShip('#rebel-builder', 1)
common.assertShipTypeIs(test, '#rebel-builder', 3, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 3, 'Rookie Pilot')
# ...but only sends valid upgrades
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Proton Torpedoes')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 3, 2)
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Engine Upgrade')
# Non-uniques
common.cloneShip('#rebel-builder', 2)
common.assertShipTypeIs(test, '#rebel-builder', 4, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 4, 'Red Squadron Pilot')
# Don't clone uniques
common.addUpgrade('#rebel-builder', 2, 2, 'R2-D2')
common.cloneShip('#rebel-builder', 2)
common.assertShipTypeIs(test, '#rebel-builder', 5, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 5, 'Red Squadron Pilot')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 5, 2)
# Handle cloning when a unique would confer an upgrade
common.addShip('#rebel-builder', 'X-Wing', '<NAME>')
common.addUpgrade('#rebel-builder', 6, 2, 'R2-D6')
common.addUpgrade('#rebel-builder', 6, 4, 'Calculation')
common.cloneShip('#rebel-builder', 6)
common.assertShipTypeIs(test, '#rebel-builder', 7, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 7, 'Rookie Pilot')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 7, 2)
test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 7, 4}"
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy A-Wing with Test Pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'A-Wing'
pilot: 'Green Squadron Pilot'
upgrades: [
'Deadeye'
null
'A-Wing Test Pilot'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 44)
common.removeShip('#rebel-builder', 2)
common.addUpgrade('#rebel-builder', 1, 5, 'Squad Leader')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 42)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy B-Wing with B-Wing/E2", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'B-Wing'
pilot: 'Blue Squadron Pilot'
upgrades: [
'Fire-Control System'
null
'Proton Torpedoes'
null
'B-Wing/E2'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 6, 'Targeting Coordinator')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 33 * 2)
common.removeShip('#rebel-builder', 1)
common.addUpgrade('#rebel-builder', 1, 6, '<NAME>')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 59)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy Royal Guard Pilot with Royal Guard TIE", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'TIE Interceptor'
pilot: 'Royal Guard Pilot'
upgrades: [
'Determination'
'Royal Guard TIE'
'Stealth Device'
]
}
])
common.addUpgrade('#empire-builder', 1, 4, 'Hull Upgrade')
common.cloneShip('#empire-builder', 1)
common.assertTotalPoints(test, '#empire-builder', 58)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
casper.test.begin "Copy IG-88", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'Aggressor'
pilot: 'IG-88C'
upgrades: [
'Lone Wolf'
'Advanced Sensors'
'Heavy Laser Cannon'
null
null
null
'IG-2000'
'Autothrusters'
]
}
])
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(2, 1)}")
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(3, 1)}")
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(4, 1)}")
# Clone should do nothing now
common.cloneShip('#scum-builder', 1)
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForShipIndex(5)}")
common.assertTotalPoints(test, '#scum-builder', 194)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
.run ->
test.done()
| true | common = require './common'
common.setup()
casper.test.begin "Copy pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'PI:NAME:<NAME>END_PI'
upgrades: [
'Lone Wolf'
'Proton Torpedoes'
'R5-P9'
'Engine Upgrade'
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
# Unique pilots can't be cloned, but the clone will pick either a generic
# or the cheapest named
.then ->
@log("#rebel-builder #{common.selectorForCloneShip(1)}")
test.assertVisible("#rebel-builder #{common.selectorForCloneShip(1)}", "Unique pilots may be cloned")
# Unique clones to generic
common.cloneShip('#rebel-builder', 1)
common.assertShipTypeIs(test, '#rebel-builder', 3, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 3, 'Rookie Pilot')
# ...but only sends valid upgrades
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Proton Torpedoes')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 3, 2)
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Engine Upgrade')
# Non-uniques
common.cloneShip('#rebel-builder', 2)
common.assertShipTypeIs(test, '#rebel-builder', 4, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 4, 'Red Squadron Pilot')
# Don't clone uniques
common.addUpgrade('#rebel-builder', 2, 2, 'R2-D2')
common.cloneShip('#rebel-builder', 2)
common.assertShipTypeIs(test, '#rebel-builder', 5, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 5, 'Red Squadron Pilot')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 5, 2)
# Handle cloning when a unique would confer an upgrade
common.addShip('#rebel-builder', 'X-Wing', 'PI:NAME:<NAME>END_PI')
common.addUpgrade('#rebel-builder', 6, 2, 'R2-D6')
common.addUpgrade('#rebel-builder', 6, 4, 'Calculation')
common.cloneShip('#rebel-builder', 6)
common.assertShipTypeIs(test, '#rebel-builder', 7, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 7, 'Rookie Pilot')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 7, 2)
test.assertDoesntExist "#rebel-builder #{common.selectorForUpgradeIndex 7, 4}"
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy A-Wing with Test Pilot", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'A-Wing'
pilot: 'Green Squadron Pilot'
upgrades: [
'Deadeye'
null
'A-Wing Test Pilot'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 5, 'Expert Handling')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 44)
common.removeShip('#rebel-builder', 2)
common.addUpgrade('#rebel-builder', 1, 5, 'Squad Leader')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 42)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy B-Wing with B-Wing/E2", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'B-Wing'
pilot: 'Blue Squadron Pilot'
upgrades: [
'Fire-Control System'
null
'Proton Torpedoes'
null
'B-Wing/E2'
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 6, 'Targeting Coordinator')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 33 * 2)
common.removeShip('#rebel-builder', 1)
common.addUpgrade('#rebel-builder', 1, 6, 'PI:NAME:<NAME>END_PI')
common.cloneShip('#rebel-builder', 1)
common.assertTotalPoints(test, '#rebel-builder', 59)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "Copy Royal Guard Pilot with Royal Guard TIE", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.createList('#empire-builder', [
{
ship: 'TIE Interceptor'
pilot: 'Royal Guard Pilot'
upgrades: [
'Determination'
'Royal Guard TIE'
'Stealth Device'
]
}
])
common.addUpgrade('#empire-builder', 1, 4, 'Hull Upgrade')
common.cloneShip('#empire-builder', 1)
common.assertTotalPoints(test, '#empire-builder', 58)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
casper.test.begin "Copy IG-88", (test) ->
common.waitForStartup('#rebel-builder')
common.openScumBuilder()
common.createList('#scum-builder', [
{
ship: 'Aggressor'
pilot: 'IG-88C'
upgrades: [
'Lone Wolf'
'Advanced Sensors'
'Heavy Laser Cannon'
null
null
null
'IG-2000'
'Autothrusters'
]
}
])
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(2, 1)}")
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(3, 1)}")
common.cloneShip('#scum-builder', 1)
common.assertShipTypeIs(test, '#scum-builder', 2, 'Aggressor')
common.assertPilotIs(test, '#scum-builder', 2, 'IG-88A')
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForUpgradeIndex(4, 1)}")
# Clone should do nothing now
common.cloneShip('#scum-builder', 1)
common.assertSelect2IsEmpty(test, "#scum-builder #{common.selectorForShipIndex(5)}")
common.assertTotalPoints(test, '#scum-builder', 194)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
common.removeShip('#scum-builder', 1)
.run ->
test.done()
|
[
{
"context": "images inside the editable for Hallo\n# (c) 2013 Christian Grobmeier, http://www.grobmeier.de\n# This plugin may be ",
"end": 105,
"score": 0.9998655319213867,
"start": 86,
"tag": "NAME",
"value": "Christian Grobmeier"
}
] | src/plugins/image_browser.coffee | grobmeier/hallo | 1 | #
# Browser plugin to work with images inside the editable for Hallo
# (c) 2013 Christian Grobmeier, http://www.grobmeier.de
# This plugin may be freely distributed under the MIT license
#
((jQuery) ->
jQuery.widget "IKS.hallo-image-browser",
options:
editable: null
toolbar: null
uuid: ""
dialogOpts:
autoOpen: false
width: 600
height: 'auto'
modal: true
resizable: true
draggable: true
dialogClass: 'insert-image-dialog'
dialog: null
buttonCssClass: null
searchurl : null
limit: 4
protectionPrefix: /^\)\]\}',?\n/
currentpage: 1
lastquery: ""
populateToolbar: (toolbar) ->
widget = this
dialog = "
<div id=\"hallo-image-browser-container-#{@options.uuid}\">
<input class=\"hallo-image-browser-search-value\" type=\"text\" /> <button class=\"hallo-image-browser-search\">Search</button>
<hr />
<div class=\"hallo-image-browser-paging\" style=\"display:none\">
<button class=\"hallo-image-browser-paging-back\" style=\"display:none\">Back</button>
<button class=\"hallo-image-browser-paging-forward\" style=\"display:none\">Forward</button>
</div>
<div class=\"hallo-image-browser-search-result\">
<p class=\"hallo-image-browser-no-search-result\">No images to view.</p>
</div>
</div>
"
@options.dialog = jQuery("<div>").
attr('id', "#{@options.uuid}-image-browser-dialog").
html(dialog)
buttonset = jQuery("<span>").addClass @widgetName
button = jQuery '<span>'
button.hallobutton
label: 'Insert Image from Browser'
icon: 'icon-folder-open'
editable: @options.editable
command: null
queryState: false
uuid: @options.uuid
cssClass: @options.buttonCssClass
buttonset.append button
button.click ->
toolbar.hide()
widget._openDialog()
toolbar.append buttonset
@options.dialog.dialog(@options.dialogOpts)
_openDialog: ->
@lastSelection = @options.editable.getSelection()
@options.dialog.dialog("open")
@options.dialog.dialog("option", "title", "Insert Image")
@options.dialog.on 'dialogclose', => @options.editable.element.focus()
@container ?= jQuery "#hallo-image-browser-container-#{@options.uuid}"
@paging ?= jQuery '.hallo-image-browser-paging', @container
@pagingback ?= jQuery '.hallo-image-browser-paging-back', @container
@pagingforward ?= jQuery '.hallo-image-browser-paging-forward', @container
@pagingback.on "click", =>
@currentpage--;
@_search()
@pagingforward.on "click", =>
@currentpage++;
@_search()
@noresult ?= jQuery '.hallo-image-browser-no-search-result', @container
@searchvalue ?= @options.dialog.find('.hallo-image-browser-search-value')
initSearchButton = =>
@searchbutton = @options.dialog.find('.hallo-image-browser-search')
@searchbutton.on "click", => @_search()
@searchbutton ?= initSearchButton()
_search: ->
query = @searchvalue.val()
if @lastquery isnt query
@currentpage = 1
@lastquery = query
data =
limit: @options.limit
page : @currentpage
query: query
success = (data) =>
data = data.replace @options.protectionPrefix, ''
data = jQuery.parseJSON data
@_resetSearchResults()
@_paging(data.page, data.total)
@_preview_images(data.results)
jQuery.get @options.searchurl, data, success, "text"
_paging: (page, total) ->
if total < @limit
@paging.hide()
return
else
@paging.show()
if page > 1
@pagingback.show()
else
@pagingback.hide()
numberofpages = Math.ceil ( total / @options.limit )
if page < numberofpages
@pagingforward.show()
else
@pagingforward.hide()
_preview_images: (data) ->
widget = @
previewbox = jQuery '.hallo-image-browser-search-result', @container
_showImage = (definition) ->
imageContainer = jQuery ("<div></div>")
imageContainer.addClass "hallo-image-browser-preview"
image = jQuery ("<img>")
image.css("max-width", 200).css("max-height", 200)
image.attr src: definition.url
image.attr alt: definition.alt
imageContainer.append image
imageContainer.append jQuery("<p>" + definition.alt + "</p>")
imageContainer.on "click", (event) ->
image = jQuery (event.target)
widget._insert_image(image)
previewbox.append imageContainer
if data.length > 0
@noresult.hide()
_showImage(definition) for definition in data
else
@noresult.show()
_insert_image: (image) ->
image.attr('style', '')
@lastSelection.insertNode image[0]
@searchvalue.val('')
@_closeDialog()
_resetSearchResults: ->
@noresult.show()
jQuery('.hallo-image-browser-preview', @container).remove()
_closeDialog: ->
@_resetSearchResults()
@options.dialog.dialog("close")
) jQuery
| 1188 | #
# Browser plugin to work with images inside the editable for Hallo
# (c) 2013 <NAME>, http://www.grobmeier.de
# This plugin may be freely distributed under the MIT license
#
((jQuery) ->
jQuery.widget "IKS.hallo-image-browser",
options:
editable: null
toolbar: null
uuid: ""
dialogOpts:
autoOpen: false
width: 600
height: 'auto'
modal: true
resizable: true
draggable: true
dialogClass: 'insert-image-dialog'
dialog: null
buttonCssClass: null
searchurl : null
limit: 4
protectionPrefix: /^\)\]\}',?\n/
currentpage: 1
lastquery: ""
populateToolbar: (toolbar) ->
widget = this
dialog = "
<div id=\"hallo-image-browser-container-#{@options.uuid}\">
<input class=\"hallo-image-browser-search-value\" type=\"text\" /> <button class=\"hallo-image-browser-search\">Search</button>
<hr />
<div class=\"hallo-image-browser-paging\" style=\"display:none\">
<button class=\"hallo-image-browser-paging-back\" style=\"display:none\">Back</button>
<button class=\"hallo-image-browser-paging-forward\" style=\"display:none\">Forward</button>
</div>
<div class=\"hallo-image-browser-search-result\">
<p class=\"hallo-image-browser-no-search-result\">No images to view.</p>
</div>
</div>
"
@options.dialog = jQuery("<div>").
attr('id', "#{@options.uuid}-image-browser-dialog").
html(dialog)
buttonset = jQuery("<span>").addClass @widgetName
button = jQuery '<span>'
button.hallobutton
label: 'Insert Image from Browser'
icon: 'icon-folder-open'
editable: @options.editable
command: null
queryState: false
uuid: @options.uuid
cssClass: @options.buttonCssClass
buttonset.append button
button.click ->
toolbar.hide()
widget._openDialog()
toolbar.append buttonset
@options.dialog.dialog(@options.dialogOpts)
_openDialog: ->
@lastSelection = @options.editable.getSelection()
@options.dialog.dialog("open")
@options.dialog.dialog("option", "title", "Insert Image")
@options.dialog.on 'dialogclose', => @options.editable.element.focus()
@container ?= jQuery "#hallo-image-browser-container-#{@options.uuid}"
@paging ?= jQuery '.hallo-image-browser-paging', @container
@pagingback ?= jQuery '.hallo-image-browser-paging-back', @container
@pagingforward ?= jQuery '.hallo-image-browser-paging-forward', @container
@pagingback.on "click", =>
@currentpage--;
@_search()
@pagingforward.on "click", =>
@currentpage++;
@_search()
@noresult ?= jQuery '.hallo-image-browser-no-search-result', @container
@searchvalue ?= @options.dialog.find('.hallo-image-browser-search-value')
initSearchButton = =>
@searchbutton = @options.dialog.find('.hallo-image-browser-search')
@searchbutton.on "click", => @_search()
@searchbutton ?= initSearchButton()
_search: ->
query = @searchvalue.val()
if @lastquery isnt query
@currentpage = 1
@lastquery = query
data =
limit: @options.limit
page : @currentpage
query: query
success = (data) =>
data = data.replace @options.protectionPrefix, ''
data = jQuery.parseJSON data
@_resetSearchResults()
@_paging(data.page, data.total)
@_preview_images(data.results)
jQuery.get @options.searchurl, data, success, "text"
_paging: (page, total) ->
if total < @limit
@paging.hide()
return
else
@paging.show()
if page > 1
@pagingback.show()
else
@pagingback.hide()
numberofpages = Math.ceil ( total / @options.limit )
if page < numberofpages
@pagingforward.show()
else
@pagingforward.hide()
_preview_images: (data) ->
widget = @
previewbox = jQuery '.hallo-image-browser-search-result', @container
_showImage = (definition) ->
imageContainer = jQuery ("<div></div>")
imageContainer.addClass "hallo-image-browser-preview"
image = jQuery ("<img>")
image.css("max-width", 200).css("max-height", 200)
image.attr src: definition.url
image.attr alt: definition.alt
imageContainer.append image
imageContainer.append jQuery("<p>" + definition.alt + "</p>")
imageContainer.on "click", (event) ->
image = jQuery (event.target)
widget._insert_image(image)
previewbox.append imageContainer
if data.length > 0
@noresult.hide()
_showImage(definition) for definition in data
else
@noresult.show()
_insert_image: (image) ->
image.attr('style', '')
@lastSelection.insertNode image[0]
@searchvalue.val('')
@_closeDialog()
_resetSearchResults: ->
@noresult.show()
jQuery('.hallo-image-browser-preview', @container).remove()
_closeDialog: ->
@_resetSearchResults()
@options.dialog.dialog("close")
) jQuery
| true | #
# Browser plugin to work with images inside the editable for Hallo
# (c) 2013 PI:NAME:<NAME>END_PI, http://www.grobmeier.de
# This plugin may be freely distributed under the MIT license
#
((jQuery) ->
jQuery.widget "IKS.hallo-image-browser",
options:
editable: null
toolbar: null
uuid: ""
dialogOpts:
autoOpen: false
width: 600
height: 'auto'
modal: true
resizable: true
draggable: true
dialogClass: 'insert-image-dialog'
dialog: null
buttonCssClass: null
searchurl : null
limit: 4
protectionPrefix: /^\)\]\}',?\n/
currentpage: 1
lastquery: ""
populateToolbar: (toolbar) ->
widget = this
dialog = "
<div id=\"hallo-image-browser-container-#{@options.uuid}\">
<input class=\"hallo-image-browser-search-value\" type=\"text\" /> <button class=\"hallo-image-browser-search\">Search</button>
<hr />
<div class=\"hallo-image-browser-paging\" style=\"display:none\">
<button class=\"hallo-image-browser-paging-back\" style=\"display:none\">Back</button>
<button class=\"hallo-image-browser-paging-forward\" style=\"display:none\">Forward</button>
</div>
<div class=\"hallo-image-browser-search-result\">
<p class=\"hallo-image-browser-no-search-result\">No images to view.</p>
</div>
</div>
"
@options.dialog = jQuery("<div>").
attr('id', "#{@options.uuid}-image-browser-dialog").
html(dialog)
buttonset = jQuery("<span>").addClass @widgetName
button = jQuery '<span>'
button.hallobutton
label: 'Insert Image from Browser'
icon: 'icon-folder-open'
editable: @options.editable
command: null
queryState: false
uuid: @options.uuid
cssClass: @options.buttonCssClass
buttonset.append button
button.click ->
toolbar.hide()
widget._openDialog()
toolbar.append buttonset
@options.dialog.dialog(@options.dialogOpts)
_openDialog: ->
@lastSelection = @options.editable.getSelection()
@options.dialog.dialog("open")
@options.dialog.dialog("option", "title", "Insert Image")
@options.dialog.on 'dialogclose', => @options.editable.element.focus()
@container ?= jQuery "#hallo-image-browser-container-#{@options.uuid}"
@paging ?= jQuery '.hallo-image-browser-paging', @container
@pagingback ?= jQuery '.hallo-image-browser-paging-back', @container
@pagingforward ?= jQuery '.hallo-image-browser-paging-forward', @container
@pagingback.on "click", =>
@currentpage--;
@_search()
@pagingforward.on "click", =>
@currentpage++;
@_search()
@noresult ?= jQuery '.hallo-image-browser-no-search-result', @container
@searchvalue ?= @options.dialog.find('.hallo-image-browser-search-value')
initSearchButton = =>
@searchbutton = @options.dialog.find('.hallo-image-browser-search')
@searchbutton.on "click", => @_search()
@searchbutton ?= initSearchButton()
_search: ->
query = @searchvalue.val()
if @lastquery isnt query
@currentpage = 1
@lastquery = query
data =
limit: @options.limit
page : @currentpage
query: query
success = (data) =>
data = data.replace @options.protectionPrefix, ''
data = jQuery.parseJSON data
@_resetSearchResults()
@_paging(data.page, data.total)
@_preview_images(data.results)
jQuery.get @options.searchurl, data, success, "text"
_paging: (page, total) ->
if total < @limit
@paging.hide()
return
else
@paging.show()
if page > 1
@pagingback.show()
else
@pagingback.hide()
numberofpages = Math.ceil ( total / @options.limit )
if page < numberofpages
@pagingforward.show()
else
@pagingforward.hide()
_preview_images: (data) ->
widget = @
previewbox = jQuery '.hallo-image-browser-search-result', @container
_showImage = (definition) ->
imageContainer = jQuery ("<div></div>")
imageContainer.addClass "hallo-image-browser-preview"
image = jQuery ("<img>")
image.css("max-width", 200).css("max-height", 200)
image.attr src: definition.url
image.attr alt: definition.alt
imageContainer.append image
imageContainer.append jQuery("<p>" + definition.alt + "</p>")
imageContainer.on "click", (event) ->
image = jQuery (event.target)
widget._insert_image(image)
previewbox.append imageContainer
if data.length > 0
@noresult.hide()
_showImage(definition) for definition in data
else
@noresult.show()
_insert_image: (image) ->
image.attr('style', '')
@lastSelection.insertNode image[0]
@searchvalue.val('')
@_closeDialog()
_resetSearchResults: ->
@noresult.show()
jQuery('.hallo-image-browser-preview', @container).remove()
_closeDialog: ->
@_resetSearchResults()
@options.dialog.dialog("close")
) jQuery
|
[
{
"context": "archKeyword: ''\n searchResult: []\n username: ''\n password: ''\n isLogin: false\n computed:\n ",
"end": 136,
"score": 0.7092633843421936,
"start": 136,
"tag": "USERNAME",
"value": ""
},
{
"context": " searchResult: []\n username: ''\n password: ''... | static/app.coffee | exzhawk/EhentaiLoader | 0 | app = new Vue({
el: 'body'
data:
queueCount: 233
downloadCount: 233
searchKeyword: ''
searchResult: []
username: ''
password: ''
isLogin: false
computed:
noLogin: ->
return !this.isLogin
methods:
init: ->
this.checkLogin()
doSearch: ->
$this=this
$.ajax
url: '/search'
data:
q: this.searchKeyword
method: "GET"
dataType: "json"
success: (data) ->
$this.searchResult = data['posts']
checkLogin: ->
$this = this
$.ajax
url: '/login'
method: "GET"
dataType: "json"
success: (data) ->
$this.isLogin = data['isLogin']
doLogin: ->
$this = this
$.ajax
url: '/login'
data:
username: this.username
password: this.password
method: "POST"
dataType: "json"
success: (data) ->
$this.isLogin = data['isLogin']
})
app.init()
| 13429 | app = new Vue({
el: 'body'
data:
queueCount: 233
downloadCount: 233
searchKeyword: ''
searchResult: []
username: ''
password:<PASSWORD> ''
isLogin: false
computed:
noLogin: ->
return !this.isLogin
methods:
init: ->
this.checkLogin()
doSearch: ->
$this=this
$.ajax
url: '/search'
data:
q: this.searchKeyword
method: "GET"
dataType: "json"
success: (data) ->
$this.searchResult = data['posts']
checkLogin: ->
$this = this
$.ajax
url: '/login'
method: "GET"
dataType: "json"
success: (data) ->
$this.isLogin = data['isLogin']
doLogin: ->
$this = this
$.ajax
url: '/login'
data:
username: this.username
password: <PASSWORD>
method: "POST"
dataType: "json"
success: (data) ->
$this.isLogin = data['isLogin']
})
app.init()
| true | app = new Vue({
el: 'body'
data:
queueCount: 233
downloadCount: 233
searchKeyword: ''
searchResult: []
username: ''
password:PI:PASSWORD:<PASSWORD>END_PI ''
isLogin: false
computed:
noLogin: ->
return !this.isLogin
methods:
init: ->
this.checkLogin()
doSearch: ->
$this=this
$.ajax
url: '/search'
data:
q: this.searchKeyword
method: "GET"
dataType: "json"
success: (data) ->
$this.searchResult = data['posts']
checkLogin: ->
$this = this
$.ajax
url: '/login'
method: "GET"
dataType: "json"
success: (data) ->
$this.isLogin = data['isLogin']
doLogin: ->
$this = this
$.ajax
url: '/login'
data:
username: this.username
password: PI:PASSWORD:<PASSWORD>END_PI
method: "POST"
dataType: "json"
success: (data) ->
$this.isLogin = data['isLogin']
})
app.init()
|
[
{
"context": "der.flymon.net'\n port: 8086\n username: 'webface'\n password: 'webface2015'\n database: 'f",
"end": 4563,
"score": 0.9996116161346436,
"start": 4556,
"tag": "USERNAME",
"value": "webface"
},
{
"context": ": 8086\n username: 'webface'\n pas... | assets/javascripts/crutch.coffee | ZigFisher/homes-smart | 4 | window.log = -> try console.log.apply(console, arguments)
debug = ->
if window.debug? and window.console
console.debug.apply arguments
parseArgs = (qstr = window.location.search.substring(1)) ->
argv = {}
a = qstr.split('&')
for i of a
b = a[i].split('=')
argv[decodeURIComponent(b[0])] = decodeURIComponent(b[1])
argv
class @Chart
constructor: (@data, @done) ->
# log "Chart#constructor(): init chart '#{@data.name}'"
@series = []
@argv = parseArgs()
loadAndShow: =>
if @isShowChart()
# log "Chart[#{@data.name}]#loadAndShow()"
@div = $('<div>').addClass("chart")
$("#content").append @div
@div.append $('<h2>').text("Loading #{@data.name}...")
@div.append $('<img>').attr("src", "assets/images/ajax-loader.gif")
@loadData()
.then(@transformData)
.then =>
@show()
@done?()
else
@done?()
loadData: =>
log "Chart[#{@data.name}]#loadData(): query: ", @query()
new Promise (resolve, reject)=>
influxdb.query @query(), (points, err) ->
if err?
reject(err)
else
resolve(points)
transformData: (response) =>
# log "Chart[#{@data.name}]#transformData(response):", response
points = response[0].points
nodes = _.groupBy points, (point) -> point.host
series = {}
# log "nodes:", nodes
nodes = _.groupBy points, (point) -> point.host
_.each nodes, (points, host) =>
# log "#{host} points: ", points
_.each @fieldNames(), (field) ->
name = "#{host} - #{field}"
series[name] ||= {name: name, data: []}
_.each nodes, (points, host) =>
data = _.each points, (point) =>
_.each @fieldNames(), (field) ->
name = "#{point.host} - #{field}"
series[name].data.push [point.time.getTime(), point[field]]
# Fill @series if data present
for name, serie of series
if _.find(serie.data, (item) -> !!item[1])
serie.data = serie.data.reverse()
@series.push serie
# console.log "series: ", series
1
show: =>
# log "Chart#show()"
@div.empty()
params = _.clone(@data.chart)
_.merge params,
chart:
renderTo: @div[0]
height: 300
title: text: @data.chart.title
xAxis: type: 'datetime'
legend:
layout: 'horizontal'
align: 'center'
verticalAlign: 'bottom'
borderWidth: 1
series: @series
# console.log "params: ", params
if params.series.length > 0
@chart = new Highcharts.Chart params
isShowChart: =>
# log "argv", @argv
if @argv.graphs
graphs = @argv.graphs.split(",")
# Detect first occurance of @data.name
!! _.find graphs, (item) => item == @data.name
else
true
queryFields: =>
fields = @data.select?.fields
if fields?.join?
# array
fields
else if typeof fields is 'object'
# convert {counter: "cnt1"}" -> "cnt1" AS counter
_.map fields, (val, key) -> "#{val} AS #{key}"
else
# some string value
[@data.select.fields]
fieldNames: =>
fields = @data.select?.fields
if fields?.join?
# array
fields
else if typeof fields is 'object'
# convert {counter: "cnt1"}" -> "counter"
_.map fields, (val, key) -> key
else
[@data.select.fields]
macCondition: =>
macs = (str) ->
macs = str.split(",").map (s) -> "mac = '#{s}'"
"( #{macs.join(" OR ")} )"
if @argv.macs
macs @argv.macs
else if @data.select.macs?
macs @data.select.macs
else if @data.select.mac?
"mac = '#{@data.select.mac}'"
else
"mac =~ /^18FE.*/"
group: ->
if @argv.group
@argv.group
else
"10m"
period: ->
period = "3h" # default
period = @argv.period if @argv.period?
result = if @argv.start?
start = @argv.start
"time > '#{start}' AND time < '#{start}' + #{period}"
else
"time > NOW() - #{period}"
result
query: =>
fields = @queryFields().join ', '
"SELECT host, #{fields} FROM srach " +
" GROUP BY host, time(#{@group()}) fill(0) " +
" WHERE #{@macCondition()} AND (#{@period()});"
# Once DOM (document) is finished loading
$(document).ready ->
unless window.location.search.length is 0
$('#no-data').hide()
# Charts definition
window.charts = []
window.influxdb = new InfluxDB
host: 'builder.flymon.net'
port: 8086
username: 'webface'
password: 'webface2015'
database: 'flymon'
Highcharts.setOptions global: useUTC: false
# Filter and sort graphs by "graphs=g1,g2" location params
if graph_list = parseArgs().graphs
graph_list = graph_list.split(",")
filtered_graphs = []
_.each graph_list, (graph_name) ->
g = _.find window.graphs, (g) -> g.name == graph_name
filtered_graphs.push g if g?
window.graphs = filtered_graphs
# Sequental via promises
chain = Promise.resolve()
window.graphs.forEach (graph_data)->
chain = chain.then( ->
data = _.cloneDeep(defaults)
_.merge data, graph_data
chart = new Chart data
window.charts.push chart
chart.loadAndShow()
)
# # Parallel via promises
# graphs.forEach (graph_data)->
# data = _.cloneDeep(defaults)
# _.merge data, graph_data
# chart = new Chart data
# window.charts.push chart
# chart.loadAndShow()
# Sequental via Async lib
# async.eachSeries graphs, (graph_data, cb) ->
# # console.log "graph_data", graph_data
# data = _.cloneDeep(defaults)
# _.merge data, graph_data
# log "new Chart", data.name
# chart = new Chart(data, cb)
# window.charts.push chart
# chart.loadAndShow()
testSeq = ->
delay = (ms)->
new Promise (resolve, reject) ->
setTimeout((-> resolve()), ms)
delay( 500).then -> log "delay 500"
delay(1000).then -> log "delay 1000"
delay(1500).then -> log "delay 1500"
delay(2000).then -> log "delay 2000"
| 44905 | window.log = -> try console.log.apply(console, arguments)
debug = ->
if window.debug? and window.console
console.debug.apply arguments
parseArgs = (qstr = window.location.search.substring(1)) ->
argv = {}
a = qstr.split('&')
for i of a
b = a[i].split('=')
argv[decodeURIComponent(b[0])] = decodeURIComponent(b[1])
argv
class @Chart
constructor: (@data, @done) ->
# log "Chart#constructor(): init chart '#{@data.name}'"
@series = []
@argv = parseArgs()
loadAndShow: =>
if @isShowChart()
# log "Chart[#{@data.name}]#loadAndShow()"
@div = $('<div>').addClass("chart")
$("#content").append @div
@div.append $('<h2>').text("Loading #{@data.name}...")
@div.append $('<img>').attr("src", "assets/images/ajax-loader.gif")
@loadData()
.then(@transformData)
.then =>
@show()
@done?()
else
@done?()
loadData: =>
log "Chart[#{@data.name}]#loadData(): query: ", @query()
new Promise (resolve, reject)=>
influxdb.query @query(), (points, err) ->
if err?
reject(err)
else
resolve(points)
transformData: (response) =>
# log "Chart[#{@data.name}]#transformData(response):", response
points = response[0].points
nodes = _.groupBy points, (point) -> point.host
series = {}
# log "nodes:", nodes
nodes = _.groupBy points, (point) -> point.host
_.each nodes, (points, host) =>
# log "#{host} points: ", points
_.each @fieldNames(), (field) ->
name = "#{host} - #{field}"
series[name] ||= {name: name, data: []}
_.each nodes, (points, host) =>
data = _.each points, (point) =>
_.each @fieldNames(), (field) ->
name = "#{point.host} - #{field}"
series[name].data.push [point.time.getTime(), point[field]]
# Fill @series if data present
for name, serie of series
if _.find(serie.data, (item) -> !!item[1])
serie.data = serie.data.reverse()
@series.push serie
# console.log "series: ", series
1
show: =>
# log "Chart#show()"
@div.empty()
params = _.clone(@data.chart)
_.merge params,
chart:
renderTo: @div[0]
height: 300
title: text: @data.chart.title
xAxis: type: 'datetime'
legend:
layout: 'horizontal'
align: 'center'
verticalAlign: 'bottom'
borderWidth: 1
series: @series
# console.log "params: ", params
if params.series.length > 0
@chart = new Highcharts.Chart params
isShowChart: =>
# log "argv", @argv
if @argv.graphs
graphs = @argv.graphs.split(",")
# Detect first occurance of @data.name
!! _.find graphs, (item) => item == @data.name
else
true
queryFields: =>
fields = @data.select?.fields
if fields?.join?
# array
fields
else if typeof fields is 'object'
# convert {counter: "cnt1"}" -> "cnt1" AS counter
_.map fields, (val, key) -> "#{val} AS #{key}"
else
# some string value
[@data.select.fields]
fieldNames: =>
fields = @data.select?.fields
if fields?.join?
# array
fields
else if typeof fields is 'object'
# convert {counter: "cnt1"}" -> "counter"
_.map fields, (val, key) -> key
else
[@data.select.fields]
macCondition: =>
macs = (str) ->
macs = str.split(",").map (s) -> "mac = '#{s}'"
"( #{macs.join(" OR ")} )"
if @argv.macs
macs @argv.macs
else if @data.select.macs?
macs @data.select.macs
else if @data.select.mac?
"mac = '#{@data.select.mac}'"
else
"mac =~ /^18FE.*/"
group: ->
if @argv.group
@argv.group
else
"10m"
period: ->
period = "3h" # default
period = @argv.period if @argv.period?
result = if @argv.start?
start = @argv.start
"time > '#{start}' AND time < '#{start}' + #{period}"
else
"time > NOW() - #{period}"
result
query: =>
fields = @queryFields().join ', '
"SELECT host, #{fields} FROM srach " +
" GROUP BY host, time(#{@group()}) fill(0) " +
" WHERE #{@macCondition()} AND (#{@period()});"
# Once DOM (document) is finished loading
$(document).ready ->
unless window.location.search.length is 0
$('#no-data').hide()
# Charts definition
window.charts = []
window.influxdb = new InfluxDB
host: 'builder.flymon.net'
port: 8086
username: 'webface'
password: '<PASSWORD>'
database: 'flymon'
Highcharts.setOptions global: useUTC: false
# Filter and sort graphs by "graphs=g1,g2" location params
if graph_list = parseArgs().graphs
graph_list = graph_list.split(",")
filtered_graphs = []
_.each graph_list, (graph_name) ->
g = _.find window.graphs, (g) -> g.name == graph_name
filtered_graphs.push g if g?
window.graphs = filtered_graphs
# Sequental via promises
chain = Promise.resolve()
window.graphs.forEach (graph_data)->
chain = chain.then( ->
data = _.cloneDeep(defaults)
_.merge data, graph_data
chart = new Chart data
window.charts.push chart
chart.loadAndShow()
)
# # Parallel via promises
# graphs.forEach (graph_data)->
# data = _.cloneDeep(defaults)
# _.merge data, graph_data
# chart = new Chart data
# window.charts.push chart
# chart.loadAndShow()
# Sequental via Async lib
# async.eachSeries graphs, (graph_data, cb) ->
# # console.log "graph_data", graph_data
# data = _.cloneDeep(defaults)
# _.merge data, graph_data
# log "new Chart", data.name
# chart = new Chart(data, cb)
# window.charts.push chart
# chart.loadAndShow()
testSeq = ->
delay = (ms)->
new Promise (resolve, reject) ->
setTimeout((-> resolve()), ms)
delay( 500).then -> log "delay 500"
delay(1000).then -> log "delay 1000"
delay(1500).then -> log "delay 1500"
delay(2000).then -> log "delay 2000"
| true | window.log = -> try console.log.apply(console, arguments)
debug = ->
if window.debug? and window.console
console.debug.apply arguments
parseArgs = (qstr = window.location.search.substring(1)) ->
argv = {}
a = qstr.split('&')
for i of a
b = a[i].split('=')
argv[decodeURIComponent(b[0])] = decodeURIComponent(b[1])
argv
class @Chart
constructor: (@data, @done) ->
# log "Chart#constructor(): init chart '#{@data.name}'"
@series = []
@argv = parseArgs()
loadAndShow: =>
if @isShowChart()
# log "Chart[#{@data.name}]#loadAndShow()"
@div = $('<div>').addClass("chart")
$("#content").append @div
@div.append $('<h2>').text("Loading #{@data.name}...")
@div.append $('<img>').attr("src", "assets/images/ajax-loader.gif")
@loadData()
.then(@transformData)
.then =>
@show()
@done?()
else
@done?()
loadData: =>
log "Chart[#{@data.name}]#loadData(): query: ", @query()
new Promise (resolve, reject)=>
influxdb.query @query(), (points, err) ->
if err?
reject(err)
else
resolve(points)
transformData: (response) =>
# log "Chart[#{@data.name}]#transformData(response):", response
points = response[0].points
nodes = _.groupBy points, (point) -> point.host
series = {}
# log "nodes:", nodes
nodes = _.groupBy points, (point) -> point.host
_.each nodes, (points, host) =>
# log "#{host} points: ", points
_.each @fieldNames(), (field) ->
name = "#{host} - #{field}"
series[name] ||= {name: name, data: []}
_.each nodes, (points, host) =>
data = _.each points, (point) =>
_.each @fieldNames(), (field) ->
name = "#{point.host} - #{field}"
series[name].data.push [point.time.getTime(), point[field]]
# Fill @series if data present
for name, serie of series
if _.find(serie.data, (item) -> !!item[1])
serie.data = serie.data.reverse()
@series.push serie
# console.log "series: ", series
1
show: =>
# log "Chart#show()"
@div.empty()
params = _.clone(@data.chart)
_.merge params,
chart:
renderTo: @div[0]
height: 300
title: text: @data.chart.title
xAxis: type: 'datetime'
legend:
layout: 'horizontal'
align: 'center'
verticalAlign: 'bottom'
borderWidth: 1
series: @series
# console.log "params: ", params
if params.series.length > 0
@chart = new Highcharts.Chart params
isShowChart: =>
# log "argv", @argv
if @argv.graphs
graphs = @argv.graphs.split(",")
# Detect first occurance of @data.name
!! _.find graphs, (item) => item == @data.name
else
true
queryFields: =>
fields = @data.select?.fields
if fields?.join?
# array
fields
else if typeof fields is 'object'
# convert {counter: "cnt1"}" -> "cnt1" AS counter
_.map fields, (val, key) -> "#{val} AS #{key}"
else
# some string value
[@data.select.fields]
fieldNames: =>
fields = @data.select?.fields
if fields?.join?
# array
fields
else if typeof fields is 'object'
# convert {counter: "cnt1"}" -> "counter"
_.map fields, (val, key) -> key
else
[@data.select.fields]
macCondition: =>
macs = (str) ->
macs = str.split(",").map (s) -> "mac = '#{s}'"
"( #{macs.join(" OR ")} )"
if @argv.macs
macs @argv.macs
else if @data.select.macs?
macs @data.select.macs
else if @data.select.mac?
"mac = '#{@data.select.mac}'"
else
"mac =~ /^18FE.*/"
group: ->
if @argv.group
@argv.group
else
"10m"
period: ->
period = "3h" # default
period = @argv.period if @argv.period?
result = if @argv.start?
start = @argv.start
"time > '#{start}' AND time < '#{start}' + #{period}"
else
"time > NOW() - #{period}"
result
query: =>
fields = @queryFields().join ', '
"SELECT host, #{fields} FROM srach " +
" GROUP BY host, time(#{@group()}) fill(0) " +
" WHERE #{@macCondition()} AND (#{@period()});"
# Once DOM (document) is finished loading
$(document).ready ->
unless window.location.search.length is 0
$('#no-data').hide()
# Charts definition
window.charts = []
window.influxdb = new InfluxDB
host: 'builder.flymon.net'
port: 8086
username: 'webface'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
database: 'flymon'
Highcharts.setOptions global: useUTC: false
# Filter and sort graphs by "graphs=g1,g2" location params
if graph_list = parseArgs().graphs
graph_list = graph_list.split(",")
filtered_graphs = []
_.each graph_list, (graph_name) ->
g = _.find window.graphs, (g) -> g.name == graph_name
filtered_graphs.push g if g?
window.graphs = filtered_graphs
# Sequental via promises
chain = Promise.resolve()
window.graphs.forEach (graph_data)->
chain = chain.then( ->
data = _.cloneDeep(defaults)
_.merge data, graph_data
chart = new Chart data
window.charts.push chart
chart.loadAndShow()
)
# # Parallel via promises
# graphs.forEach (graph_data)->
# data = _.cloneDeep(defaults)
# _.merge data, graph_data
# chart = new Chart data
# window.charts.push chart
# chart.loadAndShow()
# Sequental via Async lib
# async.eachSeries graphs, (graph_data, cb) ->
# # console.log "graph_data", graph_data
# data = _.cloneDeep(defaults)
# _.merge data, graph_data
# log "new Chart", data.name
# chart = new Chart(data, cb)
# window.charts.push chart
# chart.loadAndShow()
testSeq = ->
delay = (ms)->
new Promise (resolve, reject) ->
setTimeout((-> resolve()), ms)
delay( 500).then -> log "delay 500"
delay(1000).then -> log "delay 1000"
delay(1500).then -> log "delay 1500"
delay(2000).then -> log "delay 2000"
|
[
{
"context": "sByLanguage.javascript.libraryTactician = \"\"\"\n // Hushbaum has been ambushed by ogres!\n // She is busy heal",
"end": 1948,
"score": 0.9980467557907104,
"start": 1940,
"tag": "NAME",
"value": "Hushbaum"
},
{
"context": "olutionsByLanguage.lua.libraryTactician = \"... | test/app/lib/aether_utils.spec.coffee | MountainWang/codecombat | 0 | solutionsByLanguage = javascript: {}, lua: {}, python: {}, coffeescript: {}, java: {}, cpp: {}
solutionsByLanguage.javascript.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
hero.moveRight();
hero.moveDown();
hero.moveRight();
"""
solutionsByLanguage.javascript.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
while(true) {
var enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
"""
solutionsByLanguage.javascript.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
hero.moveXY(23, 23);
while(true) {
var enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
"""
solutionsByLanguage.javascript.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
function pickUpCoin() {
var coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
function attackEnemy() {
var enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
"""
solutionsByLanguage.javascript.libraryTactician = """
// Hushbaum has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
var archerTarget = null;
// Soldiers spread out in a circle and defend.
function commandSoldier(soldier, soldierIndex, numSoldiers) {
var angle = Math.PI * 2 * soldierIndex / numSoldiers;
var defendPos = {x: 41, y: 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
// Find the strongest target (most health)
// This function returns something! When you call the function, you will get some value back.
function findStrongestTarget() {
var mostHealth = 0;
var bestTarget = null;
var enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(var i=0; i < enemies.length; i++) {
var enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
// If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
function commandArcher(archer) {
var nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
var soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
var archers = hero.findByType("archer");
for(var i=0; i < soldiers.length; i++) {
var soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.length);
}
// use commandArcher() to command your archers
for(i=0; i < archers.length; i++) {
var archer = archers[i];
commandArcher(archer);
}
}
"""
solutionsByLanguage.javascript.snowdrops = """
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
// Get the map of the forest.
var forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
var cells = [{row: 0, col: 4}, {row: 1, col: 0}, {row: 1, col: 2}, {row: 1, col: 4},
{row: 2, col: 1}, {row: 2, col: 3}, {row: 2, col: 5}, {row: 3, col: 0},
{row: 3, col: 2}, {row: 3, col: 4}, {row: 4, col: 1}, {row: 4, col: 2},
{row: 4, col: 3}, {row: 5, col: 0}, {row: 5, col: 3}, {row: 5, col: 5},
{row: 6, col: 1}, {row: 6, col: 3}, {row: 6, col: 4}, {row: 7, col: 0}];
for (var i = 0; i < cells.length; i++) {
var row = cells[i].row;
var col = cells[i].col;
// If row is less than forestMap length:
if (row < forestMap.length) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].length) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] === 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
"""
solutionsByLanguage.lua.dungeonsOfKithgard = """
-- Move towards the gem.
-- Don’t touch the spikes!
-- Type your code below and click Run when you’re done.
hero:moveRight()
hero:moveDown()
hero:moveRight()
"""
solutionsByLanguage.lua.peekABoom = """
-- Build traps on the path when the hero sees a munchkin!
while true do
local enemy = hero:findNearestEnemy()
if enemy then
-- Build a "fire-trap" at the Red X (41, 24)
hero:buildXY("fire-trap", 41, 24)
-- Add an else below to move back to the clearing
else
-- Move to the Wooden X (19, 19)
hero:moveXY(19, 19)
end
end
"""
solutionsByLanguage.lua.woodlandCleaver = """
-- Use your new "cleave" skill as often as you can.
hero:moveXY(23, 23)
while true do
local enemy = hero:findNearestEnemy()
if hero:isReady("cleave") then
-- Cleave the enemy!
hero:cleave(enemy)
else
-- Else (if cleave isn't ready), do your normal attack.
hero:attack(enemy)
end
end
"""
solutionsByLanguage.lua.aFineMint = """
-- Peons are trying to steal your coins!
-- Write a function to squash them before they can take your coins.
function pickUpCoin()
local coin = hero:findNearestItem()
if coin then
hero:moveXY(coin.pos.x, coin.pos.y)
end
end
-- Write the attackEnemy function below.
-- Find the nearest enemy and attack them if they exist!
function attackEnemy()
local enemy = hero:findNearestEnemy()
if enemy then
hero:attack(enemy)
end
end
while true do
attackEnemy() -- Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
end
"""
solutionsByLanguage.lua.libraryTactician = """
-- Hushbaum has been ambushed by ogres!
-- She is busy healing her soldiers, you should command them to fight!
-- The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
local archerTarget = nil
-- Soldiers spread out in a circle and defend.
function commandSoldier(soldier, soldierIndex, numSoldiers)
local angle = Math.PI * 2 * soldierIndex / numSoldiers
local defendPos = {x=41, y=40}
defendPos.x = defendPos.x + 10 * Math.cos(angle)
defendPos.y = defendPos.y + 10 * Math.sin(angle)
hero:command(soldier, "defend", defendPos)
end
-- Find the strongest target (most health)
-- This function returns something! When you call the function, you will get some value back.
function findStrongestTarget()
local mostHealth = 0
local bestTarget = nil
local enemies = hero:findEnemies()
-- Figure out which enemy has the most health, and set bestTarget to be that enemy.
for i, enemy in pairs(enemies) do
if enemy.health > mostHealth then
bestTarget = enemy
mostHealth = enemy.health
end
end
-- Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15 then
return bestTarget
else
return nil
end
end
-- If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
function commandArcher(archer)
local nearest = archer:findNearestEnemy()
if archerTarget then
hero:command(archer, "attack", archerTarget)
elseif nearest then
hero:command(archer, "attack", nearest)
end
end
while true do
-- If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0 then
-- Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
end
local soldiers = hero:findByType("soldier")
-- Create a variable containing your archers.
local archers = hero:findByType("archer")
for i, soldier in pairs(soldiers) do
commandSoldier(soldier, i, #soldiers)
end
-- use commandArcher() to command your archers
for i, archer in pairs(archers) do
commandArcher(archer)
end
end
"""
solutionsByLanguage.lua.snowdrops = """
-- We need to clear the forest of traps!
-- The scout prepared a map of the forest.
-- But be careful where you shoot! Don't start a fire.
-- Get the map of the forest.
local forestMap = hero:findNearest(hero:findFriends()).forestMap
-- The map is a 2D array where 0 is a trap.
-- The first sure shot.
hero:say("Row " + 0 + " Column " + 1 + " Fire!")
-- But for the next points, check before shooting.
-- There are an array of points to check.
local cells = {{row=0, col=4}, {row=1, col=0}, {row=1, col=2}, {row=1, col=4},
{row=2, col=1}, {row=2, col=3}, {row=2, col=5}, {row=3, col=0},
{row=3, col=2}, {row=3, col=4}, {row=4, col=1}, {row=4, col=2},
{row=4, col=3}, {row=5, col=0}, {row=5, col=3}, {row=5, col=5},
{row=6, col=1}, {row=6, col=3}, {row=6, col=4}, {row=7, col=0}}
for i in pairs(cells) do
local row = cells[i].row
local col = cells[i].col
-- If row is less than forestMap length:
if row < #forestMap then
-- If col is less than forestMap[row] length:
if col < #forestMap[row + 1] then
-- Now, we know the cell exists.
-- If it is 0, say where to shoot:
if forestMap[row + 1][col + 1] == 0 then
hero:say("Row " + row + " Column " + col + " Fire!")
end
end
end
end
"""
solutionsByLanguage.python.dungeonsOfKithgard = """
# Move towards the gem.
# Don’t touch the spikes!
# Type your code below and click Run when you’re done.
hero.moveRight()
hero.moveDown()
hero.moveRight()
"""
solutionsByLanguage.python.peekABoom = """
# Build traps on the path when the hero sees a munchkin!
while True:
enemy = hero.findNearestEnemy()
if enemy:
# Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24)
# Add an else below to move back to the clearing
else:
# Move to the Wooden X (19, 19)
hero.moveXY(19, 19)
"""
solutionsByLanguage.python.woodlandCleaver = """
# Use your new "cleave" skill as often as you can.
hero.moveXY(23, 23)
while True:
enemy = hero.findNearestEnemy()
if hero.isReady("cleave"):
# Cleave the enemy!
hero.cleave(enemy)
else:
# Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy)
"""
solutionsByLanguage.python.aFineMint = """
# Peons are trying to steal your coins!
# Write a function to squash them before they can take your coins.
def pickUpCoin():
coin = hero.findNearestItem()
if coin:
hero.moveXY(coin.pos.x, coin.pos.y)
# Write the attackEnemy function below.
# Find the nearest enemy and attack them if they exist!
def attackEnemy():
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
while True:
attackEnemy() # Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
"""
solutionsByLanguage.python.libraryTactician = """
# Hushbaum has been ambushed by ogres!
# She is busy healing her soldiers, you should command them to fight!
# The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
archerTarget = None
# Soldiers spread out in a circle and defend.
def commandSoldier(soldier, soldierIndex, numSoldiers):
angle = Math.PI * 2 * soldierIndex / numSoldiers
defendPos = {"x": 41, "y": 40}
defendPos.x += 10 * Math.cos(angle)
defendPos.y += 10 * Math.sin(angle)
hero.command(soldier, "defend", defendPos)
# Find the strongest target (most health)
# This function returns something! When you call the function, you will get some value back.
def findStrongestTarget():
mostHealth = 0
bestTarget = None
enemies = hero.findEnemies()
# Figure out which enemy has the most health, and set bestTarget to be that enemy.
for i in range(len(enemies)):
enemy = enemies[i]
if enemy.health > mostHealth:
bestTarget = enemy
mostHealth = enemy.health
# Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15:
return bestTarget
else:
return None
# If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
def commandArcher(archer):
nearest = archer.findNearestEnemy()
if archerTarget:
hero.command(archer, "attack", archerTarget)
elif nearest:
hero.command(archer, "attack", nearest)
while True:
# If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0:
# Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
soldiers = hero.findByType("soldier")
# Create a variable containing your archers.
archers = hero.findByType("archer")
for i in range(len(soldiers)):
soldier = soldiers[i]
commandSoldier(soldier, i, len(soldiers))
# use commandArcher() to command your archers
for i in range(len(archers)):
archer = archers[i]
commandArcher(archer)
"""
solutionsByLanguage.python.snowdrops = """
# We need to clear the forest of traps!
# The scout prepared a map of the forest.
# But be careful where you shoot! Don't start a fire.
# Get the map of the forest.
forestMap = hero.findNearest(hero.findFriends()).forestMap
# The map is a 2D array where 0 is a trap.
# The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!")
# But for the next points, check before shooting.
# There are an array of points to check.
cells = [{"row": 0, "col": 4}, {"row": 1, "col": 0}, {"row": 1, "col": 2}, {"row": 1, "col": 4},
{"row": 2, "col": 1}, {"row": 2, "col": 3}, {"row": 2, "col": 5}, {"row": 3, "col": 0},
{"row": 3, "col": 2}, {"row": 3, "col": 4}, {"row": 4, "col": 1}, {"row": 4, "col": 2},
{"row": 4, "col": 3}, {"row": 5, "col": 0}, {"row": 5, "col": 3}, {"row": 5, "col": 5},
{"row": 6, "col": 1}, {"row": 6, "col": 3}, {"row": 6, "col": 4}, {"row": 7, "col": 0}]
for i in range(len(cells)):
row = cells[i].row
col = cells[i].col
# If row is less than forestMap length:
if row < len(forestMap):
# If col is less than forestMap[row] length:
if col < len(forestMap[row]):
# Now, we know the cell exists.
# If it is 0, say where to shoot:
if forestMap[row][col] == 0:
hero.say("Row " + row + " Column " + col + " Fire!")
"""
solutionsByLanguage.coffeescript.dungeonsOfKithgard = """
# Move towards the gem.
# Don’t touch the spikes!
# Type your code below and click Run when you’re done.
hero.moveRight()
hero.moveDown()
hero.moveRight()
"""
solutionsByLanguage.coffeescript.peekABoom = """
# Build traps on the path when the hero sees a munchkin!
loop
enemy = hero.findNearestEnemy()
if enemy
# Build a "fire-trap" at the Red X (41, 24)
hero.buildXY "fire-trap", 41, 24
# Add an else below to move back to the clearing
else
# Move to the Wooden X (19, 19)
hero.moveXY 19, 19
"""
solutionsByLanguage.coffeescript.woodlandCleaver = """
# Use your new "cleave" skill as often as you can.
hero.moveXY 23, 23
loop
enemy = hero.findNearestEnemy()
if hero.isReady "cleave"
# Cleave the enemy!
hero.cleave enemy
else
# Else (if cleave isn't ready), do your normal attack.
hero.attack enemy
"""
solutionsByLanguage.coffeescript.aFineMint = """
# Peons are trying to steal your coins!
# Write a function to squash them before they can take your coins.
pickUpCoin = ->
coin = hero.findNearestItem()
if coin
hero.moveXY coin.pos.x, coin.pos.y
# Write the attackEnemy function below.
# Find the nearest enemy and attack them if they exist!
attackEnemy = ->
enemy = hero.findNearestEnemy()
if enemy
hero.attack enemy
loop
attackEnemy() # Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
"""
solutionsByLanguage.coffeescript.libraryTactician = """
# Hushbaum has been ambushed by ogres!
# She is busy healing her soldiers, you should command them to fight!
# The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
archerTarget = null
# Soldiers spread out in a circle and defend.
commandSoldier = (soldier, soldierIndex, numSoldiers) ->
angle = Math.PI * 2 * soldierIndex / numSoldiers
defendPos = {x: 41, y: 40}
defendPos.x += 10 * Math.cos angle
defendPos.y += 10 * Math.sin angle
hero.command soldier, "defend", defendPos
# Find the strongest target (most health)
# This function returns something! When you call the function, you will get some value back.
findStrongestTarget = ->
mostHealth = 0
bestTarget = null
enemies = hero.findEnemies()
# Figure out which enemy has the most health, and set bestTarget to be that enemy.
for enemy, i in enemies
if enemy.health > mostHealth
bestTarget = enemy
mostHealth = enemy.health
# Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15
return bestTarget
else
return null
# If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
commandArcher = (archer) ->
nearest = archer.findNearestEnemy()
if archerTarget
hero.command archer, "attack", archerTarget
else if nearest
hero.command archer, "attack", nearest
loop
# If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0
# Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
soldiers = hero.findByType "soldier"
# Create a variable containing your archers.
archers = hero.findByType "archer"
for soldier, i in soldiers
commandSoldier soldier, i, soldiers.length
# use commandArcher() to command your archers
for archer, i in archers
commandArcher archer
"""
solutionsByLanguage.coffeescript.snowdrops = """
# We need to clear the forest of traps!
# The scout prepared a map of the forest.
# But be careful where you shoot! Don't start a fire.
# Get the map of the forest.
forestMap = hero.findNearest(hero.findFriends()).forestMap
# The map is a 2D array where 0 is a trap.
# The first sure shot.
hero.say "Row " + 0 + " Column " + 1 + " Fire!"
# But for the next points, check before shooting.
# There are an array of points to check.
cells = [{row: 0, col: 4}, {row: 1, col: 0}, {row: 1, col: 2}, {row: 1, col: 4},
{row: 2, col: 1}, {row: 2, col: 3}, {row: 2, col: 5}, {row: 3, col: 0},
{row: 3, col: 2}, {row: 3, col: 4}, {row: 4, col: 1}, {row: 4, col: 2},
{row: 4, col: 3}, {row: 5, col: 0}, {row: 5, col: 3}, {row: 5, col: 5},
{row: 6, col: 1}, {row: 6, col: 3}, {row: 6, col: 4}, {row: 7, col: 0}]
for i in [0...cells.length]
row = cells[i].row
col = cells[i].col
# If row is less than forestMap length:
if row < forestMap.length
# If col is less than forestMap[row] length:
if col < forestMap[row].length
# Now, we know the cell exists.
# If it is 0, say where to shoot:
if forestMap[row][col] is 0
hero.say "Row " + row + " Column " + col + " Fire!"
"""
solutionsByLanguage.java.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
public class AI {
public static void main(String[] args) {
hero.moveRight();
hero.moveDown();
hero.moveRight();
}
}
"""
solutionsByLanguage.java.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
public class AI {
public static void main(String[] args) {
while(true) {
var enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
}
}
"""
solutionsByLanguage.java.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
public class AI {
public static void main(String[] args) {
hero.moveXY(23, 23);
while(true) {
var enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
}
}
"""
solutionsByLanguage.java.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
public class AI {
public static void pickUpCoin() {
var coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
public static void attackEnemy() {
var enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
public static void main(String[] args) {
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
}
}
"""
solutionsByLanguage.java.libraryTactician = """
// Hushbaum has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
public class AI {
var archerTarget = null;
// Soldiers spread out in a circle and defend.
public static void commandSoldier(Object soldier, Object soldierIndex, Object numSoldiers) {
var angle = Math.PI * 2 * soldierIndex / numSoldiers;
var defendPos = {41, 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
public static Object findStrongestTarget() {
var mostHealth = 0;
var bestTarget = null;
var enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(int i=0; i < enemies.length; i++) {
var enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
public static void commandArcher(Object archer) {
var nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
public static void main(String[] args) {
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
var soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
var archers = hero.findByType("archer");
for(int i=0; i < soldiers.length; i++) {
var soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.length);
}
// use commandArcher() to command your archers
for(i=0; i < archers.length; i++) {
var archer = archers[i];
commandArcher(archer);
}
}
}
}
"""
solutionsByLanguage.java.snowdrops = """
int main() {
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
// Get the map of the forest.
auto forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
auto cells = {{0, 4}, {1, 0}, {1, 2}, {1, 4},
{2, 1}, {2, 3}, {2, 5}, {3, 0},
{3, 2}, {3, 4}, {4, 1}, {4, 2},
{4, 3}, {5, 0}, {5, 3}, {5, 5},
{6, 1}, {6, 3}, {6, 4}, {7, 0}};
for (int i = 0; i < cells.size(); i++) {
auto row = cells[i].x;
auto col = cells[i].y;
// If row is less than forestMap length:
if (row < forestMap.length) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].size()) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] == 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
return 0;
}
"""
solutionsByLanguage.cpp.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
int main() {
hero.moveRight();
hero.moveDown();
hero.moveRight();
return 0;
}
"""
solutionsByLanguage.cpp.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
int main() {
while(true) {
auto enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
int main() {
hero.moveXY(23, 23);
while(true) {
auto enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
auto pickUpCoin() {
auto coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
auto attackEnemy() {
auto enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
int main() {
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
return 0;
}
"""
solutionsByLanguage.cpp.libraryTactician = """
// Hushbaum has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
// Soldiers spread out in a circle and defend.
auto commandSoldier(auto soldier, auto soldierIndex, auto numSoldiers) {
auto angle = Math.PI * 2 * soldierIndex / numSoldiers;
auto defendPos = {41, 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
// Find the strongest target (most health)
// This function returns something! When you call the function, you will get some value back.
auto findStrongestTarget() {
auto mostHealth = 0;
auto bestTarget = null;
auto enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(int i=0; i < enemies.size(); i++) {
auto enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
// If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
auto commandArcher(auto archer) {
auto nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
auto archerTarget = null;
int main() {
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
auto soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
auto archers = hero.findByType("archer");
for(int i=0; i < soldiers.size(); i++) {
auto soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.size());
}
// use commandArcher() to command your archers
for(i=0; i < archers.size(); i++) {
auto archer = archers[i];
commandArcher(archer);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.snowdrops = """
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
int main() {
// Get the map of the forest.
auto forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
auto cells = {{0, 4}, {1, 0}, {1, 2}, {1, 4},
{2, 1}, {2, 3}, {2, 5}, {3, 0},
{3, 2}, {3, 4}, {4, 1}, {4, 2},
{4, 3}, {5, 0}, {5, 3}, {5, 5},
{6, 1}, {6, 3}, {6, 4}, {7, 0}};
for (int i = 0; i < cells.size(); i++) {
auto row = cells[i].x;
auto col = cells[i].y;
// If row is less than forestMap length:
if (row < forestMap.size()) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].size()) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] == 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
return 0;
}
"""
levenshteinDistance = (str1, str2) ->
# Simple edit distance measurement between two strings
m = str1.length
n = str2.length
d = []
return n unless m
return m unless n
d[i] = [i] for i in [0..m]
d[0][j] = j for j in [1..n]
for i in [1..m]
for j in [1..n]
if str1[i-1] is str2[j-1]
d[i][j] = d[i-1][j-1]
else
d[i][j] = Math.min(
d[i-1][j]
d[i][j-1]
d[i-1][j-1]
) + 1
d[m][n]
describe 'Aether / code transpilation utility library', ->
aetherUtils = require '../../../app/lib/aether_utils'
describe 'translateJS(jsCode, "cpp", fullCode)', ->
describe 'do not add int main if fullCode set false', ->
it 'if there is no pattern needing translation', ->
expect(aetherUtils.translateJS('hero.moveRight()', 'cpp', false)).toBe('hero.moveRight()')
it 'if there is var x or var y', ->
expect(aetherUtils.translateJS('var x = 2;\nvar y = 3', 'cpp', false)).toBe('float x = 2;\nfloat y = 3')
it 'if there is ===/!==', ->
expect(aetherUtils.translateJS('if (a === 2 && b !== 1)', 'cpp', false)).toBe('if (a == 2 && b != 1)')
it 'if there is other var', ->
expect(aetherUtils.translateJS('var enemy = hero...', 'cpp', false)).toBe('auto enemy = hero...')
it 'if there is a function definition', ->
expect(aetherUtils.translateJS('function a() {}\n', 'cpp', false)).toBe('auto a() {}\n')
describe 'add int main if fullCode set true', ->
it 'if there is no pattern needing translation', ->
expect(aetherUtils.translateJS('hero.moveRight();'), 'cpp').toBe('int main() {\n hero.moveRight();\n return 0;\n}')
it 'if there is var x or var y', ->
expect(aetherUtils.translateJS('var x = 2;\nvar y = 3;', 'cpp')).toBe('int main() {\n float x = 2;\n float y = 3;\n return 0;\n}')
it 'if there is ===/!==', ->
expect(aetherUtils.translateJS('while (a === 2 && b !== 1)', 'cpp')).toBe('int main() {\n while (a == 2 && b != 1)\n return 0;\n}')
it 'if there is other var', ->
expect(aetherUtils.translateJS('var enemy = hero...', 'cpp')).toBe('int main() {\n auto enemy = hero...\n return 0;\n}')
it 'if there is a function definition', ->
expect(aetherUtils.translateJS('function a() {}\n', 'cpp')).toBe('auto a() {}\n\nint main() {\n \n return 0;\n}')
it 'if there is a function definition with parameter', ->
expect(aetherUtils.translateJS('function a(b) {}\n', 'cpp')).toBe('auto a(auto b) {}\n\nint main() {\n \n return 0;\n}')
it 'if there is a function definition with parameters', ->
expect(aetherUtils.translateJS('function a(b, c) {}\na();', 'cpp')).toBe('auto a(auto b, auto c) {}\n\nint main() {\n a();\n return 0;\n}')
describe 'if there are start comments', ->
it 'if there is no code', ->
expect(aetherUtils.translateJS('//abc\n//def\n\n', 'cpp')).toBe('//abc\n//def\n\nint main() {\n \n return 0;\n}')
it 'if there is code without function definition', ->
expect(aetherUtils.translateJS('//abc\n\nhero.moveRight()', 'cpp')).toBe('//abc\n\nint main() {\n hero.moveRight()\n return 0;\n}')
it 'if there is code with function definition', ->
expect(aetherUtils.translateJS('//abc\n\nfunction a(b, c) {}\nhero.moveRight()', 'cpp')).toBe('//abc\n\nauto a(auto b, auto c) {}\n\nint main() {\n hero.moveRight()\n return 0;\n}')
describe 'translateJS can handle full solutions', ->
unsupported = [
# Permanent (must write these solutions manually)
['lua', 'snowdrops'] # manual rewriting needed for off-by-one error with 1-indexed arrays for row/col in the map
['cpp', 'snowdrops'] # row/col literals need to be manually rewritten to x/y for our {x, y} Vector hack
['java', 'snowdrops'] # row/col literals need to be manually rewritten to [row, col] arrays, also indexed with [0] and [1]
# Temporary (should fix the code generation to be smarter)
['java', 'libraryTactician'] # Need to auto-detect self-defined function return type
['java', 'aFineMint'] # Need to not strip out each hoisted function's start comments
['cpp', 'aFineMint'] # Need to not strip out each hoisted function's start comments
]
targetLanguage = ''
targetLevel = ''
for language, solutions of solutionsByLanguage when language isnt 'javascript'
do (language, solutions) ->
describe 'in ' + language, ->
for level, code of solutions
do (level, code) ->
if _.find(unsupported, ([lang, lev]) -> lang is language and lev is level)
f = xit
else if not targetLevel and not targetLanguage
f = it
else if (targetLevel and level is targetLevel) or (targetLanguage and language is targetLanguage)
f = fit
else
f = it
f 'properly translates ' + level, ->
js = solutionsByLanguage.javascript[level]
translated = aetherUtils.translateJS js, language, true
editDistance = levenshteinDistance translated, code
expect('\n' + translated).toEqual('\n' + code)
expect(editDistance).toEqual(0)
| 155355 | solutionsByLanguage = javascript: {}, lua: {}, python: {}, coffeescript: {}, java: {}, cpp: {}
solutionsByLanguage.javascript.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
hero.moveRight();
hero.moveDown();
hero.moveRight();
"""
solutionsByLanguage.javascript.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
while(true) {
var enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
"""
solutionsByLanguage.javascript.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
hero.moveXY(23, 23);
while(true) {
var enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
"""
solutionsByLanguage.javascript.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
function pickUpCoin() {
var coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
function attackEnemy() {
var enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
"""
solutionsByLanguage.javascript.libraryTactician = """
// <NAME> has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
var archerTarget = null;
// Soldiers spread out in a circle and defend.
function commandSoldier(soldier, soldierIndex, numSoldiers) {
var angle = Math.PI * 2 * soldierIndex / numSoldiers;
var defendPos = {x: 41, y: 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
// Find the strongest target (most health)
// This function returns something! When you call the function, you will get some value back.
function findStrongestTarget() {
var mostHealth = 0;
var bestTarget = null;
var enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(var i=0; i < enemies.length; i++) {
var enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
// If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
function commandArcher(archer) {
var nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
var soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
var archers = hero.findByType("archer");
for(var i=0; i < soldiers.length; i++) {
var soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.length);
}
// use commandArcher() to command your archers
for(i=0; i < archers.length; i++) {
var archer = archers[i];
commandArcher(archer);
}
}
"""
solutionsByLanguage.javascript.snowdrops = """
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
// Get the map of the forest.
var forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
var cells = [{row: 0, col: 4}, {row: 1, col: 0}, {row: 1, col: 2}, {row: 1, col: 4},
{row: 2, col: 1}, {row: 2, col: 3}, {row: 2, col: 5}, {row: 3, col: 0},
{row: 3, col: 2}, {row: 3, col: 4}, {row: 4, col: 1}, {row: 4, col: 2},
{row: 4, col: 3}, {row: 5, col: 0}, {row: 5, col: 3}, {row: 5, col: 5},
{row: 6, col: 1}, {row: 6, col: 3}, {row: 6, col: 4}, {row: 7, col: 0}];
for (var i = 0; i < cells.length; i++) {
var row = cells[i].row;
var col = cells[i].col;
// If row is less than forestMap length:
if (row < forestMap.length) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].length) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] === 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
"""
solutionsByLanguage.lua.dungeonsOfKithgard = """
-- Move towards the gem.
-- Don’t touch the spikes!
-- Type your code below and click Run when you’re done.
hero:moveRight()
hero:moveDown()
hero:moveRight()
"""
solutionsByLanguage.lua.peekABoom = """
-- Build traps on the path when the hero sees a munchkin!
while true do
local enemy = hero:findNearestEnemy()
if enemy then
-- Build a "fire-trap" at the Red X (41, 24)
hero:buildXY("fire-trap", 41, 24)
-- Add an else below to move back to the clearing
else
-- Move to the Wooden X (19, 19)
hero:moveXY(19, 19)
end
end
"""
solutionsByLanguage.lua.woodlandCleaver = """
-- Use your new "cleave" skill as often as you can.
hero:moveXY(23, 23)
while true do
local enemy = hero:findNearestEnemy()
if hero:isReady("cleave") then
-- Cleave the enemy!
hero:cleave(enemy)
else
-- Else (if cleave isn't ready), do your normal attack.
hero:attack(enemy)
end
end
"""
solutionsByLanguage.lua.aFineMint = """
-- Peons are trying to steal your coins!
-- Write a function to squash them before they can take your coins.
function pickUpCoin()
local coin = hero:findNearestItem()
if coin then
hero:moveXY(coin.pos.x, coin.pos.y)
end
end
-- Write the attackEnemy function below.
-- Find the nearest enemy and attack them if they exist!
function attackEnemy()
local enemy = hero:findNearestEnemy()
if enemy then
hero:attack(enemy)
end
end
while true do
attackEnemy() -- Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
end
"""
solutionsByLanguage.lua.libraryTactician = """
-- <NAME> has been ambushed by ogres!
-- She is busy healing her soldiers, you should command them to fight!
-- The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
local archerTarget = nil
-- Soldiers spread out in a circle and defend.
function commandSoldier(soldier, soldierIndex, numSoldiers)
local angle = Math.PI * 2 * soldierIndex / numSoldiers
local defendPos = {x=41, y=40}
defendPos.x = defendPos.x + 10 * Math.cos(angle)
defendPos.y = defendPos.y + 10 * Math.sin(angle)
hero:command(soldier, "defend", defendPos)
end
-- Find the strongest target (most health)
-- This function returns something! When you call the function, you will get some value back.
function findStrongestTarget()
local mostHealth = 0
local bestTarget = nil
local enemies = hero:findEnemies()
-- Figure out which enemy has the most health, and set bestTarget to be that enemy.
for i, enemy in pairs(enemies) do
if enemy.health > mostHealth then
bestTarget = enemy
mostHealth = enemy.health
end
end
-- Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15 then
return bestTarget
else
return nil
end
end
-- If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
function commandArcher(archer)
local nearest = archer:findNearestEnemy()
if archerTarget then
hero:command(archer, "attack", archerTarget)
elseif nearest then
hero:command(archer, "attack", nearest)
end
end
while true do
-- If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0 then
-- Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
end
local soldiers = hero:findByType("soldier")
-- Create a variable containing your archers.
local archers = hero:findByType("archer")
for i, soldier in pairs(soldiers) do
commandSoldier(soldier, i, #soldiers)
end
-- use commandArcher() to command your archers
for i, archer in pairs(archers) do
commandArcher(archer)
end
end
"""
solutionsByLanguage.lua.snowdrops = """
-- We need to clear the forest of traps!
-- The scout prepared a map of the forest.
-- But be careful where you shoot! Don't start a fire.
-- Get the map of the forest.
local forestMap = hero:findNearest(hero:findFriends()).forestMap
-- The map is a 2D array where 0 is a trap.
-- The first sure shot.
hero:say("Row " + 0 + " Column " + 1 + " Fire!")
-- But for the next points, check before shooting.
-- There are an array of points to check.
local cells = {{row=0, col=4}, {row=1, col=0}, {row=1, col=2}, {row=1, col=4},
{row=2, col=1}, {row=2, col=3}, {row=2, col=5}, {row=3, col=0},
{row=3, col=2}, {row=3, col=4}, {row=4, col=1}, {row=4, col=2},
{row=4, col=3}, {row=5, col=0}, {row=5, col=3}, {row=5, col=5},
{row=6, col=1}, {row=6, col=3}, {row=6, col=4}, {row=7, col=0}}
for i in pairs(cells) do
local row = cells[i].row
local col = cells[i].col
-- If row is less than forestMap length:
if row < #forestMap then
-- If col is less than forestMap[row] length:
if col < #forestMap[row + 1] then
-- Now, we know the cell exists.
-- If it is 0, say where to shoot:
if forestMap[row + 1][col + 1] == 0 then
hero:say("Row " + row + " Column " + col + " Fire!")
end
end
end
end
"""
solutionsByLanguage.python.dungeonsOfKithgard = """
# Move towards the gem.
# Don’t touch the spikes!
# Type your code below and click Run when you’re done.
hero.moveRight()
hero.moveDown()
hero.moveRight()
"""
solutionsByLanguage.python.peekABoom = """
# Build traps on the path when the hero sees a munchkin!
while True:
enemy = hero.findNearestEnemy()
if enemy:
# Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24)
# Add an else below to move back to the clearing
else:
# Move to the Wooden X (19, 19)
hero.moveXY(19, 19)
"""
solutionsByLanguage.python.woodlandCleaver = """
# Use your new "cleave" skill as often as you can.
hero.moveXY(23, 23)
while True:
enemy = hero.findNearestEnemy()
if hero.isReady("cleave"):
# Cleave the enemy!
hero.cleave(enemy)
else:
# Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy)
"""
solutionsByLanguage.python.aFineMint = """
# Peons are trying to steal your coins!
# Write a function to squash them before they can take your coins.
def pickUpCoin():
coin = hero.findNearestItem()
if coin:
hero.moveXY(coin.pos.x, coin.pos.y)
# Write the attackEnemy function below.
# Find the nearest enemy and attack them if they exist!
def attackEnemy():
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
while True:
attackEnemy() # Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
"""
solutionsByLanguage.python.libraryTactician = """
# <NAME> has been ambushed by ogres!
# She is busy healing her soldiers, you should command them to fight!
# The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
archerTarget = None
# Soldiers spread out in a circle and defend.
def commandSoldier(soldier, soldierIndex, numSoldiers):
angle = Math.PI * 2 * soldierIndex / numSoldiers
defendPos = {"x": 41, "y": 40}
defendPos.x += 10 * Math.cos(angle)
defendPos.y += 10 * Math.sin(angle)
hero.command(soldier, "defend", defendPos)
# Find the strongest target (most health)
# This function returns something! When you call the function, you will get some value back.
def findStrongestTarget():
mostHealth = 0
bestTarget = None
enemies = hero.findEnemies()
# Figure out which enemy has the most health, and set bestTarget to be that enemy.
for i in range(len(enemies)):
enemy = enemies[i]
if enemy.health > mostHealth:
bestTarget = enemy
mostHealth = enemy.health
# Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15:
return bestTarget
else:
return None
# If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
def commandArcher(archer):
nearest = archer.findNearestEnemy()
if archerTarget:
hero.command(archer, "attack", archerTarget)
elif nearest:
hero.command(archer, "attack", nearest)
while True:
# If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0:
# Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
soldiers = hero.findByType("soldier")
# Create a variable containing your archers.
archers = hero.findByType("archer")
for i in range(len(soldiers)):
soldier = soldiers[i]
commandSoldier(soldier, i, len(soldiers))
# use commandArcher() to command your archers
for i in range(len(archers)):
archer = archers[i]
commandArcher(archer)
"""
solutionsByLanguage.python.snowdrops = """
# We need to clear the forest of traps!
# The scout prepared a map of the forest.
# But be careful where you shoot! Don't start a fire.
# Get the map of the forest.
forestMap = hero.findNearest(hero.findFriends()).forestMap
# The map is a 2D array where 0 is a trap.
# The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!")
# But for the next points, check before shooting.
# There are an array of points to check.
cells = [{"row": 0, "col": 4}, {"row": 1, "col": 0}, {"row": 1, "col": 2}, {"row": 1, "col": 4},
{"row": 2, "col": 1}, {"row": 2, "col": 3}, {"row": 2, "col": 5}, {"row": 3, "col": 0},
{"row": 3, "col": 2}, {"row": 3, "col": 4}, {"row": 4, "col": 1}, {"row": 4, "col": 2},
{"row": 4, "col": 3}, {"row": 5, "col": 0}, {"row": 5, "col": 3}, {"row": 5, "col": 5},
{"row": 6, "col": 1}, {"row": 6, "col": 3}, {"row": 6, "col": 4}, {"row": 7, "col": 0}]
for i in range(len(cells)):
row = cells[i].row
col = cells[i].col
# If row is less than forestMap length:
if row < len(forestMap):
# If col is less than forestMap[row] length:
if col < len(forestMap[row]):
# Now, we know the cell exists.
# If it is 0, say where to shoot:
if forestMap[row][col] == 0:
hero.say("Row " + row + " Column " + col + " Fire!")
"""
solutionsByLanguage.coffeescript.dungeonsOfKithgard = """
# Move towards the gem.
# Don’t touch the spikes!
# Type your code below and click Run when you’re done.
hero.moveRight()
hero.moveDown()
hero.moveRight()
"""
solutionsByLanguage.coffeescript.peekABoom = """
# Build traps on the path when the hero sees a munchkin!
loop
enemy = hero.findNearestEnemy()
if enemy
# Build a "fire-trap" at the Red X (41, 24)
hero.buildXY "fire-trap", 41, 24
# Add an else below to move back to the clearing
else
# Move to the Wooden X (19, 19)
hero.moveXY 19, 19
"""
solutionsByLanguage.coffeescript.woodlandCleaver = """
# Use your new "cleave" skill as often as you can.
hero.moveXY 23, 23
loop
enemy = hero.findNearestEnemy()
if hero.isReady "cleave"
# Cleave the enemy!
hero.cleave enemy
else
# Else (if cleave isn't ready), do your normal attack.
hero.attack enemy
"""
solutionsByLanguage.coffeescript.aFineMint = """
# Peons are trying to steal your coins!
# Write a function to squash them before they can take your coins.
pickUpCoin = ->
coin = hero.findNearestItem()
if coin
hero.moveXY coin.pos.x, coin.pos.y
# Write the attackEnemy function below.
# Find the nearest enemy and attack them if they exist!
attackEnemy = ->
enemy = hero.findNearestEnemy()
if enemy
hero.attack enemy
loop
attackEnemy() # Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
"""
solutionsByLanguage.coffeescript.libraryTactician = """
# <NAME> has been ambushed by ogres!
# She is busy healing her soldiers, you should command them to fight!
# The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
archerTarget = null
# Soldiers spread out in a circle and defend.
commandSoldier = (soldier, soldierIndex, numSoldiers) ->
angle = Math.PI * 2 * soldierIndex / numSoldiers
defendPos = {x: 41, y: 40}
defendPos.x += 10 * Math.cos angle
defendPos.y += 10 * Math.sin angle
hero.command soldier, "defend", defendPos
# Find the strongest target (most health)
# This function returns something! When you call the function, you will get some value back.
findStrongestTarget = ->
mostHealth = 0
bestTarget = null
enemies = hero.findEnemies()
# Figure out which enemy has the most health, and set bestTarget to be that enemy.
for enemy, i in enemies
if enemy.health > mostHealth
bestTarget = enemy
mostHealth = enemy.health
# Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15
return bestTarget
else
return null
# If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
commandArcher = (archer) ->
nearest = archer.findNearestEnemy()
if archerTarget
hero.command archer, "attack", archerTarget
else if nearest
hero.command archer, "attack", nearest
loop
# If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0
# Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
soldiers = hero.findByType "soldier"
# Create a variable containing your archers.
archers = hero.findByType "archer"
for soldier, i in soldiers
commandSoldier soldier, i, soldiers.length
# use commandArcher() to command your archers
for archer, i in archers
commandArcher archer
"""
solutionsByLanguage.coffeescript.snowdrops = """
# We need to clear the forest of traps!
# The scout prepared a map of the forest.
# But be careful where you shoot! Don't start a fire.
# Get the map of the forest.
forestMap = hero.findNearest(hero.findFriends()).forestMap
# The map is a 2D array where 0 is a trap.
# The first sure shot.
hero.say "Row " + 0 + " Column " + 1 + " Fire!"
# But for the next points, check before shooting.
# There are an array of points to check.
cells = [{row: 0, col: 4}, {row: 1, col: 0}, {row: 1, col: 2}, {row: 1, col: 4},
{row: 2, col: 1}, {row: 2, col: 3}, {row: 2, col: 5}, {row: 3, col: 0},
{row: 3, col: 2}, {row: 3, col: 4}, {row: 4, col: 1}, {row: 4, col: 2},
{row: 4, col: 3}, {row: 5, col: 0}, {row: 5, col: 3}, {row: 5, col: 5},
{row: 6, col: 1}, {row: 6, col: 3}, {row: 6, col: 4}, {row: 7, col: 0}]
for i in [0...cells.length]
row = cells[i].row
col = cells[i].col
# If row is less than forestMap length:
if row < forestMap.length
# If col is less than forestMap[row] length:
if col < forestMap[row].length
# Now, we know the cell exists.
# If it is 0, say where to shoot:
if forestMap[row][col] is 0
hero.say "Row " + row + " Column " + col + " Fire!"
"""
solutionsByLanguage.java.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
public class AI {
public static void main(String[] args) {
hero.moveRight();
hero.moveDown();
hero.moveRight();
}
}
"""
solutionsByLanguage.java.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
public class AI {
public static void main(String[] args) {
while(true) {
var enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
}
}
"""
solutionsByLanguage.java.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
public class AI {
public static void main(String[] args) {
hero.moveXY(23, 23);
while(true) {
var enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
}
}
"""
solutionsByLanguage.java.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
public class AI {
public static void pickUpCoin() {
var coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
public static void attackEnemy() {
var enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
public static void main(String[] args) {
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
}
}
"""
solutionsByLanguage.java.libraryTactician = """
// <NAME> has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
public class AI {
var archerTarget = null;
// Soldiers spread out in a circle and defend.
public static void commandSoldier(Object soldier, Object soldierIndex, Object numSoldiers) {
var angle = Math.PI * 2 * soldierIndex / numSoldiers;
var defendPos = {41, 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
public static Object findStrongestTarget() {
var mostHealth = 0;
var bestTarget = null;
var enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(int i=0; i < enemies.length; i++) {
var enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
public static void commandArcher(Object archer) {
var nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
public static void main(String[] args) {
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
var soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
var archers = hero.findByType("archer");
for(int i=0; i < soldiers.length; i++) {
var soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.length);
}
// use commandArcher() to command your archers
for(i=0; i < archers.length; i++) {
var archer = archers[i];
commandArcher(archer);
}
}
}
}
"""
solutionsByLanguage.java.snowdrops = """
int main() {
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
// Get the map of the forest.
auto forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
auto cells = {{0, 4}, {1, 0}, {1, 2}, {1, 4},
{2, 1}, {2, 3}, {2, 5}, {3, 0},
{3, 2}, {3, 4}, {4, 1}, {4, 2},
{4, 3}, {5, 0}, {5, 3}, {5, 5},
{6, 1}, {6, 3}, {6, 4}, {7, 0}};
for (int i = 0; i < cells.size(); i++) {
auto row = cells[i].x;
auto col = cells[i].y;
// If row is less than forestMap length:
if (row < forestMap.length) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].size()) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] == 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
return 0;
}
"""
solutionsByLanguage.cpp.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
int main() {
hero.moveRight();
hero.moveDown();
hero.moveRight();
return 0;
}
"""
solutionsByLanguage.cpp.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
int main() {
while(true) {
auto enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
int main() {
hero.moveXY(23, 23);
while(true) {
auto enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
auto pickUpCoin() {
auto coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
auto attackEnemy() {
auto enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
int main() {
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
return 0;
}
"""
solutionsByLanguage.cpp.libraryTactician = """
// <NAME>ushbaum has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
// Soldiers spread out in a circle and defend.
auto commandSoldier(auto soldier, auto soldierIndex, auto numSoldiers) {
auto angle = Math.PI * 2 * soldierIndex / numSoldiers;
auto defendPos = {41, 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
// Find the strongest target (most health)
// This function returns something! When you call the function, you will get some value back.
auto findStrongestTarget() {
auto mostHealth = 0;
auto bestTarget = null;
auto enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(int i=0; i < enemies.size(); i++) {
auto enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
// If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
auto commandArcher(auto archer) {
auto nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
auto archerTarget = null;
int main() {
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
auto soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
auto archers = hero.findByType("archer");
for(int i=0; i < soldiers.size(); i++) {
auto soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.size());
}
// use commandArcher() to command your archers
for(i=0; i < archers.size(); i++) {
auto archer = archers[i];
commandArcher(archer);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.snowdrops = """
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
int main() {
// Get the map of the forest.
auto forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
auto cells = {{0, 4}, {1, 0}, {1, 2}, {1, 4},
{2, 1}, {2, 3}, {2, 5}, {3, 0},
{3, 2}, {3, 4}, {4, 1}, {4, 2},
{4, 3}, {5, 0}, {5, 3}, {5, 5},
{6, 1}, {6, 3}, {6, 4}, {7, 0}};
for (int i = 0; i < cells.size(); i++) {
auto row = cells[i].x;
auto col = cells[i].y;
// If row is less than forestMap length:
if (row < forestMap.size()) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].size()) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] == 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
return 0;
}
"""
levenshteinDistance = (str1, str2) ->
# Simple edit distance measurement between two strings
m = str1.length
n = str2.length
d = []
return n unless m
return m unless n
d[i] = [i] for i in [0..m]
d[0][j] = j for j in [1..n]
for i in [1..m]
for j in [1..n]
if str1[i-1] is str2[j-1]
d[i][j] = d[i-1][j-1]
else
d[i][j] = Math.min(
d[i-1][j]
d[i][j-1]
d[i-1][j-1]
) + 1
d[m][n]
describe 'Aether / code transpilation utility library', ->
aetherUtils = require '../../../app/lib/aether_utils'
describe 'translateJS(jsCode, "cpp", fullCode)', ->
describe 'do not add int main if fullCode set false', ->
it 'if there is no pattern needing translation', ->
expect(aetherUtils.translateJS('hero.moveRight()', 'cpp', false)).toBe('hero.moveRight()')
it 'if there is var x or var y', ->
expect(aetherUtils.translateJS('var x = 2;\nvar y = 3', 'cpp', false)).toBe('float x = 2;\nfloat y = 3')
it 'if there is ===/!==', ->
expect(aetherUtils.translateJS('if (a === 2 && b !== 1)', 'cpp', false)).toBe('if (a == 2 && b != 1)')
it 'if there is other var', ->
expect(aetherUtils.translateJS('var enemy = hero...', 'cpp', false)).toBe('auto enemy = hero...')
it 'if there is a function definition', ->
expect(aetherUtils.translateJS('function a() {}\n', 'cpp', false)).toBe('auto a() {}\n')
describe 'add int main if fullCode set true', ->
it 'if there is no pattern needing translation', ->
expect(aetherUtils.translateJS('hero.moveRight();'), 'cpp').toBe('int main() {\n hero.moveRight();\n return 0;\n}')
it 'if there is var x or var y', ->
expect(aetherUtils.translateJS('var x = 2;\nvar y = 3;', 'cpp')).toBe('int main() {\n float x = 2;\n float y = 3;\n return 0;\n}')
it 'if there is ===/!==', ->
expect(aetherUtils.translateJS('while (a === 2 && b !== 1)', 'cpp')).toBe('int main() {\n while (a == 2 && b != 1)\n return 0;\n}')
it 'if there is other var', ->
expect(aetherUtils.translateJS('var enemy = hero...', 'cpp')).toBe('int main() {\n auto enemy = hero...\n return 0;\n}')
it 'if there is a function definition', ->
expect(aetherUtils.translateJS('function a() {}\n', 'cpp')).toBe('auto a() {}\n\nint main() {\n \n return 0;\n}')
it 'if there is a function definition with parameter', ->
expect(aetherUtils.translateJS('function a(b) {}\n', 'cpp')).toBe('auto a(auto b) {}\n\nint main() {\n \n return 0;\n}')
it 'if there is a function definition with parameters', ->
expect(aetherUtils.translateJS('function a(b, c) {}\na();', 'cpp')).toBe('auto a(auto b, auto c) {}\n\nint main() {\n a();\n return 0;\n}')
describe 'if there are start comments', ->
it 'if there is no code', ->
expect(aetherUtils.translateJS('//abc\n//def\n\n', 'cpp')).toBe('//abc\n//def\n\nint main() {\n \n return 0;\n}')
it 'if there is code without function definition', ->
expect(aetherUtils.translateJS('//abc\n\nhero.moveRight()', 'cpp')).toBe('//abc\n\nint main() {\n hero.moveRight()\n return 0;\n}')
it 'if there is code with function definition', ->
expect(aetherUtils.translateJS('//abc\n\nfunction a(b, c) {}\nhero.moveRight()', 'cpp')).toBe('//abc\n\nauto a(auto b, auto c) {}\n\nint main() {\n hero.moveRight()\n return 0;\n}')
describe 'translateJS can handle full solutions', ->
unsupported = [
# Permanent (must write these solutions manually)
['lua', 'snowdrops'] # manual rewriting needed for off-by-one error with 1-indexed arrays for row/col in the map
['cpp', 'snowdrops'] # row/col literals need to be manually rewritten to x/y for our {x, y} Vector hack
['java', 'snowdrops'] # row/col literals need to be manually rewritten to [row, col] arrays, also indexed with [0] and [1]
# Temporary (should fix the code generation to be smarter)
['java', 'libraryTactician'] # Need to auto-detect self-defined function return type
['java', 'aFineMint'] # Need to not strip out each hoisted function's start comments
['cpp', 'aFineMint'] # Need to not strip out each hoisted function's start comments
]
targetLanguage = ''
targetLevel = ''
for language, solutions of solutionsByLanguage when language isnt 'javascript'
do (language, solutions) ->
describe 'in ' + language, ->
for level, code of solutions
do (level, code) ->
if _.find(unsupported, ([lang, lev]) -> lang is language and lev is level)
f = xit
else if not targetLevel and not targetLanguage
f = it
else if (targetLevel and level is targetLevel) or (targetLanguage and language is targetLanguage)
f = fit
else
f = it
f 'properly translates ' + level, ->
js = solutionsByLanguage.javascript[level]
translated = aetherUtils.translateJS js, language, true
editDistance = levenshteinDistance translated, code
expect('\n' + translated).toEqual('\n' + code)
expect(editDistance).toEqual(0)
| true | solutionsByLanguage = javascript: {}, lua: {}, python: {}, coffeescript: {}, java: {}, cpp: {}
solutionsByLanguage.javascript.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
hero.moveRight();
hero.moveDown();
hero.moveRight();
"""
solutionsByLanguage.javascript.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
while(true) {
var enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
"""
solutionsByLanguage.javascript.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
hero.moveXY(23, 23);
while(true) {
var enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
"""
solutionsByLanguage.javascript.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
function pickUpCoin() {
var coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
function attackEnemy() {
var enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
"""
solutionsByLanguage.javascript.libraryTactician = """
// PI:NAME:<NAME>END_PI has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
var archerTarget = null;
// Soldiers spread out in a circle and defend.
function commandSoldier(soldier, soldierIndex, numSoldiers) {
var angle = Math.PI * 2 * soldierIndex / numSoldiers;
var defendPos = {x: 41, y: 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
// Find the strongest target (most health)
// This function returns something! When you call the function, you will get some value back.
function findStrongestTarget() {
var mostHealth = 0;
var bestTarget = null;
var enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(var i=0; i < enemies.length; i++) {
var enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
// If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
function commandArcher(archer) {
var nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
var soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
var archers = hero.findByType("archer");
for(var i=0; i < soldiers.length; i++) {
var soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.length);
}
// use commandArcher() to command your archers
for(i=0; i < archers.length; i++) {
var archer = archers[i];
commandArcher(archer);
}
}
"""
solutionsByLanguage.javascript.snowdrops = """
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
// Get the map of the forest.
var forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
var cells = [{row: 0, col: 4}, {row: 1, col: 0}, {row: 1, col: 2}, {row: 1, col: 4},
{row: 2, col: 1}, {row: 2, col: 3}, {row: 2, col: 5}, {row: 3, col: 0},
{row: 3, col: 2}, {row: 3, col: 4}, {row: 4, col: 1}, {row: 4, col: 2},
{row: 4, col: 3}, {row: 5, col: 0}, {row: 5, col: 3}, {row: 5, col: 5},
{row: 6, col: 1}, {row: 6, col: 3}, {row: 6, col: 4}, {row: 7, col: 0}];
for (var i = 0; i < cells.length; i++) {
var row = cells[i].row;
var col = cells[i].col;
// If row is less than forestMap length:
if (row < forestMap.length) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].length) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] === 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
"""
solutionsByLanguage.lua.dungeonsOfKithgard = """
-- Move towards the gem.
-- Don’t touch the spikes!
-- Type your code below and click Run when you’re done.
hero:moveRight()
hero:moveDown()
hero:moveRight()
"""
solutionsByLanguage.lua.peekABoom = """
-- Build traps on the path when the hero sees a munchkin!
while true do
local enemy = hero:findNearestEnemy()
if enemy then
-- Build a "fire-trap" at the Red X (41, 24)
hero:buildXY("fire-trap", 41, 24)
-- Add an else below to move back to the clearing
else
-- Move to the Wooden X (19, 19)
hero:moveXY(19, 19)
end
end
"""
solutionsByLanguage.lua.woodlandCleaver = """
-- Use your new "cleave" skill as often as you can.
hero:moveXY(23, 23)
while true do
local enemy = hero:findNearestEnemy()
if hero:isReady("cleave") then
-- Cleave the enemy!
hero:cleave(enemy)
else
-- Else (if cleave isn't ready), do your normal attack.
hero:attack(enemy)
end
end
"""
solutionsByLanguage.lua.aFineMint = """
-- Peons are trying to steal your coins!
-- Write a function to squash them before they can take your coins.
function pickUpCoin()
local coin = hero:findNearestItem()
if coin then
hero:moveXY(coin.pos.x, coin.pos.y)
end
end
-- Write the attackEnemy function below.
-- Find the nearest enemy and attack them if they exist!
function attackEnemy()
local enemy = hero:findNearestEnemy()
if enemy then
hero:attack(enemy)
end
end
while true do
attackEnemy() -- Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
end
"""
solutionsByLanguage.lua.libraryTactician = """
-- PI:NAME:<NAME>END_PI has been ambushed by ogres!
-- She is busy healing her soldiers, you should command them to fight!
-- The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
local archerTarget = nil
-- Soldiers spread out in a circle and defend.
function commandSoldier(soldier, soldierIndex, numSoldiers)
local angle = Math.PI * 2 * soldierIndex / numSoldiers
local defendPos = {x=41, y=40}
defendPos.x = defendPos.x + 10 * Math.cos(angle)
defendPos.y = defendPos.y + 10 * Math.sin(angle)
hero:command(soldier, "defend", defendPos)
end
-- Find the strongest target (most health)
-- This function returns something! When you call the function, you will get some value back.
function findStrongestTarget()
local mostHealth = 0
local bestTarget = nil
local enemies = hero:findEnemies()
-- Figure out which enemy has the most health, and set bestTarget to be that enemy.
for i, enemy in pairs(enemies) do
if enemy.health > mostHealth then
bestTarget = enemy
mostHealth = enemy.health
end
end
-- Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15 then
return bestTarget
else
return nil
end
end
-- If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
function commandArcher(archer)
local nearest = archer:findNearestEnemy()
if archerTarget then
hero:command(archer, "attack", archerTarget)
elseif nearest then
hero:command(archer, "attack", nearest)
end
end
while true do
-- If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0 then
-- Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
end
local soldiers = hero:findByType("soldier")
-- Create a variable containing your archers.
local archers = hero:findByType("archer")
for i, soldier in pairs(soldiers) do
commandSoldier(soldier, i, #soldiers)
end
-- use commandArcher() to command your archers
for i, archer in pairs(archers) do
commandArcher(archer)
end
end
"""
solutionsByLanguage.lua.snowdrops = """
-- We need to clear the forest of traps!
-- The scout prepared a map of the forest.
-- But be careful where you shoot! Don't start a fire.
-- Get the map of the forest.
local forestMap = hero:findNearest(hero:findFriends()).forestMap
-- The map is a 2D array where 0 is a trap.
-- The first sure shot.
hero:say("Row " + 0 + " Column " + 1 + " Fire!")
-- But for the next points, check before shooting.
-- There are an array of points to check.
local cells = {{row=0, col=4}, {row=1, col=0}, {row=1, col=2}, {row=1, col=4},
{row=2, col=1}, {row=2, col=3}, {row=2, col=5}, {row=3, col=0},
{row=3, col=2}, {row=3, col=4}, {row=4, col=1}, {row=4, col=2},
{row=4, col=3}, {row=5, col=0}, {row=5, col=3}, {row=5, col=5},
{row=6, col=1}, {row=6, col=3}, {row=6, col=4}, {row=7, col=0}}
for i in pairs(cells) do
local row = cells[i].row
local col = cells[i].col
-- If row is less than forestMap length:
if row < #forestMap then
-- If col is less than forestMap[row] length:
if col < #forestMap[row + 1] then
-- Now, we know the cell exists.
-- If it is 0, say where to shoot:
if forestMap[row + 1][col + 1] == 0 then
hero:say("Row " + row + " Column " + col + " Fire!")
end
end
end
end
"""
solutionsByLanguage.python.dungeonsOfKithgard = """
# Move towards the gem.
# Don’t touch the spikes!
# Type your code below and click Run when you’re done.
hero.moveRight()
hero.moveDown()
hero.moveRight()
"""
solutionsByLanguage.python.peekABoom = """
# Build traps on the path when the hero sees a munchkin!
while True:
enemy = hero.findNearestEnemy()
if enemy:
# Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24)
# Add an else below to move back to the clearing
else:
# Move to the Wooden X (19, 19)
hero.moveXY(19, 19)
"""
solutionsByLanguage.python.woodlandCleaver = """
# Use your new "cleave" skill as often as you can.
hero.moveXY(23, 23)
while True:
enemy = hero.findNearestEnemy()
if hero.isReady("cleave"):
# Cleave the enemy!
hero.cleave(enemy)
else:
# Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy)
"""
solutionsByLanguage.python.aFineMint = """
# Peons are trying to steal your coins!
# Write a function to squash them before they can take your coins.
def pickUpCoin():
coin = hero.findNearestItem()
if coin:
hero.moveXY(coin.pos.x, coin.pos.y)
# Write the attackEnemy function below.
# Find the nearest enemy and attack them if they exist!
def attackEnemy():
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
while True:
attackEnemy() # Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
"""
solutionsByLanguage.python.libraryTactician = """
# PI:NAME:<NAME>END_PI has been ambushed by ogres!
# She is busy healing her soldiers, you should command them to fight!
# The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
archerTarget = None
# Soldiers spread out in a circle and defend.
def commandSoldier(soldier, soldierIndex, numSoldiers):
angle = Math.PI * 2 * soldierIndex / numSoldiers
defendPos = {"x": 41, "y": 40}
defendPos.x += 10 * Math.cos(angle)
defendPos.y += 10 * Math.sin(angle)
hero.command(soldier, "defend", defendPos)
# Find the strongest target (most health)
# This function returns something! When you call the function, you will get some value back.
def findStrongestTarget():
mostHealth = 0
bestTarget = None
enemies = hero.findEnemies()
# Figure out which enemy has the most health, and set bestTarget to be that enemy.
for i in range(len(enemies)):
enemy = enemies[i]
if enemy.health > mostHealth:
bestTarget = enemy
mostHealth = enemy.health
# Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15:
return bestTarget
else:
return None
# If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
def commandArcher(archer):
nearest = archer.findNearestEnemy()
if archerTarget:
hero.command(archer, "attack", archerTarget)
elif nearest:
hero.command(archer, "attack", nearest)
while True:
# If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0:
# Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
soldiers = hero.findByType("soldier")
# Create a variable containing your archers.
archers = hero.findByType("archer")
for i in range(len(soldiers)):
soldier = soldiers[i]
commandSoldier(soldier, i, len(soldiers))
# use commandArcher() to command your archers
for i in range(len(archers)):
archer = archers[i]
commandArcher(archer)
"""
solutionsByLanguage.python.snowdrops = """
# We need to clear the forest of traps!
# The scout prepared a map of the forest.
# But be careful where you shoot! Don't start a fire.
# Get the map of the forest.
forestMap = hero.findNearest(hero.findFriends()).forestMap
# The map is a 2D array where 0 is a trap.
# The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!")
# But for the next points, check before shooting.
# There are an array of points to check.
cells = [{"row": 0, "col": 4}, {"row": 1, "col": 0}, {"row": 1, "col": 2}, {"row": 1, "col": 4},
{"row": 2, "col": 1}, {"row": 2, "col": 3}, {"row": 2, "col": 5}, {"row": 3, "col": 0},
{"row": 3, "col": 2}, {"row": 3, "col": 4}, {"row": 4, "col": 1}, {"row": 4, "col": 2},
{"row": 4, "col": 3}, {"row": 5, "col": 0}, {"row": 5, "col": 3}, {"row": 5, "col": 5},
{"row": 6, "col": 1}, {"row": 6, "col": 3}, {"row": 6, "col": 4}, {"row": 7, "col": 0}]
for i in range(len(cells)):
row = cells[i].row
col = cells[i].col
# If row is less than forestMap length:
if row < len(forestMap):
# If col is less than forestMap[row] length:
if col < len(forestMap[row]):
# Now, we know the cell exists.
# If it is 0, say where to shoot:
if forestMap[row][col] == 0:
hero.say("Row " + row + " Column " + col + " Fire!")
"""
solutionsByLanguage.coffeescript.dungeonsOfKithgard = """
# Move towards the gem.
# Don’t touch the spikes!
# Type your code below and click Run when you’re done.
hero.moveRight()
hero.moveDown()
hero.moveRight()
"""
solutionsByLanguage.coffeescript.peekABoom = """
# Build traps on the path when the hero sees a munchkin!
loop
enemy = hero.findNearestEnemy()
if enemy
# Build a "fire-trap" at the Red X (41, 24)
hero.buildXY "fire-trap", 41, 24
# Add an else below to move back to the clearing
else
# Move to the Wooden X (19, 19)
hero.moveXY 19, 19
"""
solutionsByLanguage.coffeescript.woodlandCleaver = """
# Use your new "cleave" skill as often as you can.
hero.moveXY 23, 23
loop
enemy = hero.findNearestEnemy()
if hero.isReady "cleave"
# Cleave the enemy!
hero.cleave enemy
else
# Else (if cleave isn't ready), do your normal attack.
hero.attack enemy
"""
solutionsByLanguage.coffeescript.aFineMint = """
# Peons are trying to steal your coins!
# Write a function to squash them before they can take your coins.
pickUpCoin = ->
coin = hero.findNearestItem()
if coin
hero.moveXY coin.pos.x, coin.pos.y
# Write the attackEnemy function below.
# Find the nearest enemy and attack them if they exist!
attackEnemy = ->
enemy = hero.findNearestEnemy()
if enemy
hero.attack enemy
loop
attackEnemy() # Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin()
"""
solutionsByLanguage.coffeescript.libraryTactician = """
# PI:NAME:<NAME>END_PI has been ambushed by ogres!
# She is busy healing her soldiers, you should command them to fight!
# The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
archerTarget = null
# Soldiers spread out in a circle and defend.
commandSoldier = (soldier, soldierIndex, numSoldiers) ->
angle = Math.PI * 2 * soldierIndex / numSoldiers
defendPos = {x: 41, y: 40}
defendPos.x += 10 * Math.cos angle
defendPos.y += 10 * Math.sin angle
hero.command soldier, "defend", defendPos
# Find the strongest target (most health)
# This function returns something! When you call the function, you will get some value back.
findStrongestTarget = ->
mostHealth = 0
bestTarget = null
enemies = hero.findEnemies()
# Figure out which enemy has the most health, and set bestTarget to be that enemy.
for enemy, i in enemies
if enemy.health > mostHealth
bestTarget = enemy
mostHealth = enemy.health
# Only focus archers' fire if there is a big ogre.
if bestTarget and bestTarget.health > 15
return bestTarget
else
return null
# If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
commandArcher = (archer) ->
nearest = archer.findNearestEnemy()
if archerTarget
hero.command archer, "attack", archerTarget
else if nearest
hero.command archer, "attack", nearest
loop
# If archerTarget is defeated or doesn't exist, find a new one.
if not archerTarget or archerTarget.health <= 0
# Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget()
soldiers = hero.findByType "soldier"
# Create a variable containing your archers.
archers = hero.findByType "archer"
for soldier, i in soldiers
commandSoldier soldier, i, soldiers.length
# use commandArcher() to command your archers
for archer, i in archers
commandArcher archer
"""
solutionsByLanguage.coffeescript.snowdrops = """
# We need to clear the forest of traps!
# The scout prepared a map of the forest.
# But be careful where you shoot! Don't start a fire.
# Get the map of the forest.
forestMap = hero.findNearest(hero.findFriends()).forestMap
# The map is a 2D array where 0 is a trap.
# The first sure shot.
hero.say "Row " + 0 + " Column " + 1 + " Fire!"
# But for the next points, check before shooting.
# There are an array of points to check.
cells = [{row: 0, col: 4}, {row: 1, col: 0}, {row: 1, col: 2}, {row: 1, col: 4},
{row: 2, col: 1}, {row: 2, col: 3}, {row: 2, col: 5}, {row: 3, col: 0},
{row: 3, col: 2}, {row: 3, col: 4}, {row: 4, col: 1}, {row: 4, col: 2},
{row: 4, col: 3}, {row: 5, col: 0}, {row: 5, col: 3}, {row: 5, col: 5},
{row: 6, col: 1}, {row: 6, col: 3}, {row: 6, col: 4}, {row: 7, col: 0}]
for i in [0...cells.length]
row = cells[i].row
col = cells[i].col
# If row is less than forestMap length:
if row < forestMap.length
# If col is less than forestMap[row] length:
if col < forestMap[row].length
# Now, we know the cell exists.
# If it is 0, say where to shoot:
if forestMap[row][col] is 0
hero.say "Row " + row + " Column " + col + " Fire!"
"""
solutionsByLanguage.java.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
public class AI {
public static void main(String[] args) {
hero.moveRight();
hero.moveDown();
hero.moveRight();
}
}
"""
solutionsByLanguage.java.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
public class AI {
public static void main(String[] args) {
while(true) {
var enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
}
}
"""
solutionsByLanguage.java.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
public class AI {
public static void main(String[] args) {
hero.moveXY(23, 23);
while(true) {
var enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
}
}
"""
solutionsByLanguage.java.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
public class AI {
public static void pickUpCoin() {
var coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
public static void attackEnemy() {
var enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
public static void main(String[] args) {
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
}
}
"""
solutionsByLanguage.java.libraryTactician = """
// PI:NAME:<NAME>END_PI has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
public class AI {
var archerTarget = null;
// Soldiers spread out in a circle and defend.
public static void commandSoldier(Object soldier, Object soldierIndex, Object numSoldiers) {
var angle = Math.PI * 2 * soldierIndex / numSoldiers;
var defendPos = {41, 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
public static Object findStrongestTarget() {
var mostHealth = 0;
var bestTarget = null;
var enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(int i=0; i < enemies.length; i++) {
var enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
public static void commandArcher(Object archer) {
var nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
public static void main(String[] args) {
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
var soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
var archers = hero.findByType("archer");
for(int i=0; i < soldiers.length; i++) {
var soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.length);
}
// use commandArcher() to command your archers
for(i=0; i < archers.length; i++) {
var archer = archers[i];
commandArcher(archer);
}
}
}
}
"""
solutionsByLanguage.java.snowdrops = """
int main() {
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
// Get the map of the forest.
auto forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
auto cells = {{0, 4}, {1, 0}, {1, 2}, {1, 4},
{2, 1}, {2, 3}, {2, 5}, {3, 0},
{3, 2}, {3, 4}, {4, 1}, {4, 2},
{4, 3}, {5, 0}, {5, 3}, {5, 5},
{6, 1}, {6, 3}, {6, 4}, {7, 0}};
for (int i = 0; i < cells.size(); i++) {
auto row = cells[i].x;
auto col = cells[i].y;
// If row is less than forestMap length:
if (row < forestMap.length) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].size()) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] == 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
return 0;
}
"""
solutionsByLanguage.cpp.dungeonsOfKithgard = """
// Move towards the gem.
// Don’t touch the spikes!
// Type your code below and click Run when you’re done.
int main() {
hero.moveRight();
hero.moveDown();
hero.moveRight();
return 0;
}
"""
solutionsByLanguage.cpp.peekABoom = """
// Build traps on the path when the hero sees a munchkin!
int main() {
while(true) {
auto enemy = hero.findNearestEnemy();
if(enemy) {
// Build a "fire-trap" at the Red X (41, 24)
hero.buildXY("fire-trap", 41, 24);
}
// Add an else below to move back to the clearing
else {
// Move to the Wooden X (19, 19)
hero.moveXY(19, 19);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.woodlandCleaver = """
// Use your new "cleave" skill as often as you can.
int main() {
hero.moveXY(23, 23);
while(true) {
auto enemy = hero.findNearestEnemy();
if(hero.isReady("cleave")) {
// Cleave the enemy!
hero.cleave(enemy);
} else {
// Else (if cleave isn't ready), do your normal attack.
hero.attack(enemy);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.aFineMint = """
// Peons are trying to steal your coins!
// Write a function to squash them before they can take your coins.
auto pickUpCoin() {
auto coin = hero.findNearestItem();
if(coin) {
hero.moveXY(coin.pos.x, coin.pos.y);
}
}
// Write the attackEnemy function below.
// Find the nearest enemy and attack them if they exist!
auto attackEnemy() {
auto enemy = hero.findNearestEnemy();
if(enemy) {
hero.attack(enemy);
}
}
int main() {
while(true) {
attackEnemy(); // Δ Uncomment this line after you write an attackEnemy function.
pickUpCoin();
}
return 0;
}
"""
solutionsByLanguage.cpp.libraryTactician = """
// PI:NAME:<NAME>END_PIushbaum has been ambushed by ogres!
// She is busy healing her soldiers, you should command them to fight!
// The ogres will send more troops if they think they can get to Hushbaum or your archers, so keep them inside the circle!
// Soldiers spread out in a circle and defend.
auto commandSoldier(auto soldier, auto soldierIndex, auto numSoldiers) {
auto angle = Math.PI * 2 * soldierIndex / numSoldiers;
auto defendPos = {41, 40};
defendPos.x += 10 * Math.cos(angle);
defendPos.y += 10 * Math.sin(angle);
hero.command(soldier, "defend", defendPos);
}
// Find the strongest target (most health)
// This function returns something! When you call the function, you will get some value back.
auto findStrongestTarget() {
auto mostHealth = 0;
auto bestTarget = null;
auto enemies = hero.findEnemies();
// Figure out which enemy has the most health, and set bestTarget to be that enemy.
for(int i=0; i < enemies.size(); i++) {
auto enemy = enemies[i];
if(enemy.health > mostHealth) {
bestTarget = enemy;
mostHealth = enemy.health;
}
}
// Only focus archers' fire if there is a big ogre.
if (bestTarget && bestTarget.health > 15) {
return bestTarget;
} else {
return null;
}
}
// If the strongestTarget has more than 15 health, attack that target. Otherwise, attack the nearest target.
auto commandArcher(auto archer) {
auto nearest = archer.findNearestEnemy();
if(archerTarget) {
hero.command(archer, "attack", archerTarget);
} else if(nearest) {
hero.command(archer, "attack", nearest);
}
}
auto archerTarget = null;
int main() {
while(true) {
// If archerTarget is defeated or doesn't exist, find a new one.
if(!archerTarget || archerTarget.health <= 0) {
// Set archerTarget to be the target that is returned by findStrongestTarget()
archerTarget = findStrongestTarget();
}
auto soldiers = hero.findByType("soldier");
// Create a variable containing your archers.
auto archers = hero.findByType("archer");
for(int i=0; i < soldiers.size(); i++) {
auto soldier = soldiers[i];
commandSoldier(soldier, i, soldiers.size());
}
// use commandArcher() to command your archers
for(i=0; i < archers.size(); i++) {
auto archer = archers[i];
commandArcher(archer);
}
}
return 0;
}
"""
solutionsByLanguage.cpp.snowdrops = """
// We need to clear the forest of traps!
// The scout prepared a map of the forest.
// But be careful where you shoot! Don't start a fire.
int main() {
// Get the map of the forest.
auto forestMap = hero.findNearest(hero.findFriends()).forestMap;
// The map is a 2D array where 0 is a trap.
// The first sure shot.
hero.say("Row " + 0 + " Column " + 1 + " Fire!");
// But for the next points, check before shooting.
// There are an array of points to check.
auto cells = {{0, 4}, {1, 0}, {1, 2}, {1, 4},
{2, 1}, {2, 3}, {2, 5}, {3, 0},
{3, 2}, {3, 4}, {4, 1}, {4, 2},
{4, 3}, {5, 0}, {5, 3}, {5, 5},
{6, 1}, {6, 3}, {6, 4}, {7, 0}};
for (int i = 0; i < cells.size(); i++) {
auto row = cells[i].x;
auto col = cells[i].y;
// If row is less than forestMap length:
if (row < forestMap.size()) {
// If col is less than forestMap[row] length:
if (col < forestMap[row].size()) {
// Now, we know the cell exists.
// If it is 0, say where to shoot:
if (forestMap[row][col] == 0) {
hero.say("Row " + row + " Column " + col + " Fire!");
}
}
}
}
return 0;
}
"""
levenshteinDistance = (str1, str2) ->
# Simple edit distance measurement between two strings
m = str1.length
n = str2.length
d = []
return n unless m
return m unless n
d[i] = [i] for i in [0..m]
d[0][j] = j for j in [1..n]
for i in [1..m]
for j in [1..n]
if str1[i-1] is str2[j-1]
d[i][j] = d[i-1][j-1]
else
d[i][j] = Math.min(
d[i-1][j]
d[i][j-1]
d[i-1][j-1]
) + 1
d[m][n]
describe 'Aether / code transpilation utility library', ->
aetherUtils = require '../../../app/lib/aether_utils'
describe 'translateJS(jsCode, "cpp", fullCode)', ->
describe 'do not add int main if fullCode set false', ->
it 'if there is no pattern needing translation', ->
expect(aetherUtils.translateJS('hero.moveRight()', 'cpp', false)).toBe('hero.moveRight()')
it 'if there is var x or var y', ->
expect(aetherUtils.translateJS('var x = 2;\nvar y = 3', 'cpp', false)).toBe('float x = 2;\nfloat y = 3')
it 'if there is ===/!==', ->
expect(aetherUtils.translateJS('if (a === 2 && b !== 1)', 'cpp', false)).toBe('if (a == 2 && b != 1)')
it 'if there is other var', ->
expect(aetherUtils.translateJS('var enemy = hero...', 'cpp', false)).toBe('auto enemy = hero...')
it 'if there is a function definition', ->
expect(aetherUtils.translateJS('function a() {}\n', 'cpp', false)).toBe('auto a() {}\n')
describe 'add int main if fullCode set true', ->
it 'if there is no pattern needing translation', ->
expect(aetherUtils.translateJS('hero.moveRight();'), 'cpp').toBe('int main() {\n hero.moveRight();\n return 0;\n}')
it 'if there is var x or var y', ->
expect(aetherUtils.translateJS('var x = 2;\nvar y = 3;', 'cpp')).toBe('int main() {\n float x = 2;\n float y = 3;\n return 0;\n}')
it 'if there is ===/!==', ->
expect(aetherUtils.translateJS('while (a === 2 && b !== 1)', 'cpp')).toBe('int main() {\n while (a == 2 && b != 1)\n return 0;\n}')
it 'if there is other var', ->
expect(aetherUtils.translateJS('var enemy = hero...', 'cpp')).toBe('int main() {\n auto enemy = hero...\n return 0;\n}')
it 'if there is a function definition', ->
expect(aetherUtils.translateJS('function a() {}\n', 'cpp')).toBe('auto a() {}\n\nint main() {\n \n return 0;\n}')
it 'if there is a function definition with parameter', ->
expect(aetherUtils.translateJS('function a(b) {}\n', 'cpp')).toBe('auto a(auto b) {}\n\nint main() {\n \n return 0;\n}')
it 'if there is a function definition with parameters', ->
expect(aetherUtils.translateJS('function a(b, c) {}\na();', 'cpp')).toBe('auto a(auto b, auto c) {}\n\nint main() {\n a();\n return 0;\n}')
describe 'if there are start comments', ->
it 'if there is no code', ->
expect(aetherUtils.translateJS('//abc\n//def\n\n', 'cpp')).toBe('//abc\n//def\n\nint main() {\n \n return 0;\n}')
it 'if there is code without function definition', ->
expect(aetherUtils.translateJS('//abc\n\nhero.moveRight()', 'cpp')).toBe('//abc\n\nint main() {\n hero.moveRight()\n return 0;\n}')
it 'if there is code with function definition', ->
expect(aetherUtils.translateJS('//abc\n\nfunction a(b, c) {}\nhero.moveRight()', 'cpp')).toBe('//abc\n\nauto a(auto b, auto c) {}\n\nint main() {\n hero.moveRight()\n return 0;\n}')
describe 'translateJS can handle full solutions', ->
unsupported = [
# Permanent (must write these solutions manually)
['lua', 'snowdrops'] # manual rewriting needed for off-by-one error with 1-indexed arrays for row/col in the map
['cpp', 'snowdrops'] # row/col literals need to be manually rewritten to x/y for our {x, y} Vector hack
['java', 'snowdrops'] # row/col literals need to be manually rewritten to [row, col] arrays, also indexed with [0] and [1]
# Temporary (should fix the code generation to be smarter)
['java', 'libraryTactician'] # Need to auto-detect self-defined function return type
['java', 'aFineMint'] # Need to not strip out each hoisted function's start comments
['cpp', 'aFineMint'] # Need to not strip out each hoisted function's start comments
]
targetLanguage = ''
targetLevel = ''
for language, solutions of solutionsByLanguage when language isnt 'javascript'
do (language, solutions) ->
describe 'in ' + language, ->
for level, code of solutions
do (level, code) ->
if _.find(unsupported, ([lang, lev]) -> lang is language and lev is level)
f = xit
else if not targetLevel and not targetLanguage
f = it
else if (targetLevel and level is targetLevel) or (targetLanguage and language is targetLanguage)
f = fit
else
f = it
f 'properly translates ' + level, ->
js = solutionsByLanguage.javascript[level]
translated = aetherUtils.translateJS js, language, true
editDistance = levenshteinDistance translated, code
expect('\n' + translated).toEqual('\n' + code)
expect(editDistance).toEqual(0)
|
[
{
"context": "- - - - - - - - - - - - - - - #\n# Copyright © 2015 Denis Luchkin-Zhou #\n# See L",
"end": 277,
"score": 0.9998693466186523,
"start": 259,
"tag": "NAME",
"value": "Denis Luchkin-Zhou"
}
] | gulp/client-markup.coffee | jluchiji/tranzit | 0 | # --------------------------------------------------------------------------- #
# wyvernzora.ninja build script. #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Copyright © 2015 Denis Luchkin-Zhou #
# See LICENSE.md for terms of distribution. #
# --------------------------------------------------------------------------- #
module.exports = (gulp, config) ->
gulp.task 'client:html', ->
gulp.src ['app/**.html'], base: './'
.pipe gulp.dest config.paths.dest
gulp.task 'client:jade', ->
_ = require 'underscore'
path = require 'path'
jade = require 'gulp-jade'
# Backup the old scripts array
config._scripts ?= config.scripts
# Inject bower files depending on target
if not config.concat
bower = _.map config.bower.scripts, (i) ->
path.join 'lib', i
config.scripts = bower.concat config._scripts
else
config.scripts = ['lib/bower.js'].concat config._scripts
# Backup the old stylesheets array
config._stylesheets ?= config.stylesheets
# Inject bower files depending on target
if not config.concat
bower = _.map config.bower.stylesheets, (i) ->
path.join 'lib', i
config.stylesheets = bower.concat config._stylesheets
else
config.stylesheets = ['lib/bower.css'].concat config._stylesheets
# Process markup
gulp.src ['app/**/*.jade', '!**/*.part.jade'], base: './'
.pipe jade locals: config
.pipe gulp.dest config.paths.dest
| 66585 | # --------------------------------------------------------------------------- #
# wyvernzora.ninja build script. #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Copyright © 2015 <NAME> #
# See LICENSE.md for terms of distribution. #
# --------------------------------------------------------------------------- #
module.exports = (gulp, config) ->
gulp.task 'client:html', ->
gulp.src ['app/**.html'], base: './'
.pipe gulp.dest config.paths.dest
gulp.task 'client:jade', ->
_ = require 'underscore'
path = require 'path'
jade = require 'gulp-jade'
# Backup the old scripts array
config._scripts ?= config.scripts
# Inject bower files depending on target
if not config.concat
bower = _.map config.bower.scripts, (i) ->
path.join 'lib', i
config.scripts = bower.concat config._scripts
else
config.scripts = ['lib/bower.js'].concat config._scripts
# Backup the old stylesheets array
config._stylesheets ?= config.stylesheets
# Inject bower files depending on target
if not config.concat
bower = _.map config.bower.stylesheets, (i) ->
path.join 'lib', i
config.stylesheets = bower.concat config._stylesheets
else
config.stylesheets = ['lib/bower.css'].concat config._stylesheets
# Process markup
gulp.src ['app/**/*.jade', '!**/*.part.jade'], base: './'
.pipe jade locals: config
.pipe gulp.dest config.paths.dest
| true | # --------------------------------------------------------------------------- #
# wyvernzora.ninja build script. #
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
# Copyright © 2015 PI:NAME:<NAME>END_PI #
# See LICENSE.md for terms of distribution. #
# --------------------------------------------------------------------------- #
module.exports = (gulp, config) ->
gulp.task 'client:html', ->
gulp.src ['app/**.html'], base: './'
.pipe gulp.dest config.paths.dest
gulp.task 'client:jade', ->
_ = require 'underscore'
path = require 'path'
jade = require 'gulp-jade'
# Backup the old scripts array
config._scripts ?= config.scripts
# Inject bower files depending on target
if not config.concat
bower = _.map config.bower.scripts, (i) ->
path.join 'lib', i
config.scripts = bower.concat config._scripts
else
config.scripts = ['lib/bower.js'].concat config._scripts
# Backup the old stylesheets array
config._stylesheets ?= config.stylesheets
# Inject bower files depending on target
if not config.concat
bower = _.map config.bower.stylesheets, (i) ->
path.join 'lib', i
config.stylesheets = bower.concat config._stylesheets
else
config.stylesheets = ['lib/bower.css'].concat config._stylesheets
# Process markup
gulp.src ['app/**/*.jade', '!**/*.part.jade'], base: './'
.pipe jade locals: config
.pipe gulp.dest config.paths.dest
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.986633837223053,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/pummel/test-tls-session-timeout.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# This test consists of three TLS requests --
# * The first one should result in a new connection because we don't have
# a valid session ticket.
# * The second one should result in connection resumption because we used
# the session ticket we saved from the first connection.
# * The third one should result in a new connection because the ticket
# that we used has expired by now.
doTest = ->
assert = require("assert")
tls = require("tls")
fs = require("fs")
join = require("path").join
spawn = require("child_process").spawn
SESSION_TIMEOUT = 1
keyFile = join(common.fixturesDir, "agent.key")
certFile = join(common.fixturesDir, "agent.crt")
key = fs.readFileSync(keyFile)
cert = fs.readFileSync(certFile)
options =
key: key
cert: cert
ca: [cert]
sessionTimeout: SESSION_TIMEOUT
# We need to store a sample session ticket in the fixtures directory because
# `s_client` behaves incorrectly if we do not pass in both the `-sess_in`
# and the `-sess_out` flags, and the `-sess_in` argument must point to a
# file containing a proper serialization of a session ticket.
# To avoid a source control diff, we copy the ticket to a temporary file.
sessionFileName = (->
ticketFileName = "tls-session-ticket.txt"
fixturesPath = join(common.fixturesDir, ticketFileName)
tmpPath = join(common.tmpDir, ticketFileName)
fs.writeFileSync tmpPath, fs.readFileSync(fixturesPath)
tmpPath
())
# Expects a callback -- cb(connectionType : enum ['New'|'Reused'])
Client = (cb) ->
flags = [
"s_client"
"-connect"
"localhost:" + common.PORT
"-sess_in"
sessionFileName
"-sess_out"
sessionFileName
]
client = spawn(common.opensslCli, flags,
stdio: [
"ignore"
"pipe"
"ignore"
]
)
clientOutput = ""
client.stdout.on "data", (data) ->
clientOutput += data.toString()
return
client.on "exit", (code) ->
connectionType = undefined
grepConnectionType = (line) ->
matches = line.match(/(New|Reused), /)
if matches
connectionType = matches[1]
true
lines = clientOutput.split("\n")
throw new Error("unexpected output from openssl client") unless lines.some(grepConnectionType)
cb connectionType
return
return
server = tls.createServer(options, (cleartext) ->
cleartext.on "error", (er) ->
throw er if er.code isnt "ECONNRESET"
return
cleartext.end()
return
)
server.listen common.PORT, ->
Client (connectionType) ->
assert connectionType is "New"
Client (connectionType) ->
assert connectionType is "Reused"
setTimeout (->
Client (connectionType) ->
assert connectionType is "New"
server.close()
return
return
), (SESSION_TIMEOUT + 1) * 1000
return
return
return
return
common = require("../common")
unless common.opensslCli
console.error "Skipping because node compiled without OpenSSL CLI."
process.exit 0
doTest()
| 21611 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# This test consists of three TLS requests --
# * The first one should result in a new connection because we don't have
# a valid session ticket.
# * The second one should result in connection resumption because we used
# the session ticket we saved from the first connection.
# * The third one should result in a new connection because the ticket
# that we used has expired by now.
doTest = ->
assert = require("assert")
tls = require("tls")
fs = require("fs")
join = require("path").join
spawn = require("child_process").spawn
SESSION_TIMEOUT = 1
keyFile = join(common.fixturesDir, "agent.key")
certFile = join(common.fixturesDir, "agent.crt")
key = fs.readFileSync(keyFile)
cert = fs.readFileSync(certFile)
options =
key: key
cert: cert
ca: [cert]
sessionTimeout: SESSION_TIMEOUT
# We need to store a sample session ticket in the fixtures directory because
# `s_client` behaves incorrectly if we do not pass in both the `-sess_in`
# and the `-sess_out` flags, and the `-sess_in` argument must point to a
# file containing a proper serialization of a session ticket.
# To avoid a source control diff, we copy the ticket to a temporary file.
sessionFileName = (->
ticketFileName = "tls-session-ticket.txt"
fixturesPath = join(common.fixturesDir, ticketFileName)
tmpPath = join(common.tmpDir, ticketFileName)
fs.writeFileSync tmpPath, fs.readFileSync(fixturesPath)
tmpPath
())
# Expects a callback -- cb(connectionType : enum ['New'|'Reused'])
Client = (cb) ->
flags = [
"s_client"
"-connect"
"localhost:" + common.PORT
"-sess_in"
sessionFileName
"-sess_out"
sessionFileName
]
client = spawn(common.opensslCli, flags,
stdio: [
"ignore"
"pipe"
"ignore"
]
)
clientOutput = ""
client.stdout.on "data", (data) ->
clientOutput += data.toString()
return
client.on "exit", (code) ->
connectionType = undefined
grepConnectionType = (line) ->
matches = line.match(/(New|Reused), /)
if matches
connectionType = matches[1]
true
lines = clientOutput.split("\n")
throw new Error("unexpected output from openssl client") unless lines.some(grepConnectionType)
cb connectionType
return
return
server = tls.createServer(options, (cleartext) ->
cleartext.on "error", (er) ->
throw er if er.code isnt "ECONNRESET"
return
cleartext.end()
return
)
server.listen common.PORT, ->
Client (connectionType) ->
assert connectionType is "New"
Client (connectionType) ->
assert connectionType is "Reused"
setTimeout (->
Client (connectionType) ->
assert connectionType is "New"
server.close()
return
return
), (SESSION_TIMEOUT + 1) * 1000
return
return
return
return
common = require("../common")
unless common.opensslCli
console.error "Skipping because node compiled without OpenSSL CLI."
process.exit 0
doTest()
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# This test consists of three TLS requests --
# * The first one should result in a new connection because we don't have
# a valid session ticket.
# * The second one should result in connection resumption because we used
# the session ticket we saved from the first connection.
# * The third one should result in a new connection because the ticket
# that we used has expired by now.
doTest = ->
assert = require("assert")
tls = require("tls")
fs = require("fs")
join = require("path").join
spawn = require("child_process").spawn
SESSION_TIMEOUT = 1
keyFile = join(common.fixturesDir, "agent.key")
certFile = join(common.fixturesDir, "agent.crt")
key = fs.readFileSync(keyFile)
cert = fs.readFileSync(certFile)
options =
key: key
cert: cert
ca: [cert]
sessionTimeout: SESSION_TIMEOUT
# We need to store a sample session ticket in the fixtures directory because
# `s_client` behaves incorrectly if we do not pass in both the `-sess_in`
# and the `-sess_out` flags, and the `-sess_in` argument must point to a
# file containing a proper serialization of a session ticket.
# To avoid a source control diff, we copy the ticket to a temporary file.
sessionFileName = (->
ticketFileName = "tls-session-ticket.txt"
fixturesPath = join(common.fixturesDir, ticketFileName)
tmpPath = join(common.tmpDir, ticketFileName)
fs.writeFileSync tmpPath, fs.readFileSync(fixturesPath)
tmpPath
())
# Expects a callback -- cb(connectionType : enum ['New'|'Reused'])
Client = (cb) ->
flags = [
"s_client"
"-connect"
"localhost:" + common.PORT
"-sess_in"
sessionFileName
"-sess_out"
sessionFileName
]
client = spawn(common.opensslCli, flags,
stdio: [
"ignore"
"pipe"
"ignore"
]
)
clientOutput = ""
client.stdout.on "data", (data) ->
clientOutput += data.toString()
return
client.on "exit", (code) ->
connectionType = undefined
grepConnectionType = (line) ->
matches = line.match(/(New|Reused), /)
if matches
connectionType = matches[1]
true
lines = clientOutput.split("\n")
throw new Error("unexpected output from openssl client") unless lines.some(grepConnectionType)
cb connectionType
return
return
server = tls.createServer(options, (cleartext) ->
cleartext.on "error", (er) ->
throw er if er.code isnt "ECONNRESET"
return
cleartext.end()
return
)
server.listen common.PORT, ->
Client (connectionType) ->
assert connectionType is "New"
Client (connectionType) ->
assert connectionType is "Reused"
setTimeout (->
Client (connectionType) ->
assert connectionType is "New"
server.close()
return
return
), (SESSION_TIMEOUT + 1) * 1000
return
return
return
return
common = require("../common")
unless common.opensslCli
console.error "Skipping because node compiled without OpenSSL CLI."
process.exit 0
doTest()
|
[
{
"context": " tokens: [\n token: \"irrelevant\"\n starts: 35\n ",
"end": 2630,
"score": 0.46093976497650146,
"start": 2622,
"tag": "KEY",
"value": "relevant"
},
{
"context": " tokens: [\n to... | src/coffee/expression/parse/unary.spec.coffee | jameswilddev/influx7 | 1 | describe "expression", -> describe "parse", -> describe "unary", ->
rewire = require "rewire"
describe "imports", ->
expressionParseUnary = rewire "./unary"
it "expressionParse", -> (expect expressionParseUnary.__get__ "expressionParse").toBe require "./../parse"
it "expressionParseOperatorTokens", -> (expect expressionParseUnary.__get__ "expressionParseOperatorTokens").toBe require "./operatorTokens"
describe "on calling", ->
expressionParseUnary = rewire "./unary"
operators = ["testOperatorB", "testOperatorC"]
expressionParseOperatorTokens =
testOperatorA: ["testOperatorSymbolAA", "testOperatorSymbolAB", "testOperatorSymbolAC", "testOperatorSymbolAD"]
testOperatorB: ["testOperatorSymbolBA", "testOperatorSymbolBB"]
testOperatorC: ["testOperatorSymbolCA", "testOperatorSymbolCB", "testOperatorSymbolCC"]
testOperatorD: ["testOperatorSymbolDA", "testOperatorSymbolDB"]
run = (config) ->
describe config.description, ->
result = inputCopy = operatorsCopy = expressionParseOperatorTokensCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.tokens
operatorsCopy = JSON.parse JSON.stringify operators
expressionParseOperatorTokensCopy = JSON.parse JSON.stringify expressionParseOperatorTokens
expressionParseUnary.__set__ "expressionParse", (input) ->
if config.expectTokens
(expect input).toEqual config.expectTokens
"recursed expression"
else
fail "unexpected call to expressionParse"
expressionParseUnary.__set__ "expressionParseOperatorTokens", expressionParseOperatorTokensCopy
result = expressionParseUnary inputCopy, operatorsCopy
it "returns the expected result", -> (expect result).toEqual config.output
it "does not modify the input tokens", -> (expect inputCopy).toEqual config.tokens
it "does not modify the input operators", -> (expect operatorsCopy).toEqual operators
it "does not modify expressionParseOperatorTokens", -> (expect expressionParseOperatorTokensCopy).toEqual expressionParseOperatorTokens
describe "one token", ->
run
description: "which is not a symbol or keyword match"
tokens: [
token: "irrelevant"
starts: 35
ends: 74
]
output: null
run
description: "which is an operator match on this level"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
]
output: null
run
description: "which is an operator match on another level"
tokens: [
token: "testOperatorSymbolAC"
starts: 35
ends: 74
]
output: null
describe "two tokens", ->
run
description: "which are not operator matches"
tokens: [
token: "irrelevantA"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
]
output: null
run
description: "an operator match on this level followed by another token"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
]
expectTokens: [
token: "irrelevantB"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "an operator match on this level followed by another token which is also an operator match"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
,
token: "testOperatorSymbolCA"
starts: 87
ends: 96
]
expectTokens: [
token: "testOperatorSymbolCA"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "an operator match on this level followed by the same token"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
,
token: "testOperatorSymbolBB"
starts: 87
ends: 96
]
expectTokens: [
token: "testOperatorSymbolBB"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "one token which is an operator match on another level followed by another token"
tokens: [
token: "testOperatorSymbolAC"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
]
output: null
run
description: "an irrelevant token followed by an operator match on this level"
tokens: [
token: "irrelevantB"
starts: 35
ends: 74
,
token: "testOperatorSymbolBB"
starts: 87
ends: 96
]
output: null
run
description: "an irrelevant token followed by one token which is an operator match on another level"
tokens: [
token: "irrelevantB"
starts: 35
ends: 74
,
token: "testOperatorSymbolAC"
starts: 87
ends: 96
]
output: null
describe "more than two tokens", ->
run
description: "which are not operator matches"
tokens: [
token: "irrelevantA"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
,
token: "irrelevantC"
starts: 122
ends: 146
,
token: "irrelevantD"
starts: 166
ends: 180
]
output: null
run
description: "when the first is an operator match on this level"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
,
token: "irrelevantC"
starts: 122
ends: 146
,
token: "irrelevantD"
starts: 166
ends: 180
]
expectTokens: [
token: "irrelevantB"
starts: 87
ends: 96
,
token: "irrelevantC"
starts: 122
ends: 146
,
token: "irrelevantD"
starts: 166
ends: 180
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "when multiple are an operator match on this level"
tokens: [
token: "testOperatorSymbolCC"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
,
token: "testOperatorSymbolBA"
starts: 122
ends: 146
,
token: "irrelevantD"
starts: 166
ends: 180
]
expectTokens: [
token: "irrelevantB"
starts: 87
ends: 96
,
token: "testOperatorSymbolBA"
starts: 122
ends: 146
,
token: "irrelevantD"
starts: 166
ends: 180
]
output:
call: "testOperatorC"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "when the first is an operator match not on this level"
tokens: [
token: "testOperatorSymbolDB"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
,
token: "irrelevantC"
starts: 122
ends: 146
,
token: "irrelevantD"
starts: 166
ends: 180
]
output: null | 67324 | describe "expression", -> describe "parse", -> describe "unary", ->
rewire = require "rewire"
describe "imports", ->
expressionParseUnary = rewire "./unary"
it "expressionParse", -> (expect expressionParseUnary.__get__ "expressionParse").toBe require "./../parse"
it "expressionParseOperatorTokens", -> (expect expressionParseUnary.__get__ "expressionParseOperatorTokens").toBe require "./operatorTokens"
describe "on calling", ->
expressionParseUnary = rewire "./unary"
operators = ["testOperatorB", "testOperatorC"]
expressionParseOperatorTokens =
testOperatorA: ["testOperatorSymbolAA", "testOperatorSymbolAB", "testOperatorSymbolAC", "testOperatorSymbolAD"]
testOperatorB: ["testOperatorSymbolBA", "testOperatorSymbolBB"]
testOperatorC: ["testOperatorSymbolCA", "testOperatorSymbolCB", "testOperatorSymbolCC"]
testOperatorD: ["testOperatorSymbolDA", "testOperatorSymbolDB"]
run = (config) ->
describe config.description, ->
result = inputCopy = operatorsCopy = expressionParseOperatorTokensCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.tokens
operatorsCopy = JSON.parse JSON.stringify operators
expressionParseOperatorTokensCopy = JSON.parse JSON.stringify expressionParseOperatorTokens
expressionParseUnary.__set__ "expressionParse", (input) ->
if config.expectTokens
(expect input).toEqual config.expectTokens
"recursed expression"
else
fail "unexpected call to expressionParse"
expressionParseUnary.__set__ "expressionParseOperatorTokens", expressionParseOperatorTokensCopy
result = expressionParseUnary inputCopy, operatorsCopy
it "returns the expected result", -> (expect result).toEqual config.output
it "does not modify the input tokens", -> (expect inputCopy).toEqual config.tokens
it "does not modify the input operators", -> (expect operatorsCopy).toEqual operators
it "does not modify expressionParseOperatorTokens", -> (expect expressionParseOperatorTokensCopy).toEqual expressionParseOperatorTokens
describe "one token", ->
run
description: "which is not a symbol or keyword match"
tokens: [
token: "ir<KEY>"
starts: 35
ends: 74
]
output: null
run
description: "which is an operator match on this level"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
]
output: null
run
description: "which is an operator match on another level"
tokens: [
token: "testOperatorSymbolAC"
starts: 35
ends: 74
]
output: null
describe "two tokens", ->
run
description: "which are not operator matches"
tokens: [
token: "irrelevantA"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
]
output: null
run
description: "an operator match on this level followed by another token"
tokens: [
token: "<KEY>OperatorSymbolBB"
starts: 35
ends: 74
,
token: "<KEY>B"
starts: 87
ends: 96
]
expectTokens: [
token: "irrelevantB"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "an operator match on this level followed by another token which is also an operator match"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
,
token: "testOperatorSymbolCA"
starts: 87
ends: 96
]
expectTokens: [
token: "<KEY>OperatorSymbolCA"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "an operator match on this level followed by the same token"
tokens: [
token: "<KEY>OperatorSymbolBB"
starts: 35
ends: 74
,
token: "testOperatorSymbolBB"
starts: 87
ends: 96
]
expectTokens: [
token: "testOperatorSymbolBB"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "one token which is an operator match on another level followed by another token"
tokens: [
token: "testOperatorSymbolAC"
starts: 35
ends: 74
,
token: "ir<KEY>B"
starts: 87
ends: 96
]
output: null
run
description: "an irrelevant token followed by an operator match on this level"
tokens: [
token: "irrelevantB"
starts: 35
ends: 74
,
token: "<KEY>OperatorSymbolBB"
starts: 87
ends: 96
]
output: null
run
description: "an irrelevant token followed by one token which is an operator match on another level"
tokens: [
token: "ir<KEY> <KEY>"
starts: 35
ends: 74
,
token: "testOperatorSymbolAC"
starts: 87
ends: 96
]
output: null
describe "more than two tokens", ->
run
description: "which are not operator matches"
tokens: [
token: "ir<KEY>A"
starts: 35
ends: 74
,
token: "ir<KEY> <KEY>"
starts: 87
ends: 96
,
token: "ir<KEY>C"
starts: 122
ends: 146
,
token: "ir<PASSWORD>"
starts: 166
ends: 180
]
output: null
run
description: "when the first is an operator match on this level"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
,
token: "<KEY> <KEY> <KEY>"
starts: 122
ends: 146
,
token: "<KEY> <PASSWORD>"
starts: 166
ends: 180
]
expectTokens: [
token: "irrelevantB"
starts: 87
ends: 96
,
token: "ir<KEY>C"
starts: 122
ends: 146
,
token: "<KEY>"
starts: 166
ends: 180
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "when multiple are an operator match on this level"
tokens: [
token: "testOperatorSymbolCC"
starts: 35
ends: 74
,
token: "<KEY>"
starts: 87
ends: 96
,
token: "<KEY>OperatorSymbol<KEY>"
starts: 122
ends: 146
,
token: "<KEY>"
starts: 166
ends: 180
]
expectTokens: [
token: "<KEY>"
starts: 87
ends: 96
,
token: "testOperatorSymbolBA"
starts: 122
ends: 146
,
token: "<KEY>"
starts: 166
ends: 180
]
output:
call: "testOperatorC"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "when the first is an operator match not on this level"
tokens: [
token: "<KEY>Operator<KEY>DB"
starts: 35
ends: 74
,
token: "<KEY>"
starts: 87
ends: 96
,
token: "<KEY>"
starts: 122
ends: 146
,
token: "<KEY>"
starts: 166
ends: 180
]
output: null | true | describe "expression", -> describe "parse", -> describe "unary", ->
rewire = require "rewire"
describe "imports", ->
expressionParseUnary = rewire "./unary"
it "expressionParse", -> (expect expressionParseUnary.__get__ "expressionParse").toBe require "./../parse"
it "expressionParseOperatorTokens", -> (expect expressionParseUnary.__get__ "expressionParseOperatorTokens").toBe require "./operatorTokens"
describe "on calling", ->
expressionParseUnary = rewire "./unary"
operators = ["testOperatorB", "testOperatorC"]
expressionParseOperatorTokens =
testOperatorA: ["testOperatorSymbolAA", "testOperatorSymbolAB", "testOperatorSymbolAC", "testOperatorSymbolAD"]
testOperatorB: ["testOperatorSymbolBA", "testOperatorSymbolBB"]
testOperatorC: ["testOperatorSymbolCA", "testOperatorSymbolCB", "testOperatorSymbolCC"]
testOperatorD: ["testOperatorSymbolDA", "testOperatorSymbolDB"]
run = (config) ->
describe config.description, ->
result = inputCopy = operatorsCopy = expressionParseOperatorTokensCopy = undefined
beforeEach ->
inputCopy = JSON.parse JSON.stringify config.tokens
operatorsCopy = JSON.parse JSON.stringify operators
expressionParseOperatorTokensCopy = JSON.parse JSON.stringify expressionParseOperatorTokens
expressionParseUnary.__set__ "expressionParse", (input) ->
if config.expectTokens
(expect input).toEqual config.expectTokens
"recursed expression"
else
fail "unexpected call to expressionParse"
expressionParseUnary.__set__ "expressionParseOperatorTokens", expressionParseOperatorTokensCopy
result = expressionParseUnary inputCopy, operatorsCopy
it "returns the expected result", -> (expect result).toEqual config.output
it "does not modify the input tokens", -> (expect inputCopy).toEqual config.tokens
it "does not modify the input operators", -> (expect operatorsCopy).toEqual operators
it "does not modify expressionParseOperatorTokens", -> (expect expressionParseOperatorTokensCopy).toEqual expressionParseOperatorTokens
describe "one token", ->
run
description: "which is not a symbol or keyword match"
tokens: [
token: "irPI:KEY:<KEY>END_PI"
starts: 35
ends: 74
]
output: null
run
description: "which is an operator match on this level"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
]
output: null
run
description: "which is an operator match on another level"
tokens: [
token: "testOperatorSymbolAC"
starts: 35
ends: 74
]
output: null
describe "two tokens", ->
run
description: "which are not operator matches"
tokens: [
token: "irrelevantA"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
]
output: null
run
description: "an operator match on this level followed by another token"
tokens: [
token: "PI:KEY:<KEY>END_PIOperatorSymbolBB"
starts: 35
ends: 74
,
token: "PI:KEY:<KEY>END_PIB"
starts: 87
ends: 96
]
expectTokens: [
token: "irrelevantB"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "an operator match on this level followed by another token which is also an operator match"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
,
token: "testOperatorSymbolCA"
starts: 87
ends: 96
]
expectTokens: [
token: "PI:KEY:<KEY>END_PIOperatorSymbolCA"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "an operator match on this level followed by the same token"
tokens: [
token: "PI:KEY:<KEY>END_PIOperatorSymbolBB"
starts: 35
ends: 74
,
token: "testOperatorSymbolBB"
starts: 87
ends: 96
]
expectTokens: [
token: "testOperatorSymbolBB"
starts: 87
ends: 96
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "one token which is an operator match on another level followed by another token"
tokens: [
token: "testOperatorSymbolAC"
starts: 35
ends: 74
,
token: "irPI:PASSWORD:<KEY>END_PIB"
starts: 87
ends: 96
]
output: null
run
description: "an irrelevant token followed by an operator match on this level"
tokens: [
token: "irrelevantB"
starts: 35
ends: 74
,
token: "PI:KEY:<KEY>END_PIOperatorSymbolBB"
starts: 87
ends: 96
]
output: null
run
description: "an irrelevant token followed by one token which is an operator match on another level"
tokens: [
token: "irPI:PASSWORD:<KEY>END_PI PI:KEY:<KEY>END_PI"
starts: 35
ends: 74
,
token: "testOperatorSymbolAC"
starts: 87
ends: 96
]
output: null
describe "more than two tokens", ->
run
description: "which are not operator matches"
tokens: [
token: "irPI:PASSWORD:<KEY>END_PIA"
starts: 35
ends: 74
,
token: "irPI:PASSWORD:<KEY>END_PI PI:KEY:<KEY>END_PI"
starts: 87
ends: 96
,
token: "irPI:PASSWORD:<KEY>END_PIC"
starts: 122
ends: 146
,
token: "irPI:PASSWORD:<PASSWORD>END_PI"
starts: 166
ends: 180
]
output: null
run
description: "when the first is an operator match on this level"
tokens: [
token: "testOperatorSymbolBB"
starts: 35
ends: 74
,
token: "irrelevantB"
starts: 87
ends: 96
,
token: "PI:KEY:<KEY>END_PI PI:PASSWORD:<KEY>END_PI PI:KEY:<KEY>END_PI"
starts: 122
ends: 146
,
token: "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI"
starts: 166
ends: 180
]
expectTokens: [
token: "irrelevantB"
starts: 87
ends: 96
,
token: "irPI:PASSWORD:<KEY>END_PIC"
starts: 122
ends: 146
,
token: "PI:KEY:<KEY>END_PI"
starts: 166
ends: 180
]
output:
call: "testOperatorB"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "when multiple are an operator match on this level"
tokens: [
token: "testOperatorSymbolCC"
starts: 35
ends: 74
,
token: "PI:KEY:<KEY>END_PI"
starts: 87
ends: 96
,
token: "PI:KEY:<KEY>END_PIOperatorSymbolPI:KEY:<KEY>END_PI"
starts: 122
ends: 146
,
token: "PI:KEY:<KEY>END_PI"
starts: 166
ends: 180
]
expectTokens: [
token: "PI:KEY:<KEY>END_PI"
starts: 87
ends: 96
,
token: "testOperatorSymbolBA"
starts: 122
ends: 146
,
token: "PI:KEY:<KEY>END_PI"
starts: 166
ends: 180
]
output:
call: "testOperatorC"
with: ["recursed expression"]
starts: 35
ends: 74
run
description: "when the first is an operator match not on this level"
tokens: [
token: "PI:KEY:<KEY>END_PIOperatorPI:KEY:<KEY>END_PIDB"
starts: 35
ends: 74
,
token: "PI:KEY:<KEY>END_PI"
starts: 87
ends: 96
,
token: "PI:KEY:<KEY>END_PI"
starts: 122
ends: 146
,
token: "PI:KEY:<KEY>END_PI"
starts: 166
ends: 180
]
output: null |
[
{
"context": "r = user;\n\n\t\tif (user) then user.confirmPassword = user.password\n\n\t\tsuccess = (u) -> $modalInstance.close(u)\n\n\t\ter",
"end": 1833,
"score": 0.9867088198661804,
"start": 1820,
"tag": "PASSWORD",
"value": "user.password"
},
{
"context": "lInstance, $validation,... | app/admin/user/user.controller.coffee | dianw/yama-admin | 0 | 'use strict'
class User extends Controller
constructor: ($modal, $location, RestUserService, angularPopupBoxes) ->
ctrl = @
ctrl.searchParams = $location.search()
ctrl.searchParams.hash = 0
ctrl.page = 1
@search = ->
ctrl.searchParams.hash++;
ctrl.searchParams.page = ctrl.page - 1
$location.search ctrl.searchParams
# Load list on page loaded
RestUserService.getList(ctrl.searchParams).then (users) ->
ctrl.users = users
ctrl.page = users.meta.number + 1
addRole = (user) -> user.getList('roles').then (roles) -> user.roles = roles
addRole user for user in users
@search()
@openForm = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.form.html'
controller: 'userFormController as ctrl'
size: 'md'
resolve:
user: -> user or {}
modal.result.then (u) ->
ctrl.searchParams.q = u.username
ctrl.search()
@changePasswd = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.passwd.html'
controller: 'userChangePasswdFormController as ctrl'
size: 'md'
resolve:
user: -> user
modal.result.then -> ctrl.search()
@addRole = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.role.html'
controller: 'userEditRoleFormController as ctrl'
size: 'md'
resolve:
user: -> user
modal.result.then -> ctrl.search ctrl.searchParams
# Open popup confirmation and delete user if user choose yes
@remove = (user) ->
angularPopupBoxes.confirm 'Are you sure want to delete this data?'
.result.then ->
user.remove().then -> ctrl.search ctrl.searchParams
class UserForm extends Controller
constructor: ($modalInstance, $validation, RestUserService, user) ->
ctrl = @
ctrl.roles = [];
ctrl.user = user;
if (user) then user.confirmPassword = user.password
success = (u) -> $modalInstance.close(u)
error = -> ctrl.error = true
@submit = (user, form) ->
$validation.validate(form).success ->
ctrl.error = false;
if (user.id) then user.put().then(success, error)
else RestUserService.post(user).then(success, error)
class UserChangePasswdForm extends Controller
constructor: ($modalInstance, $validation, user) ->
user.password = ''
ctrl = @
ctrl.user = user
@submit = (u, form) ->
$validation.validate(form).success ->
ctrl.error = false
u.post('password').then (-> $modalInstance.close()), (-> ctrl.error = true)
class UserEditRoleForm extends Controller
constructor: ($modalInstance, $cacheFactory, RestRoleService, user) ->
ctrl = @
ctrl.user = user;
ctrl.roles = [];
invalidateCache = -> $cacheFactory.get('$http').remove(user.one('roles').getRequestedUrl())
@loadRoles = (search) -> RestRoleService.getList(q: search).then((roles) -> ctrl.roles = roles)
@addRole = (role) -> user.one('roles', role.id).put().then(invalidateCache)
@removeRole = (role) -> user.one('roles', role.id).remove().then(invalidateCache)
@done = $modalInstance.close
| 195795 | 'use strict'
class User extends Controller
constructor: ($modal, $location, RestUserService, angularPopupBoxes) ->
ctrl = @
ctrl.searchParams = $location.search()
ctrl.searchParams.hash = 0
ctrl.page = 1
@search = ->
ctrl.searchParams.hash++;
ctrl.searchParams.page = ctrl.page - 1
$location.search ctrl.searchParams
# Load list on page loaded
RestUserService.getList(ctrl.searchParams).then (users) ->
ctrl.users = users
ctrl.page = users.meta.number + 1
addRole = (user) -> user.getList('roles').then (roles) -> user.roles = roles
addRole user for user in users
@search()
@openForm = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.form.html'
controller: 'userFormController as ctrl'
size: 'md'
resolve:
user: -> user or {}
modal.result.then (u) ->
ctrl.searchParams.q = u.username
ctrl.search()
@changePasswd = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.passwd.html'
controller: 'userChangePasswdFormController as ctrl'
size: 'md'
resolve:
user: -> user
modal.result.then -> ctrl.search()
@addRole = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.role.html'
controller: 'userEditRoleFormController as ctrl'
size: 'md'
resolve:
user: -> user
modal.result.then -> ctrl.search ctrl.searchParams
# Open popup confirmation and delete user if user choose yes
@remove = (user) ->
angularPopupBoxes.confirm 'Are you sure want to delete this data?'
.result.then ->
user.remove().then -> ctrl.search ctrl.searchParams
class UserForm extends Controller
constructor: ($modalInstance, $validation, RestUserService, user) ->
ctrl = @
ctrl.roles = [];
ctrl.user = user;
if (user) then user.confirmPassword = <PASSWORD>
success = (u) -> $modalInstance.close(u)
error = -> ctrl.error = true
@submit = (user, form) ->
$validation.validate(form).success ->
ctrl.error = false;
if (user.id) then user.put().then(success, error)
else RestUserService.post(user).then(success, error)
class UserChangePasswdForm extends Controller
constructor: ($modalInstance, $validation, user) ->
user.password =<PASSWORD> ''
ctrl = @
ctrl.user = user
@submit = (u, form) ->
$validation.validate(form).success ->
ctrl.error = false
u.post('password').then (-> $modalInstance.close()), (-> ctrl.error = true)
class UserEditRoleForm extends Controller
constructor: ($modalInstance, $cacheFactory, RestRoleService, user) ->
ctrl = @
ctrl.user = user;
ctrl.roles = [];
invalidateCache = -> $cacheFactory.get('$http').remove(user.one('roles').getRequestedUrl())
@loadRoles = (search) -> RestRoleService.getList(q: search).then((roles) -> ctrl.roles = roles)
@addRole = (role) -> user.one('roles', role.id).put().then(invalidateCache)
@removeRole = (role) -> user.one('roles', role.id).remove().then(invalidateCache)
@done = $modalInstance.close
| true | 'use strict'
class User extends Controller
constructor: ($modal, $location, RestUserService, angularPopupBoxes) ->
ctrl = @
ctrl.searchParams = $location.search()
ctrl.searchParams.hash = 0
ctrl.page = 1
@search = ->
ctrl.searchParams.hash++;
ctrl.searchParams.page = ctrl.page - 1
$location.search ctrl.searchParams
# Load list on page loaded
RestUserService.getList(ctrl.searchParams).then (users) ->
ctrl.users = users
ctrl.page = users.meta.number + 1
addRole = (user) -> user.getList('roles').then (roles) -> user.roles = roles
addRole user for user in users
@search()
@openForm = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.form.html'
controller: 'userFormController as ctrl'
size: 'md'
resolve:
user: -> user or {}
modal.result.then (u) ->
ctrl.searchParams.q = u.username
ctrl.search()
@changePasswd = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.passwd.html'
controller: 'userChangePasswdFormController as ctrl'
size: 'md'
resolve:
user: -> user
modal.result.then -> ctrl.search()
@addRole = (user) ->
modal = $modal.open
templateUrl: 'admin/user/user.role.html'
controller: 'userEditRoleFormController as ctrl'
size: 'md'
resolve:
user: -> user
modal.result.then -> ctrl.search ctrl.searchParams
# Open popup confirmation and delete user if user choose yes
@remove = (user) ->
angularPopupBoxes.confirm 'Are you sure want to delete this data?'
.result.then ->
user.remove().then -> ctrl.search ctrl.searchParams
class UserForm extends Controller
constructor: ($modalInstance, $validation, RestUserService, user) ->
ctrl = @
ctrl.roles = [];
ctrl.user = user;
if (user) then user.confirmPassword = PI:PASSWORD:<PASSWORD>END_PI
success = (u) -> $modalInstance.close(u)
error = -> ctrl.error = true
@submit = (user, form) ->
$validation.validate(form).success ->
ctrl.error = false;
if (user.id) then user.put().then(success, error)
else RestUserService.post(user).then(success, error)
class UserChangePasswdForm extends Controller
constructor: ($modalInstance, $validation, user) ->
user.password =PI:PASSWORD:<PASSWORD>END_PI ''
ctrl = @
ctrl.user = user
@submit = (u, form) ->
$validation.validate(form).success ->
ctrl.error = false
u.post('password').then (-> $modalInstance.close()), (-> ctrl.error = true)
class UserEditRoleForm extends Controller
constructor: ($modalInstance, $cacheFactory, RestRoleService, user) ->
ctrl = @
ctrl.user = user;
ctrl.roles = [];
invalidateCache = -> $cacheFactory.get('$http').remove(user.one('roles').getRequestedUrl())
@loadRoles = (search) -> RestRoleService.getList(q: search).then((roles) -> ctrl.roles = roles)
@addRole = (role) -> user.one('roles', role.id).put().then(invalidateCache)
@removeRole = (role) -> user.one('roles', role.id).remove().then(invalidateCache)
@done = $modalInstance.close
|
[
{
"context": "login = ->\n username = $('#username').val()\n userpwd = $('#userpwd').val()\n $.post ",
"end": 36,
"score": 0.7417279481887817,
"start": 28,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ername = $('#username').val()\n userpwd = $('#userpwd').val()\n $.p... | zblog/coffee/server/views/built/js/login.coffee | zoei/zblog | 0 | login = ->
username = $('#username').val()
userpwd = $('#userpwd').val()
$.post '/admin/verify',
name: username
password: userpwd
, (result)->
window.location.href = "/console"
$('#btn-login').on 'click', login | 122040 | login = ->
username = $('#username').val()
userpwd = $('#user<PASSWORD>').val()
$.post '/admin/verify',
name: username
password: <PASSWORD>
, (result)->
window.location.href = "/console"
$('#btn-login').on 'click', login | true | login = ->
username = $('#username').val()
userpwd = $('#userPI:PASSWORD:<PASSWORD>END_PI').val()
$.post '/admin/verify',
name: username
password: PI:PASSWORD:<PASSWORD>END_PI
, (result)->
window.location.href = "/console"
$('#btn-login').on 'click', login |
[
{
"context": " @fileoverview Tests for no-shadow rule.\n# @author Ilya Volodin\n###\n\n'use strict'\n\n#-----------------------------",
"end": 69,
"score": 0.9997913837432861,
"start": 57,
"tag": "NAME",
"value": "Ilya Volodin"
}
] | src/tests/rules/no-shadow.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-shadow rule.
# @author Ilya Volodin
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-shadow'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-shadow', rule,
valid: [
'''
a = 3
b = (x) ->
a++
x + a
setTimeout(
-> b(a)
0
)
'''
'''
do ->
doSomething = ->
doSomething()
'''
'class A'
'''
class A
constructor: ->
a = null
'''
'''
do ->
A = class A
'''
'''
a = null
a = null
'''
'''
foo = (a) ->
a = null
'''
,
code: '''
foo = (a) ->
a = ->
'''
options: [hoist: 'never']
,
'''
->
Object = 0
'''
,
code: '''
->
top = 0
'''
env: browser: yes
,
# ,
# code: '''
# Object = 0
# '''
# options: [builtinGlobals: yes]
# ,
# code: '''
# top = 0
# '''
# env: browser: yes
# options: [builtinGlobals: yes]
code: '''
foo = (cb) ->
((cb) ->
cb(42)
)(cb)
'''
options: [allow: ['cb']]
,
'''
foo = (cb) ->
do (cb) -> cb 42
'''
'''
a = 3
b = ->
a = 10
b = 0
setTimeout(
-> b()
0
)
'''
'''
a = ->
a = ->
'''
'''
a = ->
class a
'''
'''
do ->
a = ->
class a
'''
'''
do ->
a = class
constructor: ->
class a
'''
'''
class A
constructor: ->
A = null
'''
'''
class A
constructor: ->
class A
'''
'''
a class A
'''
'''
exports.Rewriter = class Rewriter
'''
]
invalid: [
code: '''
x = 1
a = (x) -> ++x
'''
errors: [
message: "'x' is already declared in the upper scope."
type: 'Identifier'
line: 2
column: 6
]
,
code: '''
foo = (a) ->
a = null
'''
options: [hoist: 'all']
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = (a) ->
a = ->
'''
options: [hoist: 'all']
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = (a) ->
a = ->
'''
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
do ->
a = (a) ->
'''
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = ->
Object = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'Object' is already declared in the upper scope."
type: 'Identifier'
]
,
code: '''
foo = ->
top = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'top' is already declared in the upper scope."
type: 'Identifier'
]
env: browser: yes
,
code: '''
Object = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'Object' is already declared in the upper scope."
type: 'Identifier'
]
,
code: '''
top = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'top' is already declared in the upper scope."
type: 'Identifier'
]
env: browser: yes
,
code: '''
foo = (cb) ->
((cb) -> cb(42))(cb)
'''
errors: [
message: "'cb' is already declared in the upper scope."
type: 'Identifier'
line: 2
column: 5
]
]
| 219190 | ###*
# @fileoverview Tests for no-shadow rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-shadow'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-shadow', rule,
valid: [
'''
a = 3
b = (x) ->
a++
x + a
setTimeout(
-> b(a)
0
)
'''
'''
do ->
doSomething = ->
doSomething()
'''
'class A'
'''
class A
constructor: ->
a = null
'''
'''
do ->
A = class A
'''
'''
a = null
a = null
'''
'''
foo = (a) ->
a = null
'''
,
code: '''
foo = (a) ->
a = ->
'''
options: [hoist: 'never']
,
'''
->
Object = 0
'''
,
code: '''
->
top = 0
'''
env: browser: yes
,
# ,
# code: '''
# Object = 0
# '''
# options: [builtinGlobals: yes]
# ,
# code: '''
# top = 0
# '''
# env: browser: yes
# options: [builtinGlobals: yes]
code: '''
foo = (cb) ->
((cb) ->
cb(42)
)(cb)
'''
options: [allow: ['cb']]
,
'''
foo = (cb) ->
do (cb) -> cb 42
'''
'''
a = 3
b = ->
a = 10
b = 0
setTimeout(
-> b()
0
)
'''
'''
a = ->
a = ->
'''
'''
a = ->
class a
'''
'''
do ->
a = ->
class a
'''
'''
do ->
a = class
constructor: ->
class a
'''
'''
class A
constructor: ->
A = null
'''
'''
class A
constructor: ->
class A
'''
'''
a class A
'''
'''
exports.Rewriter = class Rewriter
'''
]
invalid: [
code: '''
x = 1
a = (x) -> ++x
'''
errors: [
message: "'x' is already declared in the upper scope."
type: 'Identifier'
line: 2
column: 6
]
,
code: '''
foo = (a) ->
a = null
'''
options: [hoist: 'all']
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = (a) ->
a = ->
'''
options: [hoist: 'all']
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = (a) ->
a = ->
'''
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
do ->
a = (a) ->
'''
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = ->
Object = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'Object' is already declared in the upper scope."
type: 'Identifier'
]
,
code: '''
foo = ->
top = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'top' is already declared in the upper scope."
type: 'Identifier'
]
env: browser: yes
,
code: '''
Object = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'Object' is already declared in the upper scope."
type: 'Identifier'
]
,
code: '''
top = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'top' is already declared in the upper scope."
type: 'Identifier'
]
env: browser: yes
,
code: '''
foo = (cb) ->
((cb) -> cb(42))(cb)
'''
errors: [
message: "'cb' is already declared in the upper scope."
type: 'Identifier'
line: 2
column: 5
]
]
| true | ###*
# @fileoverview Tests for no-shadow rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-shadow'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-shadow', rule,
valid: [
'''
a = 3
b = (x) ->
a++
x + a
setTimeout(
-> b(a)
0
)
'''
'''
do ->
doSomething = ->
doSomething()
'''
'class A'
'''
class A
constructor: ->
a = null
'''
'''
do ->
A = class A
'''
'''
a = null
a = null
'''
'''
foo = (a) ->
a = null
'''
,
code: '''
foo = (a) ->
a = ->
'''
options: [hoist: 'never']
,
'''
->
Object = 0
'''
,
code: '''
->
top = 0
'''
env: browser: yes
,
# ,
# code: '''
# Object = 0
# '''
# options: [builtinGlobals: yes]
# ,
# code: '''
# top = 0
# '''
# env: browser: yes
# options: [builtinGlobals: yes]
code: '''
foo = (cb) ->
((cb) ->
cb(42)
)(cb)
'''
options: [allow: ['cb']]
,
'''
foo = (cb) ->
do (cb) -> cb 42
'''
'''
a = 3
b = ->
a = 10
b = 0
setTimeout(
-> b()
0
)
'''
'''
a = ->
a = ->
'''
'''
a = ->
class a
'''
'''
do ->
a = ->
class a
'''
'''
do ->
a = class
constructor: ->
class a
'''
'''
class A
constructor: ->
A = null
'''
'''
class A
constructor: ->
class A
'''
'''
a class A
'''
'''
exports.Rewriter = class Rewriter
'''
]
invalid: [
code: '''
x = 1
a = (x) -> ++x
'''
errors: [
message: "'x' is already declared in the upper scope."
type: 'Identifier'
line: 2
column: 6
]
,
code: '''
foo = (a) ->
a = null
'''
options: [hoist: 'all']
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = (a) ->
a = ->
'''
options: [hoist: 'all']
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = (a) ->
a = ->
'''
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
do ->
a = (a) ->
'''
errors: [
message: "'a' is already declared in the upper scope.", type: 'Identifier'
]
,
code: '''
foo = ->
Object = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'Object' is already declared in the upper scope."
type: 'Identifier'
]
,
code: '''
foo = ->
top = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'top' is already declared in the upper scope."
type: 'Identifier'
]
env: browser: yes
,
code: '''
Object = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'Object' is already declared in the upper scope."
type: 'Identifier'
]
,
code: '''
top = 0
'''
options: [builtinGlobals: yes]
errors: [
message: "'top' is already declared in the upper scope."
type: 'Identifier'
]
env: browser: yes
,
code: '''
foo = (cb) ->
((cb) -> cb(42))(cb)
'''
errors: [
message: "'cb' is already declared in the upper scope."
type: 'Identifier'
line: 2
column: 5
]
]
|
[
{
"context": " body: '{\\n \"type\": \"bulldozer\",\\n \"name\": \"willy\"}\\n'\n headers:\n 'Content-Type",
"end": 3821,
"score": 0.9767093658447266,
"start": 3816,
"tag": "NAME",
"value": "willy"
},
{
"context": " body: '{\\n \"type\": \"bulldozer\",\... | test/unit/add-hooks-test.coffee | HBOCodeLabs/dredd | 0 | require 'coffee-errors'
{assert} = require 'chai'
{EventEmitter} = require 'events'
nock = require 'nock'
proxyquire = require 'proxyquire'
sinon = require 'sinon'
globStub = require 'glob'
pathStub = require 'path'
loggerStub = require '../../src/logger'
hooksStub = require '../../src/hooks'
Runner = require '../../src/transaction-runner'
addHooks = proxyquire '../../src/add-hooks', {
'logger': loggerStub,
'glob': globStub,
'pathStub': pathStub,
'hooks': hooksStub
}
describe 'addHooks(runner, transaction)', () ->
transactions = {}
before () ->
loggerStub.transports.console.silent = true
after () ->
loggerStub.transports.console.silent = false
describe 'with no pattern', () ->
before () ->
sinon.spy globStub, 'sync'
after () ->
globStub.sync.restore()
it 'should return immediately', ()->
addHooks("", transactions)
assert.ok globStub.sync.notCalled
describe 'with valid pattern', () ->
runner =
configuration:
options:
hookfiles: './**/*_hooks.*'
before: (fn, cb) ->
return
after: (fn, cb) ->
return
it 'should return files', () ->
sinon.spy globStub, 'sync'
addHooks(runner, transactions)
assert.ok globStub.sync.called
globStub.sync.restore()
describe 'when files are valid js/coffeescript', () ->
beforeEach () ->
sinon.spy runner, 'before'
sinon.spy runner, 'after'
sinon.stub globStub, 'sync', (pattern) ->
['file1.js', 'file2.coffee']
sinon.stub pathStub, 'resolve', (path, rel) ->
""
afterEach () ->
runner.before.restore()
runner.after.restore()
globStub.sync.restore()
pathStub.resolve.restore()
it 'should load the files', () ->
addHooks(runner, transactions)
assert.ok pathStub.resolve.called
it 'should attach the hooks', () ->
# can't stub proxyquire, so we skip it by forcing files to be empty
sinon.restore globStub.sync
sinon.stub globStub, 'sync', (pattern) ->
[]
addHooks(runner, transactions)
assert.ok runner.before.calledWith 'executeTransaction'
assert.ok runner.after.calledWith 'executeTransaction'
assert.ok runner.before.calledWith 'executeAllTransactions'
assert.ok runner.after.calledWith 'executeAllTransactions'
describe 'when there is an error reading the hook files', () ->
beforeEach () ->
sinon.stub pathStub, 'resolve', (path, rel) ->
throw new Error()
sinon.spy loggerStub, 'error'
sinon.spy runner, 'before'
sinon.spy runner, 'after'
sinon.stub globStub, 'sync', (pattern) ->
['file1.xml', 'file2.md']
afterEach () ->
pathStub.resolve.restore()
loggerStub.error.restore()
runner.before.restore()
runner.after.restore()
globStub.sync.restore()
it 'should log an error', () ->
addHooks(runner, transactions)
assert.ok loggerStub.error.called
it 'should not attach the hooks', () ->
addHooks(runner, transactions)
assert.ok runner.before.notCalled
assert.ok runner.after.notCalled
describe 'when a transaction is executed', () ->
configuration =
server: 'http://localhost:3000'
emitter: new EventEmitter()
options:
'dry-run': false
method: []
header: []
reporter: []
hookfiles: './**/*_hooks.*'
transaction =
name: 'Group Machine > Machine > Delete Message > Bogus example name'
id: 'POST /machines'
host: 'localhost'
port: '3000'
request:
body: '{\n "type": "bulldozer",\n "name": "willy"}\n'
headers:
'Content-Type': 'application/json'
'User-Agent': 'Dredd/0.2.1 (Darwin 13.0.0; x64)'
'Content-Length': 44
uri: '/machines'
method: 'POST'
expected:
headers: 'content-type': 'application/json'
body: '{\n "type": "bulldozer",\n "name": "willy",\n "id": "5229c6e8e4b0bd7dbb07e29c"\n}\n'
status: '202'
origin:
resourceGroupName: 'Group Machine'
resourceName: 'Machine'
actionName: 'Delete Message'
exampleName: 'Bogus example name'
fullPath: '/machines'
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"willy"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
runner = new Runner(configuration)
sinon.stub globStub, 'sync', (pattern) ->
[]
afterEach () ->
globStub.sync.restore()
nock.cleanAll()
describe 'with hooks', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
loggerStub.info "before"
]
hooksStub.afterHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction, done) ->
loggerStub.info "after"
done()
]
afterEach () ->
loggerStub.info.restore()
it 'should run the hooks', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.calledWith "before"
assert.ok loggerStub.info.calledWith "after"
done()
describe 'with multiple hooks for the same transaction', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
loggerStub.info "first",
(transaction, cb) ->
loggerStub.info "second"
cb()
]
afterEach () ->
loggerStub.info.restore()
it 'should run all hooks', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.calledWith "first"
assert.ok loggerStub.info.calledWith "second"
done()
describe 'with a beforeAll hook', () ->
beforeAll = sinon.stub()
beforeAll.callsArg(0)
before () ->
hooksStub.beforeAll beforeAll
after () ->
hooksStub.beforeAllHooks = []
it 'should run the hooks', (done) ->
runner.executeAllTransactions [], () ->
assert.ok beforeAll.called
done()
describe 'with an afterAll hook', () ->
afterAll = sinon.stub()
afterAll.callsArg(0)
before () ->
hooksStub.afterAll afterAll
after () ->
hooksStub.afterAllHooks = []
it 'should run the hooks', (done) ->
runner.executeAllTransactions [], () ->
assert.ok afterAll.called
done()
describe 'with multiple hooks for the same events', () ->
beforeAll1 = sinon.stub()
beforeAll2 = sinon.stub()
afterAll1 = sinon.stub()
afterAll2 = sinon.stub()
before () ->
beforeAll1.callsArg(0)
beforeAll2.callsArg(0)
afterAll1.callsArg(0)
afterAll2.callsArg(0)
beforeEach () ->
hooksStub.beforeAll beforeAll1
hooksStub.afterAll afterAll1
hooksStub.afterAll afterAll2
hooksStub.beforeAll beforeAll2
after () ->
hooksStub.beforeAllHooks = []
hooksStub.afterAllHooks = []
it 'should run all the events in order', (done) ->
runner.executeAllTransactions [], () ->
assert.ok beforeAll1.calledBefore(beforeAll2)
assert.ok beforeAll2.called
assert.ok afterAll1.calledBefore(afterAll2)
assert.ok afterAll2.called
done()
describe 'with hook that throws an error', () ->
beforeEach () ->
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
JSON.parse '<<<>>>!@#!@#!@#4234234'
]
sinon.stub configuration.emitter, 'emit'
after () ->
configuration.emitter.emit.restore()
it 'should report an error with the test', (done) ->
runner.executeTransaction transaction, () ->
assert.ok emitter.emit.calledWith "test error"
done()
describe 'without hooks', () ->
beforeEach () ->
hooksStub.beforeHooks = []
hooksStub.afterHooks = []
it 'should not run the hooks', (done) ->
runner.executeTransaction transaction, () ->
done()
| 106146 | require 'coffee-errors'
{assert} = require 'chai'
{EventEmitter} = require 'events'
nock = require 'nock'
proxyquire = require 'proxyquire'
sinon = require 'sinon'
globStub = require 'glob'
pathStub = require 'path'
loggerStub = require '../../src/logger'
hooksStub = require '../../src/hooks'
Runner = require '../../src/transaction-runner'
addHooks = proxyquire '../../src/add-hooks', {
'logger': loggerStub,
'glob': globStub,
'pathStub': pathStub,
'hooks': hooksStub
}
describe 'addHooks(runner, transaction)', () ->
transactions = {}
before () ->
loggerStub.transports.console.silent = true
after () ->
loggerStub.transports.console.silent = false
describe 'with no pattern', () ->
before () ->
sinon.spy globStub, 'sync'
after () ->
globStub.sync.restore()
it 'should return immediately', ()->
addHooks("", transactions)
assert.ok globStub.sync.notCalled
describe 'with valid pattern', () ->
runner =
configuration:
options:
hookfiles: './**/*_hooks.*'
before: (fn, cb) ->
return
after: (fn, cb) ->
return
it 'should return files', () ->
sinon.spy globStub, 'sync'
addHooks(runner, transactions)
assert.ok globStub.sync.called
globStub.sync.restore()
describe 'when files are valid js/coffeescript', () ->
beforeEach () ->
sinon.spy runner, 'before'
sinon.spy runner, 'after'
sinon.stub globStub, 'sync', (pattern) ->
['file1.js', 'file2.coffee']
sinon.stub pathStub, 'resolve', (path, rel) ->
""
afterEach () ->
runner.before.restore()
runner.after.restore()
globStub.sync.restore()
pathStub.resolve.restore()
it 'should load the files', () ->
addHooks(runner, transactions)
assert.ok pathStub.resolve.called
it 'should attach the hooks', () ->
# can't stub proxyquire, so we skip it by forcing files to be empty
sinon.restore globStub.sync
sinon.stub globStub, 'sync', (pattern) ->
[]
addHooks(runner, transactions)
assert.ok runner.before.calledWith 'executeTransaction'
assert.ok runner.after.calledWith 'executeTransaction'
assert.ok runner.before.calledWith 'executeAllTransactions'
assert.ok runner.after.calledWith 'executeAllTransactions'
describe 'when there is an error reading the hook files', () ->
beforeEach () ->
sinon.stub pathStub, 'resolve', (path, rel) ->
throw new Error()
sinon.spy loggerStub, 'error'
sinon.spy runner, 'before'
sinon.spy runner, 'after'
sinon.stub globStub, 'sync', (pattern) ->
['file1.xml', 'file2.md']
afterEach () ->
pathStub.resolve.restore()
loggerStub.error.restore()
runner.before.restore()
runner.after.restore()
globStub.sync.restore()
it 'should log an error', () ->
addHooks(runner, transactions)
assert.ok loggerStub.error.called
it 'should not attach the hooks', () ->
addHooks(runner, transactions)
assert.ok runner.before.notCalled
assert.ok runner.after.notCalled
describe 'when a transaction is executed', () ->
configuration =
server: 'http://localhost:3000'
emitter: new EventEmitter()
options:
'dry-run': false
method: []
header: []
reporter: []
hookfiles: './**/*_hooks.*'
transaction =
name: 'Group Machine > Machine > Delete Message > Bogus example name'
id: 'POST /machines'
host: 'localhost'
port: '3000'
request:
body: '{\n "type": "bulldozer",\n "name": "<NAME>"}\n'
headers:
'Content-Type': 'application/json'
'User-Agent': 'Dredd/0.2.1 (Darwin 13.0.0; x64)'
'Content-Length': 44
uri: '/machines'
method: 'POST'
expected:
headers: 'content-type': 'application/json'
body: '{\n "type": "bulldozer",\n "name": "<NAME>",\n "id": "5229c6e8e4b0bd7dbb07e29c"\n}\n'
status: '202'
origin:
resourceGroupName: 'Group Machine'
resourceName: 'Machine'
actionName: 'Delete Message'
exampleName: 'Bogus example name'
fullPath: '/machines'
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"<NAME>"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
runner = new Runner(configuration)
sinon.stub globStub, 'sync', (pattern) ->
[]
afterEach () ->
globStub.sync.restore()
nock.cleanAll()
describe 'with hooks', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
loggerStub.info "before"
]
hooksStub.afterHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction, done) ->
loggerStub.info "after"
done()
]
afterEach () ->
loggerStub.info.restore()
it 'should run the hooks', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.calledWith "before"
assert.ok loggerStub.info.calledWith "after"
done()
describe 'with multiple hooks for the same transaction', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
loggerStub.info "first",
(transaction, cb) ->
loggerStub.info "second"
cb()
]
afterEach () ->
loggerStub.info.restore()
it 'should run all hooks', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.calledWith "first"
assert.ok loggerStub.info.calledWith "second"
done()
describe 'with a beforeAll hook', () ->
beforeAll = sinon.stub()
beforeAll.callsArg(0)
before () ->
hooksStub.beforeAll beforeAll
after () ->
hooksStub.beforeAllHooks = []
it 'should run the hooks', (done) ->
runner.executeAllTransactions [], () ->
assert.ok beforeAll.called
done()
describe 'with an afterAll hook', () ->
afterAll = sinon.stub()
afterAll.callsArg(0)
before () ->
hooksStub.afterAll afterAll
after () ->
hooksStub.afterAllHooks = []
it 'should run the hooks', (done) ->
runner.executeAllTransactions [], () ->
assert.ok afterAll.called
done()
describe 'with multiple hooks for the same events', () ->
beforeAll1 = sinon.stub()
beforeAll2 = sinon.stub()
afterAll1 = sinon.stub()
afterAll2 = sinon.stub()
before () ->
beforeAll1.callsArg(0)
beforeAll2.callsArg(0)
afterAll1.callsArg(0)
afterAll2.callsArg(0)
beforeEach () ->
hooksStub.beforeAll beforeAll1
hooksStub.afterAll afterAll1
hooksStub.afterAll afterAll2
hooksStub.beforeAll beforeAll2
after () ->
hooksStub.beforeAllHooks = []
hooksStub.afterAllHooks = []
it 'should run all the events in order', (done) ->
runner.executeAllTransactions [], () ->
assert.ok beforeAll1.calledBefore(beforeAll2)
assert.ok beforeAll2.called
assert.ok afterAll1.calledBefore(afterAll2)
assert.ok afterAll2.called
done()
describe 'with hook that throws an error', () ->
beforeEach () ->
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
JSON.parse '<<<>>>!@#!@#!@#4234234'
]
sinon.stub configuration.emitter, 'emit'
after () ->
configuration.emitter.emit.restore()
it 'should report an error with the test', (done) ->
runner.executeTransaction transaction, () ->
assert.ok emitter.emit.calledWith "test error"
done()
describe 'without hooks', () ->
beforeEach () ->
hooksStub.beforeHooks = []
hooksStub.afterHooks = []
it 'should not run the hooks', (done) ->
runner.executeTransaction transaction, () ->
done()
| true | require 'coffee-errors'
{assert} = require 'chai'
{EventEmitter} = require 'events'
nock = require 'nock'
proxyquire = require 'proxyquire'
sinon = require 'sinon'
globStub = require 'glob'
pathStub = require 'path'
loggerStub = require '../../src/logger'
hooksStub = require '../../src/hooks'
Runner = require '../../src/transaction-runner'
addHooks = proxyquire '../../src/add-hooks', {
'logger': loggerStub,
'glob': globStub,
'pathStub': pathStub,
'hooks': hooksStub
}
describe 'addHooks(runner, transaction)', () ->
transactions = {}
before () ->
loggerStub.transports.console.silent = true
after () ->
loggerStub.transports.console.silent = false
describe 'with no pattern', () ->
before () ->
sinon.spy globStub, 'sync'
after () ->
globStub.sync.restore()
it 'should return immediately', ()->
addHooks("", transactions)
assert.ok globStub.sync.notCalled
describe 'with valid pattern', () ->
runner =
configuration:
options:
hookfiles: './**/*_hooks.*'
before: (fn, cb) ->
return
after: (fn, cb) ->
return
it 'should return files', () ->
sinon.spy globStub, 'sync'
addHooks(runner, transactions)
assert.ok globStub.sync.called
globStub.sync.restore()
describe 'when files are valid js/coffeescript', () ->
beforeEach () ->
sinon.spy runner, 'before'
sinon.spy runner, 'after'
sinon.stub globStub, 'sync', (pattern) ->
['file1.js', 'file2.coffee']
sinon.stub pathStub, 'resolve', (path, rel) ->
""
afterEach () ->
runner.before.restore()
runner.after.restore()
globStub.sync.restore()
pathStub.resolve.restore()
it 'should load the files', () ->
addHooks(runner, transactions)
assert.ok pathStub.resolve.called
it 'should attach the hooks', () ->
# can't stub proxyquire, so we skip it by forcing files to be empty
sinon.restore globStub.sync
sinon.stub globStub, 'sync', (pattern) ->
[]
addHooks(runner, transactions)
assert.ok runner.before.calledWith 'executeTransaction'
assert.ok runner.after.calledWith 'executeTransaction'
assert.ok runner.before.calledWith 'executeAllTransactions'
assert.ok runner.after.calledWith 'executeAllTransactions'
describe 'when there is an error reading the hook files', () ->
beforeEach () ->
sinon.stub pathStub, 'resolve', (path, rel) ->
throw new Error()
sinon.spy loggerStub, 'error'
sinon.spy runner, 'before'
sinon.spy runner, 'after'
sinon.stub globStub, 'sync', (pattern) ->
['file1.xml', 'file2.md']
afterEach () ->
pathStub.resolve.restore()
loggerStub.error.restore()
runner.before.restore()
runner.after.restore()
globStub.sync.restore()
it 'should log an error', () ->
addHooks(runner, transactions)
assert.ok loggerStub.error.called
it 'should not attach the hooks', () ->
addHooks(runner, transactions)
assert.ok runner.before.notCalled
assert.ok runner.after.notCalled
describe 'when a transaction is executed', () ->
configuration =
server: 'http://localhost:3000'
emitter: new EventEmitter()
options:
'dry-run': false
method: []
header: []
reporter: []
hookfiles: './**/*_hooks.*'
transaction =
name: 'Group Machine > Machine > Delete Message > Bogus example name'
id: 'POST /machines'
host: 'localhost'
port: '3000'
request:
body: '{\n "type": "bulldozer",\n "name": "PI:NAME:<NAME>END_PI"}\n'
headers:
'Content-Type': 'application/json'
'User-Agent': 'Dredd/0.2.1 (Darwin 13.0.0; x64)'
'Content-Length': 44
uri: '/machines'
method: 'POST'
expected:
headers: 'content-type': 'application/json'
body: '{\n "type": "bulldozer",\n "name": "PI:NAME:<NAME>END_PI",\n "id": "5229c6e8e4b0bd7dbb07e29c"\n}\n'
status: '202'
origin:
resourceGroupName: 'Group Machine'
resourceName: 'Machine'
actionName: 'Delete Message'
exampleName: 'Bogus example name'
fullPath: '/machines'
beforeEach () ->
server = nock('http://localhost:3000').
post('/machines', {"type":"bulldozer","name":"PI:NAME:<NAME>END_PI"}).
reply transaction['expected']['status'],
transaction['expected']['body'],
{'Content-Type': 'application/json'}
runner = new Runner(configuration)
sinon.stub globStub, 'sync', (pattern) ->
[]
afterEach () ->
globStub.sync.restore()
nock.cleanAll()
describe 'with hooks', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
loggerStub.info "before"
]
hooksStub.afterHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction, done) ->
loggerStub.info "after"
done()
]
afterEach () ->
loggerStub.info.restore()
it 'should run the hooks', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.calledWith "before"
assert.ok loggerStub.info.calledWith "after"
done()
describe 'with multiple hooks for the same transaction', () ->
beforeEach () ->
sinon.spy loggerStub, 'info'
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
loggerStub.info "first",
(transaction, cb) ->
loggerStub.info "second"
cb()
]
afterEach () ->
loggerStub.info.restore()
it 'should run all hooks', (done) ->
runner.executeTransaction transaction, () ->
assert.ok loggerStub.info.calledWith "first"
assert.ok loggerStub.info.calledWith "second"
done()
describe 'with a beforeAll hook', () ->
beforeAll = sinon.stub()
beforeAll.callsArg(0)
before () ->
hooksStub.beforeAll beforeAll
after () ->
hooksStub.beforeAllHooks = []
it 'should run the hooks', (done) ->
runner.executeAllTransactions [], () ->
assert.ok beforeAll.called
done()
describe 'with an afterAll hook', () ->
afterAll = sinon.stub()
afterAll.callsArg(0)
before () ->
hooksStub.afterAll afterAll
after () ->
hooksStub.afterAllHooks = []
it 'should run the hooks', (done) ->
runner.executeAllTransactions [], () ->
assert.ok afterAll.called
done()
describe 'with multiple hooks for the same events', () ->
beforeAll1 = sinon.stub()
beforeAll2 = sinon.stub()
afterAll1 = sinon.stub()
afterAll2 = sinon.stub()
before () ->
beforeAll1.callsArg(0)
beforeAll2.callsArg(0)
afterAll1.callsArg(0)
afterAll2.callsArg(0)
beforeEach () ->
hooksStub.beforeAll beforeAll1
hooksStub.afterAll afterAll1
hooksStub.afterAll afterAll2
hooksStub.beforeAll beforeAll2
after () ->
hooksStub.beforeAllHooks = []
hooksStub.afterAllHooks = []
it 'should run all the events in order', (done) ->
runner.executeAllTransactions [], () ->
assert.ok beforeAll1.calledBefore(beforeAll2)
assert.ok beforeAll2.called
assert.ok afterAll1.calledBefore(afterAll2)
assert.ok afterAll2.called
done()
describe 'with hook that throws an error', () ->
beforeEach () ->
hooksStub.beforeHooks =
'Group Machine > Machine > Delete Message > Bogus example name' : [
(transaction) ->
JSON.parse '<<<>>>!@#!@#!@#4234234'
]
sinon.stub configuration.emitter, 'emit'
after () ->
configuration.emitter.emit.restore()
it 'should report an error with the test', (done) ->
runner.executeTransaction transaction, () ->
assert.ok emitter.emit.calledWith "test error"
done()
describe 'without hooks', () ->
beforeEach () ->
hooksStub.beforeHooks = []
hooksStub.afterHooks = []
it 'should not run the hooks', (done) ->
runner.executeTransaction transaction, () ->
done()
|
[
{
"context": " profile =\n sub: 'profile_id'\n email: 'user@example.com'\n given_name: 'my_first_name'\n family_n",
"end": 676,
"score": 0.9998876452445984,
"start": 660,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": " .reply 200,\n token... | test/google.coffee | moooink/loopback-satellizer | 0 | expect = require('chai').expect
loopback = require 'loopback'
nock = require 'nock'
request = require 'supertest'
component = require '../lib/index.js'
describe 'Google module', ->
app = null
agent = null
Account = null
beforeEach ->
app = require '../example/server/server.js'
app.datasources.db.automigrate()
agent = request app
Account = app.models.Account
it 'should populate model', ->
expect(Account).to.exist
expect(Account.google).to.exist
describe 'call to loopback method', ->
first = null
second = null
answer = null
profile =
sub: 'profile_id'
email: 'user@example.com'
given_name: 'my_first_name'
family_name: 'my_last_name'
birthday: new Date()
gender: 'male'
beforeEach ->
first = nock 'https://accounts.google.com'
.post '/o/oauth2/token',
code: 'this_is_a_code'
client_id: 'this_is_a_client_id'
client_secret: 'this_is_a_private_key'
redirect_uri: 'this_is_the_uri'
grant_type: 'authorization_code'
.reply 200,
token:
token: 'my_wonderfull_token'
beforeEach ->
second = nock 'https://www.googleapis.com'
.get '/plus/v1/people/me/openIdConnect'
.reply 200, profile
describe 'with post verb', ->
beforeEach (done) ->
agent.post '/api/accounts/google'
.send
code: 'this_is_a_code'
clientId: 'this_is_a_client_id'
redirectUri: 'this_is_the_uri'
.end (err, res) ->
answer =
err: err
res: res
done()
it 'should call google twice and return profile', ->
expect(first.isDone()).to.eql true
expect(second.isDone()).to.eql true
it 'should return a token', ->
expect(answer.err).to.not.exist
expect(answer.res.statusCode).to.eql 200
expect(answer.res.body).to.have.property 'id'
expect(answer.res.body).to.have.property 'userId'
# Allow satellizer to store its token
expect(answer.res.body).to.have.property 'token'
expect(answer.res.body).to.have.property 'ttl'
it 'should create the account', (done) ->
app.models.Account.count email: 'user@example.com', (err, nb) ->
expect(err).to.not.exist
expect(nb).to.eql 1
done err
it 'should map the profile in the account', (done) ->
app.models.Account.findOne
where:
email: 'user@example.com'
, (err, found) ->
expect(err).to.not.exist
expect(found).to.exist
expect(found.google).to.eql profile.sub
expect(found.firstName).to.eql profile.given_name
expect(found.lastName).to.eql profile.family_name
expect(found.gender).to.eql profile.gender
done err
describe 'with get verb', ->
beforeEach (done) ->
agent.get '/api/accounts/google'
.query
code: 'this_is_a_code'
.end (err, res) ->
answer =
err: err
res: res
done()
it 'should call google twice and return profile', ->
expect(first.isDone()).to.eql true
expect(second.isDone()).to.eql true
it 'should return a token', ->
expect(answer.err).to.not.exist
expect(answer.res.statusCode).to.eql 200
expect(answer.res.body).to.have.property 'id'
expect(answer.res.body).to.have.property 'userId'
# Allow satellizer to store its token
expect(answer.res.body).to.have.property 'token'
expect(answer.res.body).to.have.property 'ttl'
it 'should create the account', (done) ->
app.models.Account.count email: 'user@example.com', (err, nb) ->
expect(err).to.not.exist
expect(nb).to.eql 1
done err
it 'should map the profile in the account', (done) ->
app.models.Account.findOne
where:
email: 'user@example.com'
, (err, found) ->
expect(err).to.not.exist
expect(found).to.exist
expect(found.google).to.eql profile.sub
expect(found.firstName).to.eql profile.given_name
expect(found.lastName).to.eql profile.family_name
expect(found.gender).to.eql profile.gender
done err
| 199384 | expect = require('chai').expect
loopback = require 'loopback'
nock = require 'nock'
request = require 'supertest'
component = require '../lib/index.js'
describe 'Google module', ->
app = null
agent = null
Account = null
beforeEach ->
app = require '../example/server/server.js'
app.datasources.db.automigrate()
agent = request app
Account = app.models.Account
it 'should populate model', ->
expect(Account).to.exist
expect(Account.google).to.exist
describe 'call to loopback method', ->
first = null
second = null
answer = null
profile =
sub: 'profile_id'
email: '<EMAIL>'
given_name: 'my_first_name'
family_name: 'my_last_name'
birthday: new Date()
gender: 'male'
beforeEach ->
first = nock 'https://accounts.google.com'
.post '/o/oauth2/token',
code: 'this_is_a_code'
client_id: 'this_is_a_client_id'
client_secret: 'this_is_a_private_key'
redirect_uri: 'this_is_the_uri'
grant_type: 'authorization_code'
.reply 200,
token:
token: '<PASSWORD>'
beforeEach ->
second = nock 'https://www.googleapis.com'
.get '/plus/v1/people/me/openIdConnect'
.reply 200, profile
describe 'with post verb', ->
beforeEach (done) ->
agent.post '/api/accounts/google'
.send
code: 'this_is_a_code'
clientId: 'this_is_a_client_id'
redirectUri: 'this_is_the_uri'
.end (err, res) ->
answer =
err: err
res: res
done()
it 'should call google twice and return profile', ->
expect(first.isDone()).to.eql true
expect(second.isDone()).to.eql true
it 'should return a token', ->
expect(answer.err).to.not.exist
expect(answer.res.statusCode).to.eql 200
expect(answer.res.body).to.have.property 'id'
expect(answer.res.body).to.have.property 'userId'
# Allow satellizer to store its token
expect(answer.res.body).to.have.property 'token'
expect(answer.res.body).to.have.property 'ttl'
it 'should create the account', (done) ->
app.models.Account.count email: '<EMAIL>', (err, nb) ->
expect(err).to.not.exist
expect(nb).to.eql 1
done err
it 'should map the profile in the account', (done) ->
app.models.Account.findOne
where:
email: '<EMAIL>'
, (err, found) ->
expect(err).to.not.exist
expect(found).to.exist
expect(found.google).to.eql profile.sub
expect(found.firstName).to.eql profile.given_name
expect(found.lastName).to.eql profile.family_name
expect(found.gender).to.eql profile.gender
done err
describe 'with get verb', ->
beforeEach (done) ->
agent.get '/api/accounts/google'
.query
code: 'this_is_a_code'
.end (err, res) ->
answer =
err: err
res: res
done()
it 'should call google twice and return profile', ->
expect(first.isDone()).to.eql true
expect(second.isDone()).to.eql true
it 'should return a token', ->
expect(answer.err).to.not.exist
expect(answer.res.statusCode).to.eql 200
expect(answer.res.body).to.have.property 'id'
expect(answer.res.body).to.have.property 'userId'
# Allow satellizer to store its token
expect(answer.res.body).to.have.property 'token'
expect(answer.res.body).to.have.property 'ttl'
it 'should create the account', (done) ->
app.models.Account.count email: '<EMAIL>', (err, nb) ->
expect(err).to.not.exist
expect(nb).to.eql 1
done err
it 'should map the profile in the account', (done) ->
app.models.Account.findOne
where:
email: '<EMAIL>'
, (err, found) ->
expect(err).to.not.exist
expect(found).to.exist
expect(found.google).to.eql profile.sub
expect(found.firstName).to.eql profile.given_name
expect(found.lastName).to.eql profile.family_name
expect(found.gender).to.eql profile.gender
done err
| true | expect = require('chai').expect
loopback = require 'loopback'
nock = require 'nock'
request = require 'supertest'
component = require '../lib/index.js'
describe 'Google module', ->
app = null
agent = null
Account = null
beforeEach ->
app = require '../example/server/server.js'
app.datasources.db.automigrate()
agent = request app
Account = app.models.Account
it 'should populate model', ->
expect(Account).to.exist
expect(Account.google).to.exist
describe 'call to loopback method', ->
first = null
second = null
answer = null
profile =
sub: 'profile_id'
email: 'PI:EMAIL:<EMAIL>END_PI'
given_name: 'my_first_name'
family_name: 'my_last_name'
birthday: new Date()
gender: 'male'
beforeEach ->
first = nock 'https://accounts.google.com'
.post '/o/oauth2/token',
code: 'this_is_a_code'
client_id: 'this_is_a_client_id'
client_secret: 'this_is_a_private_key'
redirect_uri: 'this_is_the_uri'
grant_type: 'authorization_code'
.reply 200,
token:
token: 'PI:PASSWORD:<PASSWORD>END_PI'
beforeEach ->
second = nock 'https://www.googleapis.com'
.get '/plus/v1/people/me/openIdConnect'
.reply 200, profile
describe 'with post verb', ->
beforeEach (done) ->
agent.post '/api/accounts/google'
.send
code: 'this_is_a_code'
clientId: 'this_is_a_client_id'
redirectUri: 'this_is_the_uri'
.end (err, res) ->
answer =
err: err
res: res
done()
it 'should call google twice and return profile', ->
expect(first.isDone()).to.eql true
expect(second.isDone()).to.eql true
it 'should return a token', ->
expect(answer.err).to.not.exist
expect(answer.res.statusCode).to.eql 200
expect(answer.res.body).to.have.property 'id'
expect(answer.res.body).to.have.property 'userId'
# Allow satellizer to store its token
expect(answer.res.body).to.have.property 'token'
expect(answer.res.body).to.have.property 'ttl'
it 'should create the account', (done) ->
app.models.Account.count email: 'PI:EMAIL:<EMAIL>END_PI', (err, nb) ->
expect(err).to.not.exist
expect(nb).to.eql 1
done err
it 'should map the profile in the account', (done) ->
app.models.Account.findOne
where:
email: 'PI:EMAIL:<EMAIL>END_PI'
, (err, found) ->
expect(err).to.not.exist
expect(found).to.exist
expect(found.google).to.eql profile.sub
expect(found.firstName).to.eql profile.given_name
expect(found.lastName).to.eql profile.family_name
expect(found.gender).to.eql profile.gender
done err
describe 'with get verb', ->
beforeEach (done) ->
agent.get '/api/accounts/google'
.query
code: 'this_is_a_code'
.end (err, res) ->
answer =
err: err
res: res
done()
it 'should call google twice and return profile', ->
expect(first.isDone()).to.eql true
expect(second.isDone()).to.eql true
it 'should return a token', ->
expect(answer.err).to.not.exist
expect(answer.res.statusCode).to.eql 200
expect(answer.res.body).to.have.property 'id'
expect(answer.res.body).to.have.property 'userId'
# Allow satellizer to store its token
expect(answer.res.body).to.have.property 'token'
expect(answer.res.body).to.have.property 'ttl'
it 'should create the account', (done) ->
app.models.Account.count email: 'PI:EMAIL:<EMAIL>END_PI', (err, nb) ->
expect(err).to.not.exist
expect(nb).to.eql 1
done err
it 'should map the profile in the account', (done) ->
app.models.Account.findOne
where:
email: 'PI:EMAIL:<EMAIL>END_PI'
, (err, found) ->
expect(err).to.not.exist
expect(found).to.exist
expect(found.google).to.eql profile.sub
expect(found.firstName).to.eql profile.given_name
expect(found.lastName).to.eql profile.family_name
expect(found.gender).to.eql profile.gender
done err
|
[
{
"context": ".env.HUBOT_ZENDESK_USER}\"\n zendesk_password = \"#{process.env.HUBOT_ZENDESK_PASSWORD}\"\n auth = new Buffer(\"#{zendesk_user}:#{zendesk_",
"end": 2505,
"score": 0.9038053750991821,
"start": 2471,
"tag": "PASSWORD",
"value": "process.env.HUBOT_ZENDESK_PASSWORD"
},
{
... | scripts/zendesk.coffee | AdeTheux/hubot-slack | 0 | # Description:
# Queries Zendesk for information about support tickets
#
# Configuration:
# HUBOT_ZENDESK_USER
# HUBOT_ZENDESK_PASSWORD
# HUBOT_ZENDESK_SUBDOMAIN
#
# Commands:
# nestor zd (all) tickets - returns the total count of all unsolved tickets. The 'all' keyword is optional.
# nestor zd new tickets - returns the count of all new (unassigned) tickets
# nestor zd open tickets - returns the count of all open tickets
# nestor zd sc tickets - returns a count of tickets with pre-sales tag that are open or pending
# nestor zd ps tickets - returns a count of tickets with services tag that are open or pending
# nestor zd mentor tickets - returns a count of tickets with mentor tag that are open or pending
# nestor zd list new tickets - returns a list of all new tickets
# nestor zd list sla - returns a list of all unresolved tickets which breached the SLA
# nestor zd ticket <ID> - returns information about the specified ticket
tickets_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/tickets"
queries =
unsolved: "search.json?query=status<solved+type:ticket"
open: "search.json?query=status:open+type:ticket"
new: "search.json?query=status:new+type:ticket"
sc: "search.json?query=tags:pre_sales+status:new"
ps: "search.json?query=tags:services+status:new"
mentor: "search.json?query=tags:mentor_program+status:new"
sla: "search.json?query=tags:sla_frt_breached"
tickets: "tickets"
users: "users"
zendesk_request = (msg, url, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{process.env.HUBOT_ZENDESK_PASSWORD}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "Computer says no. And Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Computer says no. And Zendesk says: #{content.error.title}"
else
msg.send "Computer says no. And Zendesk says: #{content.error}"
return
handler content
zendesk_update_request = (msg, url, data, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{process.env.HUBOT_ZENDESK_PASSWORD}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json", "Content-Type": "application/json")
.put(JSON.stringify(data)) (err, res, body) ->
if err
msg.send "Computer says no. And Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Computer says no. And Zendesk says: #{content.error.title}"
else
msg.send "Computer says no. And Zendesk says: #{content.error}"
return
handler content
# FIXME this works about as well as a brick floats
zendesk_user = (msg, user_id) ->
zendesk_request msg, "#{queries.users}/#{user_id}.json", (result) ->
if result.error
msg.send result.description
return
result.user
agents_ids = {
"arnaud": {id:344486768, group_id:24037689},
"nils": {id:279394212, group_id:24037689},
"rav": {id:331018109, group_id:24102225},
"henry": {id:348572907, group_id:24102225},
"julie": {id:349371159, group_id:24037689},
"treasa": {id:428783569, group_id:20381087},
"bjorn": {id:435353326, group_id:24037689},
"andrey": {id:447259378, group_id:20381087},
"vlad": {id:462825616, group_id:20381087},
"sandra": {id:630250763, group_id:24037689},
"emilie": {id:686659115, group_id:24102225},
"lynne": {id:708210468, group_id:24102225},
"romain": {id:711930369, group_id:24037689},
"sofyan": {id:926668299, group_id:20381087},
"dan": {id:1082164175, group_id:20381087},
"klaus": {id:1154776105, group_id:20381087},
"frank": {id:1504381155, group_id:20381087}
}
module.exports = (robot) ->
robot.respond /(?:zd)? assign ticket ([0-9]+) to ([a-zA-Z]+)$/i, (msg) ->
ticket_id = msg.match[1]
agent = msg.match[2]
agent_details = agents_ids[agent]
if not agent_details
msg.send "#{agent} unknown :weary:"
return
data = {
ticket: {
assignee_id: agent_details.id,
group_id: agent_details.group_id
}
}
zendesk_update_request msg, "tickets/#{ticket_id}.json", data, (content) ->
msg.send "Ticket #{ticket_id} is now assigned to @#{agent}"
robot.respond /(?:zd) (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /(?:zd) new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} new tickets"
robot.respond /(?:zd) sc tickets$/i, (msg) ->
zendesk_request msg, queries.sc, (results) ->
ticket_count = results.count
msg.send ":moneybag: #{ticket_count} new tickets in Solutions Consulting queue"
robot.respond /(?:zd) ps tickets$/i, (msg) ->
zendesk_request msg, queries.ps, (results) ->
ticket_count = results.count
msg.send ":wrench: #{ticket_count} new tickets in Launch (Services) queue"
robot.respond /(?:zd) mentor tickets$/i, (msg) ->
zendesk_request msg, queries.success, (results) ->
ticket_count = results.count
msg.send ":couple_with_heart: #{ticket_count} new tickets in Mentor queue"
robot.respond /(?:zd) open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} open tickets"
robot.respond /(?:zd) list (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) list new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) list sla$/i, (msg) ->
zendesk_request msg, queries.sc, (results) ->
ticket_count = results.count
msg.send ":rotating_light: #{ticket_count} tickets currently breaching our SLA"
robot.respond /(?:zd) list open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) ticket ([\d]+)$/i, (msg) ->
ticket_id = msg.match[1]
zendesk_request msg, "#{queries.tickets}/#{ticket_id}.json", (result) ->
if result.error
msg.send result.description
return
message = ":ticket: #{tickets_url}/#{result.ticket.id} ##{result.ticket.id} (#{result.ticket.status.toUpperCase()})"
message += "\n>By: #{result.ticket.author_id}"
message += "\n>Created: #{result.ticket.created_at}"
message += "\n>"
message += "\n>#{result.ticket.description}"
msg.send message | 224016 | # Description:
# Queries Zendesk for information about support tickets
#
# Configuration:
# HUBOT_ZENDESK_USER
# HUBOT_ZENDESK_PASSWORD
# HUBOT_ZENDESK_SUBDOMAIN
#
# Commands:
# nestor zd (all) tickets - returns the total count of all unsolved tickets. The 'all' keyword is optional.
# nestor zd new tickets - returns the count of all new (unassigned) tickets
# nestor zd open tickets - returns the count of all open tickets
# nestor zd sc tickets - returns a count of tickets with pre-sales tag that are open or pending
# nestor zd ps tickets - returns a count of tickets with services tag that are open or pending
# nestor zd mentor tickets - returns a count of tickets with mentor tag that are open or pending
# nestor zd list new tickets - returns a list of all new tickets
# nestor zd list sla - returns a list of all unresolved tickets which breached the SLA
# nestor zd ticket <ID> - returns information about the specified ticket
tickets_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/tickets"
queries =
unsolved: "search.json?query=status<solved+type:ticket"
open: "search.json?query=status:open+type:ticket"
new: "search.json?query=status:new+type:ticket"
sc: "search.json?query=tags:pre_sales+status:new"
ps: "search.json?query=tags:services+status:new"
mentor: "search.json?query=tags:mentor_program+status:new"
sla: "search.json?query=tags:sla_frt_breached"
tickets: "tickets"
users: "users"
zendesk_request = (msg, url, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{process.env.HUBOT_ZENDESK_PASSWORD}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "Computer says no. And Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Computer says no. And Zendesk says: #{content.error.title}"
else
msg.send "Computer says no. And Zendesk says: #{content.error}"
return
handler content
zendesk_update_request = (msg, url, data, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{<PASSWORD>}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json", "Content-Type": "application/json")
.put(JSON.stringify(data)) (err, res, body) ->
if err
msg.send "Computer says no. And Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Computer says no. And Zendesk says: #{content.error.title}"
else
msg.send "Computer says no. And Zendesk says: #{content.error}"
return
handler content
# FIXME this works about as well as a brick floats
zendesk_user = (msg, user_id) ->
zendesk_request msg, "#{queries.users}/#{user_id}.json", (result) ->
if result.error
msg.send result.description
return
result.user
agents_ids = {
"<NAME>": {id:344486768, group_id:24037689},
"<NAME>": {id:279394212, group_id:24037689},
"<NAME>": {id:331018109, group_id:24102225},
"<NAME>": {id:348572907, group_id:24102225},
"<NAME>": {id:349371159, group_id:24037689},
"<NAME>": {id:428783569, group_id:20381087},
"<NAME>": {id:435353326, group_id:24037689},
"<NAME>": {id:447259378, group_id:20381087},
"<NAME>": {id:462825616, group_id:20381087},
"<NAME>": {id:630250763, group_id:24037689},
"<NAME>": {id:686659115, group_id:24102225},
"<NAME>": {id:708210468, group_id:24102225},
"<NAME>": {id:711930369, group_id:24037689},
"<NAME>": {id:926668299, group_id:20381087},
"<NAME>": {id:1082164175, group_id:20381087},
"<NAME>": {id:1154776105, group_id:20381087},
"frank": {id:1504381155, group_id:20381087}
}
module.exports = (robot) ->
robot.respond /(?:zd)? assign ticket ([0-9]+) to ([a-zA-Z]+)$/i, (msg) ->
ticket_id = msg.match[1]
agent = msg.match[2]
agent_details = agents_ids[agent]
if not agent_details
msg.send "#{agent} unknown :weary:"
return
data = {
ticket: {
assignee_id: agent_details.id,
group_id: agent_details.group_id
}
}
zendesk_update_request msg, "tickets/#{ticket_id}.json", data, (content) ->
msg.send "Ticket #{ticket_id} is now assigned to @#{agent}"
robot.respond /(?:zd) (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /(?:zd) new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} new tickets"
robot.respond /(?:zd) sc tickets$/i, (msg) ->
zendesk_request msg, queries.sc, (results) ->
ticket_count = results.count
msg.send ":moneybag: #{ticket_count} new tickets in Solutions Consulting queue"
robot.respond /(?:zd) ps tickets$/i, (msg) ->
zendesk_request msg, queries.ps, (results) ->
ticket_count = results.count
msg.send ":wrench: #{ticket_count} new tickets in Launch (Services) queue"
robot.respond /(?:zd) mentor tickets$/i, (msg) ->
zendesk_request msg, queries.success, (results) ->
ticket_count = results.count
msg.send ":couple_with_heart: #{ticket_count} new tickets in Mentor queue"
robot.respond /(?:zd) open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} open tickets"
robot.respond /(?:zd) list (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) list new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) list sla$/i, (msg) ->
zendesk_request msg, queries.sc, (results) ->
ticket_count = results.count
msg.send ":rotating_light: #{ticket_count} tickets currently breaching our SLA"
robot.respond /(?:zd) list open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) ticket ([\d]+)$/i, (msg) ->
ticket_id = msg.match[1]
zendesk_request msg, "#{queries.tickets}/#{ticket_id}.json", (result) ->
if result.error
msg.send result.description
return
message = ":ticket: #{tickets_url}/#{result.ticket.id} ##{result.ticket.id} (#{result.ticket.status.toUpperCase()})"
message += "\n>By: #{result.ticket.author_id}"
message += "\n>Created: #{result.ticket.created_at}"
message += "\n>"
message += "\n>#{result.ticket.description}"
msg.send message | true | # Description:
# Queries Zendesk for information about support tickets
#
# Configuration:
# HUBOT_ZENDESK_USER
# HUBOT_ZENDESK_PASSWORD
# HUBOT_ZENDESK_SUBDOMAIN
#
# Commands:
# nestor zd (all) tickets - returns the total count of all unsolved tickets. The 'all' keyword is optional.
# nestor zd new tickets - returns the count of all new (unassigned) tickets
# nestor zd open tickets - returns the count of all open tickets
# nestor zd sc tickets - returns a count of tickets with pre-sales tag that are open or pending
# nestor zd ps tickets - returns a count of tickets with services tag that are open or pending
# nestor zd mentor tickets - returns a count of tickets with mentor tag that are open or pending
# nestor zd list new tickets - returns a list of all new tickets
# nestor zd list sla - returns a list of all unresolved tickets which breached the SLA
# nestor zd ticket <ID> - returns information about the specified ticket
tickets_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/tickets"
queries =
unsolved: "search.json?query=status<solved+type:ticket"
open: "search.json?query=status:open+type:ticket"
new: "search.json?query=status:new+type:ticket"
sc: "search.json?query=tags:pre_sales+status:new"
ps: "search.json?query=tags:services+status:new"
mentor: "search.json?query=tags:mentor_program+status:new"
sla: "search.json?query=tags:sla_frt_breached"
tickets: "tickets"
users: "users"
zendesk_request = (msg, url, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{process.env.HUBOT_ZENDESK_PASSWORD}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json")
.get() (err, res, body) ->
if err
msg.send "Computer says no. And Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Computer says no. And Zendesk says: #{content.error.title}"
else
msg.send "Computer says no. And Zendesk says: #{content.error}"
return
handler content
zendesk_update_request = (msg, url, data, handler) ->
zendesk_user = "#{process.env.HUBOT_ZENDESK_USER}"
zendesk_password = "#{PI:PASSWORD:<PASSWORD>END_PI}"
auth = new Buffer("#{zendesk_user}:#{zendesk_password}").toString('base64')
zendesk_url = "https://#{process.env.HUBOT_ZENDESK_SUBDOMAIN}.zendesk.com/api/v2"
msg.http("#{zendesk_url}/#{url}")
.headers(Authorization: "Basic #{auth}", Accept: "application/json", "Content-Type": "application/json")
.put(JSON.stringify(data)) (err, res, body) ->
if err
msg.send "Computer says no. And Zendesk says: #{err}"
return
content = JSON.parse(body)
if content.error?
if content.error?.title
msg.send "Computer says no. And Zendesk says: #{content.error.title}"
else
msg.send "Computer says no. And Zendesk says: #{content.error}"
return
handler content
# FIXME this works about as well as a brick floats
zendesk_user = (msg, user_id) ->
zendesk_request msg, "#{queries.users}/#{user_id}.json", (result) ->
if result.error
msg.send result.description
return
result.user
agents_ids = {
"PI:NAME:<NAME>END_PI": {id:344486768, group_id:24037689},
"PI:NAME:<NAME>END_PI": {id:279394212, group_id:24037689},
"PI:NAME:<NAME>END_PI": {id:331018109, group_id:24102225},
"PI:NAME:<NAME>END_PI": {id:348572907, group_id:24102225},
"PI:NAME:<NAME>END_PI": {id:349371159, group_id:24037689},
"PI:NAME:<NAME>END_PI": {id:428783569, group_id:20381087},
"PI:NAME:<NAME>END_PI": {id:435353326, group_id:24037689},
"PI:NAME:<NAME>END_PI": {id:447259378, group_id:20381087},
"PI:NAME:<NAME>END_PI": {id:462825616, group_id:20381087},
"PI:NAME:<NAME>END_PI": {id:630250763, group_id:24037689},
"PI:NAME:<NAME>END_PI": {id:686659115, group_id:24102225},
"PI:NAME:<NAME>END_PI": {id:708210468, group_id:24102225},
"PI:NAME:<NAME>END_PI": {id:711930369, group_id:24037689},
"PI:NAME:<NAME>END_PI": {id:926668299, group_id:20381087},
"PI:NAME:<NAME>END_PI": {id:1082164175, group_id:20381087},
"PI:NAME:<NAME>END_PI": {id:1154776105, group_id:20381087},
"frank": {id:1504381155, group_id:20381087}
}
module.exports = (robot) ->
robot.respond /(?:zd)? assign ticket ([0-9]+) to ([a-zA-Z]+)$/i, (msg) ->
ticket_id = msg.match[1]
agent = msg.match[2]
agent_details = agents_ids[agent]
if not agent_details
msg.send "#{agent} unknown :weary:"
return
data = {
ticket: {
assignee_id: agent_details.id,
group_id: agent_details.group_id
}
}
zendesk_update_request msg, "tickets/#{ticket_id}.json", data, (content) ->
msg.send "Ticket #{ticket_id} is now assigned to @#{agent}"
robot.respond /(?:zd) (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} unsolved tickets"
robot.respond /(?:zd) new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} new tickets"
robot.respond /(?:zd) sc tickets$/i, (msg) ->
zendesk_request msg, queries.sc, (results) ->
ticket_count = results.count
msg.send ":moneybag: #{ticket_count} new tickets in Solutions Consulting queue"
robot.respond /(?:zd) ps tickets$/i, (msg) ->
zendesk_request msg, queries.ps, (results) ->
ticket_count = results.count
msg.send ":wrench: #{ticket_count} new tickets in Launch (Services) queue"
robot.respond /(?:zd) mentor tickets$/i, (msg) ->
zendesk_request msg, queries.success, (results) ->
ticket_count = results.count
msg.send ":couple_with_heart: #{ticket_count} new tickets in Mentor queue"
robot.respond /(?:zd) open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
ticket_count = results.count
msg.send "#{ticket_count} open tickets"
robot.respond /(?:zd) list (all )?tickets$/i, (msg) ->
zendesk_request msg, queries.unsolved, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) list new tickets$/i, (msg) ->
zendesk_request msg, queries.new, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) list sla$/i, (msg) ->
zendesk_request msg, queries.sc, (results) ->
ticket_count = results.count
msg.send ":rotating_light: #{ticket_count} tickets currently breaching our SLA"
robot.respond /(?:zd) list open tickets$/i, (msg) ->
zendesk_request msg, queries.open, (results) ->
for result in results.results
msg.send "Ticket #{result.id} is #{result.status}: #{tickets_url}/#{result.id}"
robot.respond /(?:zd) ticket ([\d]+)$/i, (msg) ->
ticket_id = msg.match[1]
zendesk_request msg, "#{queries.tickets}/#{ticket_id}.json", (result) ->
if result.error
msg.send result.description
return
message = ":ticket: #{tickets_url}/#{result.ticket.id} ##{result.ticket.id} (#{result.ticket.status.toUpperCase()})"
message += "\n>By: #{result.ticket.author_id}"
message += "\n>Created: #{result.ticket.created_at}"
message += "\n>"
message += "\n>#{result.ticket.description}"
msg.send message |
[
{
"context": "nd\n viewParams =\n startkey: [docId, start]\n endkey: [docId, end]\n ",
"end": 720,
"score": 0.7757365703582764,
"start": 718,
"tag": "KEY",
"value": "Id"
},
{
"context": " startkey: [docId, start]\n endkey: [docId, end]\n... | src/server/ot/operation_couch_processor.coffee | LaPingvino/rizzoma | 88 | CouchProcessor = require('../common/db/couch_processor').CouchProcessor
OperationCouchConverter = require('./operation_couch_converter').OperationCouchConverter
delimiter = require('../conf').Conf.getGeneratorConf()['delimiter']
IdUtils = require('../utils/id_utils').IdUtils
OPERATION_TYPE = require('./constants').OPERATION_TYPE
class OperationCouchProcessor extends CouchProcessor
###
Процессор операций.
###
constructor: () ->
super('operations')
@converter = OperationCouchConverter
@_cache = @_conf.getCache('op')
getByDocId: (docId, start, end=@PLUS_INF, callback) ->
return callback(null, []) if start == end
viewParams =
startkey: [docId, start]
endkey: [docId, end]
@viewWithIncludeDocs('ot_1/ot_operations', viewParams, callback)
getOpRange: (docId, start, end, callback) ->
###
Возвращает массив моделей операции по имени документа
к которому эти операции были применены.
@param docId: string
@param start: int
@param end: int
@param callback: function
###
return callback(null, []) if start == end
ids = (@_getOpId(docId, version) for version in [start...end])
@getByIds(ids, callback)
getOpRangeForMultipleDocs: (ranges, callback) ->
ids = []
for own docId, range of ranges
[start, end] = range
continue if start == end
ids.push((@_getOpId(docId, version) for version in [start...end])...)
@getByIds(ids, callback)
save: (model, callback) ->
model.setId()
super(model, callback)
_getOpId: (docId, version) ->
###
Получает из id документа и версии id операции
@param docId: string
@param version: int
###
parsedId = IdUtils.parseId(docId)
parts = [parsedId.prefix, OPERATION_TYPE]
parts.push(parsedId.extensions) if parsedId.extensions
parts.push(parsedId.id)
parts.push(version)
return parts.join(delimiter)
module.exports.OperationCouchProcessor = new OperationCouchProcessor()
| 129574 | CouchProcessor = require('../common/db/couch_processor').CouchProcessor
OperationCouchConverter = require('./operation_couch_converter').OperationCouchConverter
delimiter = require('../conf').Conf.getGeneratorConf()['delimiter']
IdUtils = require('../utils/id_utils').IdUtils
OPERATION_TYPE = require('./constants').OPERATION_TYPE
class OperationCouchProcessor extends CouchProcessor
###
Процессор операций.
###
constructor: () ->
super('operations')
@converter = OperationCouchConverter
@_cache = @_conf.getCache('op')
getByDocId: (docId, start, end=@PLUS_INF, callback) ->
return callback(null, []) if start == end
viewParams =
startkey: [doc<KEY>, start]
endkey: [doc<KEY>, end]
@viewWithIncludeDocs('ot_1/ot_operations', viewParams, callback)
getOpRange: (docId, start, end, callback) ->
###
Возвращает массив моделей операции по имени документа
к которому эти операции были применены.
@param docId: string
@param start: int
@param end: int
@param callback: function
###
return callback(null, []) if start == end
ids = (@_getOpId(docId, version) for version in [start...end])
@getByIds(ids, callback)
getOpRangeForMultipleDocs: (ranges, callback) ->
ids = []
for own docId, range of ranges
[start, end] = range
continue if start == end
ids.push((@_getOpId(docId, version) for version in [start...end])...)
@getByIds(ids, callback)
save: (model, callback) ->
model.setId()
super(model, callback)
_getOpId: (docId, version) ->
###
Получает из id документа и версии id операции
@param docId: string
@param version: int
###
parsedId = IdUtils.parseId(docId)
parts = [parsedId.prefix, OPERATION_TYPE]
parts.push(parsedId.extensions) if parsedId.extensions
parts.push(parsedId.id)
parts.push(version)
return parts.join(delimiter)
module.exports.OperationCouchProcessor = new OperationCouchProcessor()
| true | CouchProcessor = require('../common/db/couch_processor').CouchProcessor
OperationCouchConverter = require('./operation_couch_converter').OperationCouchConverter
delimiter = require('../conf').Conf.getGeneratorConf()['delimiter']
IdUtils = require('../utils/id_utils').IdUtils
OPERATION_TYPE = require('./constants').OPERATION_TYPE
class OperationCouchProcessor extends CouchProcessor
###
Процессор операций.
###
constructor: () ->
super('operations')
@converter = OperationCouchConverter
@_cache = @_conf.getCache('op')
getByDocId: (docId, start, end=@PLUS_INF, callback) ->
return callback(null, []) if start == end
viewParams =
startkey: [docPI:KEY:<KEY>END_PI, start]
endkey: [docPI:KEY:<KEY>END_PI, end]
@viewWithIncludeDocs('ot_1/ot_operations', viewParams, callback)
getOpRange: (docId, start, end, callback) ->
###
Возвращает массив моделей операции по имени документа
к которому эти операции были применены.
@param docId: string
@param start: int
@param end: int
@param callback: function
###
return callback(null, []) if start == end
ids = (@_getOpId(docId, version) for version in [start...end])
@getByIds(ids, callback)
getOpRangeForMultipleDocs: (ranges, callback) ->
ids = []
for own docId, range of ranges
[start, end] = range
continue if start == end
ids.push((@_getOpId(docId, version) for version in [start...end])...)
@getByIds(ids, callback)
save: (model, callback) ->
model.setId()
super(model, callback)
_getOpId: (docId, version) ->
###
Получает из id документа и версии id операции
@param docId: string
@param version: int
###
parsedId = IdUtils.parseId(docId)
parts = [parsedId.prefix, OPERATION_TYPE]
parts.push(parsedId.extensions) if parsedId.extensions
parts.push(parsedId.id)
parts.push(version)
return parts.join(delimiter)
module.exports.OperationCouchProcessor = new OperationCouchProcessor()
|
[
{
"context": "\n\t\tname: \"strawberry\"\n\t\tprice: 520\n\t}\n\t{\n\t\tname: \"persimmon\"\n\t\tprice: 490\n\t}\n\t{\n\t\tname: \"kiwi\"\n\t\tprice: 320\n\t",
"end": 216,
"score": 0.7390801310539246,
"start": 207,
"tag": "NAME",
"value": "persimmon"
}
] | ch04/03-data-format/test.cson | gogosub77/node-webscraping | 0 | title: "Fruits Database"
version: 2.13
items: [
{
name: "Tomato"
price: 300
}
{
name: "Banana"
price: 170
}
{
name: "Apple"
price: 210
}
{
name: "strawberry"
price: 520
}
{
name: "persimmon"
price: 490
}
{
name: "kiwi"
price: 320
}
]
| 110863 | title: "Fruits Database"
version: 2.13
items: [
{
name: "Tomato"
price: 300
}
{
name: "Banana"
price: 170
}
{
name: "Apple"
price: 210
}
{
name: "strawberry"
price: 520
}
{
name: "<NAME>"
price: 490
}
{
name: "kiwi"
price: 320
}
]
| true | title: "Fruits Database"
version: 2.13
items: [
{
name: "Tomato"
price: 300
}
{
name: "Banana"
price: 170
}
{
name: "Apple"
price: 210
}
{
name: "strawberry"
price: 520
}
{
name: "PI:NAME:<NAME>END_PI"
price: 490
}
{
name: "kiwi"
price: 320
}
]
|
[
{
"context": ".io'\n tokens:\n access_token: 'random'\n agentOptions: {}\n\n nock(instanc",
"end": 1506,
"score": 0.6226891279220581,
"start": 1500,
"tag": "KEY",
"value": "random"
},
{
"context": "stance)('authority', 'realm', {\n token: ... | test/rest/userRolesSpec.coffee | camfou/connect-nodejs | 0 | # Test dependencies
cwd = process.cwd()
path = require 'path'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
nock = require 'nock'
# Assertions
chai.use sinonChai
chai.should()
userRoles = require path.join(cwd, 'rest', 'userRoles')
describe 'REST API User Role Methods', ->
describe 'listRoles', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.get('/v1/users/authority/roles')
.reply(200, [{name: 'realm'}])
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.listRoles.bind(instance)('authority', {
token: 'token'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the roles', ->
success.should.have.been.calledWith sinon.match [{name:'realm'}]
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: 'random'
agentOptions: {}
nock(instance.configuration.issuer)
.get('/v1/users/authority/roles')
.reply(404, 'Not found')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.listRoles.bind(instance)('authority')
.then(success, failure)
after ->
nock.cleanAll()
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the roles', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
describe 'add', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.put('/v1/users/authority/roles/realm')
.reply(201, {
added: true
})
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.addRole.bind(instance)('authority', 'realm', {
token: 'token'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the role', ->
success.should.have.been.calledWith sinon.match { added: true }
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: 'random'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.put('/v1/users/invalid/roles/addition')
.reply(400, 'Bad request')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.addRole.bind(instance)('invalid', 'addition', {
token: 'token'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the role', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
describe 'delete', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: 'random'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.delete('/v1/users/authority/roles/realm')
.reply(204)
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.deleteRole.bind(instance)('authority', 'realm', {
token: 'token'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the role', ->
success.should.have.been.called
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: 'random'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.delete('/v1/users/invalid/roles/deletion')
.reply(404, 'Not found')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.deleteRole.bind(instance)('invalid', 'deletion', {
token: 'token'
}).then(success, failure)
after ->
nock.cleanAll()
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the role', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
| 187702 | # Test dependencies
cwd = process.cwd()
path = require 'path'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
nock = require 'nock'
# Assertions
chai.use sinonChai
chai.should()
userRoles = require path.join(cwd, 'rest', 'userRoles')
describe 'REST API User Role Methods', ->
describe 'listRoles', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.get('/v1/users/authority/roles')
.reply(200, [{name: 'realm'}])
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.listRoles.bind(instance)('authority', {
token: 'token'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the roles', ->
success.should.have.been.calledWith sinon.match [{name:'realm'}]
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: '<KEY>'
agentOptions: {}
nock(instance.configuration.issuer)
.get('/v1/users/authority/roles')
.reply(404, 'Not found')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.listRoles.bind(instance)('authority')
.then(success, failure)
after ->
nock.cleanAll()
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the roles', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
describe 'add', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.put('/v1/users/authority/roles/realm')
.reply(201, {
added: true
})
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.addRole.bind(instance)('authority', 'realm', {
token: '<KEY>'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the role', ->
success.should.have.been.calledWith sinon.match { added: true }
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: '<KEY>'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.put('/v1/users/invalid/roles/addition')
.reply(400, 'Bad request')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.addRole.bind(instance)('invalid', 'addition', {
token: '<KEY>'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the role', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
describe 'delete', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: '<KEY>'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.delete('/v1/users/authority/roles/realm')
.reply(204)
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.deleteRole.bind(instance)('authority', 'realm', {
token: 'token'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the role', ->
success.should.have.been.called
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: '<KEY>'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.delete('/v1/users/invalid/roles/deletion')
.reply(404, 'Not found')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.deleteRole.bind(instance)('invalid', 'deletion', {
token: 'token'
}).then(success, failure)
after ->
nock.cleanAll()
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the role', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
| true | # Test dependencies
cwd = process.cwd()
path = require 'path'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
nock = require 'nock'
# Assertions
chai.use sinonChai
chai.should()
userRoles = require path.join(cwd, 'rest', 'userRoles')
describe 'REST API User Role Methods', ->
describe 'listRoles', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.get('/v1/users/authority/roles')
.reply(200, [{name: 'realm'}])
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.listRoles.bind(instance)('authority', {
token: 'token'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the roles', ->
success.should.have.been.calledWith sinon.match [{name:'realm'}]
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: 'PI:KEY:<KEY>END_PI'
agentOptions: {}
nock(instance.configuration.issuer)
.get('/v1/users/authority/roles')
.reply(404, 'Not found')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.listRoles.bind(instance)('authority')
.then(success, failure)
after ->
nock.cleanAll()
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the roles', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
describe 'add', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.put('/v1/users/authority/roles/realm')
.reply(201, {
added: true
})
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.addRole.bind(instance)('authority', 'realm', {
token: 'PI:KEY:<KEY>END_PI'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the role', ->
success.should.have.been.calledWith sinon.match { added: true }
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: 'PI:KEY:<KEY>END_PI'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.put('/v1/users/invalid/roles/addition')
.reply(400, 'Bad request')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.addRole.bind(instance)('invalid', 'addition', {
token: 'PI:KEY:<KEY>END_PI'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the role', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
describe 'delete', ->
describe 'with a successful response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: 'PI:KEY:<KEY>END_PI'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.delete('/v1/users/authority/roles/realm')
.reply(204)
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.deleteRole.bind(instance)('authority', 'realm', {
token: 'token'
}).then(success, failure)
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should provide the role', ->
success.should.have.been.called
it 'should not catch an error', ->
failure.should.not.have.been.called
describe 'with a failure response', ->
{promise,success,failure} = {}
before () ->
instance =
configuration:
issuer: 'https://connect.anvil.io'
tokens:
access_token: 'PI:KEY:<KEY>END_PI'
agentOptions: {}
nock.cleanAll()
nock(instance.configuration.issuer)
.delete('/v1/users/invalid/roles/deletion')
.reply(404, 'Not found')
success = sinon.spy()
failure = sinon.spy()
promise = userRoles.deleteRole.bind(instance)('invalid', 'deletion', {
token: 'token'
}).then(success, failure)
after ->
nock.cleanAll()
it 'should return a promise', ->
promise.should.be.instanceof Promise
it 'should not provide the role', ->
success.should.not.have.been.called
it 'should catch an error', ->
failure.should.have.been.called
|
[
{
"context": "###\n\n Tyler Anderson 2011-2015\n\n###\n\nclass BinaryHeap\n constructor: (",
"end": 21,
"score": 0.9997606873512268,
"start": 7,
"tag": "NAME",
"value": "Tyler Anderson"
}
] | node_modules/binheap/binheap.coffee | justinoverton/fabrico-web | 0 | ###
Tyler Anderson 2011-2015
###
class BinaryHeap
constructor: (score_func) ->
@heap = []
@scoreFunction = score_func
push: (element) ->
@heap.push element
@sinkDown @heap.length - 1
true
pop: ->
result = @heap[0]
end = @heap.pop()
if @heap.length > 0
@heap[0] = end
@bubbleUp 0
result
remove: (node) ->
i = @heap.indexOf(node)
end = @heap.pop()
if i isnt @heap.length - 1
@heap[i] = end
if @scoreFunction(end) < @scoreFunction(node)
@sinkDown i
else
@bubbleUp i
true
size: ->
@heap.length
rescoreElement: (node) ->
@sinkDown @heap.indexOf(node)
sinkDown: (n) ->
element = @heap[n]
while n > 0
parentN = ((n + 1) >> 1) - 1
parent = @heap[parentN]
if @scoreFunction(element) < @scoreFunction(parent)
@heap[parentN] = element
@heap[n] = parent
n = parentN
true
else
break
true
bubbleUp: (n) ->
length = @heap.length
element = @heap[n]
elemScore = @scoreFunction(element)
loop
child2N = (n + 1) << 1
child1N = child2N - 1
swap = null
if child1N < length
child1 = @heap[child1N]
child1Score = @scoreFunction(child1)
swap = child1N if child1Score < elemScore
if child2N < length
child2 = @heap[child2N]
child2Score = @scoreFunction(child2)
swap = child2N if child2Score < (if swap is null then elemScore else child1Score)
if swap isnt null
@heap[n] = @heap[swap]
@heap[swap] = element
n = swap
true
else
break
true
module.exports = (score_function) ->
new BinaryHeap(score_function)
| 50479 | ###
<NAME> 2011-2015
###
class BinaryHeap
constructor: (score_func) ->
@heap = []
@scoreFunction = score_func
push: (element) ->
@heap.push element
@sinkDown @heap.length - 1
true
pop: ->
result = @heap[0]
end = @heap.pop()
if @heap.length > 0
@heap[0] = end
@bubbleUp 0
result
remove: (node) ->
i = @heap.indexOf(node)
end = @heap.pop()
if i isnt @heap.length - 1
@heap[i] = end
if @scoreFunction(end) < @scoreFunction(node)
@sinkDown i
else
@bubbleUp i
true
size: ->
@heap.length
rescoreElement: (node) ->
@sinkDown @heap.indexOf(node)
sinkDown: (n) ->
element = @heap[n]
while n > 0
parentN = ((n + 1) >> 1) - 1
parent = @heap[parentN]
if @scoreFunction(element) < @scoreFunction(parent)
@heap[parentN] = element
@heap[n] = parent
n = parentN
true
else
break
true
bubbleUp: (n) ->
length = @heap.length
element = @heap[n]
elemScore = @scoreFunction(element)
loop
child2N = (n + 1) << 1
child1N = child2N - 1
swap = null
if child1N < length
child1 = @heap[child1N]
child1Score = @scoreFunction(child1)
swap = child1N if child1Score < elemScore
if child2N < length
child2 = @heap[child2N]
child2Score = @scoreFunction(child2)
swap = child2N if child2Score < (if swap is null then elemScore else child1Score)
if swap isnt null
@heap[n] = @heap[swap]
@heap[swap] = element
n = swap
true
else
break
true
module.exports = (score_function) ->
new BinaryHeap(score_function)
| true | ###
PI:NAME:<NAME>END_PI 2011-2015
###
class BinaryHeap
constructor: (score_func) ->
@heap = []
@scoreFunction = score_func
push: (element) ->
@heap.push element
@sinkDown @heap.length - 1
true
pop: ->
result = @heap[0]
end = @heap.pop()
if @heap.length > 0
@heap[0] = end
@bubbleUp 0
result
remove: (node) ->
i = @heap.indexOf(node)
end = @heap.pop()
if i isnt @heap.length - 1
@heap[i] = end
if @scoreFunction(end) < @scoreFunction(node)
@sinkDown i
else
@bubbleUp i
true
size: ->
@heap.length
rescoreElement: (node) ->
@sinkDown @heap.indexOf(node)
sinkDown: (n) ->
element = @heap[n]
while n > 0
parentN = ((n + 1) >> 1) - 1
parent = @heap[parentN]
if @scoreFunction(element) < @scoreFunction(parent)
@heap[parentN] = element
@heap[n] = parent
n = parentN
true
else
break
true
bubbleUp: (n) ->
length = @heap.length
element = @heap[n]
elemScore = @scoreFunction(element)
loop
child2N = (n + 1) << 1
child1N = child2N - 1
swap = null
if child1N < length
child1 = @heap[child1N]
child1Score = @scoreFunction(child1)
swap = child1N if child1Score < elemScore
if child2N < length
child2 = @heap[child2N]
child2Score = @scoreFunction(child2)
swap = child2N if child2Score < (if swap is null then elemScore else child1Score)
if swap isnt null
@heap[n] = @heap[swap]
@heap[swap] = element
n = swap
true
else
break
true
module.exports = (score_function) ->
new BinaryHeap(score_function)
|
[
{
"context": "re('antigravity').fabricate('user', accessToken: 'footoken')\n )\n next()\n app.use \"/__gravity\", ",
"end": 4426,
"score": 0.6296706795692444,
"start": 4418,
"tag": "KEY",
"value": "footoken"
}
] | desktop/lib/setup.coffee | dblock/force | 0 | #
# Sets up intial project settings, middleware, mounted apps, and
# global configuration such as overriding Backbone.sync and
# populating sharify data
#
{
API_URL,
APP_URL,
NODE_ENV,
ARTSY_ID,
ARTSY_SECRET,
SESSION_SECRET,
SESSION_COOKIE_MAX_AGE,
MOBILE_URL,
DEFAULT_CACHE_TIME,
COOKIE_DOMAIN,
AUTO_GRAVITY_LOGIN,
SESSION_COOKIE_KEY,
API_REQUEST_TIMEOUT,
IP_BLACKLIST,
REQUEST_LIMIT,
REQUEST_EXPIRE_MS,
LOGGER_FORMAT,
OPENREDIS_URL
} = config = require "../config"
{ parse, format } = require 'url'
_ = require 'underscore'
express = require "express"
Backbone = require "backbone"
sharify = require "sharify"
http = require 'http'
path = require 'path'
cors = require 'cors'
artsyPassport = require 'artsy-passport'
artsyEigenWebAssociation = require 'artsy-eigen-web-association'
redirectMobile = require './middleware/redirect_mobile'
proxyGravity = require './middleware/proxy_to_gravity'
proxyReflection = require './middleware/proxy_to_reflection'
proxyToMerged = require './middleware/proxy_to_merged'
localsMiddleware = require './middleware/locals'
ensureSSL = require './middleware/ensure_ssl'
escapedFragmentMiddleware = require './middleware/escaped_fragment'
sameOriginMiddleware = require './middleware/same_origin'
hstsMiddleware = require './middleware/hsts'
unsupportedBrowserCheck = require './middleware/unsupported_browser'
flash = require 'connect-flash'
flashMiddleware = require './middleware/flash'
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
session = require 'cookie-session'
favicon = require 'serve-favicon'
logger = require 'morgan'
artsyXapp = require 'artsy-xapp'
fs = require 'fs'
artsyError = require 'artsy-error-handler'
cache = require './cache'
timeout = require 'connect-timeout'
bucketAssets = require 'bucket-assets'
splitTestMiddleware = require '../components/split_test/middleware'
hardcodedRedirects = require './routers/hardcoded_redirects'
require './setup_sharify.coffee'
CurrentUser = require '../models/current_user'
downcase = require './middleware/downcase'
ipfilter = require('express-ipfilter').IpFilter
module.exports = (app) ->
# Blacklist IPs
app.use ipfilter([IP_BLACKLIST.split(',')], log: false, mode: 'deny')
# Rate limited
if OPENREDIS_URL and cache.client
limiter = require('express-limiter')(app, cache.client)
limiter
path: '*'
method: 'all'
lookup: ['headers.x-forwarded-for']
total: REQUEST_LIMIT
expire: REQUEST_EXPIRE_MS
onRateLimited: (req, res, next) ->
console.log 'Rate limit exceeded for', req.headers['x-forwarded-for']
next()
# Blank page apparently used by Eigen?
app.use require '../apps/blank'
# Make sure we're using SSL
app.use ensureSSL
app.use hstsMiddleware
# Increase max sockets. The goal of this is to improve app -> api
# performance but the downside is it limits client connection reuse with keep-alive
if typeof MAX_SOCKETS == 'number' and MAX_SOCKETS > 0
http.globalAgent.maxSockets = MAX_SOCKETS
else
http.globalAgent.maxSockets = Number.MAX_VALUE
# Override Backbone to use server-side sync, inject the XAPP token,
# add redis caching, and augment sync with Q promises.
sync = require "backbone-super-sync"
sync.timeout = API_REQUEST_TIMEOUT
sync.cacheClient = cache.client
sync.defaultCacheTime = DEFAULT_CACHE_TIME
Backbone.sync = (method, model, options) ->
options.headers ?= {}
options.headers['X-XAPP-TOKEN'] = artsyXapp.token or ''
sync method, model, options
# Inject sharify data before anything
app.use sharify
# Development / Test only middlewares that compile assets, mount antigravity, and
# allow a back door to log in for tests.
if "development" is NODE_ENV
app.use require("stylus").middleware
src: path.resolve(__dirname, "../")
dest: path.resolve(__dirname, "../public")
app.use require("browserify-dev-middleware")
src: path.resolve(__dirname, "../")
transforms: [
require("jadeify"),
require('caching-coffeeify'),
require('babelify')
]
insertGlobals: true
# FIXME: Follow up with Craig re sourcemaps
debug: true
if "test" is NODE_ENV
app.use (req, res, next) ->
return next() unless req.query['test-login']
req.user = new CurrentUser(
require('antigravity').fabricate('user', accessToken: 'footoken')
)
next()
app.use "/__gravity", require("antigravity").server
# Cookie and session middleware
app.use cookieParser()
app.set 'trust proxy', true
app.use session
secret: SESSION_SECRET
domain: COOKIE_DOMAIN
name: SESSION_COOKIE_KEY
maxAge: SESSION_COOKIE_MAX_AGE
# secure uses req.connection.encrypted, but heroku has nginx terminating SSL
# secureProxy just sets secure=true
secure: "production" is NODE_ENV or "staging" is NODE_ENV
# Body parser has to be after proxy middleware for
# node-http-proxy to work with POST/PUT/DELETE
app.use proxyToMerged
app.use '/api', proxyGravity.api
app.use proxyReflection
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
# Passport middleware for authentication. CORS middleware above that because
# we want the user to be able to log-in to force via the microgravity subdomain
# the initial use case being the professional buyer application
# (this is specific to responsive pages that require log-in)
app.use cors origin: [APP_URL, MOBILE_URL, /\.artsy\.net$/]
app.use artsyPassport _.extend config,
CurrentUser: CurrentUser
ARTSY_URL: API_URL
userKeys:[
'id', 'type', 'name', 'email', 'phone', 'lab_features',
'default_profile_id', 'has_partner_access', 'collector_level', 'paddle_number'
]
# Static file middleware above apps & redirects to ensure we don't try to
# fetch /assets/:pkg.js in an attempt to check for profile or redirect assets
# fetches to the mobile website for responsive pages.
fs.readdirSync(path.resolve __dirname, '../apps').forEach (fld) ->
app.use express.static(path.resolve __dirname, "../apps/#{fld}/public")
fs.readdirSync(path.resolve __dirname, '../components').forEach (fld) ->
app.use express.static(path.resolve __dirname, "../components/#{fld}/public")
app.use favicon(path.resolve __dirname, '../public/images/favicon.ico')
app.use express.static(path.resolve __dirname, '../public')
app.use '/(.well-known/)?apple-app-site-association', artsyEigenWebAssociation
# Redirect requests before they even have to deal with Force routing
app.use downcase
app.use hardcodedRedirects
app.use redirectMobile
# General helpers and express middleware
app.use bucketAssets()
app.use flash()
app.use flashMiddleware
app.use localsMiddleware
app.use artsyError.helpers
app.use sameOriginMiddleware
app.use escapedFragmentMiddleware
app.use logger LOGGER_FORMAT
app.use unsupportedBrowserCheck
app.use splitTestMiddleware
# Mount apps
# Apps with hardcoded routes or "RESTful" routes
app.use require "../apps/home"
app.use require "../apps/editorial_features"
app.use require "../apps/apply"
app.use require "../apps/auctions"
app.use require "../apps/artist"
app.use require "../apps/artists"
app.use require "../apps/auction_lots"
app.use require "../apps/artwork_purchase"
app.use require "../apps/artwork"
app.use require "../apps/about"
app.use require "../apps/collect_art"
app.use require "../apps/collect"
app.use require "../apps/categories"
app.use require "../apps/categories2"
app.use require "../apps/consignments"
app.use require "../apps/contact"
app.use require "../apps/eoy_2016"
app.use require "../apps/how_auctions_work"
app.use require "../apps/inquiry"
app.use require "../apps/fairs"
app.use require "../apps/flash"
app.use require "../apps/partnerships"
app.use require "../apps/gene"
app.use require "../apps/geo"
app.use require "../apps/jobs"
app.use require "../apps/loyalty"
app.use require "../apps/notifications"
app.use require "../apps/order"
app.use require "../apps/personalize"
app.use require "../apps/press"
app.use require "../apps/pro_buyer"
app.use require "../apps/search"
app.use require "../apps/show"
app.use require "../apps/shows"
app.use require "../apps/tag"
app.use require "../apps/unsubscribe"
app.use require "../apps/unsupported_browser"
app.use require "../apps/style_guide"
app.use require "../apps/auth"
app.use require "../apps/static"
app.use require "../apps/clear_cache"
app.use require "../apps/sitemaps"
app.use require "../apps/rss"
app.use require '../apps/dev'
app.use require "../apps/article"
app.use require "../apps/artsy_primer"
# Non-profile dynamic vanity url apps
app.use require "../apps/galleries_institutions"
app.use require "../apps/articles"
app.use require "../apps/page"
app.use require "../apps/shortcuts"
# Apps that need to fetch a profile
app.use require "../apps/profile"
app.use require "../apps/partner2"
app.use require "../apps/partner"
app.use require "../apps/fair"
app.use require "../apps/fair_info"
app.use require "../apps/fair_organizer"
app.use require "../apps/auction"
app.use require "../apps/auction2"
app.use require "../apps/auction_support"
app.use require "../apps/feature"
# Last but not least user profiles
app.use require "../apps/user"
# route to ping for system time
app.get '/system/time', timeout('25s'), (req, res)->
res.send 200, {time: Date.now()}
# Route to ping for system up
app.get '/system/up', (req, res) ->
res.send 200, { nodejs: true }
| 42220 | #
# Sets up intial project settings, middleware, mounted apps, and
# global configuration such as overriding Backbone.sync and
# populating sharify data
#
{
API_URL,
APP_URL,
NODE_ENV,
ARTSY_ID,
ARTSY_SECRET,
SESSION_SECRET,
SESSION_COOKIE_MAX_AGE,
MOBILE_URL,
DEFAULT_CACHE_TIME,
COOKIE_DOMAIN,
AUTO_GRAVITY_LOGIN,
SESSION_COOKIE_KEY,
API_REQUEST_TIMEOUT,
IP_BLACKLIST,
REQUEST_LIMIT,
REQUEST_EXPIRE_MS,
LOGGER_FORMAT,
OPENREDIS_URL
} = config = require "../config"
{ parse, format } = require 'url'
_ = require 'underscore'
express = require "express"
Backbone = require "backbone"
sharify = require "sharify"
http = require 'http'
path = require 'path'
cors = require 'cors'
artsyPassport = require 'artsy-passport'
artsyEigenWebAssociation = require 'artsy-eigen-web-association'
redirectMobile = require './middleware/redirect_mobile'
proxyGravity = require './middleware/proxy_to_gravity'
proxyReflection = require './middleware/proxy_to_reflection'
proxyToMerged = require './middleware/proxy_to_merged'
localsMiddleware = require './middleware/locals'
ensureSSL = require './middleware/ensure_ssl'
escapedFragmentMiddleware = require './middleware/escaped_fragment'
sameOriginMiddleware = require './middleware/same_origin'
hstsMiddleware = require './middleware/hsts'
unsupportedBrowserCheck = require './middleware/unsupported_browser'
flash = require 'connect-flash'
flashMiddleware = require './middleware/flash'
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
session = require 'cookie-session'
favicon = require 'serve-favicon'
logger = require 'morgan'
artsyXapp = require 'artsy-xapp'
fs = require 'fs'
artsyError = require 'artsy-error-handler'
cache = require './cache'
timeout = require 'connect-timeout'
bucketAssets = require 'bucket-assets'
splitTestMiddleware = require '../components/split_test/middleware'
hardcodedRedirects = require './routers/hardcoded_redirects'
require './setup_sharify.coffee'
CurrentUser = require '../models/current_user'
downcase = require './middleware/downcase'
ipfilter = require('express-ipfilter').IpFilter
module.exports = (app) ->
# Blacklist IPs
app.use ipfilter([IP_BLACKLIST.split(',')], log: false, mode: 'deny')
# Rate limited
if OPENREDIS_URL and cache.client
limiter = require('express-limiter')(app, cache.client)
limiter
path: '*'
method: 'all'
lookup: ['headers.x-forwarded-for']
total: REQUEST_LIMIT
expire: REQUEST_EXPIRE_MS
onRateLimited: (req, res, next) ->
console.log 'Rate limit exceeded for', req.headers['x-forwarded-for']
next()
# Blank page apparently used by Eigen?
app.use require '../apps/blank'
# Make sure we're using SSL
app.use ensureSSL
app.use hstsMiddleware
# Increase max sockets. The goal of this is to improve app -> api
# performance but the downside is it limits client connection reuse with keep-alive
if typeof MAX_SOCKETS == 'number' and MAX_SOCKETS > 0
http.globalAgent.maxSockets = MAX_SOCKETS
else
http.globalAgent.maxSockets = Number.MAX_VALUE
# Override Backbone to use server-side sync, inject the XAPP token,
# add redis caching, and augment sync with Q promises.
sync = require "backbone-super-sync"
sync.timeout = API_REQUEST_TIMEOUT
sync.cacheClient = cache.client
sync.defaultCacheTime = DEFAULT_CACHE_TIME
Backbone.sync = (method, model, options) ->
options.headers ?= {}
options.headers['X-XAPP-TOKEN'] = artsyXapp.token or ''
sync method, model, options
# Inject sharify data before anything
app.use sharify
# Development / Test only middlewares that compile assets, mount antigravity, and
# allow a back door to log in for tests.
if "development" is NODE_ENV
app.use require("stylus").middleware
src: path.resolve(__dirname, "../")
dest: path.resolve(__dirname, "../public")
app.use require("browserify-dev-middleware")
src: path.resolve(__dirname, "../")
transforms: [
require("jadeify"),
require('caching-coffeeify'),
require('babelify')
]
insertGlobals: true
# FIXME: Follow up with Craig re sourcemaps
debug: true
if "test" is NODE_ENV
app.use (req, res, next) ->
return next() unless req.query['test-login']
req.user = new CurrentUser(
require('antigravity').fabricate('user', accessToken: '<KEY>')
)
next()
app.use "/__gravity", require("antigravity").server
# Cookie and session middleware
app.use cookieParser()
app.set 'trust proxy', true
app.use session
secret: SESSION_SECRET
domain: COOKIE_DOMAIN
name: SESSION_COOKIE_KEY
maxAge: SESSION_COOKIE_MAX_AGE
# secure uses req.connection.encrypted, but heroku has nginx terminating SSL
# secureProxy just sets secure=true
secure: "production" is NODE_ENV or "staging" is NODE_ENV
# Body parser has to be after proxy middleware for
# node-http-proxy to work with POST/PUT/DELETE
app.use proxyToMerged
app.use '/api', proxyGravity.api
app.use proxyReflection
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
# Passport middleware for authentication. CORS middleware above that because
# we want the user to be able to log-in to force via the microgravity subdomain
# the initial use case being the professional buyer application
# (this is specific to responsive pages that require log-in)
app.use cors origin: [APP_URL, MOBILE_URL, /\.artsy\.net$/]
app.use artsyPassport _.extend config,
CurrentUser: CurrentUser
ARTSY_URL: API_URL
userKeys:[
'id', 'type', 'name', 'email', 'phone', 'lab_features',
'default_profile_id', 'has_partner_access', 'collector_level', 'paddle_number'
]
# Static file middleware above apps & redirects to ensure we don't try to
# fetch /assets/:pkg.js in an attempt to check for profile or redirect assets
# fetches to the mobile website for responsive pages.
fs.readdirSync(path.resolve __dirname, '../apps').forEach (fld) ->
app.use express.static(path.resolve __dirname, "../apps/#{fld}/public")
fs.readdirSync(path.resolve __dirname, '../components').forEach (fld) ->
app.use express.static(path.resolve __dirname, "../components/#{fld}/public")
app.use favicon(path.resolve __dirname, '../public/images/favicon.ico')
app.use express.static(path.resolve __dirname, '../public')
app.use '/(.well-known/)?apple-app-site-association', artsyEigenWebAssociation
# Redirect requests before they even have to deal with Force routing
app.use downcase
app.use hardcodedRedirects
app.use redirectMobile
# General helpers and express middleware
app.use bucketAssets()
app.use flash()
app.use flashMiddleware
app.use localsMiddleware
app.use artsyError.helpers
app.use sameOriginMiddleware
app.use escapedFragmentMiddleware
app.use logger LOGGER_FORMAT
app.use unsupportedBrowserCheck
app.use splitTestMiddleware
# Mount apps
# Apps with hardcoded routes or "RESTful" routes
app.use require "../apps/home"
app.use require "../apps/editorial_features"
app.use require "../apps/apply"
app.use require "../apps/auctions"
app.use require "../apps/artist"
app.use require "../apps/artists"
app.use require "../apps/auction_lots"
app.use require "../apps/artwork_purchase"
app.use require "../apps/artwork"
app.use require "../apps/about"
app.use require "../apps/collect_art"
app.use require "../apps/collect"
app.use require "../apps/categories"
app.use require "../apps/categories2"
app.use require "../apps/consignments"
app.use require "../apps/contact"
app.use require "../apps/eoy_2016"
app.use require "../apps/how_auctions_work"
app.use require "../apps/inquiry"
app.use require "../apps/fairs"
app.use require "../apps/flash"
app.use require "../apps/partnerships"
app.use require "../apps/gene"
app.use require "../apps/geo"
app.use require "../apps/jobs"
app.use require "../apps/loyalty"
app.use require "../apps/notifications"
app.use require "../apps/order"
app.use require "../apps/personalize"
app.use require "../apps/press"
app.use require "../apps/pro_buyer"
app.use require "../apps/search"
app.use require "../apps/show"
app.use require "../apps/shows"
app.use require "../apps/tag"
app.use require "../apps/unsubscribe"
app.use require "../apps/unsupported_browser"
app.use require "../apps/style_guide"
app.use require "../apps/auth"
app.use require "../apps/static"
app.use require "../apps/clear_cache"
app.use require "../apps/sitemaps"
app.use require "../apps/rss"
app.use require '../apps/dev'
app.use require "../apps/article"
app.use require "../apps/artsy_primer"
# Non-profile dynamic vanity url apps
app.use require "../apps/galleries_institutions"
app.use require "../apps/articles"
app.use require "../apps/page"
app.use require "../apps/shortcuts"
# Apps that need to fetch a profile
app.use require "../apps/profile"
app.use require "../apps/partner2"
app.use require "../apps/partner"
app.use require "../apps/fair"
app.use require "../apps/fair_info"
app.use require "../apps/fair_organizer"
app.use require "../apps/auction"
app.use require "../apps/auction2"
app.use require "../apps/auction_support"
app.use require "../apps/feature"
# Last but not least user profiles
app.use require "../apps/user"
# route to ping for system time
app.get '/system/time', timeout('25s'), (req, res)->
res.send 200, {time: Date.now()}
# Route to ping for system up
app.get '/system/up', (req, res) ->
res.send 200, { nodejs: true }
| true | #
# Sets up intial project settings, middleware, mounted apps, and
# global configuration such as overriding Backbone.sync and
# populating sharify data
#
{
API_URL,
APP_URL,
NODE_ENV,
ARTSY_ID,
ARTSY_SECRET,
SESSION_SECRET,
SESSION_COOKIE_MAX_AGE,
MOBILE_URL,
DEFAULT_CACHE_TIME,
COOKIE_DOMAIN,
AUTO_GRAVITY_LOGIN,
SESSION_COOKIE_KEY,
API_REQUEST_TIMEOUT,
IP_BLACKLIST,
REQUEST_LIMIT,
REQUEST_EXPIRE_MS,
LOGGER_FORMAT,
OPENREDIS_URL
} = config = require "../config"
{ parse, format } = require 'url'
_ = require 'underscore'
express = require "express"
Backbone = require "backbone"
sharify = require "sharify"
http = require 'http'
path = require 'path'
cors = require 'cors'
artsyPassport = require 'artsy-passport'
artsyEigenWebAssociation = require 'artsy-eigen-web-association'
redirectMobile = require './middleware/redirect_mobile'
proxyGravity = require './middleware/proxy_to_gravity'
proxyReflection = require './middleware/proxy_to_reflection'
proxyToMerged = require './middleware/proxy_to_merged'
localsMiddleware = require './middleware/locals'
ensureSSL = require './middleware/ensure_ssl'
escapedFragmentMiddleware = require './middleware/escaped_fragment'
sameOriginMiddleware = require './middleware/same_origin'
hstsMiddleware = require './middleware/hsts'
unsupportedBrowserCheck = require './middleware/unsupported_browser'
flash = require 'connect-flash'
flashMiddleware = require './middleware/flash'
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
session = require 'cookie-session'
favicon = require 'serve-favicon'
logger = require 'morgan'
artsyXapp = require 'artsy-xapp'
fs = require 'fs'
artsyError = require 'artsy-error-handler'
cache = require './cache'
timeout = require 'connect-timeout'
bucketAssets = require 'bucket-assets'
splitTestMiddleware = require '../components/split_test/middleware'
hardcodedRedirects = require './routers/hardcoded_redirects'
require './setup_sharify.coffee'
CurrentUser = require '../models/current_user'
downcase = require './middleware/downcase'
ipfilter = require('express-ipfilter').IpFilter
module.exports = (app) ->
# Blacklist IPs
app.use ipfilter([IP_BLACKLIST.split(',')], log: false, mode: 'deny')
# Rate limited
if OPENREDIS_URL and cache.client
limiter = require('express-limiter')(app, cache.client)
limiter
path: '*'
method: 'all'
lookup: ['headers.x-forwarded-for']
total: REQUEST_LIMIT
expire: REQUEST_EXPIRE_MS
onRateLimited: (req, res, next) ->
console.log 'Rate limit exceeded for', req.headers['x-forwarded-for']
next()
# Blank page apparently used by Eigen?
app.use require '../apps/blank'
# Make sure we're using SSL
app.use ensureSSL
app.use hstsMiddleware
# Increase max sockets. The goal of this is to improve app -> api
# performance but the downside is it limits client connection reuse with keep-alive
if typeof MAX_SOCKETS == 'number' and MAX_SOCKETS > 0
http.globalAgent.maxSockets = MAX_SOCKETS
else
http.globalAgent.maxSockets = Number.MAX_VALUE
# Override Backbone to use server-side sync, inject the XAPP token,
# add redis caching, and augment sync with Q promises.
sync = require "backbone-super-sync"
sync.timeout = API_REQUEST_TIMEOUT
sync.cacheClient = cache.client
sync.defaultCacheTime = DEFAULT_CACHE_TIME
Backbone.sync = (method, model, options) ->
options.headers ?= {}
options.headers['X-XAPP-TOKEN'] = artsyXapp.token or ''
sync method, model, options
# Inject sharify data before anything
app.use sharify
# Development / Test only middlewares that compile assets, mount antigravity, and
# allow a back door to log in for tests.
if "development" is NODE_ENV
app.use require("stylus").middleware
src: path.resolve(__dirname, "../")
dest: path.resolve(__dirname, "../public")
app.use require("browserify-dev-middleware")
src: path.resolve(__dirname, "../")
transforms: [
require("jadeify"),
require('caching-coffeeify'),
require('babelify')
]
insertGlobals: true
# FIXME: Follow up with Craig re sourcemaps
debug: true
if "test" is NODE_ENV
app.use (req, res, next) ->
return next() unless req.query['test-login']
req.user = new CurrentUser(
require('antigravity').fabricate('user', accessToken: 'PI:KEY:<KEY>END_PI')
)
next()
app.use "/__gravity", require("antigravity").server
# Cookie and session middleware
app.use cookieParser()
app.set 'trust proxy', true
app.use session
secret: SESSION_SECRET
domain: COOKIE_DOMAIN
name: SESSION_COOKIE_KEY
maxAge: SESSION_COOKIE_MAX_AGE
# secure uses req.connection.encrypted, but heroku has nginx terminating SSL
# secureProxy just sets secure=true
secure: "production" is NODE_ENV or "staging" is NODE_ENV
# Body parser has to be after proxy middleware for
# node-http-proxy to work with POST/PUT/DELETE
app.use proxyToMerged
app.use '/api', proxyGravity.api
app.use proxyReflection
app.use bodyParser.json()
app.use bodyParser.urlencoded(extended: true)
# Passport middleware for authentication. CORS middleware above that because
# we want the user to be able to log-in to force via the microgravity subdomain
# the initial use case being the professional buyer application
# (this is specific to responsive pages that require log-in)
app.use cors origin: [APP_URL, MOBILE_URL, /\.artsy\.net$/]
app.use artsyPassport _.extend config,
CurrentUser: CurrentUser
ARTSY_URL: API_URL
userKeys:[
'id', 'type', 'name', 'email', 'phone', 'lab_features',
'default_profile_id', 'has_partner_access', 'collector_level', 'paddle_number'
]
# Static file middleware above apps & redirects to ensure we don't try to
# fetch /assets/:pkg.js in an attempt to check for profile or redirect assets
# fetches to the mobile website for responsive pages.
fs.readdirSync(path.resolve __dirname, '../apps').forEach (fld) ->
app.use express.static(path.resolve __dirname, "../apps/#{fld}/public")
fs.readdirSync(path.resolve __dirname, '../components').forEach (fld) ->
app.use express.static(path.resolve __dirname, "../components/#{fld}/public")
app.use favicon(path.resolve __dirname, '../public/images/favicon.ico')
app.use express.static(path.resolve __dirname, '../public')
app.use '/(.well-known/)?apple-app-site-association', artsyEigenWebAssociation
# Redirect requests before they even have to deal with Force routing
app.use downcase
app.use hardcodedRedirects
app.use redirectMobile
# General helpers and express middleware
app.use bucketAssets()
app.use flash()
app.use flashMiddleware
app.use localsMiddleware
app.use artsyError.helpers
app.use sameOriginMiddleware
app.use escapedFragmentMiddleware
app.use logger LOGGER_FORMAT
app.use unsupportedBrowserCheck
app.use splitTestMiddleware
# Mount apps
# Apps with hardcoded routes or "RESTful" routes
app.use require "../apps/home"
app.use require "../apps/editorial_features"
app.use require "../apps/apply"
app.use require "../apps/auctions"
app.use require "../apps/artist"
app.use require "../apps/artists"
app.use require "../apps/auction_lots"
app.use require "../apps/artwork_purchase"
app.use require "../apps/artwork"
app.use require "../apps/about"
app.use require "../apps/collect_art"
app.use require "../apps/collect"
app.use require "../apps/categories"
app.use require "../apps/categories2"
app.use require "../apps/consignments"
app.use require "../apps/contact"
app.use require "../apps/eoy_2016"
app.use require "../apps/how_auctions_work"
app.use require "../apps/inquiry"
app.use require "../apps/fairs"
app.use require "../apps/flash"
app.use require "../apps/partnerships"
app.use require "../apps/gene"
app.use require "../apps/geo"
app.use require "../apps/jobs"
app.use require "../apps/loyalty"
app.use require "../apps/notifications"
app.use require "../apps/order"
app.use require "../apps/personalize"
app.use require "../apps/press"
app.use require "../apps/pro_buyer"
app.use require "../apps/search"
app.use require "../apps/show"
app.use require "../apps/shows"
app.use require "../apps/tag"
app.use require "../apps/unsubscribe"
app.use require "../apps/unsupported_browser"
app.use require "../apps/style_guide"
app.use require "../apps/auth"
app.use require "../apps/static"
app.use require "../apps/clear_cache"
app.use require "../apps/sitemaps"
app.use require "../apps/rss"
app.use require '../apps/dev'
app.use require "../apps/article"
app.use require "../apps/artsy_primer"
# Non-profile dynamic vanity url apps
app.use require "../apps/galleries_institutions"
app.use require "../apps/articles"
app.use require "../apps/page"
app.use require "../apps/shortcuts"
# Apps that need to fetch a profile
app.use require "../apps/profile"
app.use require "../apps/partner2"
app.use require "../apps/partner"
app.use require "../apps/fair"
app.use require "../apps/fair_info"
app.use require "../apps/fair_organizer"
app.use require "../apps/auction"
app.use require "../apps/auction2"
app.use require "../apps/auction_support"
app.use require "../apps/feature"
# Last but not least user profiles
app.use require "../apps/user"
# route to ping for system time
app.get '/system/time', timeout('25s'), (req, res)->
res.send 200, {time: Date.now()}
# Route to ping for system up
app.get '/system/up', (req, res) ->
res.send 200, { nodejs: true }
|
[
{
"context": "###\nCopyright 2016-2019 Balena\n\nLicensed under the Apache License, Version 2.0 (",
"end": 30,
"score": 0.99880051612854,
"start": 24,
"tag": "NAME",
"value": "Balena"
}
] | lib/app-capitano.coffee | rcitterio/balena-cli | 1 | ###
Copyright 2016-2019 Balena
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.
###
Promise = require('bluebird')
capitano = require('capitano')
actions = require('./actions')
events = require('./events')
capitano.permission 'user', (done) ->
require('./utils/patterns').exitIfNotLoggedIn()
.then(done, done)
capitano.command
signature: '*'
action: (params, options, done) ->
capitano.execute(command: 'help', done)
process.exitCode = process.exitCode || 1
capitano.globalOption
signature: 'help'
boolean: true
alias: 'h'
capitano.globalOption
signature: 'version'
boolean: true
alias: 'v'
# ---------- Help Module ----------
capitano.command(actions.help.help)
# ---------- Api key module ----------
capitano.command(actions.apiKey.generate)
# ---------- App Module ----------
capitano.command(actions.app.create)
capitano.command(actions.app.list)
capitano.command(actions.app.remove)
capitano.command(actions.app.restart)
capitano.command(actions.app.info)
# ---------- Auth Module ----------
capitano.command(actions.auth.login)
capitano.command(actions.auth.logout)
capitano.command(actions.auth.whoami)
# ---------- Device Module ----------
capitano.command(actions.device.list)
capitano.command(actions.device.rename)
capitano.command(actions.device.init)
capitano.command(actions.device.remove)
capitano.command(actions.device.identify)
capitano.command(actions.device.reboot)
capitano.command(actions.device.shutdown)
capitano.command(actions.device.enableDeviceUrl)
capitano.command(actions.device.disableDeviceUrl)
capitano.command(actions.device.getDeviceUrl)
capitano.command(actions.device.hasDeviceUrl)
capitano.command(actions.device.register)
capitano.command(actions.device.move)
capitano.command(actions.device.osUpdate)
capitano.command(actions.device.info)
# ---------- Tags Module ----------
capitano.command(actions.tags.list)
capitano.command(actions.tags.set)
capitano.command(actions.tags.remove)
# ---------- OS Module ----------
capitano.command(actions.os.versions)
capitano.command(actions.os.download)
capitano.command(actions.os.buildConfig)
capitano.command(actions.os.initialize)
# ---------- Config Module ----------
capitano.command(actions.config.read)
capitano.command(actions.config.write)
capitano.command(actions.config.inject)
capitano.command(actions.config.reconfigure)
capitano.command(actions.config.generate)
# ---------- Logs Module ----------
capitano.command(actions.logs.logs)
# ---------- Tunnel Module ----------
capitano.command(actions.tunnel.tunnel)
# ---------- Preload Module ----------
capitano.command(actions.preload)
# ---------- SSH Module ----------
capitano.command(actions.ssh.ssh)
# ---------- Local balenaOS Module ----------
capitano.command(actions.local.configure)
capitano.command(actions.local.flash)
# ---------- Public utils ----------
capitano.command(actions.util.availableDrives)
#------------ Local build and deploy -------
capitano.command(actions.build)
capitano.command(actions.deploy)
#------------ Push/remote builds -------
capitano.command(actions.push.push)
exports.run = (argv) ->
cli = capitano.parse(argv.slice(2))
runCommand = ->
capitanoExecuteAsync = Promise.promisify(capitano.execute)
if cli.global?.help
capitanoExecuteAsync(command: "help #{cli.command ? ''}")
else
capitanoExecuteAsync(cli)
trackCommand = ->
getMatchCommandAsync = Promise.promisify(capitano.state.getMatchCommand)
getMatchCommandAsync(cli.command)
.then (command) ->
# cmdSignature is literally a string like, for example:
# "push <applicationOrDevice>"
# ("applicationOrDevice" is NOT replaced with its actual value)
# In case of failures like an nonexistent or invalid command,
# command.signature.toString() returns '*'
cmdSignature = command.signature.toString()
events.trackCommand(cmdSignature)
Promise.all([trackCommand(), runCommand()])
.catch(require('./errors').handleError)
| 6894 | ###
Copyright 2016-2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
Promise = require('bluebird')
capitano = require('capitano')
actions = require('./actions')
events = require('./events')
capitano.permission 'user', (done) ->
require('./utils/patterns').exitIfNotLoggedIn()
.then(done, done)
capitano.command
signature: '*'
action: (params, options, done) ->
capitano.execute(command: 'help', done)
process.exitCode = process.exitCode || 1
capitano.globalOption
signature: 'help'
boolean: true
alias: 'h'
capitano.globalOption
signature: 'version'
boolean: true
alias: 'v'
# ---------- Help Module ----------
capitano.command(actions.help.help)
# ---------- Api key module ----------
capitano.command(actions.apiKey.generate)
# ---------- App Module ----------
capitano.command(actions.app.create)
capitano.command(actions.app.list)
capitano.command(actions.app.remove)
capitano.command(actions.app.restart)
capitano.command(actions.app.info)
# ---------- Auth Module ----------
capitano.command(actions.auth.login)
capitano.command(actions.auth.logout)
capitano.command(actions.auth.whoami)
# ---------- Device Module ----------
capitano.command(actions.device.list)
capitano.command(actions.device.rename)
capitano.command(actions.device.init)
capitano.command(actions.device.remove)
capitano.command(actions.device.identify)
capitano.command(actions.device.reboot)
capitano.command(actions.device.shutdown)
capitano.command(actions.device.enableDeviceUrl)
capitano.command(actions.device.disableDeviceUrl)
capitano.command(actions.device.getDeviceUrl)
capitano.command(actions.device.hasDeviceUrl)
capitano.command(actions.device.register)
capitano.command(actions.device.move)
capitano.command(actions.device.osUpdate)
capitano.command(actions.device.info)
# ---------- Tags Module ----------
capitano.command(actions.tags.list)
capitano.command(actions.tags.set)
capitano.command(actions.tags.remove)
# ---------- OS Module ----------
capitano.command(actions.os.versions)
capitano.command(actions.os.download)
capitano.command(actions.os.buildConfig)
capitano.command(actions.os.initialize)
# ---------- Config Module ----------
capitano.command(actions.config.read)
capitano.command(actions.config.write)
capitano.command(actions.config.inject)
capitano.command(actions.config.reconfigure)
capitano.command(actions.config.generate)
# ---------- Logs Module ----------
capitano.command(actions.logs.logs)
# ---------- Tunnel Module ----------
capitano.command(actions.tunnel.tunnel)
# ---------- Preload Module ----------
capitano.command(actions.preload)
# ---------- SSH Module ----------
capitano.command(actions.ssh.ssh)
# ---------- Local balenaOS Module ----------
capitano.command(actions.local.configure)
capitano.command(actions.local.flash)
# ---------- Public utils ----------
capitano.command(actions.util.availableDrives)
#------------ Local build and deploy -------
capitano.command(actions.build)
capitano.command(actions.deploy)
#------------ Push/remote builds -------
capitano.command(actions.push.push)
exports.run = (argv) ->
cli = capitano.parse(argv.slice(2))
runCommand = ->
capitanoExecuteAsync = Promise.promisify(capitano.execute)
if cli.global?.help
capitanoExecuteAsync(command: "help #{cli.command ? ''}")
else
capitanoExecuteAsync(cli)
trackCommand = ->
getMatchCommandAsync = Promise.promisify(capitano.state.getMatchCommand)
getMatchCommandAsync(cli.command)
.then (command) ->
# cmdSignature is literally a string like, for example:
# "push <applicationOrDevice>"
# ("applicationOrDevice" is NOT replaced with its actual value)
# In case of failures like an nonexistent or invalid command,
# command.signature.toString() returns '*'
cmdSignature = command.signature.toString()
events.trackCommand(cmdSignature)
Promise.all([trackCommand(), runCommand()])
.catch(require('./errors').handleError)
| true | ###
Copyright 2016-2019 PI:NAME:<NAME>END_PI
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
###
Promise = require('bluebird')
capitano = require('capitano')
actions = require('./actions')
events = require('./events')
capitano.permission 'user', (done) ->
require('./utils/patterns').exitIfNotLoggedIn()
.then(done, done)
capitano.command
signature: '*'
action: (params, options, done) ->
capitano.execute(command: 'help', done)
process.exitCode = process.exitCode || 1
capitano.globalOption
signature: 'help'
boolean: true
alias: 'h'
capitano.globalOption
signature: 'version'
boolean: true
alias: 'v'
# ---------- Help Module ----------
capitano.command(actions.help.help)
# ---------- Api key module ----------
capitano.command(actions.apiKey.generate)
# ---------- App Module ----------
capitano.command(actions.app.create)
capitano.command(actions.app.list)
capitano.command(actions.app.remove)
capitano.command(actions.app.restart)
capitano.command(actions.app.info)
# ---------- Auth Module ----------
capitano.command(actions.auth.login)
capitano.command(actions.auth.logout)
capitano.command(actions.auth.whoami)
# ---------- Device Module ----------
capitano.command(actions.device.list)
capitano.command(actions.device.rename)
capitano.command(actions.device.init)
capitano.command(actions.device.remove)
capitano.command(actions.device.identify)
capitano.command(actions.device.reboot)
capitano.command(actions.device.shutdown)
capitano.command(actions.device.enableDeviceUrl)
capitano.command(actions.device.disableDeviceUrl)
capitano.command(actions.device.getDeviceUrl)
capitano.command(actions.device.hasDeviceUrl)
capitano.command(actions.device.register)
capitano.command(actions.device.move)
capitano.command(actions.device.osUpdate)
capitano.command(actions.device.info)
# ---------- Tags Module ----------
capitano.command(actions.tags.list)
capitano.command(actions.tags.set)
capitano.command(actions.tags.remove)
# ---------- OS Module ----------
capitano.command(actions.os.versions)
capitano.command(actions.os.download)
capitano.command(actions.os.buildConfig)
capitano.command(actions.os.initialize)
# ---------- Config Module ----------
capitano.command(actions.config.read)
capitano.command(actions.config.write)
capitano.command(actions.config.inject)
capitano.command(actions.config.reconfigure)
capitano.command(actions.config.generate)
# ---------- Logs Module ----------
capitano.command(actions.logs.logs)
# ---------- Tunnel Module ----------
capitano.command(actions.tunnel.tunnel)
# ---------- Preload Module ----------
capitano.command(actions.preload)
# ---------- SSH Module ----------
capitano.command(actions.ssh.ssh)
# ---------- Local balenaOS Module ----------
capitano.command(actions.local.configure)
capitano.command(actions.local.flash)
# ---------- Public utils ----------
capitano.command(actions.util.availableDrives)
#------------ Local build and deploy -------
capitano.command(actions.build)
capitano.command(actions.deploy)
#------------ Push/remote builds -------
capitano.command(actions.push.push)
exports.run = (argv) ->
cli = capitano.parse(argv.slice(2))
runCommand = ->
capitanoExecuteAsync = Promise.promisify(capitano.execute)
if cli.global?.help
capitanoExecuteAsync(command: "help #{cli.command ? ''}")
else
capitanoExecuteAsync(cli)
trackCommand = ->
getMatchCommandAsync = Promise.promisify(capitano.state.getMatchCommand)
getMatchCommandAsync(cli.command)
.then (command) ->
# cmdSignature is literally a string like, for example:
# "push <applicationOrDevice>"
# ("applicationOrDevice" is NOT replaced with its actual value)
# In case of failures like an nonexistent or invalid command,
# command.signature.toString() returns '*'
cmdSignature = command.signature.toString()
events.trackCommand(cmdSignature)
Promise.all([trackCommand(), runCommand()])
.catch(require('./errors').handleError)
|
[
{
"context": ", () ->\n store = new UserStore()\n target = 'info@grokbit.com'\n assert.equal store.createInstance().email, t",
"end": 227,
"score": 0.9999274611473083,
"start": 211,
"tag": "EMAIL",
"value": "info@grokbit.com"
},
{
"context": ", () ->\n store = new UserSto... | src/test/when_user_login.coffee | marinoscar/NodeExpressAuth | 0 | assert = require 'assert'
UserStore = require '../services/userStore'
describe 'using forms authentication', () ->
it 'should create a valid default instance', () ->
store = new UserStore()
target = 'info@grokbit.com'
assert.equal store.createInstance().email, target
it 'should return a valid entity when credentials are valid', () ->
store = new UserStore()
target = 'info@grokbit.com'
assert.equal store.find(target).email, target
it 'should return a null entity when credentials are not valid', () ->
store = new UserStore()
assert.equal store.find('bad value'), null | 201040 | assert = require 'assert'
UserStore = require '../services/userStore'
describe 'using forms authentication', () ->
it 'should create a valid default instance', () ->
store = new UserStore()
target = '<EMAIL>'
assert.equal store.createInstance().email, target
it 'should return a valid entity when credentials are valid', () ->
store = new UserStore()
target = '<EMAIL>'
assert.equal store.find(target).email, target
it 'should return a null entity when credentials are not valid', () ->
store = new UserStore()
assert.equal store.find('bad value'), null | true | assert = require 'assert'
UserStore = require '../services/userStore'
describe 'using forms authentication', () ->
it 'should create a valid default instance', () ->
store = new UserStore()
target = 'PI:EMAIL:<EMAIL>END_PI'
assert.equal store.createInstance().email, target
it 'should return a valid entity when credentials are valid', () ->
store = new UserStore()
target = 'PI:EMAIL:<EMAIL>END_PI'
assert.equal store.find(target).email, target
it 'should return a null entity when credentials are not valid', () ->
store = new UserStore()
assert.equal store.find('bad value'), null |
[
{
"context": "oadmap-id-1\"\n plans: [\n id: \"513617ecef8623df1391fefc\"\n ,\n id:",
"end": 661,
"score": 0.4970640540122986,
"start": 659,
"tag": "KEY",
"value": "13"
},
{
"context": "map-id-1\"\n plans: [\n id: \"513617ec... | test/spec/roadmapplanningboard/mocks/StoreFixtureFactory.coffee | sboles/app-catalog | 0 | Ext = window.Ext4 || window.Ext
Ext.define 'Rally.test.apps.roadmapplanningboard.mocks.StoreFixtureFactory',
singleton: true
requires: [
'Rally.data.Store'
'Rally.test.mock.data.WsapiModelFactory'
'Rally.apps.roadmapplanningboard.AppModelFactory'
]
getRoadmapStoreFixture: ->
@roadmapStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getRoadmapModel()
proxy:
type: 'memory'
data: [
id: "roadmap-id-1"
Name: "My Roadmap"
ref: "http://localhost:8090/plan-service/api/plan/roadmap-id-1"
plans: [
id: "513617ecef8623df1391fefc"
,
id: "513617f7ef8623df1391fefd"
,
id: "51361807ef8623df1391fefe"
]
,
id: "77"
Name: "test"
ref: "test"
plans: [
id: "3"
,
id: "rgreaesrgsrdbsrdghsrgsrese" #non-existent plan
]
]
@roadmapStoreFixture.model.setProxy 'memory'
@roadmapStoreFixture
getPlanStoreFixture: ->
@planStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getPlanModel()
proxy:
type: 'memory'
data: [
id: "513617ecef8623df1391fefc"
ref: "http://localhost:8090/plan-service/api/plan/513617ecef8623df1391fefc"
lowCapacity: 2
highCapacity: 8
Name: "Release 1.1"
theme: "Take over the world!"
roadmap:
id: 'roadmap-id-1'
timeframe:
id: "2"
features: [
id: "F1000"
,
id: "F1001"
,
id: "F1002"
]
,
id: "513617f7ef8623df1391fefd"
ref: "http://localhost:8090/plan-service/api/plan/513617f7ef8623df1391fefd"
lowCapacity: 3
highCapacity: 30
Name: "Release 1.2"
theme: "Win Foosball Championship"
timeframe:
id: "3"
roadmap:
id: 'roadmap-id-1'
features: [
id: "F1005"
,
id: "F1006"
]
,
id: "51361807ef8623df1391fefe"
ref: "http://localhost:8090/plan-service/api/plan/51361807ef8623df1391fefe"
lowCapacity: 15
highCapacity: 25
Name: "Release 2.0"
timeframe:
id: "4"
roadmap:
id: 'roadmap-id-1'
features: []
,
id: "3"
ref: "http://localhost:8090/plan-service/api/plan/3"
lowCapacity: 0
highCapacity: 0
Name: " "
timeframe:
id: "7"
features: []
]
@planStoreFixture.model.setProxy 'memory'
@planStoreFixture
featureStoreData: [
ObjectID: "1000"
_refObjectUUID: "F1000"
_ref: '/portfolioitem/feature/1000'
Name: "Android Support"
PreliminaryEstimate: {Value: 4,_refObjectName: "L"}
RefinedEstimate: 5
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1001"
_refObjectUUID: "F1001"
_ref: '/portfolioitem/feature/1001'
Name: "iOS Support"
PreliminaryEstimate: {Value: 2,_refObjectName: "L"}
RefinedEstimate: 4
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1002"
_refObjectUUID: "F1002"
_ref: '/portfolioitem/feature/1002'
Name: "HTML 5 Webapp"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
RefinedEstimate: 3
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1003"
_refObjectUUID: "F1003"
_ref: '/portfolioitem/feature/1003'
Name: "Blackberry Native App"
PreliminaryEstimate: {Value: 1,_refObjectName: "L"}
RefinedEstimate: 2
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1004"
_refObjectUUID: "F1004"
_ref: '/portfolioitem/feature/1004'
Name: "Windows Phone Support"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
RefinedEstimate: 1
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1005"
_refObjectUUID: "F1005"
_ref: '/portfolioitem/feature/1005'
Name: "Ubuntu Phone Application"
PreliminaryEstimate: {Value: 4,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1006"
_refObjectUUID: "F1006"
_ref: '/portfolioitem/feature/1006'
Name: "Tester's Large Test Card 1"
PreliminaryEstimate: {Value: 13,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1007"
_refObjectUUID: "F1007"
_ref: '/portfolioitem/feature/1007'
Name: "Tester's Large Test Card 2"
PreliminaryEstimate: {Value: 21,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1008"
_refObjectUUID: "F1008"
_ref: '/portfolioitem/feature/1008'
Name: "Tester's Large Test Card 3"
PreliminaryEstimate: {Value: 13,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1009"
_refObjectUUID: "F1009"
_ref: '/portfolioitem/feature/1009'
Name: "Tester's Large Test Card 4"
PreliminaryEstimate: {Value: 8,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
]
getFeatureStoreFixture: ->
@featureStoreFixture = Ext.create 'Rally.data.wsapi.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PortfolioItem/Feature'
proxy:
type: 'memory'
data: Rally.test.mock.ModelObjectMother.getRecords 'PortfolioItemFeature',
values: @featureStoreData
@featureStoreFixture.model.setProxy 'memory'
@featureStoreFixture
secondFeatureStoreData: [
ObjectID: "1010"
_refObjectUUID: "F1010"
_ref: '/portfolioitem/feature/1010'
Name: "Battlestar Gallactica"
PreliminaryEstimate: {Value: 6,_refObjectName: "L"}
subscriptionId: "1"
,
ObjectID: "1011"
_refObjectUUID: "F1011"
_ref: '/portfolioitem/feature/1011'
Name: "Firefly"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
subscriptionId: "1"
]
getSecondFeatureStoreFixture: ->
@secondFeatureStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PortfolioItem/Feature'
proxy:
type: 'memory'
data: Rally.test.mock.ModelObjectMother.getRecords 'PortfolioItemFeature',
values: @secondFeatureStoreData
@secondFeatureStoreFixture.model.setProxy 'memory'
@secondFeatureStoreFixture
getPreliminaryEstimateStoreFixture: ->
@preliminaryEstimateStoreFixture = Ext.create 'Rally.data.wsapi.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PreliminaryEstimate'
proxy:
type: 'memory'
data: [
{Value: 8, _refObjectName: 'L', Name: 'L', Description: 'Large'}
]
@preliminaryEstimateStoreFixture.model.setProxy 'memory'
@preliminaryEstimateStoreFixture
getTimelineStoreFixture: ->
@timelineStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getTimelineModel()
proxy:
type: 'memory'
data: [
id: 'timeline-id-1'
timeframes: [
id: 1
]
]
@timelineStoreFixture.model.setProxy 'memory'
@timelineStoreFixture
getTimeframeStoreFixture: ->
@timeframeStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getTimeframeModel()
proxy:
type: 'memory'
data: [
id: '2'
name: 'Q1'
startDate: new Date('1/01/2013')
endDate: new Date('3/31/2013')
timeline:
id: 'timeline-id-1'
,
id: '3'
name: 'Q2'
startDate: new Date('4/01/2013')
endDate: new Date('6/30/2013')
timeline:
id: 'timeline-id-1'
,
id: '4'
name: 'Future Planning Period'
startDate: new Date('7/01/2013')
endDate: new Date('6/30/2099')
timeline:
id: 'timeline-id-1'
,
id: '7'
name: ''
startDate: null
endDate: null
timeline:
id: 'timeline-id-1'
,
id: '8'
name: 'Timeframe not linked to a plan'
startDate: new Date('7/01/2014')
endDate: new Date('10/31/2014')
timeline:
id: 'timeline-id-1'
]
@timeframeStoreFixture.model.setProxy 'memory'
@timeframeStoreFixture
| 46557 | Ext = window.Ext4 || window.Ext
Ext.define 'Rally.test.apps.roadmapplanningboard.mocks.StoreFixtureFactory',
singleton: true
requires: [
'Rally.data.Store'
'Rally.test.mock.data.WsapiModelFactory'
'Rally.apps.roadmapplanningboard.AppModelFactory'
]
getRoadmapStoreFixture: ->
@roadmapStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getRoadmapModel()
proxy:
type: 'memory'
data: [
id: "roadmap-id-1"
Name: "My Roadmap"
ref: "http://localhost:8090/plan-service/api/plan/roadmap-id-1"
plans: [
id: "5<KEY>6<KEY>"
,
id: "5<KEY>"
,
id: "5<KEY>80<KEY>"
]
,
id: "77"
Name: "test"
ref: "test"
plans: [
id: "3"
,
id: "rgreaesrgsrdbsrdghsrgsrese" #non-existent plan
]
]
@roadmapStoreFixture.model.setProxy 'memory'
@roadmapStoreFixture
getPlanStoreFixture: ->
@planStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getPlanModel()
proxy:
type: 'memory'
data: [
id: "<KEY>"
ref: "http://localhost:8090/plan-service/api/plan/513617ecef8623df1391fefc"
lowCapacity: 2
highCapacity: 8
Name: "Release 1.1"
theme: "Take over the world!"
roadmap:
id: 'roadmap-id-1'
timeframe:
id: "2"
features: [
id: "F1000"
,
id: "F1001"
,
id: "F1002"
]
,
id: "513617f7ef8623df1391fefd"
ref: "http://localhost:8090/plan-service/api/plan/513617f7ef8623df1391fefd"
lowCapacity: 3
highCapacity: 30
Name: "Release 1.2"
theme: "Win Foosball Championship"
timeframe:
id: "3"
roadmap:
id: 'roadmap-id-1'
features: [
id: "F1005"
,
id: "F1006"
]
,
id: "51361807ef8623df1391fefe"
ref: "http://localhost:8090/plan-service/api/plan/51361807ef8623df1391fefe"
lowCapacity: 15
highCapacity: 25
Name: "Release 2.0"
timeframe:
id: "4"
roadmap:
id: 'roadmap-id-1'
features: []
,
id: "3"
ref: "http://localhost:8090/plan-service/api/plan/3"
lowCapacity: 0
highCapacity: 0
Name: " "
timeframe:
id: "7"
features: []
]
@planStoreFixture.model.setProxy 'memory'
@planStoreFixture
featureStoreData: [
ObjectID: "1000"
_refObjectUUID: "F1000"
_ref: '/portfolioitem/feature/1000'
Name: "Android Support"
PreliminaryEstimate: {Value: 4,_refObjectName: "L"}
RefinedEstimate: 5
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1001"
_refObjectUUID: "F1001"
_ref: '/portfolioitem/feature/1001'
Name: "iOS Support"
PreliminaryEstimate: {Value: 2,_refObjectName: "L"}
RefinedEstimate: 4
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1002"
_refObjectUUID: "F1002"
_ref: '/portfolioitem/feature/1002'
Name: "HTML 5 Webapp"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
RefinedEstimate: 3
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1003"
_refObjectUUID: "F1003"
_ref: '/portfolioitem/feature/1003'
Name: "Blackberry Native App"
PreliminaryEstimate: {Value: 1,_refObjectName: "L"}
RefinedEstimate: 2
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1004"
_refObjectUUID: "F1004"
_ref: '/portfolioitem/feature/1004'
Name: "Windows Phone Support"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
RefinedEstimate: 1
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your <NAME>", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1005"
_refObjectUUID: "F1005"
_ref: '/portfolioitem/feature/1005'
Name: "Ubuntu Phone Application"
PreliminaryEstimate: {Value: 4,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your <NAME>", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1006"
_refObjectUUID: "F1006"
_ref: '/portfolioitem/feature/1006'
Name: "Tester's Large Test Card 1"
PreliminaryEstimate: {Value: 13,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your <NAME>", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1007"
_refObjectUUID: "F1007"
_ref: '/portfolioitem/feature/1007'
Name: "Tester's Large Test Card 2"
PreliminaryEstimate: {Value: 21,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your <NAME>", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1008"
_refObjectUUID: "F1008"
_ref: '/portfolioitem/feature/1008'
Name: "Tester's Large Test Card 3"
PreliminaryEstimate: {Value: 13,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your <NAME>", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1009"
_refObjectUUID: "F1009"
_ref: '/portfolioitem/feature/1009'
Name: "Tester's Large Test Card 4"
PreliminaryEstimate: {Value: 8,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your D<NAME>", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
]
getFeatureStoreFixture: ->
@featureStoreFixture = Ext.create 'Rally.data.wsapi.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PortfolioItem/Feature'
proxy:
type: 'memory'
data: Rally.test.mock.ModelObjectMother.getRecords 'PortfolioItemFeature',
values: @featureStoreData
@featureStoreFixture.model.setProxy 'memory'
@featureStoreFixture
secondFeatureStoreData: [
ObjectID: "1010"
_refObjectUUID: "F1010"
_ref: '/portfolioitem/feature/1010'
Name: "<NAME>"
PreliminaryEstimate: {Value: 6,_refObjectName: "L"}
subscriptionId: "1"
,
ObjectID: "1011"
_refObjectUUID: "F1011"
_ref: '/portfolioitem/feature/1011'
Name: "<NAME>"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
subscriptionId: "1"
]
getSecondFeatureStoreFixture: ->
@secondFeatureStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PortfolioItem/Feature'
proxy:
type: 'memory'
data: Rally.test.mock.ModelObjectMother.getRecords 'PortfolioItemFeature',
values: @secondFeatureStoreData
@secondFeatureStoreFixture.model.setProxy 'memory'
@secondFeatureStoreFixture
getPreliminaryEstimateStoreFixture: ->
@preliminaryEstimateStoreFixture = Ext.create 'Rally.data.wsapi.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PreliminaryEstimate'
proxy:
type: 'memory'
data: [
{Value: 8, _refObjectName: 'L', Name: 'L', Description: 'Large'}
]
@preliminaryEstimateStoreFixture.model.setProxy 'memory'
@preliminaryEstimateStoreFixture
getTimelineStoreFixture: ->
@timelineStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getTimelineModel()
proxy:
type: 'memory'
data: [
id: 'timeline-id-1'
timeframes: [
id: 1
]
]
@timelineStoreFixture.model.setProxy 'memory'
@timelineStoreFixture
getTimeframeStoreFixture: ->
@timeframeStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getTimeframeModel()
proxy:
type: 'memory'
data: [
id: '2'
name: 'Q1'
startDate: new Date('1/01/2013')
endDate: new Date('3/31/2013')
timeline:
id: 'timeline-id-1'
,
id: '3'
name: 'Q2'
startDate: new Date('4/01/2013')
endDate: new Date('6/30/2013')
timeline:
id: 'timeline-id-1'
,
id: '4'
name: 'Future Planning Period'
startDate: new Date('7/01/2013')
endDate: new Date('6/30/2099')
timeline:
id: 'timeline-id-1'
,
id: '7'
name: ''
startDate: null
endDate: null
timeline:
id: 'timeline-id-1'
,
id: '8'
name: 'Timeframe not linked to a plan'
startDate: new Date('7/01/2014')
endDate: new Date('10/31/2014')
timeline:
id: 'timeline-id-1'
]
@timeframeStoreFixture.model.setProxy 'memory'
@timeframeStoreFixture
| true | Ext = window.Ext4 || window.Ext
Ext.define 'Rally.test.apps.roadmapplanningboard.mocks.StoreFixtureFactory',
singleton: true
requires: [
'Rally.data.Store'
'Rally.test.mock.data.WsapiModelFactory'
'Rally.apps.roadmapplanningboard.AppModelFactory'
]
getRoadmapStoreFixture: ->
@roadmapStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getRoadmapModel()
proxy:
type: 'memory'
data: [
id: "roadmap-id-1"
Name: "My Roadmap"
ref: "http://localhost:8090/plan-service/api/plan/roadmap-id-1"
plans: [
id: "5PI:KEY:<KEY>END_PI6PI:KEY:<KEY>END_PI"
,
id: "5PI:KEY:<KEY>END_PI"
,
id: "5PI:KEY:<KEY>END_PI80PI:KEY:<KEY>END_PI"
]
,
id: "77"
Name: "test"
ref: "test"
plans: [
id: "3"
,
id: "rgreaesrgsrdbsrdghsrgsrese" #non-existent plan
]
]
@roadmapStoreFixture.model.setProxy 'memory'
@roadmapStoreFixture
getPlanStoreFixture: ->
@planStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getPlanModel()
proxy:
type: 'memory'
data: [
id: "PI:KEY:<KEY>END_PI"
ref: "http://localhost:8090/plan-service/api/plan/513617ecef8623df1391fefc"
lowCapacity: 2
highCapacity: 8
Name: "Release 1.1"
theme: "Take over the world!"
roadmap:
id: 'roadmap-id-1'
timeframe:
id: "2"
features: [
id: "F1000"
,
id: "F1001"
,
id: "F1002"
]
,
id: "513617f7ef8623df1391fefd"
ref: "http://localhost:8090/plan-service/api/plan/513617f7ef8623df1391fefd"
lowCapacity: 3
highCapacity: 30
Name: "Release 1.2"
theme: "Win Foosball Championship"
timeframe:
id: "3"
roadmap:
id: 'roadmap-id-1'
features: [
id: "F1005"
,
id: "F1006"
]
,
id: "51361807ef8623df1391fefe"
ref: "http://localhost:8090/plan-service/api/plan/51361807ef8623df1391fefe"
lowCapacity: 15
highCapacity: 25
Name: "Release 2.0"
timeframe:
id: "4"
roadmap:
id: 'roadmap-id-1'
features: []
,
id: "3"
ref: "http://localhost:8090/plan-service/api/plan/3"
lowCapacity: 0
highCapacity: 0
Name: " "
timeframe:
id: "7"
features: []
]
@planStoreFixture.model.setProxy 'memory'
@planStoreFixture
featureStoreData: [
ObjectID: "1000"
_refObjectUUID: "F1000"
_ref: '/portfolioitem/feature/1000'
Name: "Android Support"
PreliminaryEstimate: {Value: 4,_refObjectName: "L"}
RefinedEstimate: 5
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1001"
_refObjectUUID: "F1001"
_ref: '/portfolioitem/feature/1001'
Name: "iOS Support"
PreliminaryEstimate: {Value: 2,_refObjectName: "L"}
RefinedEstimate: 4
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1002"
_refObjectUUID: "F1002"
_ref: '/portfolioitem/feature/1002'
Name: "HTML 5 Webapp"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
RefinedEstimate: 3
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1003"
_refObjectUUID: "F1003"
_ref: '/portfolioitem/feature/1003'
Name: "Blackberry Native App"
PreliminaryEstimate: {Value: 1,_refObjectName: "L"}
RefinedEstimate: 2
subscriptionId: "1"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your Daddy", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1004"
_refObjectUUID: "F1004"
_ref: '/portfolioitem/feature/1004'
Name: "Windows Phone Support"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
RefinedEstimate: 1
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your PI:NAME:<NAME>END_PI", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1005"
_refObjectUUID: "F1005"
_ref: '/portfolioitem/feature/1005'
Name: "Ubuntu Phone Application"
PreliminaryEstimate: {Value: 4,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your PI:NAME:<NAME>END_PI", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1006"
_refObjectUUID: "F1006"
_ref: '/portfolioitem/feature/1006'
Name: "Tester's Large Test Card 1"
PreliminaryEstimate: {Value: 13,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your PI:NAME:<NAME>END_PI", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1007"
_refObjectUUID: "F1007"
_ref: '/portfolioitem/feature/1007'
Name: "Tester's Large Test Card 2"
PreliminaryEstimate: {Value: 21,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your PI:NAME:<NAME>END_PI", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1008"
_refObjectUUID: "F1008"
_ref: '/portfolioitem/feature/1008'
Name: "Tester's Large Test Card 3"
PreliminaryEstimate: {Value: 13,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your PI:NAME:<NAME>END_PI", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
,
ObjectID: "1009"
_refObjectUUID: "F1009"
_ref: '/portfolioitem/feature/1009'
Name: "Tester's Large Test Card 4"
PreliminaryEstimate: {Value: 8,_refObjectName: "L"}
RefinedEstimate: 0
subscriptionId: "2"
Project: {_refObjectName: "My Project"}
Parent: {_refObjectName: "Who's Your DPI:NAME:<NAME>END_PI", FormattedID: "I1"}
LeafStoryCount: 42
DirectChildrenCount: 39
]
getFeatureStoreFixture: ->
@featureStoreFixture = Ext.create 'Rally.data.wsapi.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PortfolioItem/Feature'
proxy:
type: 'memory'
data: Rally.test.mock.ModelObjectMother.getRecords 'PortfolioItemFeature',
values: @featureStoreData
@featureStoreFixture.model.setProxy 'memory'
@featureStoreFixture
secondFeatureStoreData: [
ObjectID: "1010"
_refObjectUUID: "F1010"
_ref: '/portfolioitem/feature/1010'
Name: "PI:NAME:<NAME>END_PI"
PreliminaryEstimate: {Value: 6,_refObjectName: "L"}
subscriptionId: "1"
,
ObjectID: "1011"
_refObjectUUID: "F1011"
_ref: '/portfolioitem/feature/1011'
Name: "PI:NAME:<NAME>END_PI"
PreliminaryEstimate: {Value: 3,_refObjectName: "L"}
subscriptionId: "1"
]
getSecondFeatureStoreFixture: ->
@secondFeatureStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PortfolioItem/Feature'
proxy:
type: 'memory'
data: Rally.test.mock.ModelObjectMother.getRecords 'PortfolioItemFeature',
values: @secondFeatureStoreData
@secondFeatureStoreFixture.model.setProxy 'memory'
@secondFeatureStoreFixture
getPreliminaryEstimateStoreFixture: ->
@preliminaryEstimateStoreFixture = Ext.create 'Rally.data.wsapi.Store',
model: Rally.test.mock.data.WsapiModelFactory.getModel 'PreliminaryEstimate'
proxy:
type: 'memory'
data: [
{Value: 8, _refObjectName: 'L', Name: 'L', Description: 'Large'}
]
@preliminaryEstimateStoreFixture.model.setProxy 'memory'
@preliminaryEstimateStoreFixture
getTimelineStoreFixture: ->
@timelineStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getTimelineModel()
proxy:
type: 'memory'
data: [
id: 'timeline-id-1'
timeframes: [
id: 1
]
]
@timelineStoreFixture.model.setProxy 'memory'
@timelineStoreFixture
getTimeframeStoreFixture: ->
@timeframeStoreFixture = Ext.create 'Rally.data.Store',
model: Rally.apps.roadmapplanningboard.AppModelFactory.getTimeframeModel()
proxy:
type: 'memory'
data: [
id: '2'
name: 'Q1'
startDate: new Date('1/01/2013')
endDate: new Date('3/31/2013')
timeline:
id: 'timeline-id-1'
,
id: '3'
name: 'Q2'
startDate: new Date('4/01/2013')
endDate: new Date('6/30/2013')
timeline:
id: 'timeline-id-1'
,
id: '4'
name: 'Future Planning Period'
startDate: new Date('7/01/2013')
endDate: new Date('6/30/2099')
timeline:
id: 'timeline-id-1'
,
id: '7'
name: ''
startDate: null
endDate: null
timeline:
id: 'timeline-id-1'
,
id: '8'
name: 'Timeframe not linked to a plan'
startDate: new Date('7/01/2014')
endDate: new Date('10/31/2014')
timeline:
id: 'timeline-id-1'
]
@timeframeStoreFixture.model.setProxy 'memory'
@timeframeStoreFixture
|
[
{
"context": " All Zynq, Versal\n# Author: ZirconfleX\n# Purpose: Snippets for ATO",
"end": 288,
"score": 0.5839036703109741,
"start": 287,
"tag": "NAME",
"value": "Z"
},
{
"context": " All Zynq, Versal\n# Author: ZirconfleX\n#... | snippets/snippets.cson | ZirconfleX/Xilinx-Unisims-Vhdl-Atom | 0 | #-------------------------------------------------------------------------------------------
# VHDL Xilinx Unisim Library component snippets
# Device: Spartan-6, Virtex-5, Virtex-6, 7-Series, All Ultrascale,
# All Zynq, Versal
# Author: ZirconfleX
# Purpose: Snippets for ATOM editor created from the Xilinx
# UNISIM component libraries.
# Tools: Atom Editor
# Limitations: None
#
# Version: 0.0.2
# Filename: snippets.cson
# Date Created: 17Jan19
# Date Last Modified: 24Mar20
#-------------------------------------------------------------------------------------------
# Disclaimer:
# This file is delivered as is.
# The supplier cannot be held accountable for any typo or other flaw in this file.
# The supplier cannot be held accountable if Xilinx modifies whatsoever to its
# library of components/primitives.
#-------------------------------------------------------------------------------------------
#
'.source.vhdl':
'BITSLICE_CONTROL':
'prefix': 'BITSLICE_CONTROL'
'body': """
${1:FileName}_I_Btslce_Ctrl_${2:0} : BITSLICE_CONTROL
generic map (
CTRL_CLK => "EXTERNAL", -- string
DIV_MODE => "DIV2", -- string
EN_CLK_TO_EXT_NORTH => "DISABLE", -- string
EN_CLK_TO_EXT_SOUTH => "DISABLE", -- string
EN_DYN_ODLY_MODE => "FALSE", -- string
EN_OTHER_NCLK => "FALSE", -- string
EN_OTHER_PCLK => "FALSE", -- string
IDLY_VT_TRACK => "TRUE", -- string
INV_RXCLK => "FALSE", -- string
ODLY_VT_TRACK => "TRUE", -- string
QDLY_VT_TRACK => "TRUE", -- string
READ_IDLE_COUNT => "00" & X"0", -- std_logic_vector[5:0]
REFCLK_SRC => "PLLCLK", -- string
ROUNDING_FACTOR => 16, -- integer
RXGATE_EXTEND => "FALSE", -- string
RX_CLK_PHASE_N => "SHIFT_0", -- string
RX_CLK_PHASE_P => "SHIFT_0", -- string
RX_GATING => "DISABLE", -- string
SELF_CALIBRATE => "ENABLE", -- string
SERIAL_MODE => "FALSE", -- string
TX_GATING => "DISABLE", -- string
SIM_SPEEDUP => "FAST", -- string
SIM_VERSION => 2.0 -- real
)
port map (
RIU_CLK => $3, -- in
RIU_WR_EN => $4, -- in
RIU_NIBBLE_SEL => $5, -- in
RIU_ADDR => $6, -- in [5:0]
RIU_WR_DATA => $7, -- in [15:0]
RIU_RD_DATA => $8, -- out [15:0]
RIU_VALID => $9, -- out
PLL_CLK => $10 -- in
REFCLK => $11,-- in
RST => $12, -- in
EN_VTC => $13, -- in
VTC_RDY => $14, -- out
DLY_RDY => $15, -- out
DYN_DCI => $16, -- out [6:0]
TBYTE_IN => $17, -- in [3:0]
PHY_RDEN => $18, -- in [3:0]
PHY_RDCS0 => $29, -- in [3:0]
PHY_RDCS1 => $20, -- in [3:0]
PHY_WRCS0 => $21, -- in [3:0]
PHY_WRCS1 => $22, -- in [3:0]
CLK_FROM_EXT => $23, -- in
NCLK_NIBBLE_IN => $24, -- in
PCLK_NIBBLE_IN => $25, -- in
NCLK_NIBBLE_OUT => $26, -- out
PCLK_NIBBLE_OUT => $27, -- out
CLK_TO_EXT_NORTH => $28, -- out
CLK_TO_EXT_SOUTH => $29, -- out
RX_BIT_CTRL_OUT0 => $30, -- out [39:0]
RX_BIT_CTRL_OUT1 => $31, -- out [39:0]
RX_BIT_CTRL_OUT2 => $32, -- out [39:0]
RX_BIT_CTRL_OUT3 => $33, -- out [39:0]
RX_BIT_CTRL_OUT4 => $34, -- out [39:0]
RX_BIT_CTRL_OUT5 => $35, -- out [39:0]
RX_BIT_CTRL_OUT6 => $36, -- out [39:0]
RX_BIT_CTRL_IN0 => $37, -- in [39:0]
RX_BIT_CTRL_IN1 => $38, -- in [39:0]
RX_BIT_CTRL_IN2 => $39, -- in [39:0]
RX_BIT_CTRL_IN3 => $40, -- in [39:0]
RX_BIT_CTRL_IN4 => $41, -- in [39:0]
RX_BIT_CTRL_IN5 => $42, -- in [39:0]
RX_BIT_CTRL_IN6 => $43, -- in [39:0]
TX_BIT_CTRL_OUT0 => $44, -- out [39:0]
TX_BIT_CTRL_OUT1 => $45, -- out [39:0]
TX_BIT_CTRL_OUT2 => $46, -- out [39:0]
TX_BIT_CTRL_OUT3 => $47, -- out [39:0]
TX_BIT_CTRL_OUT4 => $48, -- out [39:0]
TX_BIT_CTRL_OUT5 => $49, -- out [39:0]
TX_BIT_CTRL_OUT6 => $50, -- out [39:0]
TX_BIT_CTRL_IN0 => $51, -- in [39:0]
TX_BIT_CTRL_IN1 => $52, -- in [39:0]
TX_BIT_CTRL_IN2 => $53, -- in [39:0]
TX_BIT_CTRL_IN3 => $54, -- in [39:0]
TX_BIT_CTRL_IN4 => $55, -- in [39:0]
TX_BIT_CTRL_IN5 => $56, -- in [39:0]
TX_BIT_CTRL_IN6 => $57, -- in [39:0]
TX_BIT_CTRL_OUT_TRI => $58, -- out [39:0]
TX_BIT_CTRL_IN_TRI => $59-- in [39:0]
);
"""
'BOUNDARY_SCAN':
'prefix': 'BSCANE2'
'body': """
${1:FileName}_I_Bscane2_${2:0} : BSCANE2
generic map (DISABLE_JTAG => "FALSE", JTAG_CHAIN => 1)
port map (
TDI => $3, -- out
TCK => $3, -- out
TMS => $4, -- out
TDO => $5, -- in
DRCK => $6, -- out
SEL => $7, -- out
SHIFT => $8, -- out
CAPTURE => $9, -- out
RESET => $10 -- out
UPDATE => $11, -- out
RUNTEST => $12 -- out
);
"""
'BUFCE_LEAF':
'prefix': 'BUFCE_LEAF'
'body': """
${1:FileName}_I_Bufce_Leaf_${2:0} : BUFCE_LEAF
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFCE_ROW':
'prefix': 'BUFCE_ROW'
'body': """
${1:FileName}_I_Bufce_Row_${2:0} : BUFCE_ROW
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFG':
'prefix': 'BUFG'
'body': """
${1:FileName}_I_Bufg_${2:0} : BUFG port map (I => $3, O => $4);
"""
'BUFG_GT':
'prefix': 'BUFG_GT'
'body': """
${1:FileName}_I_Btslce_Ctrl_${2:0} : BUFG_GT
generic map (IS_CLR_INVERTED => $2) -- '0'
port map (
I => $3, -- in
CE => $4, -- in
CEMASK => $5, -- in
CLR => $6, -- in
CLRMASK => $7, -- in
DIV => $8, -- in [2:0]
O => $9 -- out
);
"""
'BUFG_GT_SYNC':
'prefix': 'BUFG_GT_SYNC'
'body': """
${1:FileName}_I_Bufg_Gt_Sync_${2:0} : BUFG_GT_SYNC
port map (
CLK => $3, -- in
CLR => $4, -- in
CE => $5, -- in
CESYNC => $6, -- out
CLRSYNC => $7 -- out
);
"""
'BUFG_PS':
'prefix': 'BUFG_PS'
'body': """
${1:FileName}_I_Bufg_Ps_${2:0} : BUFG_PS
generic map (SIM_DEVICE => "ULTRASCALE_PLUS", STARTUP_SYNC => "FALSE");
port map (I => $3, O => $4);
"""
'BUFGCE':
'prefix': 'BUFGCE'
'body': """
${1:FileName}_I_Bufgce_${2:0} : BUFGCE
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ukogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFGCE_DIV':
'prefix': 'BUFGCE_DIV'
'body': """
${1:FileName}_I_Bufgce_Div_${2:0} : BUFGCE_DIV
generic map (
BUFGCE_DIVIDE => 1, -- integer
IS_CE_INVERTED => '0', -- std_ulogic
IS_CLR_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
CLR => $5, -- in
O => $6 -- out
);
"""
'BUFGCTRL':
'prefix': 'BUFGCTRL'
'body': """
${1:FileName}_I_Bufgctrl_${2:0} : BUFGCTRL
generic map (
CE_TYPE_CE0 => "SYNC", -- string
CE_TYPE_CE1 => "SYNC", -- string
INIT_OUT => 0, -- integer
IS_CE0_INVERTED => '0', -- std_ulogic
IS_CE1_INVERTED => '0', -- std_ulogic
IS_I0_INVERTED => '0', -- std_ulogic
IS_I1_INVERTED => '0', -- std_ulogic
IS_IGNORE0_INVERTED => '0', -- std_ulogic
IS_IGNORE1_INVERTED => '0', -- std_ulogic
IS_S0_INVERTED => '0', -- std_ulogic
IS_S1_INVERTED => '0', -- std_ulogic
PRESELECT_I0 => false, -- boolean
PRESELECT_I1 => false, -- boolean
SIM_DEVICE => "ULTRASCALE", -- string
STARTUP_SYNC => "FALSE" -- string
)
port map (
I0 => $3, -- in
I1 => $4, -- in
S0 => $5, -- in
S1 => $6, -- in
CE0 => $7, -- in
CE1 => $8, -- in
IGNORE0 => $9, -- in
IGNORE1 => $10, -- in
O => $11 -- out
);
"""
'BUFGP':
'prefix': 'BUFGP'
'body': """
${1:FileName}_I_Bufgp_${2:0} : BUFGP port map (I => $3, O => $4);
"""
'BUFH':
'prefix': 'BUFH'
'body': """
${1:FileName}_I_Bufh_${2:0} : BUFH port map (I => $3, O => $4);
"""
'BUFHCE':
'prefix': 'BUFHCE'
'body': """
${1:FileName}_I_Bufhce_${2:0} : BUFHCE
generic map (CE_TYPE => "SYNC", INIT_OUT => 0)
port map (I => $3, CE => $4, O => $5);
"""
'BUFIO':
'prefix': 'BUFIO'
'body': """
${1:FileName}_I_Bufio_${2:0} : BUFIO port map (I => $3, O => $4);
"""
'BUFMR':
'prefix': 'BUFMR'
'body': """
${1:FileName}_I_Bufmr_${2:0} : BUFMR port map (I => $3, O => $4);
"""
'BUFMRCE':
'prefix': 'BUFMRCE'
'body': """
${1:FileName}_I_Bufmrce_${2:0} : ;BUFMRCE
generic map (
CE_TYPE => "SYNC", -- string
INIT_OUT => 0, -- integer
IS_CE_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFR':
'prefix': 'BUFR'
'body': """
${1:FileName}_I_Bufr_${2:0} : BUFR
generic map (BUFR_DIVIDE => "BYPASS", SIM_DEVICE => "7SERIES")
port map (I => $3, CE => $4, CLR => $5, O => $6);
"""
'CARRY4':
'prefix': 'CARRY4'
'body': """
${1:FileName}_I_Carry4_${2:0} : CARRY4
port map (
DI => $3, -- in [3:0]
S => $4, -- in [3:0]
CYINIT => $5, -- in
CI => $6, -- in
O => $7, -- out [3:0]
CO => $8 -- out [3:0]
);
"""
'CARRY8':
'prefix': 'CARRY8'
'body': """
${1:FileName}_I_Carry8_${2:0} : CARRY8
generic map (CARRY_TYPE => "SINGLE_CY8")
port map (
CI => $3, -- in
CI_TOP => $4, -- in
DI => $5, -- in [7:0]
S => $6, -- in [7:0]
CO => $7, -- out [7:0]
O => $8 -- out [7:0]
);
"""
'CFGLUT5':
'prefix': 'CFGLUT5'
'body': """
${1:FileName}_I_Cfglut5_${2:0} : CFGLUT5
generic map (INIT => X"00000000")
port map (
CDI => $3, -- in
I0 => $4, -- in
I1 => $5, -- in
I2 => $7, -- in
I3 => $8, -- in
I4 => $9, -- in
CE => $10, -- in
CLK => $11, -- in
O5 => $12, -- out
O6 => $13, -- out
CDO => $14 -- out
);
"""
'DIFFINBUF':
'prefix': 'DIFFINBUF'
'body': """
${1:FileName}_I_Diffinbuf_${2:0} : DIFFINBUF
generic map (
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
ISTANDARD => "UNUSED", -- string
SIM_INPUT_BUFFER_OFFSET => 0 -- integer
)
port map (
DIFF_IN_N => $3, -- in
DIFF_IN_P => $4, -- in
OSC => $5, -- in [3:0]
OSC_EN => $6, -- in [1:0]
VREF => $7, -- in
O => $8, -- out
O_B => $9 -- out
);
"""
'DNA_PORT':
'prefix': 'DNA_PORT'
'body': """
${1:FileName}_I_Dna_Port_${2:0} : DNA_PORT
generic map (SIM_DNA_VALUE => X"000000000000000")
port map (
DIN => $3, -- in
READ => $4, -- in
SHIFT => $5, -- in
CLK => $6, -- in
DOUT => $7 -- out
);
"""
'DPLL':
'prefix': 'DPLL'
'body': """
${1:FileName}_I_Dpll_${2:0} : DPLL
generic map (
CLKIN_PERIOD => 0.000, -- real
REF_JITTER => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_FRACT => 0, -- integer
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
COMPENSATION => "AUTO", -- string
DESKEW_DELAY => 0, -- integer
DESKEW_DELAY_EN => "FALSE", -- string
DESKEW_DELAY_PATH => "FALSE", -- string
IS_CLKIN_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SEL_LOCKED_IN => '1', -- bit
SEL_REG_DELAY => "00", -- std_logic_vector[1:0]
USE_REG_VALID => '1' -- bit
)
port map (
CLKFB_DESKEW => $3, -- in
CLKIN_DESKEW => $4, -- in
CLKIN => $5, -- in
PWRDWN => $6, -- in
RST => $7, -- in
CLKOUT0 => $8, -- out
CLKOUT1 => $9, -- out
CLKOUT2 => $10, -- out
CLKOUT3 => $11, -- out
PSCLK => $12, -- in
PSEN => $13, -- in
PSINCDEC => $14, -- in
PSDONE => $15, -- out
DCLK => $16, -- in
DEN => $17, -- in
DWE => $18, -- in
DADDR => $19, -- in [6:0]
DI => $20, -- in [15:0]
DO => $21, -- out 15:0]
DRDY => $22, -- out
LOCKED => $23, -- out
LOCKED_DESKEW => $24, -- out
LOCKED_FB => $25 -- out
);
"""
'DSP48E1':
'prefix': 'DSP48E1'
'body': """
${1:FileName}_I_Dsp48e1_${2:0} : DSP48E1
generic map (
B_INPUT => "DIRECT", -- string
A_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
BCASCREG => 1, -- integer
ACASCREG => 1, -- integer
INMODEREG => 1, -- integer
ALUMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
OPMODEREG => 1, -- integer
PATTERN => X"000000000000", -- bit_vector
MASK => X"3FFFFFFFFFFF", -- bit_vector
AUTORESET_PATDET => "NO_RESET", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
USE_DPORT => FALSE, -- boolean
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "0000000" -- std_logic_vector[6:0]
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [24:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0]
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0]
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in [6:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
);
"""
'DSP48E2':
'prefix': 'DSP48E2'
'body': """
${1:FileName}_I_Dsp48e2_${2:0} : DSP48E2
generic map (
A_INPUT => "DIRECT", -- string
B_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
ACASCREG => 1, -- integer
BCASCREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
INMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
ALUMODEREG => 1, -- integer
OPMODEREG => 1, -- integer
AMULTSEL => "A", -- string
BMULTSEL => "B", -- string
PREADDINSEL => "A", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
AUTORESET_PATDET => "NO_RESET", -- string
AUTORESET_PRIORITY => "RESET", -- string
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
USE_WIDEXOR => "FALSE", -- string
XORSIMD => "XOR24_48_96" -- string
MASK => X"3FFFFFFFFFFF", -- std_logic_vector[47:0]
PATTERN => X"000000000000", -- std_logic_vector[47:0]
RND => X"000000000000", -- std_logic_vector[47:0]
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "000000000", -- std_logic_vector[8:0]
IS_RSTALLCARRYIN_INVERTED => '0', -- bit
IS_RSTALUMODE_INVERTED => '0', -- bit
IS_RSTA_INVERTED => '0', -- bit
IS_RSTB_INVERTED => '0', -- bit
IS_RSTCTRL_INVERTED => '0', -- bit
IS_RSTC_INVERTED => '0', -- bit
IS_RSTD_INVERTED => '0', -- bit
IS_RSTINMODE_INVERTED => '0', -- bit
IS_RSTM_INVERTED => '0', -- bit
IS_RSTP_INVERTED => '0' -- bit
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [26:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0)
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0)
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in (8:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
XOROUT => $52 -- out [7:0]
);
"""
'DSP48E5':
'prefix': 'DSP48E5'
'body': """
${1:FileName}_I_Dsp48e5_${2:0} : DSP48E5
generic map (
A_INPUT => "DIRECT", -- string
B_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
ACASCREG => 1, -- integer
BCASCREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
INMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
ALUMODEREG => 1, -- integer
OPMODEREG => 1, -- integer
AMULTSEL => "A", -- string
BMULTSEL => "B", -- string
PREADDINSEL => "A", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
AUTORESET_PATDET => "NO_RESET", -- string
AUTORESET_PRIORITY => "RESET", -- string
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
USE_WIDEXOR => "FALSE", -- string
XORSIMD => "XOR24_48_96" -- string
MASK => X"3FFFFFFFFFFF", -- std_logic_vector[47:0]
PATTERN => X"000000000000", -- std_logic_vector[47:0]
RND => X"000000000000", -- std_logic_vector[47:0]
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "000000000", -- std_logic_vector[8:0]
IS_RSTALLCARRYIN_INVERTED => '0', -- bit
IS_RSTALUMODE_INVERTED => '0', -- bit
IS_RSTA_INVERTED => '0', -- bit
IS_RSTB_INVERTED => '0', -- bit
IS_RSTCTRL_INVERTED => '0', -- bit
IS_RSTC_INVERTED => '0', -- bit
IS_RSTD_INVERTED => '0', -- bit
IS_RSTINMODE_INVERTED => '0', -- bit
IS_RSTM_INVERTED => '0', -- bit
IS_RSTP_INVERTED => '0' -- bit
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [26:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0)
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0)
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in (8:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
XOROUT => $52 -- out [7:0]
);
"""
'EFUSE_USR':
'prefix': 'EFUSE_USR'
'body': """2
${1:FileName}_I_Efuse_Usr_${:0} : EFUSE_USR
generic map ("
SIM_EFUSE_VALUE => X00000000" -- bit_vector
)
port map (t
EFUSEUSR => $3 -- out [31:0]
);
"""
'FADD':
'prefix': 'FADD'
'body': """
${1:FileName}_I_Fadd_${2:0} : FADD
generic map (
IS_I0_INVERTED => '0', -- bit
IS_I1_INVERTED => '0' -- bit
)
port map (
I0 => $3, -- in
I1 => $4, -- in
CI => $5, -- in
CO => $6, -- out
O => $7 -- out
);
"""
'FDCE':
'prefix': 'FDCE'
'body': """
${1:FileName}_I_Fdce_${2:0} : FDCE
generic map (INIT => '0', IS_CLR_INVERTED => '0',
IS_C_INVERTED => '0', IS_D_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, CLR => $6, Q => $7);
"""
'FDPE':
'prefix': 'FDPE'
'body': """
${1:FileName}_I_Fdpe_${2:0} : FDPE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_PRE_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, PRE => $6, Q => $7);
"""
'FDRE':
'prefix': 'FDRE'
'body': """
${1:FileName}_I_Fdre_${2:0} : FDRE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_R_INVERTED => '0')
port map (D => $3, CE => $3, C => $4, R => $5, Q => $6);
"""
'FDSE':
'prefix': 'FDSE'
'body': """
${1:FileName}_I_Fdse_${2:0} : FDSE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_S_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, S => $6, Q => $7);
"""
'FIFO36E2':
'prefix': 'FIFO36E2'
'body': """
${1:FileName}_I_Fifo36e2_${2:0} : FIFO36E2
generic map (
INIT => X"000000000000000000", -- [71:0]
SRVAL => X"000000000000000000", -- [71:0]
CLOCK_DOMAINS => "INDEPENDENT",
READ_WIDTH => 4,
WRITE_WIDTH => 4,
REGISTER_MODE => "UNREGISTERED",
RDCOUNT_TYPE => "RAW_PNTR",
WRCOUNT_TYPE => "RAW_PNTR",
RSTREG_PRIORITY => "RSTREG",
SLEEP_ASYNC => "FALSE",
CASCADE_ORDER => "NONE",
PROG_EMPTY_THRESH => 256,
PROG_FULL_THRESH => 256,
EN_ECC_PIPE => "FALSE",
EN_ECC_READ => "FALSE",
EN_ECC_WRITE => "FALSE",
FIRST_WORD_FALL_THROUGH => "FALSE",
IS_RDCLK_INVERTED => '0',
IS_RDEN_INVERTED => '0',
IS_RSTREG_INVERTED => '0',
IS_RST_INVERTED => '0',
IS_WRCLK_INVERTED => '0',
IS_WREN_INVERTED => '0'
)
port map (
DIN => $3, -- in [63:0]
DINP => $4, -- in [7:0]
CASDIN => $5, -- in [63:0]
CASDINP => $6, -- in [7:0]
WRCLK => $7, -- in
WREN => $8, -- in
WRCOUNT => $9, -- out [13:0]
WRERR => $10, -- out
WRRSTBUSY => $11, -- out
RDCLK => $12, -- in
RDEN => $13, -- in
RDCOUNT => $14, -- out [13:0]
RDERR => $15, -- out
RDRSTBUSY => $16, -- out
REGCE => $17, -- in
RST => $18, -- in
RSTREG => $19, -- in
SLEEP => $20, -- in
CASDOMUX => $21, -- in
CASDOMUXEN => $22, -- in
CASNXTRDEN => $23, -- in
CASOREGIMUX => $24, -- in
CASOREGIMUXEN => $25, -- in
CASPRVEMPTY => $26, -- in
INJECTDBITERR => $27, -- in
INJECTSBITERR => $28, -- in
CASNXTEMPTY => $29, -- out
CASPRVRDEN => $30, -- out
CASDOUT => $31, -- out [63:0]
CASDOUTP => $32, -- out [7:0]
DOUT => $33, -- out [63:0]
DOUTP => $34, -- out [7:0]
ECCPARITY => $35, -- out [7:0]
EMPTY => $36, -- out
FULL => $37, -- out
PROGEMPTY => $38, -- out
PROGFULL => $39, -- out
DBITERR => $40, -- out
SBITERR => $41 -- out
);
"""
'GLBL_VHD':
'prefix': 'GLBL_VHD'
'body': """
${1:FileName}_I_Glbl_Vhd_${2:0} : GLBL_VHD
generic map (
ROC_WIDTH => 100000, -- integer
TOC_WIDTH => 0 -- integer
);
"""
'HARD_SYNC':
'prefix': 'HARD_SYNC'
'body': """
${1:FileName}_I_Hard_Sync_${2:0} : HARD_SYNC
generic map (
INIT => , -- '0'
IS_CLK_INVERTED => , -- '0'
LATENCY => -- 2
)
port map (
CLK => $3, -- in
DIN => $4, -- in
DOUT => $5 -- out
);
"""
'IBUF':
'prefix': 'IBUF'
'body': """
${1:FileName}_I_Ibuf_${2:0} : IBUF
generic map (CAPACITANCE => "DONT_CARE",IBUF_DELAY_VALUE => "0",
IFD_DELAY_VALUE => "AUTO", IBUF_LOW_PWR => TRUE,
IOSTANDARD => "DEFAULT")
port map (I => $3, O => $4);
"""
'IBUFCTRL':
'prefix': 'IBUFCTRL'
'body': """
${1:FileName}_I_Ibufctrl_${2:0} : IBUFCTRL
generic map (
ISTANDARD => "UNUSED", -- string
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
T => $3, -- in
I => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7 -- out
);
"""
'IBUFDS':
'prefix': 'IBUFDS'
'body': """
${1:FileName}_I_Ibufds_${2:0} : IBUFDS
generic map (DIFF_TERM => FALSE, IOSTANDARD => "DEFAULT", CAPACITANCE => "DONT_CARE",
DQS_BIAS => "FALSE", IBUF_DELAY_VALUE => "0", IBUF_LOW_PWR => TRUE,
IFD_DELAY_VALUE => "AUTO")
port map (I => $3, IB => $4, O => $5);
"""
'IBUFDSE3':
'prefix': 'IBUFDSE3'
'body': """
${1:FileName}_I_Ibufdse3_${2:0} : IBUFDSE3
generic (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET =: 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
OSC => $6, -- in [3:0]
OSC_EN => $7, -- in [1:0]
O => $8, -- out
);
"""
'IBUFDS_DIFF_OUT':
'prefix': 'IBUFDS_DIFF_OUT'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_${2:0} : IBUFDS_DIFF_OUT
generic map (
DIFF_TERM => FALSE, -- boolean
IBUF_LOW_PWR => TRUE, -- boolean
DQS_BIAS => "FALSE", -- string
IOSTANDARD => "DEFAULT" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'IBUFDS_DIFF_OUT_IBUFDISABLE':
'prefix': 'IBUFDS_DIFF_OUT_IBUFDISABLE'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_Dsble${2:0} : IBUFDS_DIFF_OUT_IBUFDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
DQS_BIAS => "FALSE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
O => $6, -- out
OB => $7 -- out
);
"""
'IBUFDS_DIFF_OUT_INTERMDISABLE':
'prefix': 'IBUFDS_DIFF_OUT_INTERMDISABLE'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_IntrmDsble_${2:0} : IBUFDS_DIFF_OUT_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
DQS_BIAS => "FALSE", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7, -- out
OB => $8 -- out
);
"""
'IBUFDS_GTE3':
'prefix': 'IBUFDS_GTE3'
'body': """
${1:FileName}_I_Ibufds_Gte3_${2:0} : IBUFDS_GTE3
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => "00", -- [1:0]
REFCLK_ICNTL_RX => "00" -- [1:0]
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_GTE4':
'prefix': 'IBUFDS_GTE4'
'body': """
${1:FileName}_I_Ibufds_Gte4_${2:0} : IBUFDS_GTE4
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => "00", -- [1:0]
REFCLK_ICNTL_RX => "00" -- [1:0]
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_GTE5':
'prefix': 'IBUFDS_GTE5'
'body': """
${1:FileName}_I_Ibufds_Gte5_${2:0} : IBUFDS_GTE5
generic map (
REFCLK_CTL_DRV_SWING => "000", -- std_logic_vector[2:0]
REFCLK_EN_DRV => '0', -- bit
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => 0, -- integer
REFCLK_ICNTL_RX => 0 -- integer
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_IBUFDISABLE':
'prefix': 'IBUFDS_IBUFDISABLE'
'body': """
${1:FileName}_I_Ibufds_dsble_${2:0} : IBUFDS_IBUFDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
O => $6 -- out
);
"""
'IBUFDS_INTERMDISABLE':
'prefix': 'IBUFDS_INTERMDISABLE'
'body': """
${1:FileName}_I_Ibufds_IntrmDsble_${2:0} : IBUFDS_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7 -- out
);
"""
'ICAPE2':
'prefix': 'ICAPE2'
'body': """
${1:FileName}_I_Icape2_${2:0} : ICAPE2
generic map (
DEVICE_ID => X"03651093", -- bit_vector
ICAP_WIDTH => "X32", -- string
SIM_CFG_FILE_NAME => "NONE" -- string
)
port map (
I => $3, -- in [31:0]
RDWRB => $4, -- in
CSIB => $5, -- in
CLK => $6, -- in
O => $7 -- out [31:0]
);
"""
'ICAPE3':
'prefix': 'ICAPE3'
'body': """
${1:FileName}_I_Icape3_${2:0} : ICAPE3
generic map (
DEVICE_ID => X"03628093", -- bit_vector
ICAP_AUTO_SWITCH => "DISABLE", -- string
SIM_CFG_FILE_NAME => "NONE" -- string
)
port map (
I => $3, -- in [31:0]
CLK => $4, -- in
CSIB => $5, -- in
RDWRB => $6, -- in
PRDONE => $7, -- out
PRERROR => $8, -- out
AVAIL => $9, -- out
O => $10 -- out [31:0]
);
"""
'IDDR':
'prefix': 'IDDR'
'body': """
${1:FileName}_I_Iddr_${2:0} : IDDR
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
SRTYPE => "SYNC", -- string
IS_C_INVERTED => '0', -- std_ulogic
IS_D_INVERTED => '0' -- std_ulogic
)
port map (
D => $3, -- in
CE => $4, -- in
C => $5, -- in
S => $6, -- in
R => $7, -- in
Q1 => $8, -- out
Q2 => $9 -- out
);
"""
'IDDR_2CLK':
'prefix': 'IDDR_2CLK'
'body': """
${1:FileName}_I_Iddr_2clk_${2:0} : IDDR_2CLK
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
SRTYPE => "SYNC" -- string
IS_CB_INVERTED => '0', -- std_ulogic
IS_C_INVERTED => '0', -- std_ulogic
IS_D_INVERTED => '0' -- std_ulogic
)
port map (
D => $3, -- in
CE => $4, -- in
C => $5, -- in
CB => $6, -- in
S => $7, -- in
R => $8, -- in
Q1 => $9, -- out
Q2 => $10 -- out
);
"""
'IDDRE1':
'prefix': 'IDDRE1'
'body': """
${1:FileName}_I_Iddre1_${2:0} : IDDRE1
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
IS_CB_INVERTED => '0' -- bit
IS_C_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
C => $4, -- in
CB => $5, -- in
R => $6, -- in
Q1 => $7, -- out
Q2 => $8 -- out
);
"""
'IDELAYCTRL':
'prefix': 'IDELAYCTRL'
'body': """
${1:FileName}_I_Idlyctrl_${2:0} : IDELAYCTRL
generic map (SIM_DEVICE => "7SERIES")
port map(RDY => $3, REFCLK => $3, RST => $4);
"""
'IDELAYE2':
'prefix': 'IDELAYE2'
'body': """
${1:FileName}_I_Idlye2_${2:0} : IDELAYE2
generic map (
SIGNAL_PATTERN => "DATA", -- string
REFCLK_FREQUENCY => 200.0, -- real
HIGH_PERFORMANCE_MODE => "FALSE", -- string
DELAY_SRC => "IDATAIN", -- string
CINVCTRL_SEL => "FALSE", -- string
IDELAY_TYPE => "FIXED", -- string
IDELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
IS_C_INVERTED => '0', -- bit
IS_DATAIN_INVERTED => '0', -- bit
IS_IDATAIN_INVERTED => '0' -- bit
)
port map (
DATAIN => $3, -- in
IDATAIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
C => $7, -- in
CINVCTRL => $8, -- in
LD => $9, -- in
LDPIPEEN => $10, -- in
REGRST => $11, -- in
CNTVALUEIN => $12, -- in [4:0]
CNTVALUEOUT => $13, -- out [4:0]
DATAOUT => $14 -- out
);
"""
'IDELAYE2_FINEDELAY':
'prefix': 'IDELAYE2_FINEDELAY'
'body': """
${1:FileName}_I_Idlye2_fndly_${2:0} : IDELAYE2_FINEDELAY
generic map (
SIGNAL_PATTERN => "DATA", -- string
REFCLK_FREQUENCY => 200.0, -- real
HIGH_PERFORMANCE_MODE => "FALSE", -- string
DELAY_SRC => "IDATAIN", -- string
CINVCTRL_SEL => "FALSE", -- string
FINEDELAY => "BYPASS", -- string
IDELAY_TYPE => "FIXED", -- string
IDELAY_VALUE => 0, -- integer
DELAY_SRC => "IDATAIN", -- string
IS_C_INVERTED => '0', -- bit
IS_DATAIN_INVERTED => '0', -- bit
IS_IDATAIN_INVERTED => '0', -- bit
PIPE_SEL => "FALSE" -- string
)
port map (
DATAIN => $3, -- in
IDATAIN => $4, -- in
IFDLY => $5, -- in [2:0]
CE => $6, -- in
INC => $7, -- in
C => $8, -- in
CINVCTRL => $9, -- in
LD => $10, -- in
LDPIPEEN => $11, -- in
REGRST => $12, -- in
CNTVALUEIN => $13, -- in [4:0]
CNTVALUEOUT => $14, -- out [4:0]
DATAOUT => $15 -- out
);
"""
'IDELAYE3':
'prefix': 'IDELAYE3'
'body': """
${1:FileName}_I_Idlye3_${2:0} : IDELAYE3
generic map (
CASCADE => "NONE", -- string
DELAY_FORMAT => "TIME", -- string
DELAY_SRC => "IDATAIN", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
LOOPBACK => "FALSE", -- string
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
IDATAIN => $3, -- in
DATAIN => $4, -- in
CASC_IN => $5, -- in
CASC_RETURN => $6, -- in
CLK => $7, -- in
CE => $8, -- in
RST => $9, -- in
INC => $10, -- in
LOAD => $11, -- in
EN_VTC => $12, -- in
CNTVALUEIN => $13, -- in [8:0]
CNTVALUEOUT => $14, -- out [8:0]
CASC_OUT => $15, -- out
DATAOUT => $16 -- out
);
"""
'IDELAYE5':
'prefix': 'IDELAYE5'
'body': """
${1:FileName}_I_Idlye5_${2:0} : IDELAYE5
generic map (
CASCADE => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
IDATAIN => $3, -- in
CLK => $4, -- in
CE => $5, -- in
RST => $6, -- in
INC => $7, -- in
LOAD => $8, -- in
CASC_RETURN => $9, -- in
CNTVALUEIN => $10, -- in [4:0]
CNTVALUEOUT => $11, -- out [4:0]
CASC_OUT => $12, -- out
DATAOUT => $13 -- out
);
"""
'INBUF':
'prefix': 'INBUF'
'body': """
${1:FileName}_I_Inbuf_${2:0} : INBUF
generic map (
IBUF_LOW_PWR => "TRUE", -- string
ISTANDARD => "UNUSED", -- string
SIM_INPUT_BUFFER_OFFSET => 0 -- integer
)
port map (
PAD => $3, -- in
VREF => $4, -- in
OSC => $5, -- in [3:0]
OSC_EN => $6, -- in
O => $7 -- out
);
"""
'IN_FIFO':
'prefix': 'IN_FIFO'
'body': """
${1:FileName}_I_In_Fifo_${2:0} : IN_FIFO
generic map (
SYNCHRONOUS_MODE => "FALSE", -- string
ARRAY_MODE => "ARRAY_MODE_4_X_8", -- string
ALMOST_EMPTY_VALUE => 1, -- integer
ALMOST_FULL_VALUE => 1 -- integer
)
port map (
D0 => $3, -- in [3:0]
D1 => $4, -- in [3:0]
D2 => $5, -- in [3:0]
D3 => $6, -- in [3:0]
D4 => $7, -- in [3:0]
D5 => $8, -- in [7:0]
D6 => $9, -- in [7:0]
D7 => $10, -- in [3:0]
D8 => $11, -- in [3:0]
D9 => $12, -- in [3:0]
WRCLK => $13, -- in
WREN => $14, -- in
RESET => $15, -- in
RDCLK => $16, -- in
RDEN => $17, -- in
Q0 => $18, -- out [7:0]
Q1 => $19, -- out [7:0]
Q2 => $20, -- out [7:0]
Q3 => $21, -- out [7:0]
Q4 => $22, -- out [7:0]
Q5 => $23, -- out [7:0]
Q6 => $24, -- out [7:0]
Q7 => $25, -- out [7:0]
Q8 => $26, -- out [7:0]
Q9 => $27, -- out [7:0]
ALMOSTEMPTY => $28, -- out
ALMOSTFULL => $29, -- out
EMPTY => $20, -- out
FULl => $21 -- out
);
"""
'IOBUF':
'prefix': 'IOBUF'
'body': """
${1:FileName}_I_Iobuf_${2:0} : IOBUF
generic map (DRIVE => 12, IBUF_LOW_PWR => TRUE, IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, T => $4, O => $5, IO => $6);
"""
'IOBUFDS':
'prefix': 'IOBUFDS'
'body': """
${1:FileName}_I_Iobufds_${2:0} : IOBUFDS
generic map (
DIFF_TERM => FALSE, -- Boolean
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
SLEW => "SLOW", -- string
IOSTANDARD => "DEFAULT" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5, -- out
IO => $6, -- inout
IOB => $7, -- inout
);
"""
'IOBUFDSE3':
'prefix': 'IOBUFDSE3'
'body': """
${1:FileName}_I_iobufdse3_${2:0} : IOBUFDSE3
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET => 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
T => $6, -- in
O => $7, -- out
OSC => $8, -- in [3:0]
OSC_EN => $9, -- in [1:0]
IBUFDISABLE => $10, -- in
DCITERMDISABLE => $11 -- in
);
"""
'IOBUFDS_DIFF_OUT':
'prefix': 'IOBUFDS_DIFF_OUT'
'body': """
${1:FileName}_I_Iobufds_Diff_Out_${2:0} : IOBUFDS_DIFF_OUT
generic map (
DIFF_TERM => FALSE, -- boolean
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
IOSTANDARD => "DEFAULT" -- stting
)
port map (
I => $3, -- in
TM => $4, -- in
TS => $5, -- in
O => $6, -- out
OB => $7, -- out
IO => $8, -- inout
IOB => $9 -- inout
);
"""
'IOBUFDS_DIFF_OUT_INTERMDISABLE':
'prefix': 'IOBUFDS_DIFF_OUT_INTERMDISABLE'
'body': """
${1:FileName}_I_Iobufds_Diff_Out_Intrmdsble_${2:0} : IOBUFDS_DIFF_OUT_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_DEVICE => "7SERIES", -- string
USE_IBUFDISABLE => "TRUE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
TM => $6, -- in
TS => $7, -- in
O => $8, -- out
OB => $9, -- out
IBUFDISABLE => $10, -- in
INTERMDISABLE => $11 -- in
);
"""
'IOBUFDS_INTERMDISABLE':
'prefix': 'IOBUFDS_INTERMDISABLE'
'body': """
${1:FileName}_I_Iobufds_intrmdsble_${2:0} : IOBUFDS_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_DEVICE => "7SERIES", -- string
SLEW => "SLOW", -- string
USE_IBUFDISABLE => "TRUE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
T => $6, -- in
O => $7, -- out
IBUFDISABLE => $8, -- in
INTERMDISABLE => $9 -- in
);
"""
'IOBUFE3':
'prefix': 'IOBUFE3'
'body': """
${1:FileName}_I_Iobufe3_${2:0} : IOBUFE3
generic map (
DRIVE => 12, -- integer
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET => 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
IO => $3, -- inout
I => $4, -- in
T => $5, -- in
O => $6, -- out
OSC => $7, -- in [3:0]
OSC_EN => $8, -- in
VREF => $9, -- in
DCITERMDISABLE => $10, -- in
IBUFDISABLE => $11 -- in
);
"""
'ISERDES':
'prefix': 'ISERDES'
'body': """
${1:FileName}_I_Isrds_${2:0} : ISERDES
generic map (
BITSLIP_ENABLE => false, -- boolean
DATA_RATE => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
INIT_Q3 => '0', -- bit
INIT_Q4 => '0', -- bit
INTERFACE_TYPE => "MEMORY", -- string
IOBDELAY => "NONE", -- string
IOBDELAY_TYPE => "DEFAULT", -- string
IOBDELAY_VALUE => 0, -- integer
NUM_CE => 2, -- integer
SERDES_MODE => "MASTER", -- string
SRVAL_Q1 => '0', -- bit
SRVAL_Q2 => '0', -- bit
SRVAL_Q3 => '0', -- bit
SRVAL_Q4 => '0' -- bit
)
port map (
D => $3, -- in
CE1 => $4, -- in
CE2 => $5, -- in
SR => $6, -- in
REV => $7, -- in
DLYCE => $8, -- in
DLYINC => $9, -- in
DLYRST => $10, -- in
BITSLIP => $11, -- in
O => $12, -- out
Q1 => $13, -- out
Q2 => $14, -- out
Q3 => $15, -- out
Q4 => $16, -- out
Q5 => $17, -- out
Q6 => $18, -- out
CLK => $19, -- in
CLKDIV => $20, -- in
OCLK => $21, -- in
SHIFTIN1 => $22, -- in
SHIFTIN2 => $23, -- in
SHIFTOUT1 => $24, -- out
SHIFTOUT2 => $25, -- out
);
"""
'ISERDESE2':
'prefix': 'ISERDESE2'
'body': """
${1:FileName}_I_Isrdse2_${2:0} : ISERDESE2
generic map (
SERDES_MODE => "MASTER", -- string
INTERFACE_TYPE => "MEMORY", -- string
IOBDELAY => "NONE", -- string
DATA_RATE => "DDR", -- string
DATA_WIDTH => 4, -- integer
DYN_CLKDIV_INV_EN => "FALSE", -- string
DYN_CLK_INV_EN => "FALSE", -- string
NUM_CE => 2, -- integer
OFB_USED => "FALSE", -- string
INIT_Q1 => '0', -- bit;
INIT_Q2 => '0', -- bit;
INIT_Q3 => '0', -- bit;
INIT_Q4 => '0', -- bit;
SRVAL_Q1 => '0', -- bit;
SRVAL_Q2 => '0', -- bit;
SRVAL_Q3 => '0', -- bit;
SRVAL_Q4 => '0', -- bit
IS_CLKB_INVERTED => '0', -- bit
IS_CLKDIVP_INVERTED => '0', -- bit
IS_CLKDIV_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_D_INVERTED => '0', -- bit
IS_OCLKB_INVERTED => '0', -- bit
IS_OCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
DDLY => $4, -- in
OFB => $5, -- in
BITSLIP => $6, -- in
CE1 => $7, -- in
CE2 => $8, -- in
RST => $9, -- in
CLK => $10, -- in
CLKB => $11, -- in
CLKDIV => $12, -- in
CLKDIVP => $13, -- in
OCLK => $14, -- in
OCLKB => $15, -- in
DYNCLKDIVSEL => $16, -- in
DYNCLKSEL => $17, -- in
SHIFTOUT1 => $18, -- out
SHIFTOUT2 => $19, -- out
O => $20, -- out
Q1 => $21, -- out
Q2 => $22, -- out
Q3 => $23, -- out
Q4 => $24, -- out
Q5 => $25, -- out
Q6 => $26, -- out
Q7 => $27, -- out
Q8 => $28, -- out
SHIFTIN1 => $29, -- in
SHIFTIN2 => $30 -- in
);
"""
'ISERDESE3':
'prefix': 'ISERDESE3'
'body': """
${1:FileName}_I_Isrdse3_${2:0} : ISERDESE3
generic map (
DATA_WIDTH => 8, -- integer
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
FIFO_ENABLE => "FALSE", -- string
FIFO_SYNC_MODE => "FALSE", -- string
IDDR_MODE => "FALSE", -- string
IS_CLK_B_INVERTED => '0', -- std_ulogic
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSIOM => 2.0 -- real
)
port map (
D => $3, -- in
CLK => $4, -- in
CLKDIV => $5, -- in
CLK_B => $6, -- in
RST => $7, -- in
FIFO_RD_CLK => $8, -- in
FIFO_RD_EN => $9, -- in
INTERNAL_DIVCLK => $10, -- out
FIFO_EMPTY => $11, -- out
Q => $12 -- out[7:0]
);
"""
'LUT5':
'prefix': 'LUT5'
'body': """
${1:FileName}_I_Lut5_${2:0} : LUT5
generic map (
INIT => X"00000000"
)
port map (
I0 => $3, -- in
I1 => $4, -- in
I2 => $5, -- in
I3 => $6, -- in
I4 => $7, -- in
O => $8 -- out
);
"""
'LUT6_2':
'prefix': 'LUT6_2'
'body': """
${1:FileName}_I_Lut6_2_${2:0} : LUT6_2
generic map (
INIT => X"0000000000000000" -- bit_vector
)
port map (
I0 => $3, -- in
I1 => $4, -- in
I2 => $5, -- in
I3 => $6, -- in
I4 => $7, -- in
I5 => $8, -- in
O5 => $9, -- out
O6 => $10 -- out
);
"""
'MASTER_JTAG':
'prefix': 'MASTER_JTAG'
'body': """
${1:FileName}_I_Mstr_Jtag_${2:0} : MASTER_JTAG
port map (
TDO => $3, -- out
TCK => $4, -- in
TDI => $5, -- in
TMS => $6 -- in
);
"""
'MMCME2_ADV':
'prefix': 'MMCME2_ADV'
'body': """
${1:FileName}_I_Mmcme2_Adv_${2:0} : MMCME2_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
REF_JITTER1 => 0.0, -- real
REF_JITTER2 => 0.0, -- real
COMPENSATION => "ZHOLD", -- string
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, - real
CLKFBOUT_USE_FINE_PS => FALSE, -- boolean
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => FALSE, -- boolean
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => FALSE, -- boolean
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => FALSE, -- boolean
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => FALSE, -- boolean
CLKOUT4_CASCADE => FALSE, -- boolean
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => FALSE, -- boolean
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => FALSE, -- boolean
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => FALSE, -- boolean
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH",-- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => FALSE -- boolean
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
CLKFBOUT => $7, -- out
CLKFBOUTB => $8, -- out
CLKFBSTOPPED => $9, -- out
CLKINSTOPPED => $10, -- out
RST => $11, -- in
PWRDWN => $12, -- in
LOCKED => $13, -- out
CLKOUT0 => $14, -- out
CLKOUT0B => $15, -- out
CLKOUT1 => $16, -- out
CLKOUT1B => $17, -- out
CLKOUT2 => $18, -- out
CLKOUT2B => $19, -- out
CLKOUT3 => $20, -- out
CLKOUT3B => $21, -- out
CLKOUT4 => $22, -- out
CLKOUT5 => $23, -- out
CLKOUT6 => $24, -- out
DI => $25, -- in [15:0]
DADDR => $26, -- in [6:0]
DEN => $27, -- in
DWE => $28, -- in
DCLK => $29, -- in
DO => $30, -- out [15:0]
DRDY => $31, -- out
PSCLK => $32, -- in
PSEN => $33, -- in
PSINCDEC => $34, -- in
PSDONE => $35 -- out
);
"""
'MMCME3_ADV':
'prefix': 'MMCME3_ADV'
'body': """
${1:FileName}_I_Mmcme3_Adv_${2:0} : MMCME3_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
IS_CLKIN1_INVERTED => '0', -- std_ulogic
IS_CLKIN2_INVERTED => '0', -- std_ulogic
IS_CLKINSEL_INVERTED => '0', -- std_ulogic
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, -- real
CLKFBOUT_USE_FINE_PS => "FALSE", -- string
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => "FALSE", -- string
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => "FALSE", -- string
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => "FALSE", -- string
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => "FALSE", -- string
CLKOUT4_CASCADE => "FALSE", -- string
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => "FALSE", -- string
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => "FALSE", -- string
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => "FALSE", -- string
COMPENSATION => "AUTO", -- string
IS_PSEN_INVERTED => '0', -- std_ulogic
IS_PSINCDEC_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
RST => $7, -- in
PWRDWN => $8, -- in
CLKFBOUT => $9, -- out
CLKFBOUTB => $10, -- out
CLKOUT0 => $11, -- out
CLKOUT0B => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT1B => $14, -- out
CLKOUT2 => $15, -- out
CLKOUT2B => $16, -- out
CLKOUT3 => $17, -- out
CLKOUT3B => $18, -- out
CLKOUT4 => $19, -- out
CLKOUT5 => $20, -- out
CLKOUT6 => $21, -- out
CDDCREQ => $22, -- in
CDDCDONE => $23, -- out
PSCLK => $24, -- in
PSEN => $25, -- in
PSINCDEC => $26, -- in
PSDONE => $27, -- out
DCLK => $28, -- in
DI => $29, -- in [15:0]
DADDR => $30, -- in [6:0]
DEN => $31, -- in
DWE => $32, -- in
DO => $33, -- out [15:0]
DRDY => $34, -- out
CLKFBSTOPPED => $35, -- out
CLKINSTOPPED => $36, -- out
LOCKED => $37 -- out
);
"""
'MMCME4_ADV':
'prefix': 'MMCME4_ADV'
'body': """
${1:FileName}_I_Mmcme4_Adv_${2:0} : MMCME4_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
IS_CLKIN1_INVERTED => '0', -- bit
IS_CLKIN2_INVERTED => '0', -- bit
IS_CLKINSEL_INVERTED => '0', -- bit
IS_CLKFBIN_INVERTED => '0', -- bit
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, -- real
CLKFBOUT_USE_FINE_PS => "FALSE", -- string
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => "FALSE", -- string
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => "FALSE", -- string
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => "FALSE", -- string
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => "FALSE", -- string
CLKOUT4_CASCADE => "FALSE", -- string
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => "FALSE", -- string
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => "FALSE", -- string
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => "FALSE", -- string
COMPENSATION => "AUTO", -- string
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
RST => $7, -- in
PWRDWN => $8, -- in
CLKFBOUT => $9, -- out
CLKFBOUTB => $10, -- out
CLKOUT0 => $11, -- out
CLKOUT0B => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT1B => $14, -- out
CLKOUT2 => $15, -- out
CLKOUT2B => $16, -- out
CLKOUT3 => $17, -- out
CLKOUT3B => $18, -- out
CLKOUT4 => $19, -- out
CLKOUT5 => $20, -- out
CLKOUT6 => $21, -- out
CDDCREQ => $22, -- in
CDDCDONE => $23, -- out
PSCLK => $24, -- in
PSEN => $25, -- in
PSINCDEC => $26, -- in
PSDONE => $27, -- out
DCLK => $28, -- in
DI => $29, -- in [15:0]
DADDR => $30, -- in [6:0]
DEN => $31, -- in
DWE => $32, -- in
DO => $33, -- out([15:0]
DRDY => $34, -- out
CLKFBSTOPPED => $35, -- out
CLKINSTOPPED => $36, -- out
LOCKED => $37, -- out
);
"""
'MMCME5':
'prefix': 'MMCME5'
'body': """
${1:FileName}_I_Mmcme5_${2:0} : MMCME5
generic map (
BANDWIDTH => "OPTIMIZED", -- string
COMPENSATION => "AUTO", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_FRACT => 0, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT4_DIVIDE => 2, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT5_DIVIDE => 2, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT6_DIVIDE => 2, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUTFB_PHASE_CTRL => "00", -- std_logic_vector[1:0]
DESKEW_DELAY1 => 0, -- integer
DESKEW_DELAY2 => 0, -- integer
DESKEW_DELAY_EN1 => "FALSE", -- string
DESKEW_DELAY_EN2 => "FALSE", -- string
DESKEW_DELAY_PATH1 => "FALSE", -- string
DESKEW_DELAY_PATH2 => "FALSE", -- string
IS_CLKFBIN_INVERTED => '0', -- bit
IS_CLKIN1_INVERTED => '0', -- bit
IS_CLKIN2_INVERTED => '0', -- bit
IS_CLKINSEL_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000 -- integer
)
port map (
CLKIN1_DESKEW => $3, -- in
CLKFB1_DESKEW => $4, -- in
CLKIN2_DESKEW => $5, -- in
CLKFB2_DESKEW => $6, -- in
CLKIN1 => $7, -- in
CLKIN2 => $8, -- in
CLKINSEL => $9, -- in
CLKFBIN => $10, -- in
CLKFBOUT => $11, -- out
CLKOUT0 => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT2 => $14, -- out
CLKOUT3 => $15, -- out
CLKOUT4 => $16, -- out
CLKOUT5 => $17, -- out
CLKOUT6 => $18, -- out
PWRDWN => $19, -- in
RST => $20, -- in
PSCLK => $21, -- in
PSEN => $22, -- in
PSINCDEC => $23, -- in
PSDONE => $24, -- out
DCLK => $25, -- in
DEN => $26, -- in
DWE => $27, -- in
DADDR => $28, -- in [6:0]
DI => $29, -- in [15:0]
DO => $30, -- out [15:0]
DRDY => $31, -- out
CLKFBSTOPPED => $32, -- out
CLKINSTOPPED => $33, -- out
LOCKED1_DESKEW => $34, -- out
LOCKED2_DESKEW => $35, -- out
LOCKED_FB => $36, -- out
LOCKED => $37 -- out
);
"""
'MUXCY':
'prefix': 'MUXCY'
'body': """MUXCY
${1:FileName}_I_Muxcy_${2:0} :
port map (
CI => $3, -- in
DI => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF7':
'prefix': 'MUXF7'
'body': """
${1:FileName}_I_Muxf7_${2:0} : MUXF7
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF8':
'prefix': 'MUXF8'
'body': """
${1:FileName}_I_Muxf8_${2:0} : MUXF8
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF9':
'prefix': 'MUXF9'
'body': """
${1:FileName}_I_Muxf9_${2:0} : MUXF9
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'OBUF':
'prefix': 'OBUF'
'body': """
${1:FileName}_I_Obuf_${2:0} : OBUF
generic map (DRIVE => 12, IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, O => $4);
"""
'OBUFDS':
'prefix': 'OBUFDS'
'body': """
${1:FileName}_I_Obufds_${2:0} : OBUFDS
generic map (IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, O => $4, OB => $5);
"""
'OBUFDS_DPHY':
'prefix': 'OBUFDS_DPHY'
'body': """
${1:FileName}_I_Obufds_Dphy_${2:0} : OBUFDS_DPHY
generic map (
IOSTANDARD => "DEFAULT" -- string
)
port map (
HSTX_I => $3, -- in
HSTX_T => $4, -- in
LPTX_I_N => $5, -- in
LPTX_I_P => $6, -- in
LPTX_T => $7, -- in
O => $8, -- out
OB => $9 -- out
);
"""
'OBUFDS_GTE3_ADV':
'prefix': 'OBUFDS_GTE3_ADV'
'body': """
${1:FileName}_I_Obufds_Gte3_Adv_${2:0} : OBUFDS_GTE3_ADV
generic map (
REFCLK_EN_TX_PATH : bit := '0';
REFCLK_ICNTL_TX : std_logic_vector(4 downto 0) := "00000"
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
RXRECCLK_SEL => $5, -- in [1:0]
O => $6, -- out
OB => $7 -- out
);
"""
'OBUFDS_GTE4_ADV':
'prefix': 'OBUFDS_GTE4_ADV'
'body': """
${1:FileName}_I_Obufds_Gte4_Adv_${2:0} : OBUFDS_GTE4_ADV
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_ICNTL_TX => "00000" -- [4:0]
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
RXRECCLK_SEL => $5, -- in [1:0]
O => $6, -- out
OB => $7 -- out
);
"""
'OBUFDS_GTE5_ADV':
'prefix': 'OBUFDS_GTE5_ADV'
'body': """
${1:FileName}_I_Obufds_Gte5_Adv_${2:0} : OBUFDS_GTE5_ADV
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
RXRECCLK_SEL => "00" -- [1:0]
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'OBUFT':
'prefix': 'OBUFT'
'body': """
${1:FileName}_I_Obuft_${2:0} : OBUFT
generic map (
CAPACITANCE => "DONT_CARE", -- string
DRIVE => 12, -- integer
IOSTANDARD => "DEFAULT", -- string
SLEW => "SLOW" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5 -- out
);
"""
'OBUFTDS':
'prefix': 'OBUFTDS'
'body': """
${1:FileName}_I_Obuftds_${2:0} : OBUFTDS
generic map (
CAPACITANCE => "DONT_CARE", -- string
IOSTANDARD => "DEFAULT", -- string
SLEW => "SLOW" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'ODDR':
'prefix': 'ODDR'
'body': """
${1:FileName}_I_Oddr_${2:0} : ODDR
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT => '0', -- bit
SRTYPE => "SYNC" -- string
IS_C_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0' -- bit
)
port map (
D1 => $3, -- in
D2 => $4, -- in
CE => $5, -- in
C => $6, -- in
S => $7, -- in
R => $8, -- in
Q => $9 -- out
);
"""
'ODDRE1':
'prefix': 'ODDRE1'
'body': """
${1:FileName}_I_Oddre1_${2:0} : ODDRE1
generic map (
IS_C_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0', -- bit
SRVAL => '0', -- bit
SIM_DEVICE => "ULTRASCALE" -- string
)
port map (
D1 => $3, -- in
D2 => $4, -- in
C => $5, -- in
SR => $6, -- in
Q => $7 -- out
);
"""
'ODELAYE2':
'prefix': 'ODELAYE2'
'body': """
${1:FileName}_I_Odlye2_${2:0} : ODELAYE2
generic map (
CINVCTRL_SEL => "FALSE", -- string
DELAY_SRC => "ODATAIN", -- string
HIGH_PERFORMANCE_MODE => "FALSE", -- string
ODELAY_TYPE => "FIXED", -- string
ODELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
REFCLK_FREQUENCY => 200.0, -- real
SIGNAL_PATTERN => "DATA", -- string
IS_C_INVERTED => '0', -- bit
IS_ODATAIN_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CLKIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
C => $7, -- in
CINVCTRL => $8, -- in
LD => $9, -- in
LDPIPEEN => $10, -- in
REGRST => $11, -- in
DATAOUT => $12, -- out
CNTVALUEOUT => $13, -- out [4:0]
CNTVALUEIN => $14 -- in [4:0]
);
"""
'ODELAYE2_FINEDELAY':
'prefix': 'ODELAYE2_FINEDELAY'
'body': """
${1:FileName}_I_Odlye2_fndly_${2:0} : ODELAYE2_FINEDELAY
generic map (
CINVCTRL_SEL => "FALSE", -- string
DELAY_SRC => "ODATAIN", -- string
FINEDELAY => "BYPASS", -- string
HIGH_PERFORMANCE_MODE => "FALSE", -- string
ODELAY_TYPE => "FIXED", -- string
ODELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
REFCLK_FREQUENCY => 200.0, -- real
SIGNAL_PATTERN => "DATA", -- string
IS_C_INVERTED => '0', -- bit
IS_ODATAIN_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CLKIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
LD => $7, -- in
LDPIPEEN => $8, -- in
OFDLY => $9, -- in [2:0]
REGRST => $10, -- in
C => $11, -- in
CINVCTRL => $12, -- in
CNTVALUEIN => $13, -- in [4:0]
CNTVALUEOUT => $14, -- out [4:0]
DATAOUT => $15 -- out
);
"""
'ODELAYE3':
'prefix': 'ODELAYE3'
'body': """
${1:FileName}_I_Odlye3_${2:0} : ODELAYE3
generic map (
CASCADE => "NONE", -- string
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
ODATAIN => $3, -- in
CASC_IN => $4, -- in
CASC_RETURN => $5, -- in
CLK => $6, -- in
CE => $7, -- in
RST => $8, -- in
INC => $9, -- in
LOAD => $10, -- in
EN_VTC => $11, -- in
CNTVALUEIN => $12, -- in [8:0]
CNTVALUEOUT => $13, -- out [8:0]
CASC_OUT => $14, -- out
DATAOUT => $15 -- out
);
"""
'ODELAYE5':
'prefix': 'ODELAYE5'
'body': """
${1:FileName}_I_Odlye5_${2:0} : ODELAYE5
generic map (
CASCADE => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CASC_IN => $4, -- in
CE => $5, -- in
INC => $6, -- in
LOAD => $7, -- in
RST => $8, -- in
CLK => $9, -- in
CNTVALUEIN => $10, -- in [4:0]
CNTVALUEOUT => $11, -- out [4:0]
DATAOUT => $12 -- out
);
"""
'OSERDES':
'prefix': 'OSERDES'
'body': """
${1:FileName}_I_Osrds_${2:0} : OSERDES
generic map (
DATA_RATE_OQ => "DDR", -- string
DATA_RATE_TQ => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_OQ => '0', -- bit
INIT_TQ => '0', -- bit
SERDES_MODE => "MASTER", -- string
SRVAL_OQ => '0', -- bit
SRVAL_TQ => '0', -- bit
TRISTATE_WIDTH => 4 -- integer
)
port map (
SHIFTIN1 => $3, -- in
SHIFTIN2 => $4, -- in
D1 => $5, -- in
D2 => $6, -- in
D3 => $7, -- in
D4 => $8, -- in
D5 => $9, -- in
D6 => $10, -- in
OCE => $11, -- in
REV => $12, -- in
SR => $13, -- in
CLK => $14, -- in
CLKDIV => $15, -- in
T1 => $16, -- in
T2 => $17, -- in
T3 => $18, -- in
T4 => $19, -- in
TCE => $20, -- in
SHIFTOUT1 => $21, -- out;
SHIFTOUT2 => $22, -- out;
OQ => $23, -- out;
TQ => $24 -- out;
);
"""
'OSERDESE2':
'prefix': 'OSERDESE2'
'body': """
${1:FileName}_I_Osrdse2_${2:0} : OSERDESE2
generic map (
SERDES_MODE => "MASTER",-- string
DATA_RATE_TQ => "DDR", -- string
TRISTATE_WIDTH => 4, -- integer
INIT_TQ => '0', -- bit
SRVAL_TQ => '0', -- bit
DATA_RATE_OQ => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_OQ => '0', -- bit
SRVAL_OQ => '0', -- bit
TBYTE_CTL => "FALSE", -- string
TBYTE_SRC => "FALSE", -- string
IS_CLKDIV_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0', -- bit
IS_D3_INVERTED => '0', -- bit
IS_D4_INVERTED => '0', -- bit
IS_D5_INVERTED => '0', -- bit
IS_D6_INVERTED => '0', -- bit
IS_D7_INVERTED => '0', -- bit
IS_D8_INVERTED => '0', -- bit
IS_T1_INVERTED => '0', -- bit
IS_T2_INVERTED => '0', -- bit
IS_T3_INVERTED => '0', -- bit
IS_T4_INVERTED => '0', -- bit
)
port map (
SHIFTOUT1 => $3, -- out
D1 => $4, -- in
D2 => $5, -- in
D3 => $6, -- in
D4 => $7, -- in
D5 => $8, -- in
D6 => $9, -- in
D7 => $10, -- in
D8 => $11, -- in
SHIFTIN1 => $12, -- in
SHIFTIN2 => $13, -- in
OCE => $14, -- in
RST => $15, -- in
CLK => $16, -- in
CLKDIV => $17, -- in
OFB => $18, -- out
OQ => $19, -- out
TBYTEOUT => $20, -- out
T1 => $21, -- in
T2 => $22, -- in
T3 => $23, -- in
T4 => $24, -- in
TBYTEIN => $25, -- in
TCE => $26, -- in
TFB => $27, -- out
TQ => $28 -- out
SHIFTOUT2 => $29, -- out
);
"""
'OSERDESE3':
'prefix': 'OSERDESE3'
'body': """
${1:FileName}_I_Osrdse3_${2:0} : OSERDESE3
generic map (
DATA_WIDTH => 8, -- 8
INIT => '0', -- std_ulogic
IS_CLKDIV_INVERTED => '0', -- std_ulogic
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
ODDR_MODE => "FASLE", -- string
OSERDES_D_BYPASS => "FASLE", -- string
OSERDES_T_BYPASS => "FASLE", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => -- real
)
port map (
D => $3, -- in [7:0]
CLK => $4, -- in
CLKDIV => $5, -- in
RST => $6, -- in
T => $7, -- in
T_OUT => $8, -- out
OQ => $9 -- out
);
"""
'OUT_FIFO':
'prefix': 'OUT_FIFO'
'body': """
${1:FileName}_I_Out_Fifo_${2:0} : OUT_FIFO
generic map (
SYNCHRONOUS_MODE => "FALSE", -- string
ARRAY_MODE => "ARRAY_MODE_8_X_4", -- string
ALMOST_EMPTY_VALUE => 1, -- integer
ALMOST_FULL_VALUE => 1, -- integer
OUTPUT_DISABLE => "FALSE" -- string
)
port map (
D0 => $3, -- in [7:0}
D1 => $4, -- in [7:0}
D2 => $5, -- in [7:0}
D3 => $6, -- in [7:0}
D4 => $7, -- in [7:0}
D5 => $8, -- in [7:0}
D6 => $9, -- in [7:0}
D7 => $10, -- in [7:0}
D8 => $11, -- in [7:0}
D9 => $12, -- in [7:0}
WRCLK => $13, -- in
WREN => $14, -- in
RESET => $15, -- in
RDCLK => $16, -- in
RDEN => $17, -- in
Q0 => $18, -- out [3:0]
Q1 => $19, -- out [3:0]
Q2 => $20, -- out [3:0]
Q3 => $21, -- out [3:0]
Q4 => $22, -- out [3:0]
Q5 => $23, -- out [7:0]
Q6 => $24, -- out [7:0]
Q7 => $25, -- out [3:0]
Q8 => $26, -- out [3:0]
Q9 => $27, -- out [3:0]
ALMOSTEMPTY => $28, -- out
ALMOSTFULL => $29, -- out
EMPTY => $30, -- out
FULL => $31 -- out
);
"""
'PLLE2_ADV':
'prefix': 'PLLE2_ADV'
'body': """
${1:FileName}_I_Plle2_Adv_${2:0} : PLLE2_ADV
generic map(
BANDWIDTH => "OPTIMIZED", -- string
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.0, -- real
CLKIN1_PERIOD => 0.0, -- real
CLKIN2_PERIOD => 0.0, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.5, -- real
CLKOUT0_PHASE => 0.0, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.5, -- real
CLKOUT1_PHASE => 0.0, -- real
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.5, -- real
CLKOUT2_PHASE => 0.0, -- real
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.5, -- real
CLKOUT3_PHASE => 0.0, -- real
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.5, -- real
CLKOUT4_PHASE => 0.0, -- real
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.5, -- real
CLKOUT5_PHASE => 0.0, -- real
COMPENSATION => "ZHOLD", -- string
DIVCLK_DIVIDE => 1, -- integer
REF_JITTER1 => 0.0, -- real
REF_JITTER2 => 0.0, -- real
STARTUP_WAIT => "FALSE", -- string
IS_CLKINSEL_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
CLKIN1 => $3, -- in
CLKINSEL => $4, -- in
CLKFBIN => $5, -- in
CLKFBOUT => $6, -- out
CLKOUT0 => $7, -- out
CLKOUT1 => $8, -- out
CLKOUT2 => $9, -- out
CLKOUT3 => $10, -- out
CLKOUT4 => $11, -- out
CLKOUT5 => $12, -- out
RST => $13, -- in
PWRDWN => $14, -- in
LOCKED => $15, -- out
DI => $16, -- in [15:0]
DADDR => $17, -- in [6:0]
DEN => $18, -- in
DWE => $19, -- in
DCLK => $20, -- in
DO => $21, -- out [15:0]
DRDY => $22 -- out
CLKIN2 => $23, -- in
);
"""
'PLLE3_ADV':
'prefix': 'PLLE3_ADV'
'body': """
${1:FileName}_I_Plle3_Adv_${2:0} : PLLE3_ADV
generic map (
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKIN_PERIOD => 0.000, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUTPHY_MODE => "VCO_2X", -- string
COMPENSATION => "AUTO", -- string
DIVCLK_DIVIDE => 1, -- integer
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
IS_CLKIN_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REF_JITTER => 0.010, -- real
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN => $3, -- in
CLKFBIN => $4, -- in
RST => $5, -- in
PWRDWN => $6, -- in
CLKOUTPHYEN => $7, -- in
CLKFBOUT => $8, -- out
CLKOUT0 => $9, -- out
CLKOUT0B => $10, -- out
CLKOUT1 => $11, -- out
CLKOUT1B => $12, -- out
CLKOUTPHY => $13, -- out
DCLK => $14, -- in
DI => $15, -- in [15:0]
DADDR => $16, -- in [6:0]
DEN => $17, -- in
DWE => $18, -- in
DO => $19, -- out [15:0]
DRDY => $20, -- out
LOCKED => $21 -- out
);
"""
'PLLE4_ADV':
'prefix': 'PLLE4_ADV'
'body': """
${1:FileName}_I_Plle4_Adv_${2:0} :PLLE4_ADV
generic map (
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKIN_PERIOD => 0.000, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUTPHY_MODE => "VCO_2X", -- string
COMPENSATION => "AUTO", -- string
DIVCLK_DIVIDE => 1, -- integer
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
IS_CLKIN_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REF_JITTER => 0.010, -- real
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN => $3, -- in
CLKFBIN => $4, -- in
RST => $5, -- in
PWRDWN => $6, -- in
CLKOUTPHYEN => $7, -- in
CLKFBOUT => $8, -- out
CLKOUT0 => $9, -- out
CLKOUT0B => $10, -- out
CLKOUT1 => $11, -- out
CLKOUT1B => $12, -- out
CLKOUTPHY => $13, -- out
DCLK => $14, -- in
DI => $15, -- in [15:0]
DADDR => $16, -- in [6:0]
DEN => $17, -- in
DWE => $18, -- in
DO => $19, -- out [15:0]
DRDY => $20, -- out
LOCKED => $21 -- out
);
"""
'RAM256X1D':
'prefix': 'RAM256X1D'
'body': """
${1:FileName}_I_Ram256x1d_${2:0} : RAM256X1D
generic map (
INIT => X"0000000000000000000000000000000000000000000000000000000000000000", -- [255:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A => $4, -- in [7:0]
WE => $5, -- in
DPRA => $6, -- in [7:0]
WCLK => $7, -- in
DPO => $8, -- out
SPO => $9, -- out
);
"""
'RAM32M':
'prefix': 'RAM32M'
'body': """
${1:FileName}_I_Ram32m_${2:0} : RAM32M
generic map (
INIT_A => X"0000000000000000", -- [63:0]
INIT_B => X"0000000000000000", -- [63:0]
INIT_C => X"0000000000000000", -- [63:0]
INIT_D => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
DIA => $3, -- in [1:0]
DIB => $4, -- in [1:0]
DIC => $5, -- in [1:0]
DID => $6, -- in [1:0]
ADDRA => $7, -- in [4:0]
ADDRB => $8, -- in [4:0]
ADDRC => $9, -- in [4:0]
ADDRD => $10, -- in [4:0]
WE => $11, -- in
WCLK => $12, -- in
DOA => $13, -- out [1:0]
DOB => $14, -- out [1:0]
DOC => $15, -- out [1:0]
DOD => $16 -- out [1:0]
);
"""
'RAM32X1D':
'prefix': 'RAM32X1D'
'body': """
${1:FileName}_I_Ram32x1d_${2:0} : RAM32X1D
generic map (
INIT => X"00000000", -- [31:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A0 => $4, -- in
A1 => $5, -- in
A2 => $6, -- in
A3 => $7, -- in
A4 => $8, -- in
DPRA0 => $9, -- in
DPRA1 => $10, -- in
DPRA2 => $11, -- in
DPRA3 => $12, -- in
DPRA4 => $13, -- in
WE => $14, -- in
WCLK => $15, -- in
DPO => $16, -- out
SPO => $17 -- out
);
"""
'RAM64M':
'prefix': 'RAM64M'
'body': """
${1:FileName}_I_Ram64m_${2:0} : RAM64M
generic map (
INIT_A => X"0000000000000000", -- [63:0]
INIT_B => X"0000000000000000", -- [63:0]
INIT_C => X"0000000000000000", -- [63:0]
INIT_D => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
DIA => $3, -- in
DIB => $4, -- in
DIC => $5, -- in
DID => $6, -- in
ADDRA => $7, -- in [5:0]
ADDRB => $8, -- in [5:0]
ADDRC => $9, -- in [5:0]
ADDRD => $10, -- in [5:0]
WE => $11, -- in
WCLK => $12, -- in
DOA => $13, -- out
DOB => $14, -- out
DOC => $15, -- out
DOD => $16 -- out
);
"""
'RAM64X1D':
'prefix': 'RAM64X1D'
'body': """
${1:FileName}_I_Ram64x1d_${2:0} : RAM64X1D
generic map (
INIT => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A0 => $4, -- in
A1 => $5, -- in
A2 => $6, -- in
A3 => $7, -- in
A4 => $8, -- in
A5 => $9, -- in
DPRA0 => $10, -- in
DPRA1 => $11, -- in
DPRA2 => $12, -- in
DPRA3 => $13, -- in
DPRA4 => $14, -- in
DPRA5 => $15, -- in
WE => $16, -- in
WCLK => $17, -- in
DPO => $18, -- out
SPO => $19 -- out
);
"""
'RAMB36E1':
'prefix': 'RAMB36E1'
'body': """
${1:FileName}_I_Ramb36e1_${2:0} : RAMB36E1
generic map (
INIT_FILE => "NONE", -- string
RAM_MODE => "TDP", -- string
WRITE_MODE_A => "WRITE_FIRST", -- string
WRITE_MODE_B => "WRITE_FIRST", -- string
READ_WIDTH_A => 0, -- integer
READ_WIDTH_B => 0, -- integer
WRITE_WIDTH_A => 0, -- integer
WRITE_WIDTH_B => 0, -- integer
RAM_EXTENSION_A => "NONE", -- string
RAM_EXTENSION_B => "NONE", -- string
DOA_REG => 0, -- integer
DOB_REG => 0, -- integer
INIT_A => X"000000000", -- bit_vector
INIT_B => X"000000000", -- bit_vector
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- bit_vector
SRVAL_B => X"000000000", -- bit_vector
EN_ECC_READ => FALSE, -- boolean
EN_ECC_WRITE => FALSE, -- boolean
RDADDR_COLLISION_HWCONFIG => "DELAYED_WRITE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
SIM_DEVICE => "VIRTEX6", -- string
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map (
CASCADEINA => $3, -- in
DIPADIP => $4, -- in [3:0]
DIADI => $5, -- in [31:0]
DOPADOP => $6, -- out [3:0]
DOADO => $7, -- out [31:0]
CASCADEOUTA => $8, -- out
ADDRARDADDR => $9, -- in [15:0]
ENARDEN => $10, -- in
REGCEAREGCE => $11, -- in
WEA => $12, -- in [3:0]
CLKARDCLK => $13, -- in
RSTREGARSTREG => $14, -- in
RSTRAMARSTRAM => $15, -- in
CASCADEINB => $16, -- in
DIPBDIP => $17, -- in [3:0]
DIBDI => $18, -- in [31:0]
DOPBDOP => $19, -- out [3:0]
DOBDO => $20, -- out [31:0]
CASCADEOUTB => $21, -- out
ADDRBWRADDR => $22, -- in [15:0]
ENBWREN => $23, -- in
REGCEB => $24, -- in
WEBWE => $25, -- in [7:0]
CLKBWRCLK => $26, -- in
RSTREGB => $27, -- in
RSTRAMB => $28, -- in
INJECTDBITERR => $29, -- in
INJECTSBITERR => $30, -- in
DBITERR => $31, -- out
ECCPARITY => $32, -- out [7:0]
RDADDRECC => $33, -- out [8:0]
SBITERR => $34 -- out
);
"""
'RAMB36E2':
'prefix': 'RAMB36E2'
'body': """
${1:FileName}_I_Ramb36e2_${2:0} : RAMB36E2
generic map [
INIT_FILE => "NONE", -- string
CLOCK_DOMAINS => "INDEPENDENT", -- string
WRITE_MODE_A => "NO_CHANGE", -- string
WRITE_MODE_B => "NO_CHANGE", -- string
READ_WIDTH_A => 0, -- integer
READ_WIDTH_B => 0, -- integer
WRITE_WIDTH_A => 0, -- integer
WRITE_WIDTH_B => 0, -- integer
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
ENADDRENA => "FALSE", -- string
ENADDRENB => "FALSE", -- string
RDADDRCHANGEA => "FALSE", -- string
RDADDRCHANGEB => "FALSE", -- string
DOA_REG => 1, -- integer
DOB_REG => 1, -- integer
INIT_A => X"000000000", -- [35:0]
INIT_B => X"000000000", -- [35:0]
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- [35:0]
SRVAL_B => X"000000000", -- [35:0]
EN_ECC_PIPE => "FALSE", -- string
EN_ECC_READ => "FALSE", -- string
EN_ECC_WRITE => "FALSE", -- string
SLEEP_ASYNC => "FALSE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map [
ADDRARDADDR => $3, -- in [14:0],
ADDRBWRADDR => $4, -- in [14:0],
ADDRENA => $5, -- in
ADDRENB => $6, -- in
CASDIMUXA => $7, -- in
CASDIMUXB => $8, -- in
CASDINA => $9, -- in [31:0],
CASDINB => $10, -- in [31:0],
CASDINPA => $11, -- in [3:0],
CASDINPB => $12, -- in [3:0],
CASDOMUXA => $13, -- in
CASDOMUXB => $14, -- in
CASDOMUXEN_A => $15, -- in
CASDOMUXEN_B => $16, -- in
CASINDBITERR => $17, -- in
CASINSBITERR => $18, -- in
CASOREGIMUXA => $19, -- in
CASOREGIMUXB => $20, -- in
CASOREGIMUXEN_A => $21, -- in
CASOREGIMUXEN_B => $22, -- in
CLKARDCLK => $23, -- in
CLKBWRCLK => $24, -- in
DINADIN => $25, -- in [31:0],
DINBDIN => $26, -- in [31:0],
DINPADINP => $27, -- in [3:0],
DINPBDINP => $28, -- in [3:0],
ECCPIPECE => $29, -- in
ENARDEN => $30, -- in
ENBWREN => $31, -- in
INJECTDBITERR => $32, -- in
INJECTSBITERR => $33, -- in
REGCEAREGCE => $34, -- in
REGCEB => $35, -- in
RSTRAMARSTRAM => $36, -- in
RSTRAMB => $37, -- in
RSTREGARSTREG => $38, -- in
RSTREGB => $39, -- in
SLEEP => $40, -- in
WEA => $41, -- in [3:0],
WEBWE => $42, -- in [7:0]
CASDOUTA => $43, -- out [31:0],
CASDOUTB => $44, -- out [31:0],
CASDOUTPA => $45, -- out [3:0],
CASDOUTPB => $46, -- out [3:0],
CASOUTDBITERR => $47, -- out
CASOUTSBITERR => $48, -- out
DBITERR => $49, -- out
DOUTADOUT => $50, -- out [31:0],
DOUTBDOUT => $51, -- out [31:0],
DOUTPADOUTP => $52, -- out [3:0],
DOUTPBDOUTP => $53, -- out [3:0],
ECCPARITY => $54, -- out [7:0],
RDADDRECC => $55, -- out [8:0],
SBITERR => $56 -- out
);
"""
'RAMB36E5':
'prefix': 'RAMB36E5'
'body': """
${1:FileName}_I_Ramb36e5_${2:0} : RAMB36E5
generic map (
INIT_FILE => "NONE", -- string
CLOCK_DOMAINS => "INDEPENDENT", -- string
WRITE_MODE_A => "NO_CHANGE", -- string
WRITE_MODE_B => "NO_CHANGE", -- string
READ_WIDTH_A => 72, -- integer
READ_WIDTH_B => 36, -- integer
WRITE_WIDTH_A => 36, -- integer
WRITE_WIDTH_B => 72 -- integer
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
DOA_REG => 1, -- integer
DOB_REG => 1, -- integer
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- [35:0]
SRVAL_B => X"000000000", -- [35:0]
EN_ECC_PIPE => "FALSE", -- string
EN_ECC_READ => "FALSE", -- string
EN_ECC_WRITE => "FALSE", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
PR_SAVE_DATA => "FALSE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
SLEEP_ASYNC => "FALSE", -- string
IS_ARST_A_INVERTED => '0', -- bit
IS_ARST_B_INVERTED => '0', -- bit
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map (
ADDRARDADDR => $3, -- in [11:0]
ADDRBWRADDR => $4, -- in [11:0]
ARST_A => $5, -- in
ARST_B => $6, -- in
CASDINA => $7, -- in [31:0]
CASDINB => $8, -- in [31:0]
CASDINPA => $9, -- in [3:0]
CASDINPB => $10, -- in [3:0]
CASDOMUXA => $11, -- in
CASDOMUXB => $12, -- in
CASDOMUXEN_A => $13, -- in
CASDOMUXEN_B => $14, -- in
CASINDBITERR => $15, -- in
CASINSBITERR => $16, -- in
CASOREGIMUXA => $17, -- in
CASOREGIMUXB => $18, -- in
CASOREGIMUXEN_A => $19, -- in
CASOREGIMUXEN_B => $20, -- in
CLKARDCLK => $21, -- in
CLKBWRCLK => $22, -- in
DINADIN => $23, -- in [31:0]
DINBDIN => $24, -- in [31:0]
DINPADINP => $25, -- in [3:0]
DINPBDINP => $26, -- in [3:0]
ECCPIPECE => $27, -- in
ENARDEN => $28, -- in
ENBWREN => $29, -- in
INJECTDBITERR => $30, -- in
INJECTSBITERR => $31, -- in
REGCEAREGCE => $32, -- in
REGCEB => $33, -- in
RSTRAMARSTRAM => $34, -- in
RSTRAMB => $35, -- in
RSTREGARSTREG => $36, -- in
RSTREGB => $37, -- in
SLEEP => $38, -- in
WEA => $39, -- in [3:0]
WEBWE => $40, -- in [8:0]
CASDOUTA => $41, -- out [31:0]
CASDOUTB => $42, -- out [31:0]
CASDOUTPA => $43, -- out [3:0]
CASDOUTPB => $44, -- out [3:0]
CASOUTDBITERR => $45, -- out
CASOUTSBITERR => $46, -- out
DBITERR => $47, -- out
DOUTADOUT => $48, -- out [31:0]
DOUTBDOUT => $49, -- out [31:0]
DOUTPADOUTP => $50, -- out [3:0]
DOUTPBDOUTP => $51, -- out [3:0]
SBITERR => $52 -- out
),
"""
'RAMD32':
'prefix': 'RAMD32'
'body': """
${1:FileName}_I_Ramd32_${2:0} : RAMD32
generic map (
INIT => X"00000000", -- [31:0]
IS_CLK_INVERTED => '0' -- bit
)
port map (
I => $3, -- in
WE => $4, -- in
CLK => $5, -- in
RADR0 => $6, -- in
RADR1 => $7, -- in
RADR2 => $8, -- in
RADR3 => $9, -- in
RADR4 => $10, -- in
WADR0 => $11, -- in
WADR1 => $12, -- in
WADR2 => $13, -- in
WADR3 => $14, -- in
WADR4 => $15, -- in
O => $16 -- out
);
"""
'RIU_OR':
'prefix': 'RIU_OR'
'body': """
${1:FileName}_I_Riu_Or_${2:0} : RIU_OR
generic map (
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
RIU_RD_DATA_LOW => $3, -- in [15:0]
RIU_RD_DATA_UPP => $4, -- in [15:0]
RIU_RD_VALID_LOW => $5, -- in
RIU_RD_VALID_UPP => $6, -- in
RIU_RD_DATA => $7, -- out [15:0]
RIU_RD_VALID => $8 -- out
);
"""
'RXTX_BITSLICE':
'prefix': 'RXTX_BITSLICE'
'body': """
${1:FileName}_I_Rxtx_btslce_${2:0} : RXTX_BITSLICE
generic map (
RX_DATA_TYPE => "NONE", -- string
RX_DATA_WIDTH => 8, -- integer
RX_DELAY_FORMAT => "TIME", -- string
RX_DELAY_TYPE => "FIXED", -- string
RX_DELAY_VALUE => 0, -- integer
TX_DATA_WIDTH => 8, -- integer
TX_DELAY_FORMAT => "TIME", -- string
TX_DELAY_TYPE => "FIXED", -- string
TX_DELAY_VALUE => 0, -- integer
RX_REFCLK_FREQUENCY => 300.0, -- real
TX_REFCLK_FREQUENCY => 300.0, -- real
RX_UPDATE_MODE => "ASYNC", -- string
TX_UPDATE_MODE => "ASYNC", -- string
FIFO_SYNC_MODE => "FALSE", -- string
INIT => '1', -- bit
LOOPBACK => "FALSE", -- string
NATIVE_ODELAY_BYPASS => "FALSE", -- string
TBYTE_CTL => "TBYTE_IN", -- string
TX_OUTPUT_PHASE_90 => "FALSE", -- string
ENABLE_PRE_EMPHASIS => "FALSE", -- string
IS_RX_CLK_INVERTED => '0', -- bit
IS_RX_RST_DLY_INVERTED => '0', -- bit
IS_RX_RST_INVERTED => '0', -- bit
IS_TX_CLK_INVERTED => '0', -- bit
IS_TX_RST_DLY_INVERTED => '0', -- bit
IS_TX_RST_INVERTED => '0', -- bit
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
DATAIN => $3, -- in
Q => $4, -- out [7:0]
RX_RST => $5, -- in
RX_CLK => $6, -- in
RX_CE => $7, -- in
RX_RST_DLY => $8, -- in
RX_INC => $9, -- in
RX_LOAD => $10, -- in
RX_EN_VTC => $11, -- in
RX_CNTVALUEIN => $12, -- in [8:0]
RX_CNTVALUEOUT => $13, -- out [8:0]
FIFO_RD_CLK => $14, -- in
FIFO_RD_EN => $15, -- in
FIFO_EMPTY => $16, -- out
FIFO_WRCLK_OUT => $17, -- out
RX_BIT_CTRL_IN => $18, -- in [39:0]
TX_BIT_CTRL_IN => $19, -- in [39:0]
RX_BIT_CTRL_OUT => $20, -- out [39:0]
TX_BIT_CTRL_OUT => $21, -- out [39:0]
D => $22, -- in [7:0]
T => $23, -- in
TBYTE_IN => $24, -- in
O => $25, -- out
T_OUT => $26, -- out
TX_RST => $27, -- in
TX_CLK => $28, -- in
TX_CE => $29, -- in
TX_RST_DLY => $30, -- in
TX_INC => $31, -- in
TX_LOAD => $32, -- in
TX_EN_VTC => $33, -- in
TX_CNTVALUEIN => $34, -- in [8:0]
TX_CNTVALUEOUT => $35 -- out [8:0]
);
"""
'RX_BITSLICE':
'prefix': 'RX_BITSLICE'
'body': """
${1:FileName}_I_Rx_Btslce_${2:0} : RX_BITSLICE
generic map(
CASCADE => "FALSE", -- string
DATA_TYPE => "NONE", -- string
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
DELAY_VALUE_EXT => 0, -- integer
FIFO_SYNC_MODE => "FALSE", -- string
IS_CLK_EXT_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_RST_DLY_EXT_INVERTED => '0', -- bit
IS_RST_DLY_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
UPDATE_MODE_EXT => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
DATAIN => $3, -- in
FIFO_RD_CLK => $4, -- in
FIFO_RD_EN => $5, -- in
RX_BIT_CTRL_IN => $6, -- in [39:0]
TX_BIT_CTRL_IN => $7, -- in [39:0]
RX_BIT_CTRL_OUT => $8, -- out [39:0]
TX_BIT_CTRL_OUT => $9, -- out [39:0]
RST => $10, -- in
CLK => $11, -- in
CE => $12, -- in
RST_DLY => $13, -- in
INC => $14, -- in
LOAD => $15, -- in
EN_VTC => $16, -- in
CNTVALUEIN => $17, -- in [8:0]
CNTVALUEOUT => $18, -- out [8:0]
CLK_EXT => $19, -- in
CE_EXT => $20, -- in
RST_DLY_EXT => $21, -- in
INC_EXT => $22, -- in
LOAD_EXT => $23, -- in
EN_VTC_EXT => $24, -- in
CNTVALUEIN_EXT => $25, -- in [8:0]
CNTVALUEOUT_EXT => $26, -- out [8:0]
BIT_CTRL_OUT_EXT => $27, -- out [28:0]
FIFO_EMPTY => $28, -- out
FIFO_WRCLK_OUT => $29, -- out
Q => $30 -- out [7:0]
);
"""
'SRLC32E':
'prefix': 'SRLC32E'
'body': """
${1:FileName}_I_Srlc32e_${2:0} : SRLC32E
generic map (
INIT => X"00000000",
IS_CLK_INVERTED => '0'
)
port map (
D => $3, -- in
A => $4, -- in [4:0]
CE => $5, -- in
CLK => $6, -- in
Q => $7, -- out
Q31 => $8 -- out
);
"""
'STARTUPE2':
'prefix': 'STARTUPE2'
'body': """
${1:FileName}_I_Startupe2_${2:0} : STARTUPE2
generic map (
PROG_USR => "FALSE", -- string
SIM_CCLK_FREQ => 0.0 -- real
)
port map (
USRDONEO => $3, -- in
USRDONETS => $4, -- in
KEYCLEARB => $5, -- in
PACK => $6, -- in
USRCCLKO => $7, -- in
USRCCLKTS => $8, -- in
CLK => $9, -- in
GSR => $10, -- in
GTS => $11, -- in
CFGCLK => $12, -- out
CFGMCLK => $13, -- out
EOS => $14, -- out
PREQ => $15 -- out
);
"""
'STARTUPE3':
'prefix': 'STARTUPE3'
'body': """
${1:FileName}_I_Startupe3_${2:0} : STARTUPE3
generic map : (
PROG_USR => "FALSE", -- string
SIM_CCLK_FREQ => 0.0 -- real
)
port map (
USRDONEO => $3, -- in
USRDONETS => $4, -- in
KEYCLEARB => $5, -- in
PACK => $6, -- in
USRCCLKO => $7, -- in
USRCCLKTS => $8, -- in
GSR => $9, -- in
GTS => $10, -- in
DTS => $11, -- in [3:0]
FCSBO => $12, -- in
FCSBTS => $13, -- in
DO => $14, -- in [3:0]
DI => $15, -- out [3:0]
CFGCLK => $16, -- out
CFGMCLK => $17, -- out
EOS => $18, -- out
PREQ => $19 -- out
);
"""
'TX_BITSLICE':
'prefix': 'TX_BITSLICE'
'body': """
${1:FileName}_I_Tx_Btslce_${2:0} : TX_BITSLICE
generic map (
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
INIT => '1', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_RST_DLY_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
NATIVE_ODELAY_BYPASS => "FALSE", -- string
OUTPUT_PHASE_90 => "FALSE", -- string
ENABLE_PRE_EMPHASIS => "OFF", -- string
REFCLK_FREQUENCY => 300.0, -- real
TBYTE_CTL => "TBYTE_IN", -- string
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE : string => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
D => $3, -- in [7:0]
T => $4, -- in
TBYTE_IN => $5, -- in
RX_BIT_CTRL_IN => $6, -- in [39:0]
TX_BIT_CTRL_IN => $7, -- in [39:0]
RX_BIT_CTRL_OUT => $8, -- out [39:0]
TX_BIT_CTRL_OUT => $9, -- out [39:0]
RST => $10, -- in
CLK => $11, -- in
CE => $12, -- in
RST_DLY => $13, -- in
INC => $14, -- in
LOAD => $15, -- in
EN_VTC => $16, -- in
CNTVALUEIN => $17, -- in [8:0]
CNTVALUEOUT => $18, -- out [8:0]
O => $19, -- out
T_OUT => $20 -- out
);
"""
'TX_BITSLICE_TRI':
'prefix': 'TX_BITSLICE_TRI'
'body': """
${1:FileName}_I_Tx_Btslce_Tri_${2:0} : TX_BITSLICE_TRI
generic map (
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
INIT => '1', -- bit:
IS_CLK_INVERTED => '0', -- bit:
IS_RST_DLY_INVERTED => '0', -- bit:
IS_RST_INVERTED => '0', -- bit:
NATIVE_ODELAY_BYPASS => "FALSE", -- string
OUTPUT_PHASE_90 => "FALSE", -- string
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC" -- string
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VESION => 2.0 -- real
)
port map (
BIT_CTRL_IN => $3, -- in [39:0]
BIT_CTRL_OUT => $4, -- out [39:0]
RST => $5, -- in
CLK => $6, -- in
CE => $7, -- in
RST_DLY => $8, -- in
INC => $9, -- in
LOAD => $10, -- in
EN_VTC => $11, -- in
CNTVALUEIN => $12, -- in [8:0]
CNTVALUEOUT => $13, -- out [8:0]
TRI_OUT => $14 -- out
);
"""
'URAM288':
'prefix': 'URAM288'
'body': """
${1:FileName}_I_Uram288_${2:0} : URAM288
generic map (
AUTO_SLEEP_LATENCY => 8, -- integer
AVG_CONS_INACTIVE_CYCLES => 10, -- integer
BWE_MODE_A => "PARITY_INTERLEAVED", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
EN_AUTO_SLEEP_MODE => "FALSE", -- string
EN_ECC_RD_A => "FALSE", -- string
EN_ECC_RD_B => "FALSE", -- string
EN_ECC_WR_A => "FALSE", -- string
EN_ECC_WR_B => "FALSE", -- string
IREG_PRE_A => "FALSE", -- string
IREG_PRE_B => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_EN_A_INVERTED => '0', -- bit
IS_EN_B_INVERTED => '0', -- bit
IS_RDB_WR_A_INVERTED => '0', -- bit
IS_RDB_WR_B_INVERTED => '0', -- bit
IS_RST_A_INVERTED => '0', -- bit
IS_RST_B_INVERTED => '0', -- bit
MATRIX_ID => "NONE", -- string
NUM_UNIQUE_SELF_ADDR_A => 1, -- integer
NUM_UNIQUE_SELF_ADDR_B => 1, -- integer
NUM_URAM_IN_MATRIX => 1, -- integer
OREG_A => "FALSE", -- string
OREG_B => "FALSE", -- string
OREG_ECC_A => "FALSE", -- string
OREG_ECC_B => "FALSE", -- string
REG_CAS_A => "FALSE", -- string
REG_CAS_B => "FALSE", -- string
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
SELF_ADDR_A => "000" & X"00", -- [10 downto 0)
SELF_ADDR_B => "000" & X"00", -- [10 downto 0)
SELF_MASK_A => "111" & X"FF", -- [10 downto 0)
SELF_MASK_B => "111" & X"FF", -- [10 downto 0)
USE_EXT_CE_A => "FALSE", -- string
USE_EXT_CE_B => "FALSE" -- string
)
port map (
DIN_A => $3, -- in [71:0]
ADDR_A => $4, -- in [22:0]
EN_A => $5, -- in
RDB_WR_A => $6, -- in
BWE_A => $7, -- in [8:0]
INJECT_SBITERR_A => $8, -- in
INJECT_DBITERR_A => $9, -- in
OREG_CE_A => $10, -- in
OREG_ECC_CE_A => $11, -- in
RST_A => $12, -- in
DOUT_A => $13, -- out [71:0]
SBITERR_A => $14, -- out
DBITERR_A => $15, -- out
RDACCESS_A => $16, -- out
SLEEP => $17, -- in
CLK => $18, -- in
DIN_B => $19, -- in [71:0]
ADDR_B => $20, -- in [22:0]
EN_B => $21, -- in
RDB_WR_B => $22, -- in
BWE_B => $23, -- in [8:0]
INJECT_SBITERR_B => $24, -- in
INJECT_DBITERR_B => $25, -- in
OREG_CE_B => $26, -- in
OREG_ECC_CE_B => $27, -- in
RST_B => $28, -- in
DOUT_B => $29, -- out [71:0]
SBITERR_B => $30, -- out
DBITERR_B => $31, -- out
RDACCESS_B => $32, -- out
CAS_IN_ADDR_A => $33, -- in [22:0]
CAS_IN_ADDR_B => $34, -- in [22:0]
CAS_IN_BWE_A => $35, -- in [8:0]
CAS_IN_BWE_B => $36, -- in [8:0]
CAS_IN_DBITERR_A => $37, -- in
CAS_IN_DBITERR_B => $38, -- in
CAS_IN_DIN_A => $39, -- in [71:0]
CAS_IN_DIN_B => $40, -- in [71:0]
CAS_IN_DOUT_A => $41, -- in [71:0]
CAS_IN_DOUT_B => $42, -- in [71:0]
CAS_IN_EN_A => $43, -- in
CAS_IN_EN_B => $44, -- in
CAS_IN_RDACCESS_A => $45, -- in
CAS_IN_RDACCESS_B => $46, -- in
CAS_IN_RDB_WR_A => $47, -- in
CAS_IN_RDB_WR_B => $48, -- in
CAS_IN_SBITERR_A => $49, -- in
CAS_IN_SBITERR_B => $50, -- in
CAS_OUT_ADDR_A => $51, -- out [22:0]
CAS_OUT_ADDR_B => $52, -- out [22:0]
CAS_OUT_BWE_A => $53, -- out [8:0]
CAS_OUT_BWE_B => $54, -- out [8:0]
CAS_OUT_DBITERR_A => $55, -- out
CAS_OUT_DBITERR_B => $56, -- out
CAS_OUT_DIN_A => $57, -- out [71:0]
CAS_OUT_DIN_B => $58, -- out [71:0]
CAS_OUT_DOUT_A => $59, -- out [71:0]
CAS_OUT_DOUT_B => $60, -- out [71:0]
CAS_OUT_EN_A => $61, -- out
CAS_OUT_EN_B => $62, -- out
CAS_OUT_RDACCESS_A => $63, -- out
CAS_OUT_RDACCESS_B => $64, -- out
CAS_OUT_RDB_WR_A => $65, -- out
CAS_OUT_RDB_WR_B => $66, -- out
CAS_OUT_SBITERR_A => $67, -- out
CAS_OUT_SBITERR_B => $68 -- out
);
"""
'URAM288E5':
'prefix': 'URAM288E5'
'body': """
${1:FileName}_I_Uram288e5_${2:0} : URAM288E5
generic map (
INIT_FILE => "NONE", -- string
BWE_MODE_A => "PARITY_INTERLEAVED", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
READ_WIDTH_A => 72, -- integer
READ_WIDTH_B => 72, -- integer
WRITE_WIDTH_A => 72, -- integer
WRITE_WIDTH_B => 72, -- integer
IREG_PRE_A => "FALSE", -- string
IREG_PRE_B => "FALSE", -- string
OREG_A => "FALSE", -- string
OREG_B => "FALSE", -- string
OREG_ECC_A => "FALSE", -- string
OREG_ECC_B => "FALSE", -- string
REG_CAS_A => "FALSE", -- string
REG_CAS_B => "FALSE", -- string
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
SELF_ADDR_A => "000" & X"00", -- [10:0]
SELF_ADDR_B => "000" & X"00", -- [10:0]
SELF_MASK_A => "111" & X"FF", -- [10:0]
SELF_MASK_B => "111" & X"FF", -- [10:0]
USE_EXT_CE_A => "FALSE", -- string
USE_EXT_CE_B => "FALSE", -- string
CASCADE_ORDER_CTRL_A => "NONE", -- string
CASCADE_ORDER_CTRL_B => "NONE", -- string
CASCADE_ORDER_DATA_A => "NONE", -- string
CASCADE_ORDER_DATA_B => "NONE", -- string
AUTO_SLEEP_LATENCY => 8, -- integer
EN_AUTO_SLEEP_MODE => "FALSE", -- string
AVG_CONS_INACTIVE_CYCLES => 10, -- integer
EN_ECC_RD_A => "FALSE", -- string
EN_ECC_RD_B => "FALSE", -- string
EN_ECC_WR_A => "FALSE", -- string
EN_ECC_WR_B => "FALSE", -- string
MATRIX_ID => "NONE", -- string
NUM_UNIQUE_SELF_ADDR_A => 1, -- integer
NUM_UNIQUE_SELF_ADDR_B => 1, -- integer
NUM_URAM_IN_MATRIX => 1, -- integer
PR_SAVE_DATA => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_EN_A_INVERTED => '0', -- bit
IS_EN_B_INVERTED => '0', -- bit
IS_RDB_WR_A_INVERTED => '0', -- bit
IS_RDB_WR_B_INVERTED => '0', -- bit
IS_RST_A_INVERTED => '0', -- bit
IS_RST_B_INVERTED => '0' -- bit
)
port map (
DIN_A => $3, -- in [71:0]
ADDR_A => $4, -- in [25:0]
EN_A => $5, -- in
RDB_WR_A => $6, -- in
BWE_A => $7, -- in [8:0]
INJECT_SBITERR_A => $8, -- in
INJECT_DBITERR_A => $9, -- in
OREG_CE_A => $10, -- in
OREG_ECC_CE_A => $11, -- in
RST_A => $12, -- in
SLEEP => $13, -- in
CLK => $14, -- in
DIN_B => $15, -- in [71:0]
ADDR_B => $16, -- in [25:0]
EN_B => $17, -- in
RDB_WR_B => $18, -- in
BWE_B => $19, -- in [8:0]
INJECT_SBITERR_B => $20, -- in
INJECT_DBITERR_B => $21, -- in
OREG_CE_B => $22, -- in
OREG_ECC_CE_B => $23, -- in
RST_B => $24, -- in
DOUT_A => $25, -- out [71:0]
SBITERR_A => $26, -- out
DBITERR_A => $27, -- out
RDACCESS_A => $28, -- out
DOUT_B => $29, -- out [71:0]
SBITERR_B => $30, -- out
DBITERR_B => $31, -- out
RDACCESS_B => $32, -- out
CAS_IN_ADDR_A => $33, -- in [25:0]
CAS_IN_ADDR_B => $34, -- in [25:0]
CAS_IN_BWE_A => $35, -- in [8:0]
CAS_IN_BWE_B => $36, -- in [8:0]
CAS_IN_DBITERR_A => $37, -- in
CAS_IN_DBITERR_B => $38, -- in
CAS_IN_DIN_A => $39, -- in [71:0]
CAS_IN_DIN_B => $40, -- in [71:0]
CAS_IN_DOUT_A => $41, -- in [71:0]
CAS_IN_DOUT_B => $42, -- in [71:0]
CAS_IN_EN_A => $43, -- in
CAS_IN_EN_B => $44, -- in
CAS_IN_RDACCESS_A => $45, -- in
CAS_IN_RDACCESS_B => $46, -- in
CAS_IN_RDB_WR_A => $47, -- in
CAS_IN_RDB_WR_B => $48, -- in
CAS_IN_SBITERR_A => $49, -- in
CAS_IN_SBITERR_B => $50, -- in
CAS_OUT_ADDR_A => $51, -- out [25:0]
CAS_OUT_ADDR_B => $52, -- out [25:0]
CAS_OUT_BWE_A => $53, -- out [8:0]
CAS_OUT_BWE_B => $54, -- out [8:0]
CAS_OUT_DBITERR_A => $55, -- out
CAS_OUT_DBITERR_B => $56, -- out
CAS_OUT_DIN_A => $57, -- out [71:0]
CAS_OUT_DIN_B => $58, -- out [71:0]
CAS_OUT_DOUT_A => $59, -- out [71:0]
CAS_OUT_DOUT_B => $60, -- out [71:0]
CAS_OUT_EN_A => $61, -- out
CAS_OUT_EN_B => $62, -- out
CAS_OUT_RDACCESS_A => $63, -- out
CAS_OUT_RDACCESS_B => $64, -- out
CAS_OUT_RDB_WR_A => $65, -- out
CAS_OUT_RDB_WR_B => $66, -- out
CAS_OUT_SBITERR_A => $67, -- out
CAS_OUT_SBITERR_B => $68 -- out
);
"""
'USR_ACCESSE2':
'prefix': 'USR_ACCESSE2'
'body': """
${1:FileName}_I_Usr_Access_${2:0} : USR_ACCESSE2
port map (
CFGCLK => $3, -- out
DATA => $4, -- out [31:0]
DATAVALID => $5 -- out
);
"""
'XORCY':
'prefix': 'XORCY'
'body': """
$1 : XORCY
port map (
CI => $3, -- in
LI => $4, -- in
O => $5 -- out
);
"""
'XPLL':
'prefix': 'XPLL'
'body': """
${1:FileName}_I_Xpll_${2:0} : XPLL
generic map (
CLKIN_PERIOD => 0.000, -- real
REF_JITTER => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUTPHY_DIVIDE => "DIV8", -- string
DESKEW_DELAY1 => 0, -- integer
DESKEW_DELAY2 => 0, -- integer
DESKEW_DELAY_EN1 => "FALSE", -- string
DESKEW_DELAY_EN2 => "FALSE", -- string
DESKEW_DELAY_PATH1 => "FALSE", -- string
DESKEW_DELAY_PATH2 => "FALSE", -- string
IS_CLKIN_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
CLKIN1_DESKEW => $3, -- in
CLKFB1_DESKEW => $4, -- in
CLKFB2_DESKEW => $5, -- in
CLKIN2_DESKEW => $6, -- in
CLKIN => $7, -- in
RST => $8, -- in
PWRDWN => $9, -- in
CLKOUTPHYEN => $10, -- in
CLKOUT0 => $11, -- out
CLKOUT1 => $12, -- out
CLKOUT2 => $13, -- out
CLKOUT3 => $14, -- out
CLKOUTPHY => $15, -- out
PSCLK => $16, -- in
PSEN => $17, -- in
PSINCDEC => $18, -- in
PSDONE => $19, -- out
DCLK => $20, -- in
DEN => $21, -- in
DWE => $22, -- in
DADDR => $23, -- in [6:0]
DI => $24, -- in [15:0]
DO => $25, -- out [15:0]
DRDY => $26, -- out
RIU_CLK => $27, -- in
RIU_NIBBLE_SEL => $28, -- in
RIU_WR_EN => $29, -- in
RIU_ADDR => $30, -- in [7:0]
RIU_WR_DATA => $31, -- in [15:0]
RIU_RD_DATA => $32, -- out [15:0]
RIU_VALID => $33, -- out
LOCKED1_DESKEW => $34, -- out
LOCKED2_DESKEW => $35, -- out
LOCKED_FB => $36, -- out
LOCKED => $37 -- out
);
"""
'ZHOLD_DELAY':
'prefix': 'ZHOLD_DELAY'
'body': """
${1:FileName}_I_Zhld_Dly_${2:0} : ZHOLD_DELAY
generic map (
IS_DLYIN_INVERTED => '0', -- bit
ZHOLD_FABRIC => "DEFAULT", -- string
ZHOLD_IFF => "DEFAULT" -- string
)
port map (
DLYFABRIC => $3, -- out
DLYIFF => $4, -- out
DLYIN => $5 -- in
);
"""
| 68206 | #-------------------------------------------------------------------------------------------
# VHDL Xilinx Unisim Library component snippets
# Device: Spartan-6, Virtex-5, Virtex-6, 7-Series, All Ultrascale,
# All Zynq, Versal
# Author: <NAME>irconfleX
# Purpose: Snippets for ATOM editor created from the Xilinx
# UNISIM component libraries.
# Tools: Atom Editor
# Limitations: None
#
# Version: 0.0.2
# Filename: snippets.cson
# Date Created: 17Jan19
# Date Last Modified: 24Mar20
#-------------------------------------------------------------------------------------------
# Disclaimer:
# This file is delivered as is.
# The supplier cannot be held accountable for any typo or other flaw in this file.
# The supplier cannot be held accountable if Xilinx modifies whatsoever to its
# library of components/primitives.
#-------------------------------------------------------------------------------------------
#
'.source.vhdl':
'BITSLICE_CONTROL':
'prefix': 'BITSLICE_CONTROL'
'body': """
${1:FileName}_I_Btslce_Ctrl_${2:0} : BITSLICE_CONTROL
generic map (
CTRL_CLK => "EXTERNAL", -- string
DIV_MODE => "DIV2", -- string
EN_CLK_TO_EXT_NORTH => "DISABLE", -- string
EN_CLK_TO_EXT_SOUTH => "DISABLE", -- string
EN_DYN_ODLY_MODE => "FALSE", -- string
EN_OTHER_NCLK => "FALSE", -- string
EN_OTHER_PCLK => "FALSE", -- string
IDLY_VT_TRACK => "TRUE", -- string
INV_RXCLK => "FALSE", -- string
ODLY_VT_TRACK => "TRUE", -- string
QDLY_VT_TRACK => "TRUE", -- string
READ_IDLE_COUNT => "00" & X"0", -- std_logic_vector[5:0]
REFCLK_SRC => "PLLCLK", -- string
ROUNDING_FACTOR => 16, -- integer
RXGATE_EXTEND => "FALSE", -- string
RX_CLK_PHASE_N => "SHIFT_0", -- string
RX_CLK_PHASE_P => "SHIFT_0", -- string
RX_GATING => "DISABLE", -- string
SELF_CALIBRATE => "ENABLE", -- string
SERIAL_MODE => "FALSE", -- string
TX_GATING => "DISABLE", -- string
SIM_SPEEDUP => "FAST", -- string
SIM_VERSION => 2.0 -- real
)
port map (
RIU_CLK => $3, -- in
RIU_WR_EN => $4, -- in
RIU_NIBBLE_SEL => $5, -- in
RIU_ADDR => $6, -- in [5:0]
RIU_WR_DATA => $7, -- in [15:0]
RIU_RD_DATA => $8, -- out [15:0]
RIU_VALID => $9, -- out
PLL_CLK => $10 -- in
REFCLK => $11,-- in
RST => $12, -- in
EN_VTC => $13, -- in
VTC_RDY => $14, -- out
DLY_RDY => $15, -- out
DYN_DCI => $16, -- out [6:0]
TBYTE_IN => $17, -- in [3:0]
PHY_RDEN => $18, -- in [3:0]
PHY_RDCS0 => $29, -- in [3:0]
PHY_RDCS1 => $20, -- in [3:0]
PHY_WRCS0 => $21, -- in [3:0]
PHY_WRCS1 => $22, -- in [3:0]
CLK_FROM_EXT => $23, -- in
NCLK_NIBBLE_IN => $24, -- in
PCLK_NIBBLE_IN => $25, -- in
NCLK_NIBBLE_OUT => $26, -- out
PCLK_NIBBLE_OUT => $27, -- out
CLK_TO_EXT_NORTH => $28, -- out
CLK_TO_EXT_SOUTH => $29, -- out
RX_BIT_CTRL_OUT0 => $30, -- out [39:0]
RX_BIT_CTRL_OUT1 => $31, -- out [39:0]
RX_BIT_CTRL_OUT2 => $32, -- out [39:0]
RX_BIT_CTRL_OUT3 => $33, -- out [39:0]
RX_BIT_CTRL_OUT4 => $34, -- out [39:0]
RX_BIT_CTRL_OUT5 => $35, -- out [39:0]
RX_BIT_CTRL_OUT6 => $36, -- out [39:0]
RX_BIT_CTRL_IN0 => $37, -- in [39:0]
RX_BIT_CTRL_IN1 => $38, -- in [39:0]
RX_BIT_CTRL_IN2 => $39, -- in [39:0]
RX_BIT_CTRL_IN3 => $40, -- in [39:0]
RX_BIT_CTRL_IN4 => $41, -- in [39:0]
RX_BIT_CTRL_IN5 => $42, -- in [39:0]
RX_BIT_CTRL_IN6 => $43, -- in [39:0]
TX_BIT_CTRL_OUT0 => $44, -- out [39:0]
TX_BIT_CTRL_OUT1 => $45, -- out [39:0]
TX_BIT_CTRL_OUT2 => $46, -- out [39:0]
TX_BIT_CTRL_OUT3 => $47, -- out [39:0]
TX_BIT_CTRL_OUT4 => $48, -- out [39:0]
TX_BIT_CTRL_OUT5 => $49, -- out [39:0]
TX_BIT_CTRL_OUT6 => $50, -- out [39:0]
TX_BIT_CTRL_IN0 => $51, -- in [39:0]
TX_BIT_CTRL_IN1 => $52, -- in [39:0]
TX_BIT_CTRL_IN2 => $53, -- in [39:0]
TX_BIT_CTRL_IN3 => $54, -- in [39:0]
TX_BIT_CTRL_IN4 => $55, -- in [39:0]
TX_BIT_CTRL_IN5 => $56, -- in [39:0]
TX_BIT_CTRL_IN6 => $57, -- in [39:0]
TX_BIT_CTRL_OUT_TRI => $58, -- out [39:0]
TX_BIT_CTRL_IN_TRI => $59-- in [39:0]
);
"""
'BOUNDARY_SCAN':
'prefix': 'BSCANE2'
'body': """
${1:FileName}_I_Bscane2_${2:0} : BSCANE2
generic map (DISABLE_JTAG => "FALSE", JTAG_CHAIN => 1)
port map (
TDI => $3, -- out
TCK => $3, -- out
TMS => $4, -- out
TDO => $5, -- in
DRCK => $6, -- out
SEL => $7, -- out
SHIFT => $8, -- out
CAPTURE => $9, -- out
RESET => $10 -- out
UPDATE => $11, -- out
RUNTEST => $12 -- out
);
"""
'BUFCE_LEAF':
'prefix': 'BUFCE_LEAF'
'body': """
${1:FileName}_I_Bufce_Leaf_${2:0} : BUFCE_LEAF
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFCE_ROW':
'prefix': 'BUFCE_ROW'
'body': """
${1:FileName}_I_Bufce_Row_${2:0} : BUFCE_ROW
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFG':
'prefix': 'BUFG'
'body': """
${1:FileName}_I_Bufg_${2:0} : BUFG port map (I => $3, O => $4);
"""
'BUFG_GT':
'prefix': 'BUFG_GT'
'body': """
${1:FileName}_I_Btslce_Ctrl_${2:0} : BUFG_GT
generic map (IS_CLR_INVERTED => $2) -- '0'
port map (
I => $3, -- in
CE => $4, -- in
CEMASK => $5, -- in
CLR => $6, -- in
CLRMASK => $7, -- in
DIV => $8, -- in [2:0]
O => $9 -- out
);
"""
'BUFG_GT_SYNC':
'prefix': 'BUFG_GT_SYNC'
'body': """
${1:FileName}_I_Bufg_Gt_Sync_${2:0} : BUFG_GT_SYNC
port map (
CLK => $3, -- in
CLR => $4, -- in
CE => $5, -- in
CESYNC => $6, -- out
CLRSYNC => $7 -- out
);
"""
'BUFG_PS':
'prefix': 'BUFG_PS'
'body': """
${1:FileName}_I_Bufg_Ps_${2:0} : BUFG_PS
generic map (SIM_DEVICE => "ULTRASCALE_PLUS", STARTUP_SYNC => "FALSE");
port map (I => $3, O => $4);
"""
'BUFGCE':
'prefix': 'BUFGCE'
'body': """
${1:FileName}_I_Bufgce_${2:0} : BUFGCE
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ukogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFGCE_DIV':
'prefix': 'BUFGCE_DIV'
'body': """
${1:FileName}_I_Bufgce_Div_${2:0} : BUFGCE_DIV
generic map (
BUFGCE_DIVIDE => 1, -- integer
IS_CE_INVERTED => '0', -- std_ulogic
IS_CLR_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
CLR => $5, -- in
O => $6 -- out
);
"""
'BUFGCTRL':
'prefix': 'BUFGCTRL'
'body': """
${1:FileName}_I_Bufgctrl_${2:0} : BUFGCTRL
generic map (
CE_TYPE_CE0 => "SYNC", -- string
CE_TYPE_CE1 => "SYNC", -- string
INIT_OUT => 0, -- integer
IS_CE0_INVERTED => '0', -- std_ulogic
IS_CE1_INVERTED => '0', -- std_ulogic
IS_I0_INVERTED => '0', -- std_ulogic
IS_I1_INVERTED => '0', -- std_ulogic
IS_IGNORE0_INVERTED => '0', -- std_ulogic
IS_IGNORE1_INVERTED => '0', -- std_ulogic
IS_S0_INVERTED => '0', -- std_ulogic
IS_S1_INVERTED => '0', -- std_ulogic
PRESELECT_I0 => false, -- boolean
PRESELECT_I1 => false, -- boolean
SIM_DEVICE => "ULTRASCALE", -- string
STARTUP_SYNC => "FALSE" -- string
)
port map (
I0 => $3, -- in
I1 => $4, -- in
S0 => $5, -- in
S1 => $6, -- in
CE0 => $7, -- in
CE1 => $8, -- in
IGNORE0 => $9, -- in
IGNORE1 => $10, -- in
O => $11 -- out
);
"""
'BUFGP':
'prefix': 'BUFGP'
'body': """
${1:FileName}_I_Bufgp_${2:0} : BUFGP port map (I => $3, O => $4);
"""
'BUFH':
'prefix': 'BUFH'
'body': """
${1:FileName}_I_Bufh_${2:0} : BUFH port map (I => $3, O => $4);
"""
'BUFHCE':
'prefix': 'BUFHCE'
'body': """
${1:FileName}_I_Bufhce_${2:0} : BUFHCE
generic map (CE_TYPE => "SYNC", INIT_OUT => 0)
port map (I => $3, CE => $4, O => $5);
"""
'BUFIO':
'prefix': 'BUFIO'
'body': """
${1:FileName}_I_Bufio_${2:0} : BUFIO port map (I => $3, O => $4);
"""
'BUFMR':
'prefix': 'BUFMR'
'body': """
${1:FileName}_I_Bufmr_${2:0} : BUFMR port map (I => $3, O => $4);
"""
'BUFMRCE':
'prefix': 'BUFMRCE'
'body': """
${1:FileName}_I_Bufmrce_${2:0} : ;BUFMRCE
generic map (
CE_TYPE => "SYNC", -- string
INIT_OUT => 0, -- integer
IS_CE_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFR':
'prefix': 'BUFR'
'body': """
${1:FileName}_I_Bufr_${2:0} : BUFR
generic map (BUFR_DIVIDE => "BYPASS", SIM_DEVICE => "7SERIES")
port map (I => $3, CE => $4, CLR => $5, O => $6);
"""
'CARRY4':
'prefix': 'CARRY4'
'body': """
${1:FileName}_I_Carry4_${2:0} : CARRY4
port map (
DI => $3, -- in [3:0]
S => $4, -- in [3:0]
CYINIT => $5, -- in
CI => $6, -- in
O => $7, -- out [3:0]
CO => $8 -- out [3:0]
);
"""
'CARRY8':
'prefix': 'CARRY8'
'body': """
${1:FileName}_I_Carry8_${2:0} : CARRY8
generic map (CARRY_TYPE => "SINGLE_CY8")
port map (
CI => $3, -- in
CI_TOP => $4, -- in
DI => $5, -- in [7:0]
S => $6, -- in [7:0]
CO => $7, -- out [7:0]
O => $8 -- out [7:0]
);
"""
'CFGLUT5':
'prefix': 'CFGLUT5'
'body': """
${1:FileName}_I_Cfglut5_${2:0} : CFGLUT5
generic map (INIT => X"00000000")
port map (
CDI => $3, -- in
I0 => $4, -- in
I1 => $5, -- in
I2 => $7, -- in
I3 => $8, -- in
I4 => $9, -- in
CE => $10, -- in
CLK => $11, -- in
O5 => $12, -- out
O6 => $13, -- out
CDO => $14 -- out
);
"""
'DIFFINBUF':
'prefix': 'DIFFINBUF'
'body': """
${1:FileName}_I_Diffinbuf_${2:0} : DIFFINBUF
generic map (
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
ISTANDARD => "UNUSED", -- string
SIM_INPUT_BUFFER_OFFSET => 0 -- integer
)
port map (
DIFF_IN_N => $3, -- in
DIFF_IN_P => $4, -- in
OSC => $5, -- in [3:0]
OSC_EN => $6, -- in [1:0]
VREF => $7, -- in
O => $8, -- out
O_B => $9 -- out
);
"""
'DNA_PORT':
'prefix': 'DNA_PORT'
'body': """
${1:FileName}_I_Dna_Port_${2:0} : DNA_PORT
generic map (SIM_DNA_VALUE => X"000000000000000")
port map (
DIN => $3, -- in
READ => $4, -- in
SHIFT => $5, -- in
CLK => $6, -- in
DOUT => $7 -- out
);
"""
'DPLL':
'prefix': 'DPLL'
'body': """
${1:FileName}_I_Dpll_${2:0} : DPLL
generic map (
CLKIN_PERIOD => 0.000, -- real
REF_JITTER => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_FRACT => 0, -- integer
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
COMPENSATION => "AUTO", -- string
DESKEW_DELAY => 0, -- integer
DESKEW_DELAY_EN => "FALSE", -- string
DESKEW_DELAY_PATH => "FALSE", -- string
IS_CLKIN_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SEL_LOCKED_IN => '1', -- bit
SEL_REG_DELAY => "00", -- std_logic_vector[1:0]
USE_REG_VALID => '1' -- bit
)
port map (
CLKFB_DESKEW => $3, -- in
CLKIN_DESKEW => $4, -- in
CLKIN => $5, -- in
PWRDWN => $6, -- in
RST => $7, -- in
CLKOUT0 => $8, -- out
CLKOUT1 => $9, -- out
CLKOUT2 => $10, -- out
CLKOUT3 => $11, -- out
PSCLK => $12, -- in
PSEN => $13, -- in
PSINCDEC => $14, -- in
PSDONE => $15, -- out
DCLK => $16, -- in
DEN => $17, -- in
DWE => $18, -- in
DADDR => $19, -- in [6:0]
DI => $20, -- in [15:0]
DO => $21, -- out 15:0]
DRDY => $22, -- out
LOCKED => $23, -- out
LOCKED_DESKEW => $24, -- out
LOCKED_FB => $25 -- out
);
"""
'DSP48E1':
'prefix': 'DSP48E1'
'body': """
${1:FileName}_I_Dsp48e1_${2:0} : DSP48E1
generic map (
B_INPUT => "DIRECT", -- string
A_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
BCASCREG => 1, -- integer
ACASCREG => 1, -- integer
INMODEREG => 1, -- integer
ALUMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
OPMODEREG => 1, -- integer
PATTERN => X"000000000000", -- bit_vector
MASK => X"3FFFFFFFFFFF", -- bit_vector
AUTORESET_PATDET => "NO_RESET", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
USE_DPORT => FALSE, -- boolean
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "0000000" -- std_logic_vector[6:0]
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [24:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0]
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0]
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in [6:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
);
"""
'DSP48E2':
'prefix': 'DSP48E2'
'body': """
${1:FileName}_I_Dsp48e2_${2:0} : DSP48E2
generic map (
A_INPUT => "DIRECT", -- string
B_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
ACASCREG => 1, -- integer
BCASCREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
INMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
ALUMODEREG => 1, -- integer
OPMODEREG => 1, -- integer
AMULTSEL => "A", -- string
BMULTSEL => "B", -- string
PREADDINSEL => "A", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
AUTORESET_PATDET => "NO_RESET", -- string
AUTORESET_PRIORITY => "RESET", -- string
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
USE_WIDEXOR => "FALSE", -- string
XORSIMD => "XOR24_48_96" -- string
MASK => X"3FFFFFFFFFFF", -- std_logic_vector[47:0]
PATTERN => X"000000000000", -- std_logic_vector[47:0]
RND => X"000000000000", -- std_logic_vector[47:0]
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "000000000", -- std_logic_vector[8:0]
IS_RSTALLCARRYIN_INVERTED => '0', -- bit
IS_RSTALUMODE_INVERTED => '0', -- bit
IS_RSTA_INVERTED => '0', -- bit
IS_RSTB_INVERTED => '0', -- bit
IS_RSTCTRL_INVERTED => '0', -- bit
IS_RSTC_INVERTED => '0', -- bit
IS_RSTD_INVERTED => '0', -- bit
IS_RSTINMODE_INVERTED => '0', -- bit
IS_RSTM_INVERTED => '0', -- bit
IS_RSTP_INVERTED => '0' -- bit
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [26:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0)
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0)
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in (8:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
XOROUT => $52 -- out [7:0]
);
"""
'DSP48E5':
'prefix': 'DSP48E5'
'body': """
${1:FileName}_I_Dsp48e5_${2:0} : DSP48E5
generic map (
A_INPUT => "DIRECT", -- string
B_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
ACASCREG => 1, -- integer
BCASCREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
INMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
ALUMODEREG => 1, -- integer
OPMODEREG => 1, -- integer
AMULTSEL => "A", -- string
BMULTSEL => "B", -- string
PREADDINSEL => "A", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
AUTORESET_PATDET => "NO_RESET", -- string
AUTORESET_PRIORITY => "RESET", -- string
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
USE_WIDEXOR => "FALSE", -- string
XORSIMD => "XOR24_48_96" -- string
MASK => X"3FFFFFFFFFFF", -- std_logic_vector[47:0]
PATTERN => X"000000000000", -- std_logic_vector[47:0]
RND => X"000000000000", -- std_logic_vector[47:0]
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "000000000", -- std_logic_vector[8:0]
IS_RSTALLCARRYIN_INVERTED => '0', -- bit
IS_RSTALUMODE_INVERTED => '0', -- bit
IS_RSTA_INVERTED => '0', -- bit
IS_RSTB_INVERTED => '0', -- bit
IS_RSTCTRL_INVERTED => '0', -- bit
IS_RSTC_INVERTED => '0', -- bit
IS_RSTD_INVERTED => '0', -- bit
IS_RSTINMODE_INVERTED => '0', -- bit
IS_RSTM_INVERTED => '0', -- bit
IS_RSTP_INVERTED => '0' -- bit
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [26:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0)
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0)
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in (8:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
XOROUT => $52 -- out [7:0]
);
"""
'EFUSE_USR':
'prefix': 'EFUSE_USR'
'body': """2
${1:FileName}_I_Efuse_Usr_${:0} : EFUSE_USR
generic map ("
SIM_EFUSE_VALUE => X00000000" -- bit_vector
)
port map (t
EFUSEUSR => $3 -- out [31:0]
);
"""
'FADD':
'prefix': 'FADD'
'body': """
${1:FileName}_I_Fadd_${2:0} : FADD
generic map (
IS_I0_INVERTED => '0', -- bit
IS_I1_INVERTED => '0' -- bit
)
port map (
I0 => $3, -- in
I1 => $4, -- in
CI => $5, -- in
CO => $6, -- out
O => $7 -- out
);
"""
'FDCE':
'prefix': 'FDCE'
'body': """
${1:FileName}_I_Fdce_${2:0} : FDCE
generic map (INIT => '0', IS_CLR_INVERTED => '0',
IS_C_INVERTED => '0', IS_D_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, CLR => $6, Q => $7);
"""
'FDPE':
'prefix': 'FDPE'
'body': """
${1:FileName}_I_Fdpe_${2:0} : FDPE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_PRE_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, PRE => $6, Q => $7);
"""
'FDRE':
'prefix': 'FDRE'
'body': """
${1:FileName}_I_Fdre_${2:0} : FDRE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_R_INVERTED => '0')
port map (D => $3, CE => $3, C => $4, R => $5, Q => $6);
"""
'FDSE':
'prefix': 'FDSE'
'body': """
${1:FileName}_I_Fdse_${2:0} : FDSE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_S_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, S => $6, Q => $7);
"""
'FIFO36E2':
'prefix': 'FIFO36E2'
'body': """
${1:FileName}_I_Fifo36e2_${2:0} : FIFO36E2
generic map (
INIT => X"000000000000000000", -- [71:0]
SRVAL => X"000000000000000000", -- [71:0]
CLOCK_DOMAINS => "INDEPENDENT",
READ_WIDTH => 4,
WRITE_WIDTH => 4,
REGISTER_MODE => "UNREGISTERED",
RDCOUNT_TYPE => "RAW_PNTR",
WRCOUNT_TYPE => "RAW_PNTR",
RSTREG_PRIORITY => "RSTREG",
SLEEP_ASYNC => "FALSE",
CASCADE_ORDER => "NONE",
PROG_EMPTY_THRESH => 256,
PROG_FULL_THRESH => 256,
EN_ECC_PIPE => "FALSE",
EN_ECC_READ => "FALSE",
EN_ECC_WRITE => "FALSE",
FIRST_WORD_FALL_THROUGH => "FALSE",
IS_RDCLK_INVERTED => '0',
IS_RDEN_INVERTED => '0',
IS_RSTREG_INVERTED => '0',
IS_RST_INVERTED => '0',
IS_WRCLK_INVERTED => '0',
IS_WREN_INVERTED => '0'
)
port map (
DIN => $3, -- in [63:0]
DINP => $4, -- in [7:0]
CASDIN => $5, -- in [63:0]
CASDINP => $6, -- in [7:0]
WRCLK => $7, -- in
WREN => $8, -- in
WRCOUNT => $9, -- out [13:0]
WRERR => $10, -- out
WRRSTBUSY => $11, -- out
RDCLK => $12, -- in
RDEN => $13, -- in
RDCOUNT => $14, -- out [13:0]
RDERR => $15, -- out
RDRSTBUSY => $16, -- out
REGCE => $17, -- in
RST => $18, -- in
RSTREG => $19, -- in
SLEEP => $20, -- in
CASDOMUX => $21, -- in
CASDOMUXEN => $22, -- in
CASNXTRDEN => $23, -- in
CASOREGIMUX => $24, -- in
CASOREGIMUXEN => $25, -- in
CASPRVEMPTY => $26, -- in
INJECTDBITERR => $27, -- in
INJECTSBITERR => $28, -- in
CASNXTEMPTY => $29, -- out
CASPRVRDEN => $30, -- out
CASDOUT => $31, -- out [63:0]
CASDOUTP => $32, -- out [7:0]
DOUT => $33, -- out [63:0]
DOUTP => $34, -- out [7:0]
ECCPARITY => $35, -- out [7:0]
EMPTY => $36, -- out
FULL => $37, -- out
PROGEMPTY => $38, -- out
PROGFULL => $39, -- out
DBITERR => $40, -- out
SBITERR => $41 -- out
);
"""
'GLBL_VHD':
'prefix': 'GLBL_VHD'
'body': """
${1:FileName}_I_Glbl_Vhd_${2:0} : GLBL_VHD
generic map (
ROC_WIDTH => 100000, -- integer
TOC_WIDTH => 0 -- integer
);
"""
'HARD_SYNC':
'prefix': 'HARD_SYNC'
'body': """
${1:FileName}_I_Hard_Sync_${2:0} : HARD_SYNC
generic map (
INIT => , -- '0'
IS_CLK_INVERTED => , -- '0'
LATENCY => -- 2
)
port map (
CLK => $3, -- in
DIN => $4, -- in
DOUT => $5 -- out
);
"""
'IBUF':
'prefix': 'IBUF'
'body': """
${1:FileName}_I_Ibuf_${2:0} : IBUF
generic map (CAPACITANCE => "DONT_CARE",IBUF_DELAY_VALUE => "0",
IFD_DELAY_VALUE => "AUTO", IBUF_LOW_PWR => TRUE,
IOSTANDARD => "DEFAULT")
port map (I => $3, O => $4);
"""
'IBUFCTRL':
'prefix': 'IBUFCTRL'
'body': """
${1:FileName}_I_Ibufctrl_${2:0} : IBUFCTRL
generic map (
ISTANDARD => "UNUSED", -- string
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
T => $3, -- in
I => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7 -- out
);
"""
'IBUFDS':
'prefix': 'IBUFDS'
'body': """
${1:FileName}_I_Ibufds_${2:0} : IBUFDS
generic map (DIFF_TERM => FALSE, IOSTANDARD => "DEFAULT", CAPACITANCE => "DONT_CARE",
DQS_BIAS => "FALSE", IBUF_DELAY_VALUE => "0", IBUF_LOW_PWR => TRUE,
IFD_DELAY_VALUE => "AUTO")
port map (I => $3, IB => $4, O => $5);
"""
'IBUFDSE3':
'prefix': 'IBUFDSE3'
'body': """
${1:FileName}_I_Ibufdse3_${2:0} : IBUFDSE3
generic (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET =: 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
OSC => $6, -- in [3:0]
OSC_EN => $7, -- in [1:0]
O => $8, -- out
);
"""
'IBUFDS_DIFF_OUT':
'prefix': 'IBUFDS_DIFF_OUT'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_${2:0} : IBUFDS_DIFF_OUT
generic map (
DIFF_TERM => FALSE, -- boolean
IBUF_LOW_PWR => TRUE, -- boolean
DQS_BIAS => "FALSE", -- string
IOSTANDARD => "DEFAULT" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'IBUFDS_DIFF_OUT_IBUFDISABLE':
'prefix': 'IBUFDS_DIFF_OUT_IBUFDISABLE'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_Dsble${2:0} : IBUFDS_DIFF_OUT_IBUFDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
DQS_BIAS => "FALSE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
O => $6, -- out
OB => $7 -- out
);
"""
'IBUFDS_DIFF_OUT_INTERMDISABLE':
'prefix': 'IBUFDS_DIFF_OUT_INTERMDISABLE'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_IntrmDsble_${2:0} : IBUFDS_DIFF_OUT_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
DQS_BIAS => "FALSE", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7, -- out
OB => $8 -- out
);
"""
'IBUFDS_GTE3':
'prefix': 'IBUFDS_GTE3'
'body': """
${1:FileName}_I_Ibufds_Gte3_${2:0} : IBUFDS_GTE3
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => "00", -- [1:0]
REFCLK_ICNTL_RX => "00" -- [1:0]
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_GTE4':
'prefix': 'IBUFDS_GTE4'
'body': """
${1:FileName}_I_Ibufds_Gte4_${2:0} : IBUFDS_GTE4
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => "00", -- [1:0]
REFCLK_ICNTL_RX => "00" -- [1:0]
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_GTE5':
'prefix': 'IBUFDS_GTE5'
'body': """
${1:FileName}_I_Ibufds_Gte5_${2:0} : IBUFDS_GTE5
generic map (
REFCLK_CTL_DRV_SWING => "000", -- std_logic_vector[2:0]
REFCLK_EN_DRV => '0', -- bit
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => 0, -- integer
REFCLK_ICNTL_RX => 0 -- integer
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_IBUFDISABLE':
'prefix': 'IBUFDS_IBUFDISABLE'
'body': """
${1:FileName}_I_Ibufds_dsble_${2:0} : IBUFDS_IBUFDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
O => $6 -- out
);
"""
'IBUFDS_INTERMDISABLE':
'prefix': 'IBUFDS_INTERMDISABLE'
'body': """
${1:FileName}_I_Ibufds_IntrmDsble_${2:0} : IBUFDS_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7 -- out
);
"""
'ICAPE2':
'prefix': 'ICAPE2'
'body': """
${1:FileName}_I_Icape2_${2:0} : ICAPE2
generic map (
DEVICE_ID => X"03651093", -- bit_vector
ICAP_WIDTH => "X32", -- string
SIM_CFG_FILE_NAME => "NONE" -- string
)
port map (
I => $3, -- in [31:0]
RDWRB => $4, -- in
CSIB => $5, -- in
CLK => $6, -- in
O => $7 -- out [31:0]
);
"""
'ICAPE3':
'prefix': 'ICAPE3'
'body': """
${1:FileName}_I_Icape3_${2:0} : ICAPE3
generic map (
DEVICE_ID => X"03628093", -- bit_vector
ICAP_AUTO_SWITCH => "DISABLE", -- string
SIM_CFG_FILE_NAME => "NONE" -- string
)
port map (
I => $3, -- in [31:0]
CLK => $4, -- in
CSIB => $5, -- in
RDWRB => $6, -- in
PRDONE => $7, -- out
PRERROR => $8, -- out
AVAIL => $9, -- out
O => $10 -- out [31:0]
);
"""
'IDDR':
'prefix': 'IDDR'
'body': """
${1:FileName}_I_Iddr_${2:0} : IDDR
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
SRTYPE => "SYNC", -- string
IS_C_INVERTED => '0', -- std_ulogic
IS_D_INVERTED => '0' -- std_ulogic
)
port map (
D => $3, -- in
CE => $4, -- in
C => $5, -- in
S => $6, -- in
R => $7, -- in
Q1 => $8, -- out
Q2 => $9 -- out
);
"""
'IDDR_2CLK':
'prefix': 'IDDR_2CLK'
'body': """
${1:FileName}_I_Iddr_2clk_${2:0} : IDDR_2CLK
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
SRTYPE => "SYNC" -- string
IS_CB_INVERTED => '0', -- std_ulogic
IS_C_INVERTED => '0', -- std_ulogic
IS_D_INVERTED => '0' -- std_ulogic
)
port map (
D => $3, -- in
CE => $4, -- in
C => $5, -- in
CB => $6, -- in
S => $7, -- in
R => $8, -- in
Q1 => $9, -- out
Q2 => $10 -- out
);
"""
'IDDRE1':
'prefix': 'IDDRE1'
'body': """
${1:FileName}_I_Iddre1_${2:0} : IDDRE1
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
IS_CB_INVERTED => '0' -- bit
IS_C_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
C => $4, -- in
CB => $5, -- in
R => $6, -- in
Q1 => $7, -- out
Q2 => $8 -- out
);
"""
'IDELAYCTRL':
'prefix': 'IDELAYCTRL'
'body': """
${1:FileName}_I_Idlyctrl_${2:0} : IDELAYCTRL
generic map (SIM_DEVICE => "7SERIES")
port map(RDY => $3, REFCLK => $3, RST => $4);
"""
'IDELAYE2':
'prefix': 'IDELAYE2'
'body': """
${1:FileName}_I_Idlye2_${2:0} : IDELAYE2
generic map (
SIGNAL_PATTERN => "DATA", -- string
REFCLK_FREQUENCY => 200.0, -- real
HIGH_PERFORMANCE_MODE => "FALSE", -- string
DELAY_SRC => "IDATAIN", -- string
CINVCTRL_SEL => "FALSE", -- string
IDELAY_TYPE => "FIXED", -- string
IDELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
IS_C_INVERTED => '0', -- bit
IS_DATAIN_INVERTED => '0', -- bit
IS_IDATAIN_INVERTED => '0' -- bit
)
port map (
DATAIN => $3, -- in
IDATAIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
C => $7, -- in
CINVCTRL => $8, -- in
LD => $9, -- in
LDPIPEEN => $10, -- in
REGRST => $11, -- in
CNTVALUEIN => $12, -- in [4:0]
CNTVALUEOUT => $13, -- out [4:0]
DATAOUT => $14 -- out
);
"""
'IDELAYE2_FINEDELAY':
'prefix': 'IDELAYE2_FINEDELAY'
'body': """
${1:FileName}_I_Idlye2_fndly_${2:0} : IDELAYE2_FINEDELAY
generic map (
SIGNAL_PATTERN => "DATA", -- string
REFCLK_FREQUENCY => 200.0, -- real
HIGH_PERFORMANCE_MODE => "FALSE", -- string
DELAY_SRC => "IDATAIN", -- string
CINVCTRL_SEL => "FALSE", -- string
FINEDELAY => "BYPASS", -- string
IDELAY_TYPE => "FIXED", -- string
IDELAY_VALUE => 0, -- integer
DELAY_SRC => "IDATAIN", -- string
IS_C_INVERTED => '0', -- bit
IS_DATAIN_INVERTED => '0', -- bit
IS_IDATAIN_INVERTED => '0', -- bit
PIPE_SEL => "FALSE" -- string
)
port map (
DATAIN => $3, -- in
IDATAIN => $4, -- in
IFDLY => $5, -- in [2:0]
CE => $6, -- in
INC => $7, -- in
C => $8, -- in
CINVCTRL => $9, -- in
LD => $10, -- in
LDPIPEEN => $11, -- in
REGRST => $12, -- in
CNTVALUEIN => $13, -- in [4:0]
CNTVALUEOUT => $14, -- out [4:0]
DATAOUT => $15 -- out
);
"""
'IDELAYE3':
'prefix': 'IDELAYE3'
'body': """
${1:FileName}_I_Idlye3_${2:0} : IDELAYE3
generic map (
CASCADE => "NONE", -- string
DELAY_FORMAT => "TIME", -- string
DELAY_SRC => "IDATAIN", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
LOOPBACK => "FALSE", -- string
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
IDATAIN => $3, -- in
DATAIN => $4, -- in
CASC_IN => $5, -- in
CASC_RETURN => $6, -- in
CLK => $7, -- in
CE => $8, -- in
RST => $9, -- in
INC => $10, -- in
LOAD => $11, -- in
EN_VTC => $12, -- in
CNTVALUEIN => $13, -- in [8:0]
CNTVALUEOUT => $14, -- out [8:0]
CASC_OUT => $15, -- out
DATAOUT => $16 -- out
);
"""
'IDELAYE5':
'prefix': 'IDELAYE5'
'body': """
${1:FileName}_I_Idlye5_${2:0} : IDELAYE5
generic map (
CASCADE => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
IDATAIN => $3, -- in
CLK => $4, -- in
CE => $5, -- in
RST => $6, -- in
INC => $7, -- in
LOAD => $8, -- in
CASC_RETURN => $9, -- in
CNTVALUEIN => $10, -- in [4:0]
CNTVALUEOUT => $11, -- out [4:0]
CASC_OUT => $12, -- out
DATAOUT => $13 -- out
);
"""
'INBUF':
'prefix': 'INBUF'
'body': """
${1:FileName}_I_Inbuf_${2:0} : INBUF
generic map (
IBUF_LOW_PWR => "TRUE", -- string
ISTANDARD => "UNUSED", -- string
SIM_INPUT_BUFFER_OFFSET => 0 -- integer
)
port map (
PAD => $3, -- in
VREF => $4, -- in
OSC => $5, -- in [3:0]
OSC_EN => $6, -- in
O => $7 -- out
);
"""
'IN_FIFO':
'prefix': 'IN_FIFO'
'body': """
${1:FileName}_I_In_Fifo_${2:0} : IN_FIFO
generic map (
SYNCHRONOUS_MODE => "FALSE", -- string
ARRAY_MODE => "ARRAY_MODE_4_X_8", -- string
ALMOST_EMPTY_VALUE => 1, -- integer
ALMOST_FULL_VALUE => 1 -- integer
)
port map (
D0 => $3, -- in [3:0]
D1 => $4, -- in [3:0]
D2 => $5, -- in [3:0]
D3 => $6, -- in [3:0]
D4 => $7, -- in [3:0]
D5 => $8, -- in [7:0]
D6 => $9, -- in [7:0]
D7 => $10, -- in [3:0]
D8 => $11, -- in [3:0]
D9 => $12, -- in [3:0]
WRCLK => $13, -- in
WREN => $14, -- in
RESET => $15, -- in
RDCLK => $16, -- in
RDEN => $17, -- in
Q0 => $18, -- out [7:0]
Q1 => $19, -- out [7:0]
Q2 => $20, -- out [7:0]
Q3 => $21, -- out [7:0]
Q4 => $22, -- out [7:0]
Q5 => $23, -- out [7:0]
Q6 => $24, -- out [7:0]
Q7 => $25, -- out [7:0]
Q8 => $26, -- out [7:0]
Q9 => $27, -- out [7:0]
ALMOSTEMPTY => $28, -- out
ALMOSTFULL => $29, -- out
EMPTY => $20, -- out
FULl => $21 -- out
);
"""
'IOBUF':
'prefix': 'IOBUF'
'body': """
${1:FileName}_I_Iobuf_${2:0} : IOBUF
generic map (DRIVE => 12, IBUF_LOW_PWR => TRUE, IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, T => $4, O => $5, IO => $6);
"""
'IOBUFDS':
'prefix': 'IOBUFDS'
'body': """
${1:FileName}_I_Iobufds_${2:0} : IOBUFDS
generic map (
DIFF_TERM => FALSE, -- Boolean
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
SLEW => "SLOW", -- string
IOSTANDARD => "DEFAULT" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5, -- out
IO => $6, -- inout
IOB => $7, -- inout
);
"""
'IOBUFDSE3':
'prefix': 'IOBUFDSE3'
'body': """
${1:FileName}_I_iobufdse3_${2:0} : IOBUFDSE3
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET => 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
T => $6, -- in
O => $7, -- out
OSC => $8, -- in [3:0]
OSC_EN => $9, -- in [1:0]
IBUFDISABLE => $10, -- in
DCITERMDISABLE => $11 -- in
);
"""
'IOBUFDS_DIFF_OUT':
'prefix': 'IOBUFDS_DIFF_OUT'
'body': """
${1:FileName}_I_Iobufds_Diff_Out_${2:0} : IOBUFDS_DIFF_OUT
generic map (
DIFF_TERM => FALSE, -- boolean
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
IOSTANDARD => "DEFAULT" -- stting
)
port map (
I => $3, -- in
TM => $4, -- in
TS => $5, -- in
O => $6, -- out
OB => $7, -- out
IO => $8, -- inout
IOB => $9 -- inout
);
"""
'IOBUFDS_DIFF_OUT_INTERMDISABLE':
'prefix': 'IOBUFDS_DIFF_OUT_INTERMDISABLE'
'body': """
${1:FileName}_I_Iobufds_Diff_Out_Intrmdsble_${2:0} : IOBUFDS_DIFF_OUT_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_DEVICE => "7SERIES", -- string
USE_IBUFDISABLE => "TRUE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
TM => $6, -- in
TS => $7, -- in
O => $8, -- out
OB => $9, -- out
IBUFDISABLE => $10, -- in
INTERMDISABLE => $11 -- in
);
"""
'IOBUFDS_INTERMDISABLE':
'prefix': 'IOBUFDS_INTERMDISABLE'
'body': """
${1:FileName}_I_Iobufds_intrmdsble_${2:0} : IOBUFDS_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_DEVICE => "7SERIES", -- string
SLEW => "SLOW", -- string
USE_IBUFDISABLE => "TRUE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
T => $6, -- in
O => $7, -- out
IBUFDISABLE => $8, -- in
INTERMDISABLE => $9 -- in
);
"""
'IOBUFE3':
'prefix': 'IOBUFE3'
'body': """
${1:FileName}_I_Iobufe3_${2:0} : IOBUFE3
generic map (
DRIVE => 12, -- integer
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET => 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
IO => $3, -- inout
I => $4, -- in
T => $5, -- in
O => $6, -- out
OSC => $7, -- in [3:0]
OSC_EN => $8, -- in
VREF => $9, -- in
DCITERMDISABLE => $10, -- in
IBUFDISABLE => $11 -- in
);
"""
'ISERDES':
'prefix': 'ISERDES'
'body': """
${1:FileName}_I_Isrds_${2:0} : ISERDES
generic map (
BITSLIP_ENABLE => false, -- boolean
DATA_RATE => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
INIT_Q3 => '0', -- bit
INIT_Q4 => '0', -- bit
INTERFACE_TYPE => "MEMORY", -- string
IOBDELAY => "NONE", -- string
IOBDELAY_TYPE => "DEFAULT", -- string
IOBDELAY_VALUE => 0, -- integer
NUM_CE => 2, -- integer
SERDES_MODE => "MASTER", -- string
SRVAL_Q1 => '0', -- bit
SRVAL_Q2 => '0', -- bit
SRVAL_Q3 => '0', -- bit
SRVAL_Q4 => '0' -- bit
)
port map (
D => $3, -- in
CE1 => $4, -- in
CE2 => $5, -- in
SR => $6, -- in
REV => $7, -- in
DLYCE => $8, -- in
DLYINC => $9, -- in
DLYRST => $10, -- in
BITSLIP => $11, -- in
O => $12, -- out
Q1 => $13, -- out
Q2 => $14, -- out
Q3 => $15, -- out
Q4 => $16, -- out
Q5 => $17, -- out
Q6 => $18, -- out
CLK => $19, -- in
CLKDIV => $20, -- in
OCLK => $21, -- in
SHIFTIN1 => $22, -- in
SHIFTIN2 => $23, -- in
SHIFTOUT1 => $24, -- out
SHIFTOUT2 => $25, -- out
);
"""
'ISERDESE2':
'prefix': 'ISERDESE2'
'body': """
${1:FileName}_I_Isrdse2_${2:0} : ISERDESE2
generic map (
SERDES_MODE => "MASTER", -- string
INTERFACE_TYPE => "MEMORY", -- string
IOBDELAY => "NONE", -- string
DATA_RATE => "DDR", -- string
DATA_WIDTH => 4, -- integer
DYN_CLKDIV_INV_EN => "FALSE", -- string
DYN_CLK_INV_EN => "FALSE", -- string
NUM_CE => 2, -- integer
OFB_USED => "FALSE", -- string
INIT_Q1 => '0', -- bit;
INIT_Q2 => '0', -- bit;
INIT_Q3 => '0', -- bit;
INIT_Q4 => '0', -- bit;
SRVAL_Q1 => '0', -- bit;
SRVAL_Q2 => '0', -- bit;
SRVAL_Q3 => '0', -- bit;
SRVAL_Q4 => '0', -- bit
IS_CLKB_INVERTED => '0', -- bit
IS_CLKDIVP_INVERTED => '0', -- bit
IS_CLKDIV_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_D_INVERTED => '0', -- bit
IS_OCLKB_INVERTED => '0', -- bit
IS_OCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
DDLY => $4, -- in
OFB => $5, -- in
BITSLIP => $6, -- in
CE1 => $7, -- in
CE2 => $8, -- in
RST => $9, -- in
CLK => $10, -- in
CLKB => $11, -- in
CLKDIV => $12, -- in
CLKDIVP => $13, -- in
OCLK => $14, -- in
OCLKB => $15, -- in
DYNCLKDIVSEL => $16, -- in
DYNCLKSEL => $17, -- in
SHIFTOUT1 => $18, -- out
SHIFTOUT2 => $19, -- out
O => $20, -- out
Q1 => $21, -- out
Q2 => $22, -- out
Q3 => $23, -- out
Q4 => $24, -- out
Q5 => $25, -- out
Q6 => $26, -- out
Q7 => $27, -- out
Q8 => $28, -- out
SHIFTIN1 => $29, -- in
SHIFTIN2 => $30 -- in
);
"""
'ISERDESE3':
'prefix': 'ISERDESE3'
'body': """
${1:FileName}_I_Isrdse3_${2:0} : ISERDESE3
generic map (
DATA_WIDTH => 8, -- integer
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
FIFO_ENABLE => "FALSE", -- string
FIFO_SYNC_MODE => "FALSE", -- string
IDDR_MODE => "FALSE", -- string
IS_CLK_B_INVERTED => '0', -- std_ulogic
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSIOM => 2.0 -- real
)
port map (
D => $3, -- in
CLK => $4, -- in
CLKDIV => $5, -- in
CLK_B => $6, -- in
RST => $7, -- in
FIFO_RD_CLK => $8, -- in
FIFO_RD_EN => $9, -- in
INTERNAL_DIVCLK => $10, -- out
FIFO_EMPTY => $11, -- out
Q => $12 -- out[7:0]
);
"""
'LUT5':
'prefix': 'LUT5'
'body': """
${1:FileName}_I_Lut5_${2:0} : LUT5
generic map (
INIT => X"00000000"
)
port map (
I0 => $3, -- in
I1 => $4, -- in
I2 => $5, -- in
I3 => $6, -- in
I4 => $7, -- in
O => $8 -- out
);
"""
'LUT6_2':
'prefix': 'LUT6_2'
'body': """
${1:FileName}_I_Lut6_2_${2:0} : LUT6_2
generic map (
INIT => X"0000000000000000" -- bit_vector
)
port map (
I0 => $3, -- in
I1 => $4, -- in
I2 => $5, -- in
I3 => $6, -- in
I4 => $7, -- in
I5 => $8, -- in
O5 => $9, -- out
O6 => $10 -- out
);
"""
'MASTER_JTAG':
'prefix': 'MASTER_JTAG'
'body': """
${1:FileName}_I_Mstr_Jtag_${2:0} : MASTER_JTAG
port map (
TDO => $3, -- out
TCK => $4, -- in
TDI => $5, -- in
TMS => $6 -- in
);
"""
'MMCME2_ADV':
'prefix': 'MMCME2_ADV'
'body': """
${1:FileName}_I_Mmcme2_Adv_${2:0} : MMCME2_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
REF_JITTER1 => 0.0, -- real
REF_JITTER2 => 0.0, -- real
COMPENSATION => "ZHOLD", -- string
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, - real
CLKFBOUT_USE_FINE_PS => FALSE, -- boolean
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => FALSE, -- boolean
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => FALSE, -- boolean
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => FALSE, -- boolean
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => FALSE, -- boolean
CLKOUT4_CASCADE => FALSE, -- boolean
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => FALSE, -- boolean
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => FALSE, -- boolean
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => FALSE, -- boolean
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH",-- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => FALSE -- boolean
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
CLKFBOUT => $7, -- out
CLKFBOUTB => $8, -- out
CLKFBSTOPPED => $9, -- out
CLKINSTOPPED => $10, -- out
RST => $11, -- in
PWRDWN => $12, -- in
LOCKED => $13, -- out
CLKOUT0 => $14, -- out
CLKOUT0B => $15, -- out
CLKOUT1 => $16, -- out
CLKOUT1B => $17, -- out
CLKOUT2 => $18, -- out
CLKOUT2B => $19, -- out
CLKOUT3 => $20, -- out
CLKOUT3B => $21, -- out
CLKOUT4 => $22, -- out
CLKOUT5 => $23, -- out
CLKOUT6 => $24, -- out
DI => $25, -- in [15:0]
DADDR => $26, -- in [6:0]
DEN => $27, -- in
DWE => $28, -- in
DCLK => $29, -- in
DO => $30, -- out [15:0]
DRDY => $31, -- out
PSCLK => $32, -- in
PSEN => $33, -- in
PSINCDEC => $34, -- in
PSDONE => $35 -- out
);
"""
'MMCME3_ADV':
'prefix': 'MMCME3_ADV'
'body': """
${1:FileName}_I_Mmcme3_Adv_${2:0} : MMCME3_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
IS_CLKIN1_INVERTED => '0', -- std_ulogic
IS_CLKIN2_INVERTED => '0', -- std_ulogic
IS_CLKINSEL_INVERTED => '0', -- std_ulogic
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, -- real
CLKFBOUT_USE_FINE_PS => "FALSE", -- string
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => "FALSE", -- string
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => "FALSE", -- string
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => "FALSE", -- string
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => "FALSE", -- string
CLKOUT4_CASCADE => "FALSE", -- string
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => "FALSE", -- string
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => "FALSE", -- string
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => "FALSE", -- string
COMPENSATION => "AUTO", -- string
IS_PSEN_INVERTED => '0', -- std_ulogic
IS_PSINCDEC_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
RST => $7, -- in
PWRDWN => $8, -- in
CLKFBOUT => $9, -- out
CLKFBOUTB => $10, -- out
CLKOUT0 => $11, -- out
CLKOUT0B => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT1B => $14, -- out
CLKOUT2 => $15, -- out
CLKOUT2B => $16, -- out
CLKOUT3 => $17, -- out
CLKOUT3B => $18, -- out
CLKOUT4 => $19, -- out
CLKOUT5 => $20, -- out
CLKOUT6 => $21, -- out
CDDCREQ => $22, -- in
CDDCDONE => $23, -- out
PSCLK => $24, -- in
PSEN => $25, -- in
PSINCDEC => $26, -- in
PSDONE => $27, -- out
DCLK => $28, -- in
DI => $29, -- in [15:0]
DADDR => $30, -- in [6:0]
DEN => $31, -- in
DWE => $32, -- in
DO => $33, -- out [15:0]
DRDY => $34, -- out
CLKFBSTOPPED => $35, -- out
CLKINSTOPPED => $36, -- out
LOCKED => $37 -- out
);
"""
'MMCME4_ADV':
'prefix': 'MMCME4_ADV'
'body': """
${1:FileName}_I_Mmcme4_Adv_${2:0} : MMCME4_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
IS_CLKIN1_INVERTED => '0', -- bit
IS_CLKIN2_INVERTED => '0', -- bit
IS_CLKINSEL_INVERTED => '0', -- bit
IS_CLKFBIN_INVERTED => '0', -- bit
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, -- real
CLKFBOUT_USE_FINE_PS => "FALSE", -- string
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => "FALSE", -- string
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => "FALSE", -- string
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => "FALSE", -- string
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => "FALSE", -- string
CLKOUT4_CASCADE => "FALSE", -- string
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => "FALSE", -- string
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => "FALSE", -- string
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => "FALSE", -- string
COMPENSATION => "AUTO", -- string
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
RST => $7, -- in
PWRDWN => $8, -- in
CLKFBOUT => $9, -- out
CLKFBOUTB => $10, -- out
CLKOUT0 => $11, -- out
CLKOUT0B => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT1B => $14, -- out
CLKOUT2 => $15, -- out
CLKOUT2B => $16, -- out
CLKOUT3 => $17, -- out
CLKOUT3B => $18, -- out
CLKOUT4 => $19, -- out
CLKOUT5 => $20, -- out
CLKOUT6 => $21, -- out
CDDCREQ => $22, -- in
CDDCDONE => $23, -- out
PSCLK => $24, -- in
PSEN => $25, -- in
PSINCDEC => $26, -- in
PSDONE => $27, -- out
DCLK => $28, -- in
DI => $29, -- in [15:0]
DADDR => $30, -- in [6:0]
DEN => $31, -- in
DWE => $32, -- in
DO => $33, -- out([15:0]
DRDY => $34, -- out
CLKFBSTOPPED => $35, -- out
CLKINSTOPPED => $36, -- out
LOCKED => $37, -- out
);
"""
'MMCME5':
'prefix': 'MMCME5'
'body': """
${1:FileName}_I_Mmcme5_${2:0} : MMCME5
generic map (
BANDWIDTH => "OPTIMIZED", -- string
COMPENSATION => "AUTO", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_FRACT => 0, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT4_DIVIDE => 2, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT5_DIVIDE => 2, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT6_DIVIDE => 2, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUTFB_PHASE_CTRL => "00", -- std_logic_vector[1:0]
DESKEW_DELAY1 => 0, -- integer
DESKEW_DELAY2 => 0, -- integer
DESKEW_DELAY_EN1 => "FALSE", -- string
DESKEW_DELAY_EN2 => "FALSE", -- string
DESKEW_DELAY_PATH1 => "FALSE", -- string
DESKEW_DELAY_PATH2 => "FALSE", -- string
IS_CLKFBIN_INVERTED => '0', -- bit
IS_CLKIN1_INVERTED => '0', -- bit
IS_CLKIN2_INVERTED => '0', -- bit
IS_CLKINSEL_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000 -- integer
)
port map (
CLKIN1_DESKEW => $3, -- in
CLKFB1_DESKEW => $4, -- in
CLKIN2_DESKEW => $5, -- in
CLKFB2_DESKEW => $6, -- in
CLKIN1 => $7, -- in
CLKIN2 => $8, -- in
CLKINSEL => $9, -- in
CLKFBIN => $10, -- in
CLKFBOUT => $11, -- out
CLKOUT0 => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT2 => $14, -- out
CLKOUT3 => $15, -- out
CLKOUT4 => $16, -- out
CLKOUT5 => $17, -- out
CLKOUT6 => $18, -- out
PWRDWN => $19, -- in
RST => $20, -- in
PSCLK => $21, -- in
PSEN => $22, -- in
PSINCDEC => $23, -- in
PSDONE => $24, -- out
DCLK => $25, -- in
DEN => $26, -- in
DWE => $27, -- in
DADDR => $28, -- in [6:0]
DI => $29, -- in [15:0]
DO => $30, -- out [15:0]
DRDY => $31, -- out
CLKFBSTOPPED => $32, -- out
CLKINSTOPPED => $33, -- out
LOCKED1_DESKEW => $34, -- out
LOCKED2_DESKEW => $35, -- out
LOCKED_FB => $36, -- out
LOCKED => $37 -- out
);
"""
'MUXCY':
'prefix': 'MUXCY'
'body': """MUXCY
${1:FileName}_I_Muxcy_${2:0} :
port map (
CI => $3, -- in
DI => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF7':
'prefix': 'MUXF7'
'body': """
${1:FileName}_I_Muxf7_${2:0} : MUXF7
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF8':
'prefix': 'MUXF8'
'body': """
${1:FileName}_I_Muxf8_${2:0} : MUXF8
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF9':
'prefix': 'MUXF9'
'body': """
${1:FileName}_I_Muxf9_${2:0} : MUXF9
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'OBUF':
'prefix': 'OBUF'
'body': """
${1:FileName}_I_Obuf_${2:0} : OBUF
generic map (DRIVE => 12, IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, O => $4);
"""
'OBUFDS':
'prefix': 'OBUFDS'
'body': """
${1:FileName}_I_Obufds_${2:0} : OBUFDS
generic map (IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, O => $4, OB => $5);
"""
'OBUFDS_DPHY':
'prefix': 'OBUFDS_DPHY'
'body': """
${1:FileName}_I_Obufds_Dphy_${2:0} : OBUFDS_DPHY
generic map (
IOSTANDARD => "DEFAULT" -- string
)
port map (
HSTX_I => $3, -- in
HSTX_T => $4, -- in
LPTX_I_N => $5, -- in
LPTX_I_P => $6, -- in
LPTX_T => $7, -- in
O => $8, -- out
OB => $9 -- out
);
"""
'OBUFDS_GTE3_ADV':
'prefix': 'OBUFDS_GTE3_ADV'
'body': """
${1:FileName}_I_Obufds_Gte3_Adv_${2:0} : OBUFDS_GTE3_ADV
generic map (
REFCLK_EN_TX_PATH : bit := '0';
REFCLK_ICNTL_TX : std_logic_vector(4 downto 0) := "00000"
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
RXRECCLK_SEL => $5, -- in [1:0]
O => $6, -- out
OB => $7 -- out
);
"""
'OBUFDS_GTE4_ADV':
'prefix': 'OBUFDS_GTE4_ADV'
'body': """
${1:FileName}_I_Obufds_Gte4_Adv_${2:0} : OBUFDS_GTE4_ADV
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_ICNTL_TX => "00000" -- [4:0]
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
RXRECCLK_SEL => $5, -- in [1:0]
O => $6, -- out
OB => $7 -- out
);
"""
'OBUFDS_GTE5_ADV':
'prefix': 'OBUFDS_GTE5_ADV'
'body': """
${1:FileName}_I_Obufds_Gte5_Adv_${2:0} : OBUFDS_GTE5_ADV
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
RXRECCLK_SEL => "00" -- [1:0]
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'OBUFT':
'prefix': 'OBUFT'
'body': """
${1:FileName}_I_Obuft_${2:0} : OBUFT
generic map (
CAPACITANCE => "DONT_CARE", -- string
DRIVE => 12, -- integer
IOSTANDARD => "DEFAULT", -- string
SLEW => "SLOW" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5 -- out
);
"""
'OBUFTDS':
'prefix': 'OBUFTDS'
'body': """
${1:FileName}_I_Obuftds_${2:0} : OBUFTDS
generic map (
CAPACITANCE => "DONT_CARE", -- string
IOSTANDARD => "DEFAULT", -- string
SLEW => "SLOW" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'ODDR':
'prefix': 'ODDR'
'body': """
${1:FileName}_I_Oddr_${2:0} : ODDR
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT => '0', -- bit
SRTYPE => "SYNC" -- string
IS_C_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0' -- bit
)
port map (
D1 => $3, -- in
D2 => $4, -- in
CE => $5, -- in
C => $6, -- in
S => $7, -- in
R => $8, -- in
Q => $9 -- out
);
"""
'ODDRE1':
'prefix': 'ODDRE1'
'body': """
${1:FileName}_I_Oddre1_${2:0} : ODDRE1
generic map (
IS_C_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0', -- bit
SRVAL => '0', -- bit
SIM_DEVICE => "ULTRASCALE" -- string
)
port map (
D1 => $3, -- in
D2 => $4, -- in
C => $5, -- in
SR => $6, -- in
Q => $7 -- out
);
"""
'ODELAYE2':
'prefix': 'ODELAYE2'
'body': """
${1:FileName}_I_Odlye2_${2:0} : ODELAYE2
generic map (
CINVCTRL_SEL => "FALSE", -- string
DELAY_SRC => "ODATAIN", -- string
HIGH_PERFORMANCE_MODE => "FALSE", -- string
ODELAY_TYPE => "FIXED", -- string
ODELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
REFCLK_FREQUENCY => 200.0, -- real
SIGNAL_PATTERN => "DATA", -- string
IS_C_INVERTED => '0', -- bit
IS_ODATAIN_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CLKIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
C => $7, -- in
CINVCTRL => $8, -- in
LD => $9, -- in
LDPIPEEN => $10, -- in
REGRST => $11, -- in
DATAOUT => $12, -- out
CNTVALUEOUT => $13, -- out [4:0]
CNTVALUEIN => $14 -- in [4:0]
);
"""
'ODELAYE2_FINEDELAY':
'prefix': 'ODELAYE2_FINEDELAY'
'body': """
${1:FileName}_I_Odlye2_fndly_${2:0} : ODELAYE2_FINEDELAY
generic map (
CINVCTRL_SEL => "FALSE", -- string
DELAY_SRC => "ODATAIN", -- string
FINEDELAY => "BYPASS", -- string
HIGH_PERFORMANCE_MODE => "FALSE", -- string
ODELAY_TYPE => "FIXED", -- string
ODELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
REFCLK_FREQUENCY => 200.0, -- real
SIGNAL_PATTERN => "DATA", -- string
IS_C_INVERTED => '0', -- bit
IS_ODATAIN_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CLKIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
LD => $7, -- in
LDPIPEEN => $8, -- in
OFDLY => $9, -- in [2:0]
REGRST => $10, -- in
C => $11, -- in
CINVCTRL => $12, -- in
CNTVALUEIN => $13, -- in [4:0]
CNTVALUEOUT => $14, -- out [4:0]
DATAOUT => $15 -- out
);
"""
'ODELAYE3':
'prefix': 'ODELAYE3'
'body': """
${1:FileName}_I_Odlye3_${2:0} : ODELAYE3
generic map (
CASCADE => "NONE", -- string
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
ODATAIN => $3, -- in
CASC_IN => $4, -- in
CASC_RETURN => $5, -- in
CLK => $6, -- in
CE => $7, -- in
RST => $8, -- in
INC => $9, -- in
LOAD => $10, -- in
EN_VTC => $11, -- in
CNTVALUEIN => $12, -- in [8:0]
CNTVALUEOUT => $13, -- out [8:0]
CASC_OUT => $14, -- out
DATAOUT => $15 -- out
);
"""
'ODELAYE5':
'prefix': 'ODELAYE5'
'body': """
${1:FileName}_I_Odlye5_${2:0} : ODELAYE5
generic map (
CASCADE => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CASC_IN => $4, -- in
CE => $5, -- in
INC => $6, -- in
LOAD => $7, -- in
RST => $8, -- in
CLK => $9, -- in
CNTVALUEIN => $10, -- in [4:0]
CNTVALUEOUT => $11, -- out [4:0]
DATAOUT => $12 -- out
);
"""
'OSERDES':
'prefix': 'OSERDES'
'body': """
${1:FileName}_I_Osrds_${2:0} : OSERDES
generic map (
DATA_RATE_OQ => "DDR", -- string
DATA_RATE_TQ => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_OQ => '0', -- bit
INIT_TQ => '0', -- bit
SERDES_MODE => "MASTER", -- string
SRVAL_OQ => '0', -- bit
SRVAL_TQ => '0', -- bit
TRISTATE_WIDTH => 4 -- integer
)
port map (
SHIFTIN1 => $3, -- in
SHIFTIN2 => $4, -- in
D1 => $5, -- in
D2 => $6, -- in
D3 => $7, -- in
D4 => $8, -- in
D5 => $9, -- in
D6 => $10, -- in
OCE => $11, -- in
REV => $12, -- in
SR => $13, -- in
CLK => $14, -- in
CLKDIV => $15, -- in
T1 => $16, -- in
T2 => $17, -- in
T3 => $18, -- in
T4 => $19, -- in
TCE => $20, -- in
SHIFTOUT1 => $21, -- out;
SHIFTOUT2 => $22, -- out;
OQ => $23, -- out;
TQ => $24 -- out;
);
"""
'OSERDESE2':
'prefix': 'OSERDESE2'
'body': """
${1:FileName}_I_Osrdse2_${2:0} : OSERDESE2
generic map (
SERDES_MODE => "MASTER",-- string
DATA_RATE_TQ => "DDR", -- string
TRISTATE_WIDTH => 4, -- integer
INIT_TQ => '0', -- bit
SRVAL_TQ => '0', -- bit
DATA_RATE_OQ => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_OQ => '0', -- bit
SRVAL_OQ => '0', -- bit
TBYTE_CTL => "FALSE", -- string
TBYTE_SRC => "FALSE", -- string
IS_CLKDIV_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0', -- bit
IS_D3_INVERTED => '0', -- bit
IS_D4_INVERTED => '0', -- bit
IS_D5_INVERTED => '0', -- bit
IS_D6_INVERTED => '0', -- bit
IS_D7_INVERTED => '0', -- bit
IS_D8_INVERTED => '0', -- bit
IS_T1_INVERTED => '0', -- bit
IS_T2_INVERTED => '0', -- bit
IS_T3_INVERTED => '0', -- bit
IS_T4_INVERTED => '0', -- bit
)
port map (
SHIFTOUT1 => $3, -- out
D1 => $4, -- in
D2 => $5, -- in
D3 => $6, -- in
D4 => $7, -- in
D5 => $8, -- in
D6 => $9, -- in
D7 => $10, -- in
D8 => $11, -- in
SHIFTIN1 => $12, -- in
SHIFTIN2 => $13, -- in
OCE => $14, -- in
RST => $15, -- in
CLK => $16, -- in
CLKDIV => $17, -- in
OFB => $18, -- out
OQ => $19, -- out
TBYTEOUT => $20, -- out
T1 => $21, -- in
T2 => $22, -- in
T3 => $23, -- in
T4 => $24, -- in
TBYTEIN => $25, -- in
TCE => $26, -- in
TFB => $27, -- out
TQ => $28 -- out
SHIFTOUT2 => $29, -- out
);
"""
'OSERDESE3':
'prefix': 'OSERDESE3'
'body': """
${1:FileName}_I_Osrdse3_${2:0} : OSERDESE3
generic map (
DATA_WIDTH => 8, -- 8
INIT => '0', -- std_ulogic
IS_CLKDIV_INVERTED => '0', -- std_ulogic
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
ODDR_MODE => "FASLE", -- string
OSERDES_D_BYPASS => "FASLE", -- string
OSERDES_T_BYPASS => "FASLE", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => -- real
)
port map (
D => $3, -- in [7:0]
CLK => $4, -- in
CLKDIV => $5, -- in
RST => $6, -- in
T => $7, -- in
T_OUT => $8, -- out
OQ => $9 -- out
);
"""
'OUT_FIFO':
'prefix': 'OUT_FIFO'
'body': """
${1:FileName}_I_Out_Fifo_${2:0} : OUT_FIFO
generic map (
SYNCHRONOUS_MODE => "FALSE", -- string
ARRAY_MODE => "ARRAY_MODE_8_X_4", -- string
ALMOST_EMPTY_VALUE => 1, -- integer
ALMOST_FULL_VALUE => 1, -- integer
OUTPUT_DISABLE => "FALSE" -- string
)
port map (
D0 => $3, -- in [7:0}
D1 => $4, -- in [7:0}
D2 => $5, -- in [7:0}
D3 => $6, -- in [7:0}
D4 => $7, -- in [7:0}
D5 => $8, -- in [7:0}
D6 => $9, -- in [7:0}
D7 => $10, -- in [7:0}
D8 => $11, -- in [7:0}
D9 => $12, -- in [7:0}
WRCLK => $13, -- in
WREN => $14, -- in
RESET => $15, -- in
RDCLK => $16, -- in
RDEN => $17, -- in
Q0 => $18, -- out [3:0]
Q1 => $19, -- out [3:0]
Q2 => $20, -- out [3:0]
Q3 => $21, -- out [3:0]
Q4 => $22, -- out [3:0]
Q5 => $23, -- out [7:0]
Q6 => $24, -- out [7:0]
Q7 => $25, -- out [3:0]
Q8 => $26, -- out [3:0]
Q9 => $27, -- out [3:0]
ALMOSTEMPTY => $28, -- out
ALMOSTFULL => $29, -- out
EMPTY => $30, -- out
FULL => $31 -- out
);
"""
'PLLE2_ADV':
'prefix': 'PLLE2_ADV'
'body': """
${1:FileName}_I_Plle2_Adv_${2:0} : PLLE2_ADV
generic map(
BANDWIDTH => "OPTIMIZED", -- string
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.0, -- real
CLKIN1_PERIOD => 0.0, -- real
CLKIN2_PERIOD => 0.0, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.5, -- real
CLKOUT0_PHASE => 0.0, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.5, -- real
CLKOUT1_PHASE => 0.0, -- real
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.5, -- real
CLKOUT2_PHASE => 0.0, -- real
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.5, -- real
CLKOUT3_PHASE => 0.0, -- real
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.5, -- real
CLKOUT4_PHASE => 0.0, -- real
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.5, -- real
CLKOUT5_PHASE => 0.0, -- real
COMPENSATION => "ZHOLD", -- string
DIVCLK_DIVIDE => 1, -- integer
REF_JITTER1 => 0.0, -- real
REF_JITTER2 => 0.0, -- real
STARTUP_WAIT => "FALSE", -- string
IS_CLKINSEL_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
CLKIN1 => $3, -- in
CLKINSEL => $4, -- in
CLKFBIN => $5, -- in
CLKFBOUT => $6, -- out
CLKOUT0 => $7, -- out
CLKOUT1 => $8, -- out
CLKOUT2 => $9, -- out
CLKOUT3 => $10, -- out
CLKOUT4 => $11, -- out
CLKOUT5 => $12, -- out
RST => $13, -- in
PWRDWN => $14, -- in
LOCKED => $15, -- out
DI => $16, -- in [15:0]
DADDR => $17, -- in [6:0]
DEN => $18, -- in
DWE => $19, -- in
DCLK => $20, -- in
DO => $21, -- out [15:0]
DRDY => $22 -- out
CLKIN2 => $23, -- in
);
"""
'PLLE3_ADV':
'prefix': 'PLLE3_ADV'
'body': """
${1:FileName}_I_Plle3_Adv_${2:0} : PLLE3_ADV
generic map (
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKIN_PERIOD => 0.000, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUTPHY_MODE => "VCO_2X", -- string
COMPENSATION => "AUTO", -- string
DIVCLK_DIVIDE => 1, -- integer
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
IS_CLKIN_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REF_JITTER => 0.010, -- real
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN => $3, -- in
CLKFBIN => $4, -- in
RST => $5, -- in
PWRDWN => $6, -- in
CLKOUTPHYEN => $7, -- in
CLKFBOUT => $8, -- out
CLKOUT0 => $9, -- out
CLKOUT0B => $10, -- out
CLKOUT1 => $11, -- out
CLKOUT1B => $12, -- out
CLKOUTPHY => $13, -- out
DCLK => $14, -- in
DI => $15, -- in [15:0]
DADDR => $16, -- in [6:0]
DEN => $17, -- in
DWE => $18, -- in
DO => $19, -- out [15:0]
DRDY => $20, -- out
LOCKED => $21 -- out
);
"""
'PLLE4_ADV':
'prefix': 'PLLE4_ADV'
'body': """
${1:FileName}_I_Plle4_Adv_${2:0} :PLLE4_ADV
generic map (
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKIN_PERIOD => 0.000, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUTPHY_MODE => "VCO_2X", -- string
COMPENSATION => "AUTO", -- string
DIVCLK_DIVIDE => 1, -- integer
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
IS_CLKIN_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REF_JITTER => 0.010, -- real
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN => $3, -- in
CLKFBIN => $4, -- in
RST => $5, -- in
PWRDWN => $6, -- in
CLKOUTPHYEN => $7, -- in
CLKFBOUT => $8, -- out
CLKOUT0 => $9, -- out
CLKOUT0B => $10, -- out
CLKOUT1 => $11, -- out
CLKOUT1B => $12, -- out
CLKOUTPHY => $13, -- out
DCLK => $14, -- in
DI => $15, -- in [15:0]
DADDR => $16, -- in [6:0]
DEN => $17, -- in
DWE => $18, -- in
DO => $19, -- out [15:0]
DRDY => $20, -- out
LOCKED => $21 -- out
);
"""
'RAM256X1D':
'prefix': 'RAM256X1D'
'body': """
${1:FileName}_I_Ram256x1d_${2:0} : RAM256X1D
generic map (
INIT => X"0000000000000000000000000000000000000000000000000000000000000000", -- [255:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A => $4, -- in [7:0]
WE => $5, -- in
DPRA => $6, -- in [7:0]
WCLK => $7, -- in
DPO => $8, -- out
SPO => $9, -- out
);
"""
'RAM32M':
'prefix': 'RAM32M'
'body': """
${1:FileName}_I_Ram32m_${2:0} : RAM32M
generic map (
INIT_A => X"0000000000000000", -- [63:0]
INIT_B => X"0000000000000000", -- [63:0]
INIT_C => X"0000000000000000", -- [63:0]
INIT_D => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
DIA => $3, -- in [1:0]
DIB => $4, -- in [1:0]
DIC => $5, -- in [1:0]
DID => $6, -- in [1:0]
ADDRA => $7, -- in [4:0]
ADDRB => $8, -- in [4:0]
ADDRC => $9, -- in [4:0]
ADDRD => $10, -- in [4:0]
WE => $11, -- in
WCLK => $12, -- in
DOA => $13, -- out [1:0]
DOB => $14, -- out [1:0]
DOC => $15, -- out [1:0]
DOD => $16 -- out [1:0]
);
"""
'RAM32X1D':
'prefix': 'RAM32X1D'
'body': """
${1:FileName}_I_Ram32x1d_${2:0} : RAM32X1D
generic map (
INIT => X"00000000", -- [31:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A0 => $4, -- in
A1 => $5, -- in
A2 => $6, -- in
A3 => $7, -- in
A4 => $8, -- in
DPRA0 => $9, -- in
DPRA1 => $10, -- in
DPRA2 => $11, -- in
DPRA3 => $12, -- in
DPRA4 => $13, -- in
WE => $14, -- in
WCLK => $15, -- in
DPO => $16, -- out
SPO => $17 -- out
);
"""
'RAM64M':
'prefix': 'RAM64M'
'body': """
${1:FileName}_I_Ram64m_${2:0} : RAM64M
generic map (
INIT_A => X"0000000000000000", -- [63:0]
INIT_B => X"0000000000000000", -- [63:0]
INIT_C => X"0000000000000000", -- [63:0]
INIT_D => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
DIA => $3, -- in
DIB => $4, -- in
DIC => $5, -- in
DID => $6, -- in
ADDRA => $7, -- in [5:0]
ADDRB => $8, -- in [5:0]
ADDRC => $9, -- in [5:0]
ADDRD => $10, -- in [5:0]
WE => $11, -- in
WCLK => $12, -- in
DOA => $13, -- out
DOB => $14, -- out
DOC => $15, -- out
DOD => $16 -- out
);
"""
'RAM64X1D':
'prefix': 'RAM64X1D'
'body': """
${1:FileName}_I_Ram64x1d_${2:0} : RAM64X1D
generic map (
INIT => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A0 => $4, -- in
A1 => $5, -- in
A2 => $6, -- in
A3 => $7, -- in
A4 => $8, -- in
A5 => $9, -- in
DPRA0 => $10, -- in
DPRA1 => $11, -- in
DPRA2 => $12, -- in
DPRA3 => $13, -- in
DPRA4 => $14, -- in
DPRA5 => $15, -- in
WE => $16, -- in
WCLK => $17, -- in
DPO => $18, -- out
SPO => $19 -- out
);
"""
'RAMB36E1':
'prefix': 'RAMB36E1'
'body': """
${1:FileName}_I_Ramb36e1_${2:0} : RAMB36E1
generic map (
INIT_FILE => "NONE", -- string
RAM_MODE => "TDP", -- string
WRITE_MODE_A => "WRITE_FIRST", -- string
WRITE_MODE_B => "WRITE_FIRST", -- string
READ_WIDTH_A => 0, -- integer
READ_WIDTH_B => 0, -- integer
WRITE_WIDTH_A => 0, -- integer
WRITE_WIDTH_B => 0, -- integer
RAM_EXTENSION_A => "NONE", -- string
RAM_EXTENSION_B => "NONE", -- string
DOA_REG => 0, -- integer
DOB_REG => 0, -- integer
INIT_A => X"000000000", -- bit_vector
INIT_B => X"000000000", -- bit_vector
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- bit_vector
SRVAL_B => X"000000000", -- bit_vector
EN_ECC_READ => FALSE, -- boolean
EN_ECC_WRITE => FALSE, -- boolean
RDADDR_COLLISION_HWCONFIG => "DELAYED_WRITE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
SIM_DEVICE => "VIRTEX6", -- string
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map (
CASCADEINA => $3, -- in
DIPADIP => $4, -- in [3:0]
DIADI => $5, -- in [31:0]
DOPADOP => $6, -- out [3:0]
DOADO => $7, -- out [31:0]
CASCADEOUTA => $8, -- out
ADDRARDADDR => $9, -- in [15:0]
ENARDEN => $10, -- in
REGCEAREGCE => $11, -- in
WEA => $12, -- in [3:0]
CLKARDCLK => $13, -- in
RSTREGARSTREG => $14, -- in
RSTRAMARSTRAM => $15, -- in
CASCADEINB => $16, -- in
DIPBDIP => $17, -- in [3:0]
DIBDI => $18, -- in [31:0]
DOPBDOP => $19, -- out [3:0]
DOBDO => $20, -- out [31:0]
CASCADEOUTB => $21, -- out
ADDRBWRADDR => $22, -- in [15:0]
ENBWREN => $23, -- in
REGCEB => $24, -- in
WEBWE => $25, -- in [7:0]
CLKBWRCLK => $26, -- in
RSTREGB => $27, -- in
RSTRAMB => $28, -- in
INJECTDBITERR => $29, -- in
INJECTSBITERR => $30, -- in
DBITERR => $31, -- out
ECCPARITY => $32, -- out [7:0]
RDADDRECC => $33, -- out [8:0]
SBITERR => $34 -- out
);
"""
'RAMB36E2':
'prefix': 'RAMB36E2'
'body': """
${1:FileName}_I_Ramb36e2_${2:0} : RAMB36E2
generic map [
INIT_FILE => "NONE", -- string
CLOCK_DOMAINS => "INDEPENDENT", -- string
WRITE_MODE_A => "NO_CHANGE", -- string
WRITE_MODE_B => "NO_CHANGE", -- string
READ_WIDTH_A => 0, -- integer
READ_WIDTH_B => 0, -- integer
WRITE_WIDTH_A => 0, -- integer
WRITE_WIDTH_B => 0, -- integer
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
ENADDRENA => "FALSE", -- string
ENADDRENB => "FALSE", -- string
RDADDRCHANGEA => "FALSE", -- string
RDADDRCHANGEB => "FALSE", -- string
DOA_REG => 1, -- integer
DOB_REG => 1, -- integer
INIT_A => X"000000000", -- [35:0]
INIT_B => X"000000000", -- [35:0]
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- [35:0]
SRVAL_B => X"000000000", -- [35:0]
EN_ECC_PIPE => "FALSE", -- string
EN_ECC_READ => "FALSE", -- string
EN_ECC_WRITE => "FALSE", -- string
SLEEP_ASYNC => "FALSE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map [
ADDRARDADDR => $3, -- in [14:0],
ADDRBWRADDR => $4, -- in [14:0],
ADDRENA => $5, -- in
ADDRENB => $6, -- in
CASDIMUXA => $7, -- in
CASDIMUXB => $8, -- in
CASDINA => $9, -- in [31:0],
CASDINB => $10, -- in [31:0],
CASDINPA => $11, -- in [3:0],
CASDINPB => $12, -- in [3:0],
CASDOMUXA => $13, -- in
CASDOMUXB => $14, -- in
CASDOMUXEN_A => $15, -- in
CASDOMUXEN_B => $16, -- in
CASINDBITERR => $17, -- in
CASINSBITERR => $18, -- in
CASOREGIMUXA => $19, -- in
CASOREGIMUXB => $20, -- in
CASOREGIMUXEN_A => $21, -- in
CASOREGIMUXEN_B => $22, -- in
CLKARDCLK => $23, -- in
CLKBWRCLK => $24, -- in
DINADIN => $25, -- in [31:0],
DINBDIN => $26, -- in [31:0],
DINPADINP => $27, -- in [3:0],
DINPBDINP => $28, -- in [3:0],
ECCPIPECE => $29, -- in
ENARDEN => $30, -- in
ENBWREN => $31, -- in
INJECTDBITERR => $32, -- in
INJECTSBITERR => $33, -- in
REGCEAREGCE => $34, -- in
REGCEB => $35, -- in
RSTRAMARSTRAM => $36, -- in
RSTRAMB => $37, -- in
RSTREGARSTREG => $38, -- in
RSTREGB => $39, -- in
SLEEP => $40, -- in
WEA => $41, -- in [3:0],
WEBWE => $42, -- in [7:0]
CASDOUTA => $43, -- out [31:0],
CASDOUTB => $44, -- out [31:0],
CASDOUTPA => $45, -- out [3:0],
CASDOUTPB => $46, -- out [3:0],
CASOUTDBITERR => $47, -- out
CASOUTSBITERR => $48, -- out
DBITERR => $49, -- out
DOUTADOUT => $50, -- out [31:0],
DOUTBDOUT => $51, -- out [31:0],
DOUTPADOUTP => $52, -- out [3:0],
DOUTPBDOUTP => $53, -- out [3:0],
ECCPARITY => $54, -- out [7:0],
RDADDRECC => $55, -- out [8:0],
SBITERR => $56 -- out
);
"""
'RAMB36E5':
'prefix': 'RAMB36E5'
'body': """
${1:FileName}_I_Ramb36e5_${2:0} : RAMB36E5
generic map (
INIT_FILE => "NONE", -- string
CLOCK_DOMAINS => "INDEPENDENT", -- string
WRITE_MODE_A => "NO_CHANGE", -- string
WRITE_MODE_B => "NO_CHANGE", -- string
READ_WIDTH_A => 72, -- integer
READ_WIDTH_B => 36, -- integer
WRITE_WIDTH_A => 36, -- integer
WRITE_WIDTH_B => 72 -- integer
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
DOA_REG => 1, -- integer
DOB_REG => 1, -- integer
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- [35:0]
SRVAL_B => X"000000000", -- [35:0]
EN_ECC_PIPE => "FALSE", -- string
EN_ECC_READ => "FALSE", -- string
EN_ECC_WRITE => "FALSE", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
PR_SAVE_DATA => "FALSE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
SLEEP_ASYNC => "FALSE", -- string
IS_ARST_A_INVERTED => '0', -- bit
IS_ARST_B_INVERTED => '0', -- bit
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map (
ADDRARDADDR => $3, -- in [11:0]
ADDRBWRADDR => $4, -- in [11:0]
ARST_A => $5, -- in
ARST_B => $6, -- in
CASDINA => $7, -- in [31:0]
CASDINB => $8, -- in [31:0]
CASDINPA => $9, -- in [3:0]
CASDINPB => $10, -- in [3:0]
CASDOMUXA => $11, -- in
CASDOMUXB => $12, -- in
CASDOMUXEN_A => $13, -- in
CASDOMUXEN_B => $14, -- in
CASINDBITERR => $15, -- in
CASINSBITERR => $16, -- in
CASOREGIMUXA => $17, -- in
CASOREGIMUXB => $18, -- in
CASOREGIMUXEN_A => $19, -- in
CASOREGIMUXEN_B => $20, -- in
CLKARDCLK => $21, -- in
CLKBWRCLK => $22, -- in
DINADIN => $23, -- in [31:0]
DINBDIN => $24, -- in [31:0]
DINPADINP => $25, -- in [3:0]
DINPBDINP => $26, -- in [3:0]
ECCPIPECE => $27, -- in
ENARDEN => $28, -- in
ENBWREN => $29, -- in
INJECTDBITERR => $30, -- in
INJECTSBITERR => $31, -- in
REGCEAREGCE => $32, -- in
REGCEB => $33, -- in
RSTRAMARSTRAM => $34, -- in
RSTRAMB => $35, -- in
RSTREGARSTREG => $36, -- in
RSTREGB => $37, -- in
SLEEP => $38, -- in
WEA => $39, -- in [3:0]
WEBWE => $40, -- in [8:0]
CASDOUTA => $41, -- out [31:0]
CASDOUTB => $42, -- out [31:0]
CASDOUTPA => $43, -- out [3:0]
CASDOUTPB => $44, -- out [3:0]
CASOUTDBITERR => $45, -- out
CASOUTSBITERR => $46, -- out
DBITERR => $47, -- out
DOUTADOUT => $48, -- out [31:0]
DOUTBDOUT => $49, -- out [31:0]
DOUTPADOUTP => $50, -- out [3:0]
DOUTPBDOUTP => $51, -- out [3:0]
SBITERR => $52 -- out
),
"""
'RAMD32':
'prefix': 'RAMD32'
'body': """
${1:FileName}_I_Ramd32_${2:0} : RAMD32
generic map (
INIT => X"00000000", -- [31:0]
IS_CLK_INVERTED => '0' -- bit
)
port map (
I => $3, -- in
WE => $4, -- in
CLK => $5, -- in
RADR0 => $6, -- in
RADR1 => $7, -- in
RADR2 => $8, -- in
RADR3 => $9, -- in
RADR4 => $10, -- in
WADR0 => $11, -- in
WADR1 => $12, -- in
WADR2 => $13, -- in
WADR3 => $14, -- in
WADR4 => $15, -- in
O => $16 -- out
);
"""
'RIU_OR':
'prefix': 'RIU_OR'
'body': """
${1:FileName}_I_Riu_Or_${2:0} : RIU_OR
generic map (
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
RIU_RD_DATA_LOW => $3, -- in [15:0]
RIU_RD_DATA_UPP => $4, -- in [15:0]
RIU_RD_VALID_LOW => $5, -- in
RIU_RD_VALID_UPP => $6, -- in
RIU_RD_DATA => $7, -- out [15:0]
RIU_RD_VALID => $8 -- out
);
"""
'RXTX_BITSLICE':
'prefix': 'RXTX_BITSLICE'
'body': """
${1:FileName}_I_Rxtx_btslce_${2:0} : RXTX_BITSLICE
generic map (
RX_DATA_TYPE => "NONE", -- string
RX_DATA_WIDTH => 8, -- integer
RX_DELAY_FORMAT => "TIME", -- string
RX_DELAY_TYPE => "FIXED", -- string
RX_DELAY_VALUE => 0, -- integer
TX_DATA_WIDTH => 8, -- integer
TX_DELAY_FORMAT => "TIME", -- string
TX_DELAY_TYPE => "FIXED", -- string
TX_DELAY_VALUE => 0, -- integer
RX_REFCLK_FREQUENCY => 300.0, -- real
TX_REFCLK_FREQUENCY => 300.0, -- real
RX_UPDATE_MODE => "ASYNC", -- string
TX_UPDATE_MODE => "ASYNC", -- string
FIFO_SYNC_MODE => "FALSE", -- string
INIT => '1', -- bit
LOOPBACK => "FALSE", -- string
NATIVE_ODELAY_BYPASS => "FALSE", -- string
TBYTE_CTL => "TBYTE_IN", -- string
TX_OUTPUT_PHASE_90 => "FALSE", -- string
ENABLE_PRE_EMPHASIS => "FALSE", -- string
IS_RX_CLK_INVERTED => '0', -- bit
IS_RX_RST_DLY_INVERTED => '0', -- bit
IS_RX_RST_INVERTED => '0', -- bit
IS_TX_CLK_INVERTED => '0', -- bit
IS_TX_RST_DLY_INVERTED => '0', -- bit
IS_TX_RST_INVERTED => '0', -- bit
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
DATAIN => $3, -- in
Q => $4, -- out [7:0]
RX_RST => $5, -- in
RX_CLK => $6, -- in
RX_CE => $7, -- in
RX_RST_DLY => $8, -- in
RX_INC => $9, -- in
RX_LOAD => $10, -- in
RX_EN_VTC => $11, -- in
RX_CNTVALUEIN => $12, -- in [8:0]
RX_CNTVALUEOUT => $13, -- out [8:0]
FIFO_RD_CLK => $14, -- in
FIFO_RD_EN => $15, -- in
FIFO_EMPTY => $16, -- out
FIFO_WRCLK_OUT => $17, -- out
RX_BIT_CTRL_IN => $18, -- in [39:0]
TX_BIT_CTRL_IN => $19, -- in [39:0]
RX_BIT_CTRL_OUT => $20, -- out [39:0]
TX_BIT_CTRL_OUT => $21, -- out [39:0]
D => $22, -- in [7:0]
T => $23, -- in
TBYTE_IN => $24, -- in
O => $25, -- out
T_OUT => $26, -- out
TX_RST => $27, -- in
TX_CLK => $28, -- in
TX_CE => $29, -- in
TX_RST_DLY => $30, -- in
TX_INC => $31, -- in
TX_LOAD => $32, -- in
TX_EN_VTC => $33, -- in
TX_CNTVALUEIN => $34, -- in [8:0]
TX_CNTVALUEOUT => $35 -- out [8:0]
);
"""
'RX_BITSLICE':
'prefix': 'RX_BITSLICE'
'body': """
${1:FileName}_I_Rx_Btslce_${2:0} : RX_BITSLICE
generic map(
CASCADE => "FALSE", -- string
DATA_TYPE => "NONE", -- string
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
DELAY_VALUE_EXT => 0, -- integer
FIFO_SYNC_MODE => "FALSE", -- string
IS_CLK_EXT_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_RST_DLY_EXT_INVERTED => '0', -- bit
IS_RST_DLY_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
UPDATE_MODE_EXT => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
DATAIN => $3, -- in
FIFO_RD_CLK => $4, -- in
FIFO_RD_EN => $5, -- in
RX_BIT_CTRL_IN => $6, -- in [39:0]
TX_BIT_CTRL_IN => $7, -- in [39:0]
RX_BIT_CTRL_OUT => $8, -- out [39:0]
TX_BIT_CTRL_OUT => $9, -- out [39:0]
RST => $10, -- in
CLK => $11, -- in
CE => $12, -- in
RST_DLY => $13, -- in
INC => $14, -- in
LOAD => $15, -- in
EN_VTC => $16, -- in
CNTVALUEIN => $17, -- in [8:0]
CNTVALUEOUT => $18, -- out [8:0]
CLK_EXT => $19, -- in
CE_EXT => $20, -- in
RST_DLY_EXT => $21, -- in
INC_EXT => $22, -- in
LOAD_EXT => $23, -- in
EN_VTC_EXT => $24, -- in
CNTVALUEIN_EXT => $25, -- in [8:0]
CNTVALUEOUT_EXT => $26, -- out [8:0]
BIT_CTRL_OUT_EXT => $27, -- out [28:0]
FIFO_EMPTY => $28, -- out
FIFO_WRCLK_OUT => $29, -- out
Q => $30 -- out [7:0]
);
"""
'SRLC32E':
'prefix': 'SRLC32E'
'body': """
${1:FileName}_I_Srlc32e_${2:0} : SRLC32E
generic map (
INIT => X"00000000",
IS_CLK_INVERTED => '0'
)
port map (
D => $3, -- in
A => $4, -- in [4:0]
CE => $5, -- in
CLK => $6, -- in
Q => $7, -- out
Q31 => $8 -- out
);
"""
'STARTUPE2':
'prefix': 'STARTUPE2'
'body': """
${1:FileName}_I_Startupe2_${2:0} : STARTUPE2
generic map (
PROG_USR => "FALSE", -- string
SIM_CCLK_FREQ => 0.0 -- real
)
port map (
USRDONEO => $3, -- in
USRDONETS => $4, -- in
KEYCLEARB => $5, -- in
PACK => $6, -- in
USRCCLKO => $7, -- in
USRCCLKTS => $8, -- in
CLK => $9, -- in
GSR => $10, -- in
GTS => $11, -- in
CFGCLK => $12, -- out
CFGMCLK => $13, -- out
EOS => $14, -- out
PREQ => $15 -- out
);
"""
'STARTUPE3':
'prefix': 'STARTUPE3'
'body': """
${1:FileName}_I_Startupe3_${2:0} : STARTUPE3
generic map : (
PROG_USR => "FALSE", -- string
SIM_CCLK_FREQ => 0.0 -- real
)
port map (
USRDONEO => $3, -- in
USRDONETS => $4, -- in
KEYCLEARB => $5, -- in
PACK => $6, -- in
USRCCLKO => $7, -- in
USRCCLKTS => $8, -- in
GSR => $9, -- in
GTS => $10, -- in
DTS => $11, -- in [3:0]
FCSBO => $12, -- in
FCSBTS => $13, -- in
DO => $14, -- in [3:0]
DI => $15, -- out [3:0]
CFGCLK => $16, -- out
CFGMCLK => $17, -- out
EOS => $18, -- out
PREQ => $19 -- out
);
"""
'TX_BITSLICE':
'prefix': 'TX_BITSLICE'
'body': """
${1:FileName}_I_Tx_Btslce_${2:0} : TX_BITSLICE
generic map (
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
INIT => '1', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_RST_DLY_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
NATIVE_ODELAY_BYPASS => "FALSE", -- string
OUTPUT_PHASE_90 => "FALSE", -- string
ENABLE_PRE_EMPHASIS => "OFF", -- string
REFCLK_FREQUENCY => 300.0, -- real
TBYTE_CTL => "TBYTE_IN", -- string
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE : string => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
D => $3, -- in [7:0]
T => $4, -- in
TBYTE_IN => $5, -- in
RX_BIT_CTRL_IN => $6, -- in [39:0]
TX_BIT_CTRL_IN => $7, -- in [39:0]
RX_BIT_CTRL_OUT => $8, -- out [39:0]
TX_BIT_CTRL_OUT => $9, -- out [39:0]
RST => $10, -- in
CLK => $11, -- in
CE => $12, -- in
RST_DLY => $13, -- in
INC => $14, -- in
LOAD => $15, -- in
EN_VTC => $16, -- in
CNTVALUEIN => $17, -- in [8:0]
CNTVALUEOUT => $18, -- out [8:0]
O => $19, -- out
T_OUT => $20 -- out
);
"""
'TX_BITSLICE_TRI':
'prefix': 'TX_BITSLICE_TRI'
'body': """
${1:FileName}_I_Tx_Btslce_Tri_${2:0} : TX_BITSLICE_TRI
generic map (
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
INIT => '1', -- bit:
IS_CLK_INVERTED => '0', -- bit:
IS_RST_DLY_INVERTED => '0', -- bit:
IS_RST_INVERTED => '0', -- bit:
NATIVE_ODELAY_BYPASS => "FALSE", -- string
OUTPUT_PHASE_90 => "FALSE", -- string
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC" -- string
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VESION => 2.0 -- real
)
port map (
BIT_CTRL_IN => $3, -- in [39:0]
BIT_CTRL_OUT => $4, -- out [39:0]
RST => $5, -- in
CLK => $6, -- in
CE => $7, -- in
RST_DLY => $8, -- in
INC => $9, -- in
LOAD => $10, -- in
EN_VTC => $11, -- in
CNTVALUEIN => $12, -- in [8:0]
CNTVALUEOUT => $13, -- out [8:0]
TRI_OUT => $14 -- out
);
"""
'URAM288':
'prefix': 'URAM288'
'body': """
${1:FileName}_I_Uram288_${2:0} : URAM288
generic map (
AUTO_SLEEP_LATENCY => 8, -- integer
AVG_CONS_INACTIVE_CYCLES => 10, -- integer
BWE_MODE_A => "PARITY_INTERLEAVED", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
EN_AUTO_SLEEP_MODE => "FALSE", -- string
EN_ECC_RD_A => "FALSE", -- string
EN_ECC_RD_B => "FALSE", -- string
EN_ECC_WR_A => "FALSE", -- string
EN_ECC_WR_B => "FALSE", -- string
IREG_PRE_A => "FALSE", -- string
IREG_PRE_B => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_EN_A_INVERTED => '0', -- bit
IS_EN_B_INVERTED => '0', -- bit
IS_RDB_WR_A_INVERTED => '0', -- bit
IS_RDB_WR_B_INVERTED => '0', -- bit
IS_RST_A_INVERTED => '0', -- bit
IS_RST_B_INVERTED => '0', -- bit
MATRIX_ID => "NONE", -- string
NUM_UNIQUE_SELF_ADDR_A => 1, -- integer
NUM_UNIQUE_SELF_ADDR_B => 1, -- integer
NUM_URAM_IN_MATRIX => 1, -- integer
OREG_A => "FALSE", -- string
OREG_B => "FALSE", -- string
OREG_ECC_A => "FALSE", -- string
OREG_ECC_B => "FALSE", -- string
REG_CAS_A => "FALSE", -- string
REG_CAS_B => "FALSE", -- string
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
SELF_ADDR_A => "000" & X"00", -- [10 downto 0)
SELF_ADDR_B => "000" & X"00", -- [10 downto 0)
SELF_MASK_A => "111" & X"FF", -- [10 downto 0)
SELF_MASK_B => "111" & X"FF", -- [10 downto 0)
USE_EXT_CE_A => "FALSE", -- string
USE_EXT_CE_B => "FALSE" -- string
)
port map (
DIN_A => $3, -- in [71:0]
ADDR_A => $4, -- in [22:0]
EN_A => $5, -- in
RDB_WR_A => $6, -- in
BWE_A => $7, -- in [8:0]
INJECT_SBITERR_A => $8, -- in
INJECT_DBITERR_A => $9, -- in
OREG_CE_A => $10, -- in
OREG_ECC_CE_A => $11, -- in
RST_A => $12, -- in
DOUT_A => $13, -- out [71:0]
SBITERR_A => $14, -- out
DBITERR_A => $15, -- out
RDACCESS_A => $16, -- out
SLEEP => $17, -- in
CLK => $18, -- in
DIN_B => $19, -- in [71:0]
ADDR_B => $20, -- in [22:0]
EN_B => $21, -- in
RDB_WR_B => $22, -- in
BWE_B => $23, -- in [8:0]
INJECT_SBITERR_B => $24, -- in
INJECT_DBITERR_B => $25, -- in
OREG_CE_B => $26, -- in
OREG_ECC_CE_B => $27, -- in
RST_B => $28, -- in
DOUT_B => $29, -- out [71:0]
SBITERR_B => $30, -- out
DBITERR_B => $31, -- out
RDACCESS_B => $32, -- out
CAS_IN_ADDR_A => $33, -- in [22:0]
CAS_IN_ADDR_B => $34, -- in [22:0]
CAS_IN_BWE_A => $35, -- in [8:0]
CAS_IN_BWE_B => $36, -- in [8:0]
CAS_IN_DBITERR_A => $37, -- in
CAS_IN_DBITERR_B => $38, -- in
CAS_IN_DIN_A => $39, -- in [71:0]
CAS_IN_DIN_B => $40, -- in [71:0]
CAS_IN_DOUT_A => $41, -- in [71:0]
CAS_IN_DOUT_B => $42, -- in [71:0]
CAS_IN_EN_A => $43, -- in
CAS_IN_EN_B => $44, -- in
CAS_IN_RDACCESS_A => $45, -- in
CAS_IN_RDACCESS_B => $46, -- in
CAS_IN_RDB_WR_A => $47, -- in
CAS_IN_RDB_WR_B => $48, -- in
CAS_IN_SBITERR_A => $49, -- in
CAS_IN_SBITERR_B => $50, -- in
CAS_OUT_ADDR_A => $51, -- out [22:0]
CAS_OUT_ADDR_B => $52, -- out [22:0]
CAS_OUT_BWE_A => $53, -- out [8:0]
CAS_OUT_BWE_B => $54, -- out [8:0]
CAS_OUT_DBITERR_A => $55, -- out
CAS_OUT_DBITERR_B => $56, -- out
CAS_OUT_DIN_A => $57, -- out [71:0]
CAS_OUT_DIN_B => $58, -- out [71:0]
CAS_OUT_DOUT_A => $59, -- out [71:0]
CAS_OUT_DOUT_B => $60, -- out [71:0]
CAS_OUT_EN_A => $61, -- out
CAS_OUT_EN_B => $62, -- out
CAS_OUT_RDACCESS_A => $63, -- out
CAS_OUT_RDACCESS_B => $64, -- out
CAS_OUT_RDB_WR_A => $65, -- out
CAS_OUT_RDB_WR_B => $66, -- out
CAS_OUT_SBITERR_A => $67, -- out
CAS_OUT_SBITERR_B => $68 -- out
);
"""
'URAM288E5':
'prefix': 'URAM288E5'
'body': """
${1:FileName}_I_Uram288e5_${2:0} : URAM288E5
generic map (
INIT_FILE => "NONE", -- string
BWE_MODE_A => "PARITY_INTERLEAVED", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
READ_WIDTH_A => 72, -- integer
READ_WIDTH_B => 72, -- integer
WRITE_WIDTH_A => 72, -- integer
WRITE_WIDTH_B => 72, -- integer
IREG_PRE_A => "FALSE", -- string
IREG_PRE_B => "FALSE", -- string
OREG_A => "FALSE", -- string
OREG_B => "FALSE", -- string
OREG_ECC_A => "FALSE", -- string
OREG_ECC_B => "FALSE", -- string
REG_CAS_A => "FALSE", -- string
REG_CAS_B => "FALSE", -- string
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
SELF_ADDR_A => "000" & X"00", -- [10:0]
SELF_ADDR_B => "000" & X"00", -- [10:0]
SELF_MASK_A => "111" & X"FF", -- [10:0]
SELF_MASK_B => "111" & X"FF", -- [10:0]
USE_EXT_CE_A => "FALSE", -- string
USE_EXT_CE_B => "FALSE", -- string
CASCADE_ORDER_CTRL_A => "NONE", -- string
CASCADE_ORDER_CTRL_B => "NONE", -- string
CASCADE_ORDER_DATA_A => "NONE", -- string
CASCADE_ORDER_DATA_B => "NONE", -- string
AUTO_SLEEP_LATENCY => 8, -- integer
EN_AUTO_SLEEP_MODE => "FALSE", -- string
AVG_CONS_INACTIVE_CYCLES => 10, -- integer
EN_ECC_RD_A => "FALSE", -- string
EN_ECC_RD_B => "FALSE", -- string
EN_ECC_WR_A => "FALSE", -- string
EN_ECC_WR_B => "FALSE", -- string
MATRIX_ID => "NONE", -- string
NUM_UNIQUE_SELF_ADDR_A => 1, -- integer
NUM_UNIQUE_SELF_ADDR_B => 1, -- integer
NUM_URAM_IN_MATRIX => 1, -- integer
PR_SAVE_DATA => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_EN_A_INVERTED => '0', -- bit
IS_EN_B_INVERTED => '0', -- bit
IS_RDB_WR_A_INVERTED => '0', -- bit
IS_RDB_WR_B_INVERTED => '0', -- bit
IS_RST_A_INVERTED => '0', -- bit
IS_RST_B_INVERTED => '0' -- bit
)
port map (
DIN_A => $3, -- in [71:0]
ADDR_A => $4, -- in [25:0]
EN_A => $5, -- in
RDB_WR_A => $6, -- in
BWE_A => $7, -- in [8:0]
INJECT_SBITERR_A => $8, -- in
INJECT_DBITERR_A => $9, -- in
OREG_CE_A => $10, -- in
OREG_ECC_CE_A => $11, -- in
RST_A => $12, -- in
SLEEP => $13, -- in
CLK => $14, -- in
DIN_B => $15, -- in [71:0]
ADDR_B => $16, -- in [25:0]
EN_B => $17, -- in
RDB_WR_B => $18, -- in
BWE_B => $19, -- in [8:0]
INJECT_SBITERR_B => $20, -- in
INJECT_DBITERR_B => $21, -- in
OREG_CE_B => $22, -- in
OREG_ECC_CE_B => $23, -- in
RST_B => $24, -- in
DOUT_A => $25, -- out [71:0]
SBITERR_A => $26, -- out
DBITERR_A => $27, -- out
RDACCESS_A => $28, -- out
DOUT_B => $29, -- out [71:0]
SBITERR_B => $30, -- out
DBITERR_B => $31, -- out
RDACCESS_B => $32, -- out
CAS_IN_ADDR_A => $33, -- in [25:0]
CAS_IN_ADDR_B => $34, -- in [25:0]
CAS_IN_BWE_A => $35, -- in [8:0]
CAS_IN_BWE_B => $36, -- in [8:0]
CAS_IN_DBITERR_A => $37, -- in
CAS_IN_DBITERR_B => $38, -- in
CAS_IN_DIN_A => $39, -- in [71:0]
CAS_IN_DIN_B => $40, -- in [71:0]
CAS_IN_DOUT_A => $41, -- in [71:0]
CAS_IN_DOUT_B => $42, -- in [71:0]
CAS_IN_EN_A => $43, -- in
CAS_IN_EN_B => $44, -- in
CAS_IN_RDACCESS_A => $45, -- in
CAS_IN_RDACCESS_B => $46, -- in
CAS_IN_RDB_WR_A => $47, -- in
CAS_IN_RDB_WR_B => $48, -- in
CAS_IN_SBITERR_A => $49, -- in
CAS_IN_SBITERR_B => $50, -- in
CAS_OUT_ADDR_A => $51, -- out [25:0]
CAS_OUT_ADDR_B => $52, -- out [25:0]
CAS_OUT_BWE_A => $53, -- out [8:0]
CAS_OUT_BWE_B => $54, -- out [8:0]
CAS_OUT_DBITERR_A => $55, -- out
CAS_OUT_DBITERR_B => $56, -- out
CAS_OUT_DIN_A => $57, -- out [71:0]
CAS_OUT_DIN_B => $58, -- out [71:0]
CAS_OUT_DOUT_A => $59, -- out [71:0]
CAS_OUT_DOUT_B => $60, -- out [71:0]
CAS_OUT_EN_A => $61, -- out
CAS_OUT_EN_B => $62, -- out
CAS_OUT_RDACCESS_A => $63, -- out
CAS_OUT_RDACCESS_B => $64, -- out
CAS_OUT_RDB_WR_A => $65, -- out
CAS_OUT_RDB_WR_B => $66, -- out
CAS_OUT_SBITERR_A => $67, -- out
CAS_OUT_SBITERR_B => $68 -- out
);
"""
'USR_ACCESSE2':
'prefix': 'USR_ACCESSE2'
'body': """
${1:FileName}_I_Usr_Access_${2:0} : USR_ACCESSE2
port map (
CFGCLK => $3, -- out
DATA => $4, -- out [31:0]
DATAVALID => $5 -- out
);
"""
'XORCY':
'prefix': 'XORCY'
'body': """
$1 : XORCY
port map (
CI => $3, -- in
LI => $4, -- in
O => $5 -- out
);
"""
'XPLL':
'prefix': 'XPLL'
'body': """
${1:FileName}_I_Xpll_${2:0} : XPLL
generic map (
CLKIN_PERIOD => 0.000, -- real
REF_JITTER => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUTPHY_DIVIDE => "DIV8", -- string
DESKEW_DELAY1 => 0, -- integer
DESKEW_DELAY2 => 0, -- integer
DESKEW_DELAY_EN1 => "FALSE", -- string
DESKEW_DELAY_EN2 => "FALSE", -- string
DESKEW_DELAY_PATH1 => "FALSE", -- string
DESKEW_DELAY_PATH2 => "FALSE", -- string
IS_CLKIN_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
CLKIN1_DESKEW => $3, -- in
CLKFB1_DESKEW => $4, -- in
CLKFB2_DESKEW => $5, -- in
CLKIN2_DESKEW => $6, -- in
CLKIN => $7, -- in
RST => $8, -- in
PWRDWN => $9, -- in
CLKOUTPHYEN => $10, -- in
CLKOUT0 => $11, -- out
CLKOUT1 => $12, -- out
CLKOUT2 => $13, -- out
CLKOUT3 => $14, -- out
CLKOUTPHY => $15, -- out
PSCLK => $16, -- in
PSEN => $17, -- in
PSINCDEC => $18, -- in
PSDONE => $19, -- out
DCLK => $20, -- in
DEN => $21, -- in
DWE => $22, -- in
DADDR => $23, -- in [6:0]
DI => $24, -- in [15:0]
DO => $25, -- out [15:0]
DRDY => $26, -- out
RIU_CLK => $27, -- in
RIU_NIBBLE_SEL => $28, -- in
RIU_WR_EN => $29, -- in
RIU_ADDR => $30, -- in [7:0]
RIU_WR_DATA => $31, -- in [15:0]
RIU_RD_DATA => $32, -- out [15:0]
RIU_VALID => $33, -- out
LOCKED1_DESKEW => $34, -- out
LOCKED2_DESKEW => $35, -- out
LOCKED_FB => $36, -- out
LOCKED => $37 -- out
);
"""
'ZHOLD_DELAY':
'prefix': 'ZHOLD_DELAY'
'body': """
${1:FileName}_I_Zhld_Dly_${2:0} : ZHOLD_DELAY
generic map (
IS_DLYIN_INVERTED => '0', -- bit
ZHOLD_FABRIC => "DEFAULT", -- string
ZHOLD_IFF => "DEFAULT" -- string
)
port map (
DLYFABRIC => $3, -- out
DLYIFF => $4, -- out
DLYIN => $5 -- in
);
"""
| true | #-------------------------------------------------------------------------------------------
# VHDL Xilinx Unisim Library component snippets
# Device: Spartan-6, Virtex-5, Virtex-6, 7-Series, All Ultrascale,
# All Zynq, Versal
# Author: PI:NAME:<NAME>END_PIirconfleX
# Purpose: Snippets for ATOM editor created from the Xilinx
# UNISIM component libraries.
# Tools: Atom Editor
# Limitations: None
#
# Version: 0.0.2
# Filename: snippets.cson
# Date Created: 17Jan19
# Date Last Modified: 24Mar20
#-------------------------------------------------------------------------------------------
# Disclaimer:
# This file is delivered as is.
# The supplier cannot be held accountable for any typo or other flaw in this file.
# The supplier cannot be held accountable if Xilinx modifies whatsoever to its
# library of components/primitives.
#-------------------------------------------------------------------------------------------
#
'.source.vhdl':
'BITSLICE_CONTROL':
'prefix': 'BITSLICE_CONTROL'
'body': """
${1:FileName}_I_Btslce_Ctrl_${2:0} : BITSLICE_CONTROL
generic map (
CTRL_CLK => "EXTERNAL", -- string
DIV_MODE => "DIV2", -- string
EN_CLK_TO_EXT_NORTH => "DISABLE", -- string
EN_CLK_TO_EXT_SOUTH => "DISABLE", -- string
EN_DYN_ODLY_MODE => "FALSE", -- string
EN_OTHER_NCLK => "FALSE", -- string
EN_OTHER_PCLK => "FALSE", -- string
IDLY_VT_TRACK => "TRUE", -- string
INV_RXCLK => "FALSE", -- string
ODLY_VT_TRACK => "TRUE", -- string
QDLY_VT_TRACK => "TRUE", -- string
READ_IDLE_COUNT => "00" & X"0", -- std_logic_vector[5:0]
REFCLK_SRC => "PLLCLK", -- string
ROUNDING_FACTOR => 16, -- integer
RXGATE_EXTEND => "FALSE", -- string
RX_CLK_PHASE_N => "SHIFT_0", -- string
RX_CLK_PHASE_P => "SHIFT_0", -- string
RX_GATING => "DISABLE", -- string
SELF_CALIBRATE => "ENABLE", -- string
SERIAL_MODE => "FALSE", -- string
TX_GATING => "DISABLE", -- string
SIM_SPEEDUP => "FAST", -- string
SIM_VERSION => 2.0 -- real
)
port map (
RIU_CLK => $3, -- in
RIU_WR_EN => $4, -- in
RIU_NIBBLE_SEL => $5, -- in
RIU_ADDR => $6, -- in [5:0]
RIU_WR_DATA => $7, -- in [15:0]
RIU_RD_DATA => $8, -- out [15:0]
RIU_VALID => $9, -- out
PLL_CLK => $10 -- in
REFCLK => $11,-- in
RST => $12, -- in
EN_VTC => $13, -- in
VTC_RDY => $14, -- out
DLY_RDY => $15, -- out
DYN_DCI => $16, -- out [6:0]
TBYTE_IN => $17, -- in [3:0]
PHY_RDEN => $18, -- in [3:0]
PHY_RDCS0 => $29, -- in [3:0]
PHY_RDCS1 => $20, -- in [3:0]
PHY_WRCS0 => $21, -- in [3:0]
PHY_WRCS1 => $22, -- in [3:0]
CLK_FROM_EXT => $23, -- in
NCLK_NIBBLE_IN => $24, -- in
PCLK_NIBBLE_IN => $25, -- in
NCLK_NIBBLE_OUT => $26, -- out
PCLK_NIBBLE_OUT => $27, -- out
CLK_TO_EXT_NORTH => $28, -- out
CLK_TO_EXT_SOUTH => $29, -- out
RX_BIT_CTRL_OUT0 => $30, -- out [39:0]
RX_BIT_CTRL_OUT1 => $31, -- out [39:0]
RX_BIT_CTRL_OUT2 => $32, -- out [39:0]
RX_BIT_CTRL_OUT3 => $33, -- out [39:0]
RX_BIT_CTRL_OUT4 => $34, -- out [39:0]
RX_BIT_CTRL_OUT5 => $35, -- out [39:0]
RX_BIT_CTRL_OUT6 => $36, -- out [39:0]
RX_BIT_CTRL_IN0 => $37, -- in [39:0]
RX_BIT_CTRL_IN1 => $38, -- in [39:0]
RX_BIT_CTRL_IN2 => $39, -- in [39:0]
RX_BIT_CTRL_IN3 => $40, -- in [39:0]
RX_BIT_CTRL_IN4 => $41, -- in [39:0]
RX_BIT_CTRL_IN5 => $42, -- in [39:0]
RX_BIT_CTRL_IN6 => $43, -- in [39:0]
TX_BIT_CTRL_OUT0 => $44, -- out [39:0]
TX_BIT_CTRL_OUT1 => $45, -- out [39:0]
TX_BIT_CTRL_OUT2 => $46, -- out [39:0]
TX_BIT_CTRL_OUT3 => $47, -- out [39:0]
TX_BIT_CTRL_OUT4 => $48, -- out [39:0]
TX_BIT_CTRL_OUT5 => $49, -- out [39:0]
TX_BIT_CTRL_OUT6 => $50, -- out [39:0]
TX_BIT_CTRL_IN0 => $51, -- in [39:0]
TX_BIT_CTRL_IN1 => $52, -- in [39:0]
TX_BIT_CTRL_IN2 => $53, -- in [39:0]
TX_BIT_CTRL_IN3 => $54, -- in [39:0]
TX_BIT_CTRL_IN4 => $55, -- in [39:0]
TX_BIT_CTRL_IN5 => $56, -- in [39:0]
TX_BIT_CTRL_IN6 => $57, -- in [39:0]
TX_BIT_CTRL_OUT_TRI => $58, -- out [39:0]
TX_BIT_CTRL_IN_TRI => $59-- in [39:0]
);
"""
'BOUNDARY_SCAN':
'prefix': 'BSCANE2'
'body': """
${1:FileName}_I_Bscane2_${2:0} : BSCANE2
generic map (DISABLE_JTAG => "FALSE", JTAG_CHAIN => 1)
port map (
TDI => $3, -- out
TCK => $3, -- out
TMS => $4, -- out
TDO => $5, -- in
DRCK => $6, -- out
SEL => $7, -- out
SHIFT => $8, -- out
CAPTURE => $9, -- out
RESET => $10 -- out
UPDATE => $11, -- out
RUNTEST => $12 -- out
);
"""
'BUFCE_LEAF':
'prefix': 'BUFCE_LEAF'
'body': """
${1:FileName}_I_Bufce_Leaf_${2:0} : BUFCE_LEAF
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFCE_ROW':
'prefix': 'BUFCE_ROW'
'body': """
${1:FileName}_I_Bufce_Row_${2:0} : BUFCE_ROW
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFG':
'prefix': 'BUFG'
'body': """
${1:FileName}_I_Bufg_${2:0} : BUFG port map (I => $3, O => $4);
"""
'BUFG_GT':
'prefix': 'BUFG_GT'
'body': """
${1:FileName}_I_Btslce_Ctrl_${2:0} : BUFG_GT
generic map (IS_CLR_INVERTED => $2) -- '0'
port map (
I => $3, -- in
CE => $4, -- in
CEMASK => $5, -- in
CLR => $6, -- in
CLRMASK => $7, -- in
DIV => $8, -- in [2:0]
O => $9 -- out
);
"""
'BUFG_GT_SYNC':
'prefix': 'BUFG_GT_SYNC'
'body': """
${1:FileName}_I_Bufg_Gt_Sync_${2:0} : BUFG_GT_SYNC
port map (
CLK => $3, -- in
CLR => $4, -- in
CE => $5, -- in
CESYNC => $6, -- out
CLRSYNC => $7 -- out
);
"""
'BUFG_PS':
'prefix': 'BUFG_PS'
'body': """
${1:FileName}_I_Bufg_Ps_${2:0} : BUFG_PS
generic map (SIM_DEVICE => "ULTRASCALE_PLUS", STARTUP_SYNC => "FALSE");
port map (I => $3, O => $4);
"""
'BUFGCE':
'prefix': 'BUFGCE'
'body': """
${1:FileName}_I_Bufgce_${2:0} : BUFGCE
generic map (
CE_TYPE => "SYNC", -- string
IS_CE_INVERTED => '0', -- std_ukogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFGCE_DIV':
'prefix': 'BUFGCE_DIV'
'body': """
${1:FileName}_I_Bufgce_Div_${2:0} : BUFGCE_DIV
generic map (
BUFGCE_DIVIDE => 1, -- integer
IS_CE_INVERTED => '0', -- std_ulogic
IS_CLR_INVERTED => '0', -- std_ulogic
IS_I_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
CLR => $5, -- in
O => $6 -- out
);
"""
'BUFGCTRL':
'prefix': 'BUFGCTRL'
'body': """
${1:FileName}_I_Bufgctrl_${2:0} : BUFGCTRL
generic map (
CE_TYPE_CE0 => "SYNC", -- string
CE_TYPE_CE1 => "SYNC", -- string
INIT_OUT => 0, -- integer
IS_CE0_INVERTED => '0', -- std_ulogic
IS_CE1_INVERTED => '0', -- std_ulogic
IS_I0_INVERTED => '0', -- std_ulogic
IS_I1_INVERTED => '0', -- std_ulogic
IS_IGNORE0_INVERTED => '0', -- std_ulogic
IS_IGNORE1_INVERTED => '0', -- std_ulogic
IS_S0_INVERTED => '0', -- std_ulogic
IS_S1_INVERTED => '0', -- std_ulogic
PRESELECT_I0 => false, -- boolean
PRESELECT_I1 => false, -- boolean
SIM_DEVICE => "ULTRASCALE", -- string
STARTUP_SYNC => "FALSE" -- string
)
port map (
I0 => $3, -- in
I1 => $4, -- in
S0 => $5, -- in
S1 => $6, -- in
CE0 => $7, -- in
CE1 => $8, -- in
IGNORE0 => $9, -- in
IGNORE1 => $10, -- in
O => $11 -- out
);
"""
'BUFGP':
'prefix': 'BUFGP'
'body': """
${1:FileName}_I_Bufgp_${2:0} : BUFGP port map (I => $3, O => $4);
"""
'BUFH':
'prefix': 'BUFH'
'body': """
${1:FileName}_I_Bufh_${2:0} : BUFH port map (I => $3, O => $4);
"""
'BUFHCE':
'prefix': 'BUFHCE'
'body': """
${1:FileName}_I_Bufhce_${2:0} : BUFHCE
generic map (CE_TYPE => "SYNC", INIT_OUT => 0)
port map (I => $3, CE => $4, O => $5);
"""
'BUFIO':
'prefix': 'BUFIO'
'body': """
${1:FileName}_I_Bufio_${2:0} : BUFIO port map (I => $3, O => $4);
"""
'BUFMR':
'prefix': 'BUFMR'
'body': """
${1:FileName}_I_Bufmr_${2:0} : BUFMR port map (I => $3, O => $4);
"""
'BUFMRCE':
'prefix': 'BUFMRCE'
'body': """
${1:FileName}_I_Bufmrce_${2:0} : ;BUFMRCE
generic map (
CE_TYPE => "SYNC", -- string
INIT_OUT => 0, -- integer
IS_CE_INVERTED => '0' -- std_ulogic
)
port map (
I => $3, -- in
CE => $4, -- in
O => $5 -- out
);
"""
'BUFR':
'prefix': 'BUFR'
'body': """
${1:FileName}_I_Bufr_${2:0} : BUFR
generic map (BUFR_DIVIDE => "BYPASS", SIM_DEVICE => "7SERIES")
port map (I => $3, CE => $4, CLR => $5, O => $6);
"""
'CARRY4':
'prefix': 'CARRY4'
'body': """
${1:FileName}_I_Carry4_${2:0} : CARRY4
port map (
DI => $3, -- in [3:0]
S => $4, -- in [3:0]
CYINIT => $5, -- in
CI => $6, -- in
O => $7, -- out [3:0]
CO => $8 -- out [3:0]
);
"""
'CARRY8':
'prefix': 'CARRY8'
'body': """
${1:FileName}_I_Carry8_${2:0} : CARRY8
generic map (CARRY_TYPE => "SINGLE_CY8")
port map (
CI => $3, -- in
CI_TOP => $4, -- in
DI => $5, -- in [7:0]
S => $6, -- in [7:0]
CO => $7, -- out [7:0]
O => $8 -- out [7:0]
);
"""
'CFGLUT5':
'prefix': 'CFGLUT5'
'body': """
${1:FileName}_I_Cfglut5_${2:0} : CFGLUT5
generic map (INIT => X"00000000")
port map (
CDI => $3, -- in
I0 => $4, -- in
I1 => $5, -- in
I2 => $7, -- in
I3 => $8, -- in
I4 => $9, -- in
CE => $10, -- in
CLK => $11, -- in
O5 => $12, -- out
O6 => $13, -- out
CDO => $14 -- out
);
"""
'DIFFINBUF':
'prefix': 'DIFFINBUF'
'body': """
${1:FileName}_I_Diffinbuf_${2:0} : DIFFINBUF
generic map (
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
ISTANDARD => "UNUSED", -- string
SIM_INPUT_BUFFER_OFFSET => 0 -- integer
)
port map (
DIFF_IN_N => $3, -- in
DIFF_IN_P => $4, -- in
OSC => $5, -- in [3:0]
OSC_EN => $6, -- in [1:0]
VREF => $7, -- in
O => $8, -- out
O_B => $9 -- out
);
"""
'DNA_PORT':
'prefix': 'DNA_PORT'
'body': """
${1:FileName}_I_Dna_Port_${2:0} : DNA_PORT
generic map (SIM_DNA_VALUE => X"000000000000000")
port map (
DIN => $3, -- in
READ => $4, -- in
SHIFT => $5, -- in
CLK => $6, -- in
DOUT => $7 -- out
);
"""
'DPLL':
'prefix': 'DPLL'
'body': """
${1:FileName}_I_Dpll_${2:0} : DPLL
generic map (
CLKIN_PERIOD => 0.000, -- real
REF_JITTER => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_FRACT => 0, -- integer
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
COMPENSATION => "AUTO", -- string
DESKEW_DELAY => 0, -- integer
DESKEW_DELAY_EN => "FALSE", -- string
DESKEW_DELAY_PATH => "FALSE", -- string
IS_CLKIN_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SEL_LOCKED_IN => '1', -- bit
SEL_REG_DELAY => "00", -- std_logic_vector[1:0]
USE_REG_VALID => '1' -- bit
)
port map (
CLKFB_DESKEW => $3, -- in
CLKIN_DESKEW => $4, -- in
CLKIN => $5, -- in
PWRDWN => $6, -- in
RST => $7, -- in
CLKOUT0 => $8, -- out
CLKOUT1 => $9, -- out
CLKOUT2 => $10, -- out
CLKOUT3 => $11, -- out
PSCLK => $12, -- in
PSEN => $13, -- in
PSINCDEC => $14, -- in
PSDONE => $15, -- out
DCLK => $16, -- in
DEN => $17, -- in
DWE => $18, -- in
DADDR => $19, -- in [6:0]
DI => $20, -- in [15:0]
DO => $21, -- out 15:0]
DRDY => $22, -- out
LOCKED => $23, -- out
LOCKED_DESKEW => $24, -- out
LOCKED_FB => $25 -- out
);
"""
'DSP48E1':
'prefix': 'DSP48E1'
'body': """
${1:FileName}_I_Dsp48e1_${2:0} : DSP48E1
generic map (
B_INPUT => "DIRECT", -- string
A_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
BCASCREG => 1, -- integer
ACASCREG => 1, -- integer
INMODEREG => 1, -- integer
ALUMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
OPMODEREG => 1, -- integer
PATTERN => X"000000000000", -- bit_vector
MASK => X"3FFFFFFFFFFF", -- bit_vector
AUTORESET_PATDET => "NO_RESET", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
USE_DPORT => FALSE, -- boolean
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "0000000" -- std_logic_vector[6:0]
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [24:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0]
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0]
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in [6:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
);
"""
'DSP48E2':
'prefix': 'DSP48E2'
'body': """
${1:FileName}_I_Dsp48e2_${2:0} : DSP48E2
generic map (
A_INPUT => "DIRECT", -- string
B_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
ACASCREG => 1, -- integer
BCASCREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
INMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
ALUMODEREG => 1, -- integer
OPMODEREG => 1, -- integer
AMULTSEL => "A", -- string
BMULTSEL => "B", -- string
PREADDINSEL => "A", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
AUTORESET_PATDET => "NO_RESET", -- string
AUTORESET_PRIORITY => "RESET", -- string
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
USE_WIDEXOR => "FALSE", -- string
XORSIMD => "XOR24_48_96" -- string
MASK => X"3FFFFFFFFFFF", -- std_logic_vector[47:0]
PATTERN => X"000000000000", -- std_logic_vector[47:0]
RND => X"000000000000", -- std_logic_vector[47:0]
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "000000000", -- std_logic_vector[8:0]
IS_RSTALLCARRYIN_INVERTED => '0', -- bit
IS_RSTALUMODE_INVERTED => '0', -- bit
IS_RSTA_INVERTED => '0', -- bit
IS_RSTB_INVERTED => '0', -- bit
IS_RSTCTRL_INVERTED => '0', -- bit
IS_RSTC_INVERTED => '0', -- bit
IS_RSTD_INVERTED => '0', -- bit
IS_RSTINMODE_INVERTED => '0', -- bit
IS_RSTM_INVERTED => '0', -- bit
IS_RSTP_INVERTED => '0' -- bit
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [26:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0)
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0)
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in (8:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
XOROUT => $52 -- out [7:0]
);
"""
'DSP48E5':
'prefix': 'DSP48E5'
'body': """
${1:FileName}_I_Dsp48e5_${2:0} : DSP48E5
generic map (
A_INPUT => "DIRECT", -- string
B_INPUT => "DIRECT", -- string
AREG => 1, -- integer
BREG => 1, -- integer
CREG => 1, -- integer
DREG => 1, -- integer
ADREG => 1, -- integer
ACASCREG => 1, -- integer
BCASCREG => 1, -- integer
MREG => 1, -- integer
PREG => 1, -- integer
INMODEREG => 1, -- integer
CARRYINREG => 1, -- integer
CARRYINSELREG => 1, -- integer
ALUMODEREG => 1, -- integer
OPMODEREG => 1, -- integer
AMULTSEL => "A", -- string
BMULTSEL => "B", -- string
PREADDINSEL => "A", -- string
SEL_MASK => "MASK", -- string
SEL_PATTERN => "PATTERN", -- string
AUTORESET_PATDET => "NO_RESET", -- string
AUTORESET_PRIORITY => "RESET", -- string
USE_MULT => "MULTIPLY", -- string
USE_PATTERN_DETECT => "NO_PATDET", -- string
USE_SIMD => "ONE48", -- string
USE_WIDEXOR => "FALSE", -- string
XORSIMD => "XOR24_48_96" -- string
MASK => X"3FFFFFFFFFFF", -- std_logic_vector[47:0]
PATTERN => X"000000000000", -- std_logic_vector[47:0]
RND => X"000000000000", -- std_logic_vector[47:0]
IS_ALUMODE_INVERTED => "0000", -- std_logic_vector[3:0]
IS_CARRYIN_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_INMODE_INVERTED => "00000", -- std_logic_vector[4:0]
IS_OPMODE_INVERTED => "000000000", -- std_logic_vector[8:0]
IS_RSTALLCARRYIN_INVERTED => '0', -- bit
IS_RSTALUMODE_INVERTED => '0', -- bit
IS_RSTA_INVERTED => '0', -- bit
IS_RSTB_INVERTED => '0', -- bit
IS_RSTCTRL_INVERTED => '0', -- bit
IS_RSTC_INVERTED => '0', -- bit
IS_RSTD_INVERTED => '0', -- bit
IS_RSTINMODE_INVERTED => '0', -- bit
IS_RSTM_INVERTED => '0', -- bit
IS_RSTP_INVERTED => '0' -- bit
)
port map (
B => $3, -- in [17:0]
BCIN => $4, -- in [17:0]
CEB1 => $5, -- in
CEB2 => $6, -- in
RSTB => $7, -- in
BCOUT => $8, -- out [17:0]
A => $9, -- in [29:0]
ACIN => $10, -- in [29:0]
CEA1 => $11, -- in
CEA2 => $12, -- in
RSTA => $13, -- in
ACOUT => $14, -- out [29:0]
D => $15, -- in [26:0]
CED => $16, -- in
RSTD => $17, -- in
CEAD => $18, -- in
ALUMODE => $19, -- in [3:0)
CEALUMODE => $20, -- in
RSTALUMODE => $21, -- in
INMODE => $22, -- in [4:0]
CEINMODE => $23, -- in
RSTINMODE => $24, -- in
C => $25, -- in [47:0)
CEC => $26, -- in
RSTC => $27, -- in
CARRYIN => $28, -- in
CECARRYIN => $29, -- in
RSTALLCARRYIN => $30, -- in
CARRYCASCIN => $31, -- in
CARRYINSEL => $32, -- in [2:0]
CARRYCASCOUT => $33, -- out
CARRYOUT => $34, -- out [3:0]
PCIN => $35, -- in [47:0]
PCOUT => $36, -- out [47:0]
OPMODE => $37, -- in (8:0]
CECTRL => $38, -- in
RSTCTRL => $39, -- in
MULTSIGNIN => $40, -- in
CEM => $41, -- in
RSTM => $42, -- in
MULTSIGNOUT => $43, -- out
CLK => $44, -- in
P => $45, -- out [47:0]
CEP => $46, -- in
RSTP => $47, -- in
PATTERNBDETECT => $48, -- out
PATTERNDETECT => $49, -- out
OVERFLOW => $50, -- out
UNDERFLOW => $51, -- out
XOROUT => $52 -- out [7:0]
);
"""
'EFUSE_USR':
'prefix': 'EFUSE_USR'
'body': """2
${1:FileName}_I_Efuse_Usr_${:0} : EFUSE_USR
generic map ("
SIM_EFUSE_VALUE => X00000000" -- bit_vector
)
port map (t
EFUSEUSR => $3 -- out [31:0]
);
"""
'FADD':
'prefix': 'FADD'
'body': """
${1:FileName}_I_Fadd_${2:0} : FADD
generic map (
IS_I0_INVERTED => '0', -- bit
IS_I1_INVERTED => '0' -- bit
)
port map (
I0 => $3, -- in
I1 => $4, -- in
CI => $5, -- in
CO => $6, -- out
O => $7 -- out
);
"""
'FDCE':
'prefix': 'FDCE'
'body': """
${1:FileName}_I_Fdce_${2:0} : FDCE
generic map (INIT => '0', IS_CLR_INVERTED => '0',
IS_C_INVERTED => '0', IS_D_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, CLR => $6, Q => $7);
"""
'FDPE':
'prefix': 'FDPE'
'body': """
${1:FileName}_I_Fdpe_${2:0} : FDPE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_PRE_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, PRE => $6, Q => $7);
"""
'FDRE':
'prefix': 'FDRE'
'body': """
${1:FileName}_I_Fdre_${2:0} : FDRE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_R_INVERTED => '0')
port map (D => $3, CE => $3, C => $4, R => $5, Q => $6);
"""
'FDSE':
'prefix': 'FDSE'
'body': """
${1:FileName}_I_Fdse_${2:0} : FDSE
generic map (INIT => '0', IS_C_INVERTED => '0',
IS_D_INVERTED => '0', IS_S_INVERTED => '0')
port map (D => $3, CE => $4, C => $5, S => $6, Q => $7);
"""
'FIFO36E2':
'prefix': 'FIFO36E2'
'body': """
${1:FileName}_I_Fifo36e2_${2:0} : FIFO36E2
generic map (
INIT => X"000000000000000000", -- [71:0]
SRVAL => X"000000000000000000", -- [71:0]
CLOCK_DOMAINS => "INDEPENDENT",
READ_WIDTH => 4,
WRITE_WIDTH => 4,
REGISTER_MODE => "UNREGISTERED",
RDCOUNT_TYPE => "RAW_PNTR",
WRCOUNT_TYPE => "RAW_PNTR",
RSTREG_PRIORITY => "RSTREG",
SLEEP_ASYNC => "FALSE",
CASCADE_ORDER => "NONE",
PROG_EMPTY_THRESH => 256,
PROG_FULL_THRESH => 256,
EN_ECC_PIPE => "FALSE",
EN_ECC_READ => "FALSE",
EN_ECC_WRITE => "FALSE",
FIRST_WORD_FALL_THROUGH => "FALSE",
IS_RDCLK_INVERTED => '0',
IS_RDEN_INVERTED => '0',
IS_RSTREG_INVERTED => '0',
IS_RST_INVERTED => '0',
IS_WRCLK_INVERTED => '0',
IS_WREN_INVERTED => '0'
)
port map (
DIN => $3, -- in [63:0]
DINP => $4, -- in [7:0]
CASDIN => $5, -- in [63:0]
CASDINP => $6, -- in [7:0]
WRCLK => $7, -- in
WREN => $8, -- in
WRCOUNT => $9, -- out [13:0]
WRERR => $10, -- out
WRRSTBUSY => $11, -- out
RDCLK => $12, -- in
RDEN => $13, -- in
RDCOUNT => $14, -- out [13:0]
RDERR => $15, -- out
RDRSTBUSY => $16, -- out
REGCE => $17, -- in
RST => $18, -- in
RSTREG => $19, -- in
SLEEP => $20, -- in
CASDOMUX => $21, -- in
CASDOMUXEN => $22, -- in
CASNXTRDEN => $23, -- in
CASOREGIMUX => $24, -- in
CASOREGIMUXEN => $25, -- in
CASPRVEMPTY => $26, -- in
INJECTDBITERR => $27, -- in
INJECTSBITERR => $28, -- in
CASNXTEMPTY => $29, -- out
CASPRVRDEN => $30, -- out
CASDOUT => $31, -- out [63:0]
CASDOUTP => $32, -- out [7:0]
DOUT => $33, -- out [63:0]
DOUTP => $34, -- out [7:0]
ECCPARITY => $35, -- out [7:0]
EMPTY => $36, -- out
FULL => $37, -- out
PROGEMPTY => $38, -- out
PROGFULL => $39, -- out
DBITERR => $40, -- out
SBITERR => $41 -- out
);
"""
'GLBL_VHD':
'prefix': 'GLBL_VHD'
'body': """
${1:FileName}_I_Glbl_Vhd_${2:0} : GLBL_VHD
generic map (
ROC_WIDTH => 100000, -- integer
TOC_WIDTH => 0 -- integer
);
"""
'HARD_SYNC':
'prefix': 'HARD_SYNC'
'body': """
${1:FileName}_I_Hard_Sync_${2:0} : HARD_SYNC
generic map (
INIT => , -- '0'
IS_CLK_INVERTED => , -- '0'
LATENCY => -- 2
)
port map (
CLK => $3, -- in
DIN => $4, -- in
DOUT => $5 -- out
);
"""
'IBUF':
'prefix': 'IBUF'
'body': """
${1:FileName}_I_Ibuf_${2:0} : IBUF
generic map (CAPACITANCE => "DONT_CARE",IBUF_DELAY_VALUE => "0",
IFD_DELAY_VALUE => "AUTO", IBUF_LOW_PWR => TRUE,
IOSTANDARD => "DEFAULT")
port map (I => $3, O => $4);
"""
'IBUFCTRL':
'prefix': 'IBUFCTRL'
'body': """
${1:FileName}_I_Ibufctrl_${2:0} : IBUFCTRL
generic map (
ISTANDARD => "UNUSED", -- string
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
T => $3, -- in
I => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7 -- out
);
"""
'IBUFDS':
'prefix': 'IBUFDS'
'body': """
${1:FileName}_I_Ibufds_${2:0} : IBUFDS
generic map (DIFF_TERM => FALSE, IOSTANDARD => "DEFAULT", CAPACITANCE => "DONT_CARE",
DQS_BIAS => "FALSE", IBUF_DELAY_VALUE => "0", IBUF_LOW_PWR => TRUE,
IFD_DELAY_VALUE => "AUTO")
port map (I => $3, IB => $4, O => $5);
"""
'IBUFDSE3':
'prefix': 'IBUFDSE3'
'body': """
${1:FileName}_I_Ibufdse3_${2:0} : IBUFDSE3
generic (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET =: 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
OSC => $6, -- in [3:0]
OSC_EN => $7, -- in [1:0]
O => $8, -- out
);
"""
'IBUFDS_DIFF_OUT':
'prefix': 'IBUFDS_DIFF_OUT'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_${2:0} : IBUFDS_DIFF_OUT
generic map (
DIFF_TERM => FALSE, -- boolean
IBUF_LOW_PWR => TRUE, -- boolean
DQS_BIAS => "FALSE", -- string
IOSTANDARD => "DEFAULT" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'IBUFDS_DIFF_OUT_IBUFDISABLE':
'prefix': 'IBUFDS_DIFF_OUT_IBUFDISABLE'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_Dsble${2:0} : IBUFDS_DIFF_OUT_IBUFDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
DQS_BIAS => "FALSE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
O => $6, -- out
OB => $7 -- out
);
"""
'IBUFDS_DIFF_OUT_INTERMDISABLE':
'prefix': 'IBUFDS_DIFF_OUT_INTERMDISABLE'
'body': """
${1:FileName}_I_Ibufds_Diff_Out_IntrmDsble_${2:0} : IBUFDS_DIFF_OUT_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
DQS_BIAS => "FALSE", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7, -- out
OB => $8 -- out
);
"""
'IBUFDS_GTE3':
'prefix': 'IBUFDS_GTE3'
'body': """
${1:FileName}_I_Ibufds_Gte3_${2:0} : IBUFDS_GTE3
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => "00", -- [1:0]
REFCLK_ICNTL_RX => "00" -- [1:0]
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_GTE4':
'prefix': 'IBUFDS_GTE4'
'body': """
${1:FileName}_I_Ibufds_Gte4_${2:0} : IBUFDS_GTE4
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => "00", -- [1:0]
REFCLK_ICNTL_RX => "00" -- [1:0]
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_GTE5':
'prefix': 'IBUFDS_GTE5'
'body': """
${1:FileName}_I_Ibufds_Gte5_${2:0} : IBUFDS_GTE5
generic map (
REFCLK_CTL_DRV_SWING => "000", -- std_logic_vector[2:0]
REFCLK_EN_DRV => '0', -- bit
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_HROW_CK_SEL => 0, -- integer
REFCLK_ICNTL_RX => 0 -- integer
)
port map (
I => $3, -- in
IB => $4, -- in
CEB => $5, -- in
O => $6, -- out
ODIV2 => $7 -- out
);
"""
'IBUFDS_IBUFDISABLE':
'prefix': 'IBUFDS_IBUFDISABLE'
'body': """
${1:FileName}_I_Ibufds_dsble_${2:0} : IBUFDS_IBUFDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
O => $6 -- out
);
"""
'IBUFDS_INTERMDISABLE':
'prefix': 'IBUFDS_INTERMDISABLE'
'body': """
${1:FileName}_I_Ibufds_IntrmDsble_${2:0} : IBUFDS_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
USE_IBUFDISABLE => "TRUE", -- string
SIM_DEVICE => "7SERIES" -- string
)
port map (
I => $3, -- in
IB => $4, -- in
IBUFDISABLE => $5, -- in
INTERMDISABLE => $6, -- in
O => $7 -- out
);
"""
'ICAPE2':
'prefix': 'ICAPE2'
'body': """
${1:FileName}_I_Icape2_${2:0} : ICAPE2
generic map (
DEVICE_ID => X"03651093", -- bit_vector
ICAP_WIDTH => "X32", -- string
SIM_CFG_FILE_NAME => "NONE" -- string
)
port map (
I => $3, -- in [31:0]
RDWRB => $4, -- in
CSIB => $5, -- in
CLK => $6, -- in
O => $7 -- out [31:0]
);
"""
'ICAPE3':
'prefix': 'ICAPE3'
'body': """
${1:FileName}_I_Icape3_${2:0} : ICAPE3
generic map (
DEVICE_ID => X"03628093", -- bit_vector
ICAP_AUTO_SWITCH => "DISABLE", -- string
SIM_CFG_FILE_NAME => "NONE" -- string
)
port map (
I => $3, -- in [31:0]
CLK => $4, -- in
CSIB => $5, -- in
RDWRB => $6, -- in
PRDONE => $7, -- out
PRERROR => $8, -- out
AVAIL => $9, -- out
O => $10 -- out [31:0]
);
"""
'IDDR':
'prefix': 'IDDR'
'body': """
${1:FileName}_I_Iddr_${2:0} : IDDR
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
SRTYPE => "SYNC", -- string
IS_C_INVERTED => '0', -- std_ulogic
IS_D_INVERTED => '0' -- std_ulogic
)
port map (
D => $3, -- in
CE => $4, -- in
C => $5, -- in
S => $6, -- in
R => $7, -- in
Q1 => $8, -- out
Q2 => $9 -- out
);
"""
'IDDR_2CLK':
'prefix': 'IDDR_2CLK'
'body': """
${1:FileName}_I_Iddr_2clk_${2:0} : IDDR_2CLK
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
SRTYPE => "SYNC" -- string
IS_CB_INVERTED => '0', -- std_ulogic
IS_C_INVERTED => '0', -- std_ulogic
IS_D_INVERTED => '0' -- std_ulogic
)
port map (
D => $3, -- in
CE => $4, -- in
C => $5, -- in
CB => $6, -- in
S => $7, -- in
R => $8, -- in
Q1 => $9, -- out
Q2 => $10 -- out
);
"""
'IDDRE1':
'prefix': 'IDDRE1'
'body': """
${1:FileName}_I_Iddre1_${2:0} : IDDRE1
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
IS_CB_INVERTED => '0' -- bit
IS_C_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
C => $4, -- in
CB => $5, -- in
R => $6, -- in
Q1 => $7, -- out
Q2 => $8 -- out
);
"""
'IDELAYCTRL':
'prefix': 'IDELAYCTRL'
'body': """
${1:FileName}_I_Idlyctrl_${2:0} : IDELAYCTRL
generic map (SIM_DEVICE => "7SERIES")
port map(RDY => $3, REFCLK => $3, RST => $4);
"""
'IDELAYE2':
'prefix': 'IDELAYE2'
'body': """
${1:FileName}_I_Idlye2_${2:0} : IDELAYE2
generic map (
SIGNAL_PATTERN => "DATA", -- string
REFCLK_FREQUENCY => 200.0, -- real
HIGH_PERFORMANCE_MODE => "FALSE", -- string
DELAY_SRC => "IDATAIN", -- string
CINVCTRL_SEL => "FALSE", -- string
IDELAY_TYPE => "FIXED", -- string
IDELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
IS_C_INVERTED => '0', -- bit
IS_DATAIN_INVERTED => '0', -- bit
IS_IDATAIN_INVERTED => '0' -- bit
)
port map (
DATAIN => $3, -- in
IDATAIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
C => $7, -- in
CINVCTRL => $8, -- in
LD => $9, -- in
LDPIPEEN => $10, -- in
REGRST => $11, -- in
CNTVALUEIN => $12, -- in [4:0]
CNTVALUEOUT => $13, -- out [4:0]
DATAOUT => $14 -- out
);
"""
'IDELAYE2_FINEDELAY':
'prefix': 'IDELAYE2_FINEDELAY'
'body': """
${1:FileName}_I_Idlye2_fndly_${2:0} : IDELAYE2_FINEDELAY
generic map (
SIGNAL_PATTERN => "DATA", -- string
REFCLK_FREQUENCY => 200.0, -- real
HIGH_PERFORMANCE_MODE => "FALSE", -- string
DELAY_SRC => "IDATAIN", -- string
CINVCTRL_SEL => "FALSE", -- string
FINEDELAY => "BYPASS", -- string
IDELAY_TYPE => "FIXED", -- string
IDELAY_VALUE => 0, -- integer
DELAY_SRC => "IDATAIN", -- string
IS_C_INVERTED => '0', -- bit
IS_DATAIN_INVERTED => '0', -- bit
IS_IDATAIN_INVERTED => '0', -- bit
PIPE_SEL => "FALSE" -- string
)
port map (
DATAIN => $3, -- in
IDATAIN => $4, -- in
IFDLY => $5, -- in [2:0]
CE => $6, -- in
INC => $7, -- in
C => $8, -- in
CINVCTRL => $9, -- in
LD => $10, -- in
LDPIPEEN => $11, -- in
REGRST => $12, -- in
CNTVALUEIN => $13, -- in [4:0]
CNTVALUEOUT => $14, -- out [4:0]
DATAOUT => $15 -- out
);
"""
'IDELAYE3':
'prefix': 'IDELAYE3'
'body': """
${1:FileName}_I_Idlye3_${2:0} : IDELAYE3
generic map (
CASCADE => "NONE", -- string
DELAY_FORMAT => "TIME", -- string
DELAY_SRC => "IDATAIN", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
LOOPBACK => "FALSE", -- string
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
IDATAIN => $3, -- in
DATAIN => $4, -- in
CASC_IN => $5, -- in
CASC_RETURN => $6, -- in
CLK => $7, -- in
CE => $8, -- in
RST => $9, -- in
INC => $10, -- in
LOAD => $11, -- in
EN_VTC => $12, -- in
CNTVALUEIN => $13, -- in [8:0]
CNTVALUEOUT => $14, -- out [8:0]
CASC_OUT => $15, -- out
DATAOUT => $16 -- out
);
"""
'IDELAYE5':
'prefix': 'IDELAYE5'
'body': """
${1:FileName}_I_Idlye5_${2:0} : IDELAYE5
generic map (
CASCADE => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
IDATAIN => $3, -- in
CLK => $4, -- in
CE => $5, -- in
RST => $6, -- in
INC => $7, -- in
LOAD => $8, -- in
CASC_RETURN => $9, -- in
CNTVALUEIN => $10, -- in [4:0]
CNTVALUEOUT => $11, -- out [4:0]
CASC_OUT => $12, -- out
DATAOUT => $13 -- out
);
"""
'INBUF':
'prefix': 'INBUF'
'body': """
${1:FileName}_I_Inbuf_${2:0} : INBUF
generic map (
IBUF_LOW_PWR => "TRUE", -- string
ISTANDARD => "UNUSED", -- string
SIM_INPUT_BUFFER_OFFSET => 0 -- integer
)
port map (
PAD => $3, -- in
VREF => $4, -- in
OSC => $5, -- in [3:0]
OSC_EN => $6, -- in
O => $7 -- out
);
"""
'IN_FIFO':
'prefix': 'IN_FIFO'
'body': """
${1:FileName}_I_In_Fifo_${2:0} : IN_FIFO
generic map (
SYNCHRONOUS_MODE => "FALSE", -- string
ARRAY_MODE => "ARRAY_MODE_4_X_8", -- string
ALMOST_EMPTY_VALUE => 1, -- integer
ALMOST_FULL_VALUE => 1 -- integer
)
port map (
D0 => $3, -- in [3:0]
D1 => $4, -- in [3:0]
D2 => $5, -- in [3:0]
D3 => $6, -- in [3:0]
D4 => $7, -- in [3:0]
D5 => $8, -- in [7:0]
D6 => $9, -- in [7:0]
D7 => $10, -- in [3:0]
D8 => $11, -- in [3:0]
D9 => $12, -- in [3:0]
WRCLK => $13, -- in
WREN => $14, -- in
RESET => $15, -- in
RDCLK => $16, -- in
RDEN => $17, -- in
Q0 => $18, -- out [7:0]
Q1 => $19, -- out [7:0]
Q2 => $20, -- out [7:0]
Q3 => $21, -- out [7:0]
Q4 => $22, -- out [7:0]
Q5 => $23, -- out [7:0]
Q6 => $24, -- out [7:0]
Q7 => $25, -- out [7:0]
Q8 => $26, -- out [7:0]
Q9 => $27, -- out [7:0]
ALMOSTEMPTY => $28, -- out
ALMOSTFULL => $29, -- out
EMPTY => $20, -- out
FULl => $21 -- out
);
"""
'IOBUF':
'prefix': 'IOBUF'
'body': """
${1:FileName}_I_Iobuf_${2:0} : IOBUF
generic map (DRIVE => 12, IBUF_LOW_PWR => TRUE, IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, T => $4, O => $5, IO => $6);
"""
'IOBUFDS':
'prefix': 'IOBUFDS'
'body': """
${1:FileName}_I_Iobufds_${2:0} : IOBUFDS
generic map (
DIFF_TERM => FALSE, -- Boolean
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
SLEW => "SLOW", -- string
IOSTANDARD => "DEFAULT" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5, -- out
IO => $6, -- inout
IOB => $7, -- inout
);
"""
'IOBUFDSE3':
'prefix': 'IOBUFDSE3'
'body': """
${1:FileName}_I_iobufdse3_${2:0} : IOBUFDSE3
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET => 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
T => $6, -- in
O => $7, -- out
OSC => $8, -- in [3:0]
OSC_EN => $9, -- in [1:0]
IBUFDISABLE => $10, -- in
DCITERMDISABLE => $11 -- in
);
"""
'IOBUFDS_DIFF_OUT':
'prefix': 'IOBUFDS_DIFF_OUT'
'body': """
${1:FileName}_I_Iobufds_Diff_Out_${2:0} : IOBUFDS_DIFF_OUT
generic map (
DIFF_TERM => FALSE, -- boolean
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => TRUE, -- boolean
IOSTANDARD => "DEFAULT" -- stting
)
port map (
I => $3, -- in
TM => $4, -- in
TS => $5, -- in
O => $6, -- out
OB => $7, -- out
IO => $8, -- inout
IOB => $9 -- inout
);
"""
'IOBUFDS_DIFF_OUT_INTERMDISABLE':
'prefix': 'IOBUFDS_DIFF_OUT_INTERMDISABLE'
'body': """
${1:FileName}_I_Iobufds_Diff_Out_Intrmdsble_${2:0} : IOBUFDS_DIFF_OUT_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_DEVICE => "7SERIES", -- string
USE_IBUFDISABLE => "TRUE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
TM => $6, -- in
TS => $7, -- in
O => $8, -- out
OB => $9, -- out
IBUFDISABLE => $10, -- in
INTERMDISABLE => $11 -- in
);
"""
'IOBUFDS_INTERMDISABLE':
'prefix': 'IOBUFDS_INTERMDISABLE'
'body': """
${1:FileName}_I_Iobufds_intrmdsble_${2:0} : IOBUFDS_INTERMDISABLE
generic map (
DIFF_TERM => "FALSE", -- string
DQS_BIAS => "FALSE", -- string
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_DEVICE => "7SERIES", -- string
SLEW => "SLOW", -- string
USE_IBUFDISABLE => "TRUE" -- string
)
port map (
IO => $3, -- inout
IOB => $4, -- inout
I => $5, -- in
T => $6, -- in
O => $7, -- out
IBUFDISABLE => $8, -- in
INTERMDISABLE => $9 -- in
);
"""
'IOBUFE3':
'prefix': 'IOBUFE3'
'body': """
${1:FileName}_I_Iobufe3_${2:0} : IOBUFE3
generic map (
DRIVE => 12, -- integer
IBUF_LOW_PWR => "TRUE", -- string
IOSTANDARD => "DEFAULT", -- string
SIM_INPUT_BUFFER_OFFSET => 0, -- integer
USE_IBUFDISABLE => "FALSE" -- string
)
port map (
IO => $3, -- inout
I => $4, -- in
T => $5, -- in
O => $6, -- out
OSC => $7, -- in [3:0]
OSC_EN => $8, -- in
VREF => $9, -- in
DCITERMDISABLE => $10, -- in
IBUFDISABLE => $11 -- in
);
"""
'ISERDES':
'prefix': 'ISERDES'
'body': """
${1:FileName}_I_Isrds_${2:0} : ISERDES
generic map (
BITSLIP_ENABLE => false, -- boolean
DATA_RATE => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_Q1 => '0', -- bit
INIT_Q2 => '0', -- bit
INIT_Q3 => '0', -- bit
INIT_Q4 => '0', -- bit
INTERFACE_TYPE => "MEMORY", -- string
IOBDELAY => "NONE", -- string
IOBDELAY_TYPE => "DEFAULT", -- string
IOBDELAY_VALUE => 0, -- integer
NUM_CE => 2, -- integer
SERDES_MODE => "MASTER", -- string
SRVAL_Q1 => '0', -- bit
SRVAL_Q2 => '0', -- bit
SRVAL_Q3 => '0', -- bit
SRVAL_Q4 => '0' -- bit
)
port map (
D => $3, -- in
CE1 => $4, -- in
CE2 => $5, -- in
SR => $6, -- in
REV => $7, -- in
DLYCE => $8, -- in
DLYINC => $9, -- in
DLYRST => $10, -- in
BITSLIP => $11, -- in
O => $12, -- out
Q1 => $13, -- out
Q2 => $14, -- out
Q3 => $15, -- out
Q4 => $16, -- out
Q5 => $17, -- out
Q6 => $18, -- out
CLK => $19, -- in
CLKDIV => $20, -- in
OCLK => $21, -- in
SHIFTIN1 => $22, -- in
SHIFTIN2 => $23, -- in
SHIFTOUT1 => $24, -- out
SHIFTOUT2 => $25, -- out
);
"""
'ISERDESE2':
'prefix': 'ISERDESE2'
'body': """
${1:FileName}_I_Isrdse2_${2:0} : ISERDESE2
generic map (
SERDES_MODE => "MASTER", -- string
INTERFACE_TYPE => "MEMORY", -- string
IOBDELAY => "NONE", -- string
DATA_RATE => "DDR", -- string
DATA_WIDTH => 4, -- integer
DYN_CLKDIV_INV_EN => "FALSE", -- string
DYN_CLK_INV_EN => "FALSE", -- string
NUM_CE => 2, -- integer
OFB_USED => "FALSE", -- string
INIT_Q1 => '0', -- bit;
INIT_Q2 => '0', -- bit;
INIT_Q3 => '0', -- bit;
INIT_Q4 => '0', -- bit;
SRVAL_Q1 => '0', -- bit;
SRVAL_Q2 => '0', -- bit;
SRVAL_Q3 => '0', -- bit;
SRVAL_Q4 => '0', -- bit
IS_CLKB_INVERTED => '0', -- bit
IS_CLKDIVP_INVERTED => '0', -- bit
IS_CLKDIV_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_D_INVERTED => '0', -- bit
IS_OCLKB_INVERTED => '0', -- bit
IS_OCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
DDLY => $4, -- in
OFB => $5, -- in
BITSLIP => $6, -- in
CE1 => $7, -- in
CE2 => $8, -- in
RST => $9, -- in
CLK => $10, -- in
CLKB => $11, -- in
CLKDIV => $12, -- in
CLKDIVP => $13, -- in
OCLK => $14, -- in
OCLKB => $15, -- in
DYNCLKDIVSEL => $16, -- in
DYNCLKSEL => $17, -- in
SHIFTOUT1 => $18, -- out
SHIFTOUT2 => $19, -- out
O => $20, -- out
Q1 => $21, -- out
Q2 => $22, -- out
Q3 => $23, -- out
Q4 => $24, -- out
Q5 => $25, -- out
Q6 => $26, -- out
Q7 => $27, -- out
Q8 => $28, -- out
SHIFTIN1 => $29, -- in
SHIFTIN2 => $30 -- in
);
"""
'ISERDESE3':
'prefix': 'ISERDESE3'
'body': """
${1:FileName}_I_Isrdse3_${2:0} : ISERDESE3
generic map (
DATA_WIDTH => 8, -- integer
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
FIFO_ENABLE => "FALSE", -- string
FIFO_SYNC_MODE => "FALSE", -- string
IDDR_MODE => "FALSE", -- string
IS_CLK_B_INVERTED => '0', -- std_ulogic
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSIOM => 2.0 -- real
)
port map (
D => $3, -- in
CLK => $4, -- in
CLKDIV => $5, -- in
CLK_B => $6, -- in
RST => $7, -- in
FIFO_RD_CLK => $8, -- in
FIFO_RD_EN => $9, -- in
INTERNAL_DIVCLK => $10, -- out
FIFO_EMPTY => $11, -- out
Q => $12 -- out[7:0]
);
"""
'LUT5':
'prefix': 'LUT5'
'body': """
${1:FileName}_I_Lut5_${2:0} : LUT5
generic map (
INIT => X"00000000"
)
port map (
I0 => $3, -- in
I1 => $4, -- in
I2 => $5, -- in
I3 => $6, -- in
I4 => $7, -- in
O => $8 -- out
);
"""
'LUT6_2':
'prefix': 'LUT6_2'
'body': """
${1:FileName}_I_Lut6_2_${2:0} : LUT6_2
generic map (
INIT => X"0000000000000000" -- bit_vector
)
port map (
I0 => $3, -- in
I1 => $4, -- in
I2 => $5, -- in
I3 => $6, -- in
I4 => $7, -- in
I5 => $8, -- in
O5 => $9, -- out
O6 => $10 -- out
);
"""
'MASTER_JTAG':
'prefix': 'MASTER_JTAG'
'body': """
${1:FileName}_I_Mstr_Jtag_${2:0} : MASTER_JTAG
port map (
TDO => $3, -- out
TCK => $4, -- in
TDI => $5, -- in
TMS => $6 -- in
);
"""
'MMCME2_ADV':
'prefix': 'MMCME2_ADV'
'body': """
${1:FileName}_I_Mmcme2_Adv_${2:0} : MMCME2_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
REF_JITTER1 => 0.0, -- real
REF_JITTER2 => 0.0, -- real
COMPENSATION => "ZHOLD", -- string
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, - real
CLKFBOUT_USE_FINE_PS => FALSE, -- boolean
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => FALSE, -- boolean
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => FALSE, -- boolean
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => FALSE, -- boolean
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => FALSE, -- boolean
CLKOUT4_CASCADE => FALSE, -- boolean
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => FALSE, -- boolean
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => FALSE, -- boolean
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => FALSE, -- boolean
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH",-- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => FALSE -- boolean
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
CLKFBOUT => $7, -- out
CLKFBOUTB => $8, -- out
CLKFBSTOPPED => $9, -- out
CLKINSTOPPED => $10, -- out
RST => $11, -- in
PWRDWN => $12, -- in
LOCKED => $13, -- out
CLKOUT0 => $14, -- out
CLKOUT0B => $15, -- out
CLKOUT1 => $16, -- out
CLKOUT1B => $17, -- out
CLKOUT2 => $18, -- out
CLKOUT2B => $19, -- out
CLKOUT3 => $20, -- out
CLKOUT3B => $21, -- out
CLKOUT4 => $22, -- out
CLKOUT5 => $23, -- out
CLKOUT6 => $24, -- out
DI => $25, -- in [15:0]
DADDR => $26, -- in [6:0]
DEN => $27, -- in
DWE => $28, -- in
DCLK => $29, -- in
DO => $30, -- out [15:0]
DRDY => $31, -- out
PSCLK => $32, -- in
PSEN => $33, -- in
PSINCDEC => $34, -- in
PSDONE => $35 -- out
);
"""
'MMCME3_ADV':
'prefix': 'MMCME3_ADV'
'body': """
${1:FileName}_I_Mmcme3_Adv_${2:0} : MMCME3_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
IS_CLKIN1_INVERTED => '0', -- std_ulogic
IS_CLKIN2_INVERTED => '0', -- std_ulogic
IS_CLKINSEL_INVERTED => '0', -- std_ulogic
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, -- real
CLKFBOUT_USE_FINE_PS => "FALSE", -- string
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => "FALSE", -- string
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => "FALSE", -- string
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => "FALSE", -- string
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => "FALSE", -- string
CLKOUT4_CASCADE => "FALSE", -- string
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => "FALSE", -- string
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => "FALSE", -- string
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => "FALSE", -- string
COMPENSATION => "AUTO", -- string
IS_PSEN_INVERTED => '0', -- std_ulogic
IS_PSINCDEC_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
RST => $7, -- in
PWRDWN => $8, -- in
CLKFBOUT => $9, -- out
CLKFBOUTB => $10, -- out
CLKOUT0 => $11, -- out
CLKOUT0B => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT1B => $14, -- out
CLKOUT2 => $15, -- out
CLKOUT2B => $16, -- out
CLKOUT3 => $17, -- out
CLKOUT3B => $18, -- out
CLKOUT4 => $19, -- out
CLKOUT5 => $20, -- out
CLKOUT6 => $21, -- out
CDDCREQ => $22, -- in
CDDCDONE => $23, -- out
PSCLK => $24, -- in
PSEN => $25, -- in
PSINCDEC => $26, -- in
PSDONE => $27, -- out
DCLK => $28, -- in
DI => $29, -- in [15:0]
DADDR => $30, -- in [6:0]
DEN => $31, -- in
DWE => $32, -- in
DO => $33, -- out [15:0]
DRDY => $34, -- out
CLKFBSTOPPED => $35, -- out
CLKINSTOPPED => $36, -- out
LOCKED => $37 -- out
);
"""
'MMCME4_ADV':
'prefix': 'MMCME4_ADV'
'body': """
${1:FileName}_I_Mmcme4_Adv_${2:0} : MMCME4_ADV
generic map (
BANDWIDTH => "OPTIMIZED", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
IS_CLKIN1_INVERTED => '0', -- bit
IS_CLKIN2_INVERTED => '0', -- bit
IS_CLKINSEL_INVERTED => '0', -- bit
IS_CLKFBIN_INVERTED => '0', -- bit
CLKFBOUT_MULT_F => 5.000, -- real
CLKFBOUT_PHASE => 0.000, -- real
CLKFBOUT_USE_FINE_PS => "FALSE", -- string
CLKOUT0_DIVIDE_F => 1.000, -- real
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_USE_FINE_PS => "FALSE", -- string
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_USE_FINE_PS => "FALSE", -- string
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_USE_FINE_PS => "FALSE", -- string
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_USE_FINE_PS => "FALSE", -- string
CLKOUT4_CASCADE => "FALSE", -- string
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_USE_FINE_PS => "FALSE", -- string
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_USE_FINE_PS => "FALSE", -- string
CLKOUT6_DIVIDE => 1, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_USE_FINE_PS => "FALSE", -- string
COMPENSATION => "AUTO", -- string
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000, -- integer
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN1 => $3, -- in
CLKIN2 => $4, -- in
CLKINSEL => $5, -- in
CLKFBIN => $6, -- in
RST => $7, -- in
PWRDWN => $8, -- in
CLKFBOUT => $9, -- out
CLKFBOUTB => $10, -- out
CLKOUT0 => $11, -- out
CLKOUT0B => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT1B => $14, -- out
CLKOUT2 => $15, -- out
CLKOUT2B => $16, -- out
CLKOUT3 => $17, -- out
CLKOUT3B => $18, -- out
CLKOUT4 => $19, -- out
CLKOUT5 => $20, -- out
CLKOUT6 => $21, -- out
CDDCREQ => $22, -- in
CDDCDONE => $23, -- out
PSCLK => $24, -- in
PSEN => $25, -- in
PSINCDEC => $26, -- in
PSDONE => $27, -- out
DCLK => $28, -- in
DI => $29, -- in [15:0]
DADDR => $30, -- in [6:0]
DEN => $31, -- in
DWE => $32, -- in
DO => $33, -- out([15:0]
DRDY => $34, -- out
CLKFBSTOPPED => $35, -- out
CLKINSTOPPED => $36, -- out
LOCKED => $37, -- out
);
"""
'MMCME5':
'prefix': 'MMCME5'
'body': """
${1:FileName}_I_Mmcme5_${2:0} : MMCME5
generic map (
BANDWIDTH => "OPTIMIZED", -- string
COMPENSATION => "AUTO", -- string
REF_JITTER1 => 0.010, -- real
REF_JITTER2 => 0.010, -- real
CLKIN1_PERIOD => 0.000, -- real
CLKIN2_PERIOD => 0.000, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_FRACT => 0, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT4_DIVIDE => 2, -- integer
CLKOUT4_DUTY_CYCLE => 0.500, -- real
CLKOUT4_PHASE => 0.000, -- real
CLKOUT4_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT5_DIVIDE => 2, -- integer
CLKOUT5_DUTY_CYCLE => 0.500, -- real
CLKOUT5_PHASE => 0.000, -- real
CLKOUT5_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT6_DIVIDE => 2, -- integer
CLKOUT6_DUTY_CYCLE => 0.500, -- real
CLKOUT6_PHASE => 0.000, -- real
CLKOUT6_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUTFB_PHASE_CTRL => "00", -- std_logic_vector[1:0]
DESKEW_DELAY1 => 0, -- integer
DESKEW_DELAY2 => 0, -- integer
DESKEW_DELAY_EN1 => "FALSE", -- string
DESKEW_DELAY_EN2 => "FALSE", -- string
DESKEW_DELAY_PATH1 => "FALSE", -- string
DESKEW_DELAY_PATH2 => "FALSE", -- string
IS_CLKFBIN_INVERTED => '0', -- bit
IS_CLKIN1_INVERTED => '0', -- bit
IS_CLKIN2_INVERTED => '0', -- bit
IS_CLKINSEL_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
SS_EN => "FALSE", -- string
SS_MODE => "CENTER_HIGH", -- string
SS_MOD_PERIOD => 10000 -- integer
)
port map (
CLKIN1_DESKEW => $3, -- in
CLKFB1_DESKEW => $4, -- in
CLKIN2_DESKEW => $5, -- in
CLKFB2_DESKEW => $6, -- in
CLKIN1 => $7, -- in
CLKIN2 => $8, -- in
CLKINSEL => $9, -- in
CLKFBIN => $10, -- in
CLKFBOUT => $11, -- out
CLKOUT0 => $12, -- out
CLKOUT1 => $13, -- out
CLKOUT2 => $14, -- out
CLKOUT3 => $15, -- out
CLKOUT4 => $16, -- out
CLKOUT5 => $17, -- out
CLKOUT6 => $18, -- out
PWRDWN => $19, -- in
RST => $20, -- in
PSCLK => $21, -- in
PSEN => $22, -- in
PSINCDEC => $23, -- in
PSDONE => $24, -- out
DCLK => $25, -- in
DEN => $26, -- in
DWE => $27, -- in
DADDR => $28, -- in [6:0]
DI => $29, -- in [15:0]
DO => $30, -- out [15:0]
DRDY => $31, -- out
CLKFBSTOPPED => $32, -- out
CLKINSTOPPED => $33, -- out
LOCKED1_DESKEW => $34, -- out
LOCKED2_DESKEW => $35, -- out
LOCKED_FB => $36, -- out
LOCKED => $37 -- out
);
"""
'MUXCY':
'prefix': 'MUXCY'
'body': """MUXCY
${1:FileName}_I_Muxcy_${2:0} :
port map (
CI => $3, -- in
DI => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF7':
'prefix': 'MUXF7'
'body': """
${1:FileName}_I_Muxf7_${2:0} : MUXF7
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF8':
'prefix': 'MUXF8'
'body': """
${1:FileName}_I_Muxf8_${2:0} : MUXF8
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'MUXF9':
'prefix': 'MUXF9'
'body': """
${1:FileName}_I_Muxf9_${2:0} : MUXF9
port map (
I0 => $3, -- in
I1 => $4, -- in
S => $5, -- in
O => $6 -- out
);
"""
'OBUF':
'prefix': 'OBUF'
'body': """
${1:FileName}_I_Obuf_${2:0} : OBUF
generic map (DRIVE => 12, IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, O => $4);
"""
'OBUFDS':
'prefix': 'OBUFDS'
'body': """
${1:FileName}_I_Obufds_${2:0} : OBUFDS
generic map (IOSTANDARD => "DEFAULT", SLEW => "SLOW")
port map (I => $3, O => $4, OB => $5);
"""
'OBUFDS_DPHY':
'prefix': 'OBUFDS_DPHY'
'body': """
${1:FileName}_I_Obufds_Dphy_${2:0} : OBUFDS_DPHY
generic map (
IOSTANDARD => "DEFAULT" -- string
)
port map (
HSTX_I => $3, -- in
HSTX_T => $4, -- in
LPTX_I_N => $5, -- in
LPTX_I_P => $6, -- in
LPTX_T => $7, -- in
O => $8, -- out
OB => $9 -- out
);
"""
'OBUFDS_GTE3_ADV':
'prefix': 'OBUFDS_GTE3_ADV'
'body': """
${1:FileName}_I_Obufds_Gte3_Adv_${2:0} : OBUFDS_GTE3_ADV
generic map (
REFCLK_EN_TX_PATH : bit := '0';
REFCLK_ICNTL_TX : std_logic_vector(4 downto 0) := "00000"
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
RXRECCLK_SEL => $5, -- in [1:0]
O => $6, -- out
OB => $7 -- out
);
"""
'OBUFDS_GTE4_ADV':
'prefix': 'OBUFDS_GTE4_ADV'
'body': """
${1:FileName}_I_Obufds_Gte4_Adv_${2:0} : OBUFDS_GTE4_ADV
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
REFCLK_ICNTL_TX => "00000" -- [4:0]
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
RXRECCLK_SEL => $5, -- in [1:0]
O => $6, -- out
OB => $7 -- out
);
"""
'OBUFDS_GTE5_ADV':
'prefix': 'OBUFDS_GTE5_ADV'
'body': """
${1:FileName}_I_Obufds_Gte5_Adv_${2:0} : OBUFDS_GTE5_ADV
generic map (
REFCLK_EN_TX_PATH => '0', -- bit
RXRECCLK_SEL => "00" -- [1:0]
)
port map (
I => $3, -- in [3:0]
CEB => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'OBUFT':
'prefix': 'OBUFT'
'body': """
${1:FileName}_I_Obuft_${2:0} : OBUFT
generic map (
CAPACITANCE => "DONT_CARE", -- string
DRIVE => 12, -- integer
IOSTANDARD => "DEFAULT", -- string
SLEW => "SLOW" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5 -- out
);
"""
'OBUFTDS':
'prefix': 'OBUFTDS'
'body': """
${1:FileName}_I_Obuftds_${2:0} : OBUFTDS
generic map (
CAPACITANCE => "DONT_CARE", -- string
IOSTANDARD => "DEFAULT", -- string
SLEW => "SLOW" -- string
)
port map (
I => $3, -- in
T => $4, -- in
O => $5, -- out
OB => $6 -- out
);
"""
'ODDR':
'prefix': 'ODDR'
'body': """
${1:FileName}_I_Oddr_${2:0} : ODDR
generic map (
DDR_CLK_EDGE => "OPPOSITE_EDGE", -- string
INIT => '0', -- bit
SRTYPE => "SYNC" -- string
IS_C_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0' -- bit
)
port map (
D1 => $3, -- in
D2 => $4, -- in
CE => $5, -- in
C => $6, -- in
S => $7, -- in
R => $8, -- in
Q => $9 -- out
);
"""
'ODDRE1':
'prefix': 'ODDRE1'
'body': """
${1:FileName}_I_Oddre1_${2:0} : ODDRE1
generic map (
IS_C_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0', -- bit
SRVAL => '0', -- bit
SIM_DEVICE => "ULTRASCALE" -- string
)
port map (
D1 => $3, -- in
D2 => $4, -- in
C => $5, -- in
SR => $6, -- in
Q => $7 -- out
);
"""
'ODELAYE2':
'prefix': 'ODELAYE2'
'body': """
${1:FileName}_I_Odlye2_${2:0} : ODELAYE2
generic map (
CINVCTRL_SEL => "FALSE", -- string
DELAY_SRC => "ODATAIN", -- string
HIGH_PERFORMANCE_MODE => "FALSE", -- string
ODELAY_TYPE => "FIXED", -- string
ODELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
REFCLK_FREQUENCY => 200.0, -- real
SIGNAL_PATTERN => "DATA", -- string
IS_C_INVERTED => '0', -- bit
IS_ODATAIN_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CLKIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
C => $7, -- in
CINVCTRL => $8, -- in
LD => $9, -- in
LDPIPEEN => $10, -- in
REGRST => $11, -- in
DATAOUT => $12, -- out
CNTVALUEOUT => $13, -- out [4:0]
CNTVALUEIN => $14 -- in [4:0]
);
"""
'ODELAYE2_FINEDELAY':
'prefix': 'ODELAYE2_FINEDELAY'
'body': """
${1:FileName}_I_Odlye2_fndly_${2:0} : ODELAYE2_FINEDELAY
generic map (
CINVCTRL_SEL => "FALSE", -- string
DELAY_SRC => "ODATAIN", -- string
FINEDELAY => "BYPASS", -- string
HIGH_PERFORMANCE_MODE => "FALSE", -- string
ODELAY_TYPE => "FIXED", -- string
ODELAY_VALUE => 0, -- integer
PIPE_SEL => "FALSE", -- string
REFCLK_FREQUENCY => 200.0, -- real
SIGNAL_PATTERN => "DATA", -- string
IS_C_INVERTED => '0', -- bit
IS_ODATAIN_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CLKIN => $4, -- in
CE => $5, -- in
INC => $6, -- in
LD => $7, -- in
LDPIPEEN => $8, -- in
OFDLY => $9, -- in [2:0]
REGRST => $10, -- in
C => $11, -- in
CINVCTRL => $12, -- in
CNTVALUEIN => $13, -- in [4:0]
CNTVALUEOUT => $14, -- out [4:0]
DATAOUT => $15 -- out
);
"""
'ODELAYE3':
'prefix': 'ODELAYE3'
'body': """
${1:FileName}_I_Odlye3_${2:0} : ODELAYE3
generic map (
CASCADE => "NONE", -- string
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
ODATAIN => $3, -- in
CASC_IN => $4, -- in
CASC_RETURN => $5, -- in
CLK => $6, -- in
CE => $7, -- in
RST => $8, -- in
INC => $9, -- in
LOAD => $10, -- in
EN_VTC => $11, -- in
CNTVALUEIN => $12, -- in [8:0]
CNTVALUEOUT => $13, -- out [8:0]
CASC_OUT => $14, -- out
DATAOUT => $15 -- out
);
"""
'ODELAYE5':
'prefix': 'ODELAYE5'
'body': """
${1:FileName}_I_Odlye5_${2:0} : ODELAYE5
generic map (
CASCADE => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
ODATAIN => $3, -- in
CASC_IN => $4, -- in
CE => $5, -- in
INC => $6, -- in
LOAD => $7, -- in
RST => $8, -- in
CLK => $9, -- in
CNTVALUEIN => $10, -- in [4:0]
CNTVALUEOUT => $11, -- out [4:0]
DATAOUT => $12 -- out
);
"""
'OSERDES':
'prefix': 'OSERDES'
'body': """
${1:FileName}_I_Osrds_${2:0} : OSERDES
generic map (
DATA_RATE_OQ => "DDR", -- string
DATA_RATE_TQ => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_OQ => '0', -- bit
INIT_TQ => '0', -- bit
SERDES_MODE => "MASTER", -- string
SRVAL_OQ => '0', -- bit
SRVAL_TQ => '0', -- bit
TRISTATE_WIDTH => 4 -- integer
)
port map (
SHIFTIN1 => $3, -- in
SHIFTIN2 => $4, -- in
D1 => $5, -- in
D2 => $6, -- in
D3 => $7, -- in
D4 => $8, -- in
D5 => $9, -- in
D6 => $10, -- in
OCE => $11, -- in
REV => $12, -- in
SR => $13, -- in
CLK => $14, -- in
CLKDIV => $15, -- in
T1 => $16, -- in
T2 => $17, -- in
T3 => $18, -- in
T4 => $19, -- in
TCE => $20, -- in
SHIFTOUT1 => $21, -- out;
SHIFTOUT2 => $22, -- out;
OQ => $23, -- out;
TQ => $24 -- out;
);
"""
'OSERDESE2':
'prefix': 'OSERDESE2'
'body': """
${1:FileName}_I_Osrdse2_${2:0} : OSERDESE2
generic map (
SERDES_MODE => "MASTER",-- string
DATA_RATE_TQ => "DDR", -- string
TRISTATE_WIDTH => 4, -- integer
INIT_TQ => '0', -- bit
SRVAL_TQ => '0', -- bit
DATA_RATE_OQ => "DDR", -- string
DATA_WIDTH => 4, -- integer
INIT_OQ => '0', -- bit
SRVAL_OQ => '0', -- bit
TBYTE_CTL => "FALSE", -- string
TBYTE_SRC => "FALSE", -- string
IS_CLKDIV_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_D1_INVERTED => '0', -- bit
IS_D2_INVERTED => '0', -- bit
IS_D3_INVERTED => '0', -- bit
IS_D4_INVERTED => '0', -- bit
IS_D5_INVERTED => '0', -- bit
IS_D6_INVERTED => '0', -- bit
IS_D7_INVERTED => '0', -- bit
IS_D8_INVERTED => '0', -- bit
IS_T1_INVERTED => '0', -- bit
IS_T2_INVERTED => '0', -- bit
IS_T3_INVERTED => '0', -- bit
IS_T4_INVERTED => '0', -- bit
)
port map (
SHIFTOUT1 => $3, -- out
D1 => $4, -- in
D2 => $5, -- in
D3 => $6, -- in
D4 => $7, -- in
D5 => $8, -- in
D6 => $9, -- in
D7 => $10, -- in
D8 => $11, -- in
SHIFTIN1 => $12, -- in
SHIFTIN2 => $13, -- in
OCE => $14, -- in
RST => $15, -- in
CLK => $16, -- in
CLKDIV => $17, -- in
OFB => $18, -- out
OQ => $19, -- out
TBYTEOUT => $20, -- out
T1 => $21, -- in
T2 => $22, -- in
T3 => $23, -- in
T4 => $24, -- in
TBYTEIN => $25, -- in
TCE => $26, -- in
TFB => $27, -- out
TQ => $28 -- out
SHIFTOUT2 => $29, -- out
);
"""
'OSERDESE3':
'prefix': 'OSERDESE3'
'body': """
${1:FileName}_I_Osrdse3_${2:0} : OSERDESE3
generic map (
DATA_WIDTH => 8, -- 8
INIT => '0', -- std_ulogic
IS_CLKDIV_INVERTED => '0', -- std_ulogic
IS_CLK_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
ODDR_MODE => "FASLE", -- string
OSERDES_D_BYPASS => "FASLE", -- string
OSERDES_T_BYPASS => "FASLE", -- string
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => -- real
)
port map (
D => $3, -- in [7:0]
CLK => $4, -- in
CLKDIV => $5, -- in
RST => $6, -- in
T => $7, -- in
T_OUT => $8, -- out
OQ => $9 -- out
);
"""
'OUT_FIFO':
'prefix': 'OUT_FIFO'
'body': """
${1:FileName}_I_Out_Fifo_${2:0} : OUT_FIFO
generic map (
SYNCHRONOUS_MODE => "FALSE", -- string
ARRAY_MODE => "ARRAY_MODE_8_X_4", -- string
ALMOST_EMPTY_VALUE => 1, -- integer
ALMOST_FULL_VALUE => 1, -- integer
OUTPUT_DISABLE => "FALSE" -- string
)
port map (
D0 => $3, -- in [7:0}
D1 => $4, -- in [7:0}
D2 => $5, -- in [7:0}
D3 => $6, -- in [7:0}
D4 => $7, -- in [7:0}
D5 => $8, -- in [7:0}
D6 => $9, -- in [7:0}
D7 => $10, -- in [7:0}
D8 => $11, -- in [7:0}
D9 => $12, -- in [7:0}
WRCLK => $13, -- in
WREN => $14, -- in
RESET => $15, -- in
RDCLK => $16, -- in
RDEN => $17, -- in
Q0 => $18, -- out [3:0]
Q1 => $19, -- out [3:0]
Q2 => $20, -- out [3:0]
Q3 => $21, -- out [3:0]
Q4 => $22, -- out [3:0]
Q5 => $23, -- out [7:0]
Q6 => $24, -- out [7:0]
Q7 => $25, -- out [3:0]
Q8 => $26, -- out [3:0]
Q9 => $27, -- out [3:0]
ALMOSTEMPTY => $28, -- out
ALMOSTFULL => $29, -- out
EMPTY => $30, -- out
FULL => $31 -- out
);
"""
'PLLE2_ADV':
'prefix': 'PLLE2_ADV'
'body': """
${1:FileName}_I_Plle2_Adv_${2:0} : PLLE2_ADV
generic map(
BANDWIDTH => "OPTIMIZED", -- string
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.0, -- real
CLKIN1_PERIOD => 0.0, -- real
CLKIN2_PERIOD => 0.0, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.5, -- real
CLKOUT0_PHASE => 0.0, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.5, -- real
CLKOUT1_PHASE => 0.0, -- real
CLKOUT2_DIVIDE => 1, -- integer
CLKOUT2_DUTY_CYCLE => 0.5, -- real
CLKOUT2_PHASE => 0.0, -- real
CLKOUT3_DIVIDE => 1, -- integer
CLKOUT3_DUTY_CYCLE => 0.5, -- real
CLKOUT3_PHASE => 0.0, -- real
CLKOUT4_DIVIDE => 1, -- integer
CLKOUT4_DUTY_CYCLE => 0.5, -- real
CLKOUT4_PHASE => 0.0, -- real
CLKOUT5_DIVIDE => 1, -- integer
CLKOUT5_DUTY_CYCLE => 0.5, -- real
CLKOUT5_PHASE => 0.0, -- real
COMPENSATION => "ZHOLD", -- string
DIVCLK_DIVIDE => 1, -- integer
REF_JITTER1 => 0.0, -- real
REF_JITTER2 => 0.0, -- real
STARTUP_WAIT => "FALSE", -- string
IS_CLKINSEL_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
CLKIN1 => $3, -- in
CLKINSEL => $4, -- in
CLKFBIN => $5, -- in
CLKFBOUT => $6, -- out
CLKOUT0 => $7, -- out
CLKOUT1 => $8, -- out
CLKOUT2 => $9, -- out
CLKOUT3 => $10, -- out
CLKOUT4 => $11, -- out
CLKOUT5 => $12, -- out
RST => $13, -- in
PWRDWN => $14, -- in
LOCKED => $15, -- out
DI => $16, -- in [15:0]
DADDR => $17, -- in [6:0]
DEN => $18, -- in
DWE => $19, -- in
DCLK => $20, -- in
DO => $21, -- out [15:0]
DRDY => $22 -- out
CLKIN2 => $23, -- in
);
"""
'PLLE3_ADV':
'prefix': 'PLLE3_ADV'
'body': """
${1:FileName}_I_Plle3_Adv_${2:0} : PLLE3_ADV
generic map (
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKIN_PERIOD => 0.000, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUTPHY_MODE => "VCO_2X", -- string
COMPENSATION => "AUTO", -- string
DIVCLK_DIVIDE => 1, -- integer
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
IS_CLKIN_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REF_JITTER => 0.010, -- real
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN => $3, -- in
CLKFBIN => $4, -- in
RST => $5, -- in
PWRDWN => $6, -- in
CLKOUTPHYEN => $7, -- in
CLKFBOUT => $8, -- out
CLKOUT0 => $9, -- out
CLKOUT0B => $10, -- out
CLKOUT1 => $11, -- out
CLKOUT1B => $12, -- out
CLKOUTPHY => $13, -- out
DCLK => $14, -- in
DI => $15, -- in [15:0]
DADDR => $16, -- in [6:0]
DEN => $17, -- in
DWE => $18, -- in
DO => $19, -- out [15:0]
DRDY => $20, -- out
LOCKED => $21 -- out
);
"""
'PLLE4_ADV':
'prefix': 'PLLE4_ADV'
'body': """
${1:FileName}_I_Plle4_Adv_${2:0} :PLLE4_ADV
generic map (
CLKFBOUT_MULT => 5, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKIN_PERIOD => 0.000, -- real
CLKOUT0_DIVIDE => 1, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT1_DIVIDE => 1, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUTPHY_MODE => "VCO_2X", -- string
COMPENSATION => "AUTO", -- string
DIVCLK_DIVIDE => 1, -- integer
IS_CLKFBIN_INVERTED => '0', -- std_ulogic
IS_CLKIN_INVERTED => '0', -- std_ulogic
IS_PWRDWN_INVERTED => '0', -- std_ulogic
IS_RST_INVERTED => '0', -- std_ulogic
REF_JITTER => 0.010, -- real
STARTUP_WAIT => "FALSE" -- string
)
port map (
CLKIN => $3, -- in
CLKFBIN => $4, -- in
RST => $5, -- in
PWRDWN => $6, -- in
CLKOUTPHYEN => $7, -- in
CLKFBOUT => $8, -- out
CLKOUT0 => $9, -- out
CLKOUT0B => $10, -- out
CLKOUT1 => $11, -- out
CLKOUT1B => $12, -- out
CLKOUTPHY => $13, -- out
DCLK => $14, -- in
DI => $15, -- in [15:0]
DADDR => $16, -- in [6:0]
DEN => $17, -- in
DWE => $18, -- in
DO => $19, -- out [15:0]
DRDY => $20, -- out
LOCKED => $21 -- out
);
"""
'RAM256X1D':
'prefix': 'RAM256X1D'
'body': """
${1:FileName}_I_Ram256x1d_${2:0} : RAM256X1D
generic map (
INIT => X"0000000000000000000000000000000000000000000000000000000000000000", -- [255:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A => $4, -- in [7:0]
WE => $5, -- in
DPRA => $6, -- in [7:0]
WCLK => $7, -- in
DPO => $8, -- out
SPO => $9, -- out
);
"""
'RAM32M':
'prefix': 'RAM32M'
'body': """
${1:FileName}_I_Ram32m_${2:0} : RAM32M
generic map (
INIT_A => X"0000000000000000", -- [63:0]
INIT_B => X"0000000000000000", -- [63:0]
INIT_C => X"0000000000000000", -- [63:0]
INIT_D => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
DIA => $3, -- in [1:0]
DIB => $4, -- in [1:0]
DIC => $5, -- in [1:0]
DID => $6, -- in [1:0]
ADDRA => $7, -- in [4:0]
ADDRB => $8, -- in [4:0]
ADDRC => $9, -- in [4:0]
ADDRD => $10, -- in [4:0]
WE => $11, -- in
WCLK => $12, -- in
DOA => $13, -- out [1:0]
DOB => $14, -- out [1:0]
DOC => $15, -- out [1:0]
DOD => $16 -- out [1:0]
);
"""
'RAM32X1D':
'prefix': 'RAM32X1D'
'body': """
${1:FileName}_I_Ram32x1d_${2:0} : RAM32X1D
generic map (
INIT => X"00000000", -- [31:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A0 => $4, -- in
A1 => $5, -- in
A2 => $6, -- in
A3 => $7, -- in
A4 => $8, -- in
DPRA0 => $9, -- in
DPRA1 => $10, -- in
DPRA2 => $11, -- in
DPRA3 => $12, -- in
DPRA4 => $13, -- in
WE => $14, -- in
WCLK => $15, -- in
DPO => $16, -- out
SPO => $17 -- out
);
"""
'RAM64M':
'prefix': 'RAM64M'
'body': """
${1:FileName}_I_Ram64m_${2:0} : RAM64M
generic map (
INIT_A => X"0000000000000000", -- [63:0]
INIT_B => X"0000000000000000", -- [63:0]
INIT_C => X"0000000000000000", -- [63:0]
INIT_D => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
DIA => $3, -- in
DIB => $4, -- in
DIC => $5, -- in
DID => $6, -- in
ADDRA => $7, -- in [5:0]
ADDRB => $8, -- in [5:0]
ADDRC => $9, -- in [5:0]
ADDRD => $10, -- in [5:0]
WE => $11, -- in
WCLK => $12, -- in
DOA => $13, -- out
DOB => $14, -- out
DOC => $15, -- out
DOD => $16 -- out
);
"""
'RAM64X1D':
'prefix': 'RAM64X1D'
'body': """
${1:FileName}_I_Ram64x1d_${2:0} : RAM64X1D
generic map (
INIT => X"0000000000000000", -- [63:0]
IS_WCLK_INVERTED => '0' -- bit
)
port map (
D => $3, -- in
A0 => $4, -- in
A1 => $5, -- in
A2 => $6, -- in
A3 => $7, -- in
A4 => $8, -- in
A5 => $9, -- in
DPRA0 => $10, -- in
DPRA1 => $11, -- in
DPRA2 => $12, -- in
DPRA3 => $13, -- in
DPRA4 => $14, -- in
DPRA5 => $15, -- in
WE => $16, -- in
WCLK => $17, -- in
DPO => $18, -- out
SPO => $19 -- out
);
"""
'RAMB36E1':
'prefix': 'RAMB36E1'
'body': """
${1:FileName}_I_Ramb36e1_${2:0} : RAMB36E1
generic map (
INIT_FILE => "NONE", -- string
RAM_MODE => "TDP", -- string
WRITE_MODE_A => "WRITE_FIRST", -- string
WRITE_MODE_B => "WRITE_FIRST", -- string
READ_WIDTH_A => 0, -- integer
READ_WIDTH_B => 0, -- integer
WRITE_WIDTH_A => 0, -- integer
WRITE_WIDTH_B => 0, -- integer
RAM_EXTENSION_A => "NONE", -- string
RAM_EXTENSION_B => "NONE", -- string
DOA_REG => 0, -- integer
DOB_REG => 0, -- integer
INIT_A => X"000000000", -- bit_vector
INIT_B => X"000000000", -- bit_vector
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- bit_vector
SRVAL_B => X"000000000", -- bit_vector
EN_ECC_READ => FALSE, -- boolean
EN_ECC_WRITE => FALSE, -- boolean
RDADDR_COLLISION_HWCONFIG => "DELAYED_WRITE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
SIM_DEVICE => "VIRTEX6", -- string
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map (
CASCADEINA => $3, -- in
DIPADIP => $4, -- in [3:0]
DIADI => $5, -- in [31:0]
DOPADOP => $6, -- out [3:0]
DOADO => $7, -- out [31:0]
CASCADEOUTA => $8, -- out
ADDRARDADDR => $9, -- in [15:0]
ENARDEN => $10, -- in
REGCEAREGCE => $11, -- in
WEA => $12, -- in [3:0]
CLKARDCLK => $13, -- in
RSTREGARSTREG => $14, -- in
RSTRAMARSTRAM => $15, -- in
CASCADEINB => $16, -- in
DIPBDIP => $17, -- in [3:0]
DIBDI => $18, -- in [31:0]
DOPBDOP => $19, -- out [3:0]
DOBDO => $20, -- out [31:0]
CASCADEOUTB => $21, -- out
ADDRBWRADDR => $22, -- in [15:0]
ENBWREN => $23, -- in
REGCEB => $24, -- in
WEBWE => $25, -- in [7:0]
CLKBWRCLK => $26, -- in
RSTREGB => $27, -- in
RSTRAMB => $28, -- in
INJECTDBITERR => $29, -- in
INJECTSBITERR => $30, -- in
DBITERR => $31, -- out
ECCPARITY => $32, -- out [7:0]
RDADDRECC => $33, -- out [8:0]
SBITERR => $34 -- out
);
"""
'RAMB36E2':
'prefix': 'RAMB36E2'
'body': """
${1:FileName}_I_Ramb36e2_${2:0} : RAMB36E2
generic map [
INIT_FILE => "NONE", -- string
CLOCK_DOMAINS => "INDEPENDENT", -- string
WRITE_MODE_A => "NO_CHANGE", -- string
WRITE_MODE_B => "NO_CHANGE", -- string
READ_WIDTH_A => 0, -- integer
READ_WIDTH_B => 0, -- integer
WRITE_WIDTH_A => 0, -- integer
WRITE_WIDTH_B => 0, -- integer
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
ENADDRENA => "FALSE", -- string
ENADDRENB => "FALSE", -- string
RDADDRCHANGEA => "FALSE", -- string
RDADDRCHANGEB => "FALSE", -- string
DOA_REG => 1, -- integer
DOB_REG => 1, -- integer
INIT_A => X"000000000", -- [35:0]
INIT_B => X"000000000", -- [35:0]
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- [35:0]
SRVAL_B => X"000000000", -- [35:0]
EN_ECC_PIPE => "FALSE", -- string
EN_ECC_READ => "FALSE", -- string
EN_ECC_WRITE => "FALSE", -- string
SLEEP_ASYNC => "FALSE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map [
ADDRARDADDR => $3, -- in [14:0],
ADDRBWRADDR => $4, -- in [14:0],
ADDRENA => $5, -- in
ADDRENB => $6, -- in
CASDIMUXA => $7, -- in
CASDIMUXB => $8, -- in
CASDINA => $9, -- in [31:0],
CASDINB => $10, -- in [31:0],
CASDINPA => $11, -- in [3:0],
CASDINPB => $12, -- in [3:0],
CASDOMUXA => $13, -- in
CASDOMUXB => $14, -- in
CASDOMUXEN_A => $15, -- in
CASDOMUXEN_B => $16, -- in
CASINDBITERR => $17, -- in
CASINSBITERR => $18, -- in
CASOREGIMUXA => $19, -- in
CASOREGIMUXB => $20, -- in
CASOREGIMUXEN_A => $21, -- in
CASOREGIMUXEN_B => $22, -- in
CLKARDCLK => $23, -- in
CLKBWRCLK => $24, -- in
DINADIN => $25, -- in [31:0],
DINBDIN => $26, -- in [31:0],
DINPADINP => $27, -- in [3:0],
DINPBDINP => $28, -- in [3:0],
ECCPIPECE => $29, -- in
ENARDEN => $30, -- in
ENBWREN => $31, -- in
INJECTDBITERR => $32, -- in
INJECTSBITERR => $33, -- in
REGCEAREGCE => $34, -- in
REGCEB => $35, -- in
RSTRAMARSTRAM => $36, -- in
RSTRAMB => $37, -- in
RSTREGARSTREG => $38, -- in
RSTREGB => $39, -- in
SLEEP => $40, -- in
WEA => $41, -- in [3:0],
WEBWE => $42, -- in [7:0]
CASDOUTA => $43, -- out [31:0],
CASDOUTB => $44, -- out [31:0],
CASDOUTPA => $45, -- out [3:0],
CASDOUTPB => $46, -- out [3:0],
CASOUTDBITERR => $47, -- out
CASOUTSBITERR => $48, -- out
DBITERR => $49, -- out
DOUTADOUT => $50, -- out [31:0],
DOUTBDOUT => $51, -- out [31:0],
DOUTPADOUTP => $52, -- out [3:0],
DOUTPBDOUTP => $53, -- out [3:0],
ECCPARITY => $54, -- out [7:0],
RDADDRECC => $55, -- out [8:0],
SBITERR => $56 -- out
);
"""
'RAMB36E5':
'prefix': 'RAMB36E5'
'body': """
${1:FileName}_I_Ramb36e5_${2:0} : RAMB36E5
generic map (
INIT_FILE => "NONE", -- string
CLOCK_DOMAINS => "INDEPENDENT", -- string
WRITE_MODE_A => "NO_CHANGE", -- string
WRITE_MODE_B => "NO_CHANGE", -- string
READ_WIDTH_A => 72, -- integer
READ_WIDTH_B => 36, -- integer
WRITE_WIDTH_A => 36, -- integer
WRITE_WIDTH_B => 72 -- integer
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
DOA_REG => 1, -- integer
DOB_REG => 1, -- integer
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
RSTREG_PRIORITY_A => "RSTREG", -- string
RSTREG_PRIORITY_B => "RSTREG", -- string
SRVAL_A => X"000000000", -- [35:0]
SRVAL_B => X"000000000", -- [35:0]
EN_ECC_PIPE => "FALSE", -- string
EN_ECC_READ => "FALSE", -- string
EN_ECC_WRITE => "FALSE", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
PR_SAVE_DATA => "FALSE", -- string
SIM_COLLISION_CHECK => "ALL", -- string
SLEEP_ASYNC => "FALSE", -- string
IS_ARST_A_INVERTED => '0', -- bit
IS_ARST_B_INVERTED => '0', -- bit
IS_CLKARDCLK_INVERTED => '0', -- bit
IS_CLKBWRCLK_INVERTED => '0', -- bit
IS_ENARDEN_INVERTED => '0', -- bit
IS_ENBWREN_INVERTED => '0', -- bit
IS_RSTRAMARSTRAM_INVERTED => '0', -- bit
IS_RSTRAMB_INVERTED => '0', -- bit
IS_RSTREGARSTREG_INVERTED => '0', -- bit
IS_RSTREGB_INVERTED => '0' -- bit
)
port map (
ADDRARDADDR => $3, -- in [11:0]
ADDRBWRADDR => $4, -- in [11:0]
ARST_A => $5, -- in
ARST_B => $6, -- in
CASDINA => $7, -- in [31:0]
CASDINB => $8, -- in [31:0]
CASDINPA => $9, -- in [3:0]
CASDINPB => $10, -- in [3:0]
CASDOMUXA => $11, -- in
CASDOMUXB => $12, -- in
CASDOMUXEN_A => $13, -- in
CASDOMUXEN_B => $14, -- in
CASINDBITERR => $15, -- in
CASINSBITERR => $16, -- in
CASOREGIMUXA => $17, -- in
CASOREGIMUXB => $18, -- in
CASOREGIMUXEN_A => $19, -- in
CASOREGIMUXEN_B => $20, -- in
CLKARDCLK => $21, -- in
CLKBWRCLK => $22, -- in
DINADIN => $23, -- in [31:0]
DINBDIN => $24, -- in [31:0]
DINPADINP => $25, -- in [3:0]
DINPBDINP => $26, -- in [3:0]
ECCPIPECE => $27, -- in
ENARDEN => $28, -- in
ENBWREN => $29, -- in
INJECTDBITERR => $30, -- in
INJECTSBITERR => $31, -- in
REGCEAREGCE => $32, -- in
REGCEB => $33, -- in
RSTRAMARSTRAM => $34, -- in
RSTRAMB => $35, -- in
RSTREGARSTREG => $36, -- in
RSTREGB => $37, -- in
SLEEP => $38, -- in
WEA => $39, -- in [3:0]
WEBWE => $40, -- in [8:0]
CASDOUTA => $41, -- out [31:0]
CASDOUTB => $42, -- out [31:0]
CASDOUTPA => $43, -- out [3:0]
CASDOUTPB => $44, -- out [3:0]
CASOUTDBITERR => $45, -- out
CASOUTSBITERR => $46, -- out
DBITERR => $47, -- out
DOUTADOUT => $48, -- out [31:0]
DOUTBDOUT => $49, -- out [31:0]
DOUTPADOUTP => $50, -- out [3:0]
DOUTPBDOUTP => $51, -- out [3:0]
SBITERR => $52 -- out
),
"""
'RAMD32':
'prefix': 'RAMD32'
'body': """
${1:FileName}_I_Ramd32_${2:0} : RAMD32
generic map (
INIT => X"00000000", -- [31:0]
IS_CLK_INVERTED => '0' -- bit
)
port map (
I => $3, -- in
WE => $4, -- in
CLK => $5, -- in
RADR0 => $6, -- in
RADR1 => $7, -- in
RADR2 => $8, -- in
RADR3 => $9, -- in
RADR4 => $10, -- in
WADR0 => $11, -- in
WADR1 => $12, -- in
WADR2 => $13, -- in
WADR3 => $14, -- in
WADR4 => $15, -- in
O => $16 -- out
);
"""
'RIU_OR':
'prefix': 'RIU_OR'
'body': """
${1:FileName}_I_Riu_Or_${2:0} : RIU_OR
generic map (
SIM_DEVICE => "ULTRASCALE", -- string
SIM_VERSION => 2.0 -- real
)
port map (
RIU_RD_DATA_LOW => $3, -- in [15:0]
RIU_RD_DATA_UPP => $4, -- in [15:0]
RIU_RD_VALID_LOW => $5, -- in
RIU_RD_VALID_UPP => $6, -- in
RIU_RD_DATA => $7, -- out [15:0]
RIU_RD_VALID => $8 -- out
);
"""
'RXTX_BITSLICE':
'prefix': 'RXTX_BITSLICE'
'body': """
${1:FileName}_I_Rxtx_btslce_${2:0} : RXTX_BITSLICE
generic map (
RX_DATA_TYPE => "NONE", -- string
RX_DATA_WIDTH => 8, -- integer
RX_DELAY_FORMAT => "TIME", -- string
RX_DELAY_TYPE => "FIXED", -- string
RX_DELAY_VALUE => 0, -- integer
TX_DATA_WIDTH => 8, -- integer
TX_DELAY_FORMAT => "TIME", -- string
TX_DELAY_TYPE => "FIXED", -- string
TX_DELAY_VALUE => 0, -- integer
RX_REFCLK_FREQUENCY => 300.0, -- real
TX_REFCLK_FREQUENCY => 300.0, -- real
RX_UPDATE_MODE => "ASYNC", -- string
TX_UPDATE_MODE => "ASYNC", -- string
FIFO_SYNC_MODE => "FALSE", -- string
INIT => '1', -- bit
LOOPBACK => "FALSE", -- string
NATIVE_ODELAY_BYPASS => "FALSE", -- string
TBYTE_CTL => "TBYTE_IN", -- string
TX_OUTPUT_PHASE_90 => "FALSE", -- string
ENABLE_PRE_EMPHASIS => "FALSE", -- string
IS_RX_CLK_INVERTED => '0', -- bit
IS_RX_RST_DLY_INVERTED => '0', -- bit
IS_RX_RST_INVERTED => '0', -- bit
IS_TX_CLK_INVERTED => '0', -- bit
IS_TX_RST_DLY_INVERTED => '0', -- bit
IS_TX_RST_INVERTED => '0', -- bit
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
DATAIN => $3, -- in
Q => $4, -- out [7:0]
RX_RST => $5, -- in
RX_CLK => $6, -- in
RX_CE => $7, -- in
RX_RST_DLY => $8, -- in
RX_INC => $9, -- in
RX_LOAD => $10, -- in
RX_EN_VTC => $11, -- in
RX_CNTVALUEIN => $12, -- in [8:0]
RX_CNTVALUEOUT => $13, -- out [8:0]
FIFO_RD_CLK => $14, -- in
FIFO_RD_EN => $15, -- in
FIFO_EMPTY => $16, -- out
FIFO_WRCLK_OUT => $17, -- out
RX_BIT_CTRL_IN => $18, -- in [39:0]
TX_BIT_CTRL_IN => $19, -- in [39:0]
RX_BIT_CTRL_OUT => $20, -- out [39:0]
TX_BIT_CTRL_OUT => $21, -- out [39:0]
D => $22, -- in [7:0]
T => $23, -- in
TBYTE_IN => $24, -- in
O => $25, -- out
T_OUT => $26, -- out
TX_RST => $27, -- in
TX_CLK => $28, -- in
TX_CE => $29, -- in
TX_RST_DLY => $30, -- in
TX_INC => $31, -- in
TX_LOAD => $32, -- in
TX_EN_VTC => $33, -- in
TX_CNTVALUEIN => $34, -- in [8:0]
TX_CNTVALUEOUT => $35 -- out [8:0]
);
"""
'RX_BITSLICE':
'prefix': 'RX_BITSLICE'
'body': """
${1:FileName}_I_Rx_Btslce_${2:0} : RX_BITSLICE
generic map(
CASCADE => "FALSE", -- string
DATA_TYPE => "NONE", -- string
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
DELAY_VALUE_EXT => 0, -- integer
FIFO_SYNC_MODE => "FALSE", -- string
IS_CLK_EXT_INVERTED => '0', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_RST_DLY_EXT_INVERTED => '0', -- bit
IS_RST_DLY_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC", -- string
UPDATE_MODE_EXT => "ASYNC", -- string
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
DATAIN => $3, -- in
FIFO_RD_CLK => $4, -- in
FIFO_RD_EN => $5, -- in
RX_BIT_CTRL_IN => $6, -- in [39:0]
TX_BIT_CTRL_IN => $7, -- in [39:0]
RX_BIT_CTRL_OUT => $8, -- out [39:0]
TX_BIT_CTRL_OUT => $9, -- out [39:0]
RST => $10, -- in
CLK => $11, -- in
CE => $12, -- in
RST_DLY => $13, -- in
INC => $14, -- in
LOAD => $15, -- in
EN_VTC => $16, -- in
CNTVALUEIN => $17, -- in [8:0]
CNTVALUEOUT => $18, -- out [8:0]
CLK_EXT => $19, -- in
CE_EXT => $20, -- in
RST_DLY_EXT => $21, -- in
INC_EXT => $22, -- in
LOAD_EXT => $23, -- in
EN_VTC_EXT => $24, -- in
CNTVALUEIN_EXT => $25, -- in [8:0]
CNTVALUEOUT_EXT => $26, -- out [8:0]
BIT_CTRL_OUT_EXT => $27, -- out [28:0]
FIFO_EMPTY => $28, -- out
FIFO_WRCLK_OUT => $29, -- out
Q => $30 -- out [7:0]
);
"""
'SRLC32E':
'prefix': 'SRLC32E'
'body': """
${1:FileName}_I_Srlc32e_${2:0} : SRLC32E
generic map (
INIT => X"00000000",
IS_CLK_INVERTED => '0'
)
port map (
D => $3, -- in
A => $4, -- in [4:0]
CE => $5, -- in
CLK => $6, -- in
Q => $7, -- out
Q31 => $8 -- out
);
"""
'STARTUPE2':
'prefix': 'STARTUPE2'
'body': """
${1:FileName}_I_Startupe2_${2:0} : STARTUPE2
generic map (
PROG_USR => "FALSE", -- string
SIM_CCLK_FREQ => 0.0 -- real
)
port map (
USRDONEO => $3, -- in
USRDONETS => $4, -- in
KEYCLEARB => $5, -- in
PACK => $6, -- in
USRCCLKO => $7, -- in
USRCCLKTS => $8, -- in
CLK => $9, -- in
GSR => $10, -- in
GTS => $11, -- in
CFGCLK => $12, -- out
CFGMCLK => $13, -- out
EOS => $14, -- out
PREQ => $15 -- out
);
"""
'STARTUPE3':
'prefix': 'STARTUPE3'
'body': """
${1:FileName}_I_Startupe3_${2:0} : STARTUPE3
generic map : (
PROG_USR => "FALSE", -- string
SIM_CCLK_FREQ => 0.0 -- real
)
port map (
USRDONEO => $3, -- in
USRDONETS => $4, -- in
KEYCLEARB => $5, -- in
PACK => $6, -- in
USRCCLKO => $7, -- in
USRCCLKTS => $8, -- in
GSR => $9, -- in
GTS => $10, -- in
DTS => $11, -- in [3:0]
FCSBO => $12, -- in
FCSBTS => $13, -- in
DO => $14, -- in [3:0]
DI => $15, -- out [3:0]
CFGCLK => $16, -- out
CFGMCLK => $17, -- out
EOS => $18, -- out
PREQ => $19 -- out
);
"""
'TX_BITSLICE':
'prefix': 'TX_BITSLICE'
'body': """
${1:FileName}_I_Tx_Btslce_${2:0} : TX_BITSLICE
generic map (
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
INIT => '1', -- bit
IS_CLK_INVERTED => '0', -- bit
IS_RST_DLY_INVERTED => '0', -- bit
IS_RST_INVERTED => '0', -- bit
NATIVE_ODELAY_BYPASS => "FALSE", -- string
OUTPUT_PHASE_90 => "FALSE", -- string
ENABLE_PRE_EMPHASIS => "OFF", -- string
REFCLK_FREQUENCY => 300.0, -- real
TBYTE_CTL => "TBYTE_IN", -- string
UPDATE_MODE => "ASYNC", -- string
SIM_DEVICE : string => "ULTRASCALE" -- string
SIM_VERSION => 2.0 -- real
)
port map (
D => $3, -- in [7:0]
T => $4, -- in
TBYTE_IN => $5, -- in
RX_BIT_CTRL_IN => $6, -- in [39:0]
TX_BIT_CTRL_IN => $7, -- in [39:0]
RX_BIT_CTRL_OUT => $8, -- out [39:0]
TX_BIT_CTRL_OUT => $9, -- out [39:0]
RST => $10, -- in
CLK => $11, -- in
CE => $12, -- in
RST_DLY => $13, -- in
INC => $14, -- in
LOAD => $15, -- in
EN_VTC => $16, -- in
CNTVALUEIN => $17, -- in [8:0]
CNTVALUEOUT => $18, -- out [8:0]
O => $19, -- out
T_OUT => $20 -- out
);
"""
'TX_BITSLICE_TRI':
'prefix': 'TX_BITSLICE_TRI'
'body': """
${1:FileName}_I_Tx_Btslce_Tri_${2:0} : TX_BITSLICE_TRI
generic map (
DATA_WIDTH => 8, -- integer
DELAY_FORMAT => "TIME", -- string
DELAY_TYPE => "FIXED", -- string
DELAY_VALUE => 0, -- integer
INIT => '1', -- bit:
IS_CLK_INVERTED => '0', -- bit:
IS_RST_DLY_INVERTED => '0', -- bit:
IS_RST_INVERTED => '0', -- bit:
NATIVE_ODELAY_BYPASS => "FALSE", -- string
OUTPUT_PHASE_90 => "FALSE", -- string
REFCLK_FREQUENCY => 300.0, -- real
UPDATE_MODE => "ASYNC" -- string
SIM_DEVICE => "ULTRASCALE" -- string
SIM_VESION => 2.0 -- real
)
port map (
BIT_CTRL_IN => $3, -- in [39:0]
BIT_CTRL_OUT => $4, -- out [39:0]
RST => $5, -- in
CLK => $6, -- in
CE => $7, -- in
RST_DLY => $8, -- in
INC => $9, -- in
LOAD => $10, -- in
EN_VTC => $11, -- in
CNTVALUEIN => $12, -- in [8:0]
CNTVALUEOUT => $13, -- out [8:0]
TRI_OUT => $14 -- out
);
"""
'URAM288':
'prefix': 'URAM288'
'body': """
${1:FileName}_I_Uram288_${2:0} : URAM288
generic map (
AUTO_SLEEP_LATENCY => 8, -- integer
AVG_CONS_INACTIVE_CYCLES => 10, -- integer
BWE_MODE_A => "PARITY_INTERLEAVED", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
CASCADE_ORDER_A => "NONE", -- string
CASCADE_ORDER_B => "NONE", -- string
EN_AUTO_SLEEP_MODE => "FALSE", -- string
EN_ECC_RD_A => "FALSE", -- string
EN_ECC_RD_B => "FALSE", -- string
EN_ECC_WR_A => "FALSE", -- string
EN_ECC_WR_B => "FALSE", -- string
IREG_PRE_A => "FALSE", -- string
IREG_PRE_B => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_EN_A_INVERTED => '0', -- bit
IS_EN_B_INVERTED => '0', -- bit
IS_RDB_WR_A_INVERTED => '0', -- bit
IS_RDB_WR_B_INVERTED => '0', -- bit
IS_RST_A_INVERTED => '0', -- bit
IS_RST_B_INVERTED => '0', -- bit
MATRIX_ID => "NONE", -- string
NUM_UNIQUE_SELF_ADDR_A => 1, -- integer
NUM_UNIQUE_SELF_ADDR_B => 1, -- integer
NUM_URAM_IN_MATRIX => 1, -- integer
OREG_A => "FALSE", -- string
OREG_B => "FALSE", -- string
OREG_ECC_A => "FALSE", -- string
OREG_ECC_B => "FALSE", -- string
REG_CAS_A => "FALSE", -- string
REG_CAS_B => "FALSE", -- string
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
SELF_ADDR_A => "000" & X"00", -- [10 downto 0)
SELF_ADDR_B => "000" & X"00", -- [10 downto 0)
SELF_MASK_A => "111" & X"FF", -- [10 downto 0)
SELF_MASK_B => "111" & X"FF", -- [10 downto 0)
USE_EXT_CE_A => "FALSE", -- string
USE_EXT_CE_B => "FALSE" -- string
)
port map (
DIN_A => $3, -- in [71:0]
ADDR_A => $4, -- in [22:0]
EN_A => $5, -- in
RDB_WR_A => $6, -- in
BWE_A => $7, -- in [8:0]
INJECT_SBITERR_A => $8, -- in
INJECT_DBITERR_A => $9, -- in
OREG_CE_A => $10, -- in
OREG_ECC_CE_A => $11, -- in
RST_A => $12, -- in
DOUT_A => $13, -- out [71:0]
SBITERR_A => $14, -- out
DBITERR_A => $15, -- out
RDACCESS_A => $16, -- out
SLEEP => $17, -- in
CLK => $18, -- in
DIN_B => $19, -- in [71:0]
ADDR_B => $20, -- in [22:0]
EN_B => $21, -- in
RDB_WR_B => $22, -- in
BWE_B => $23, -- in [8:0]
INJECT_SBITERR_B => $24, -- in
INJECT_DBITERR_B => $25, -- in
OREG_CE_B => $26, -- in
OREG_ECC_CE_B => $27, -- in
RST_B => $28, -- in
DOUT_B => $29, -- out [71:0]
SBITERR_B => $30, -- out
DBITERR_B => $31, -- out
RDACCESS_B => $32, -- out
CAS_IN_ADDR_A => $33, -- in [22:0]
CAS_IN_ADDR_B => $34, -- in [22:0]
CAS_IN_BWE_A => $35, -- in [8:0]
CAS_IN_BWE_B => $36, -- in [8:0]
CAS_IN_DBITERR_A => $37, -- in
CAS_IN_DBITERR_B => $38, -- in
CAS_IN_DIN_A => $39, -- in [71:0]
CAS_IN_DIN_B => $40, -- in [71:0]
CAS_IN_DOUT_A => $41, -- in [71:0]
CAS_IN_DOUT_B => $42, -- in [71:0]
CAS_IN_EN_A => $43, -- in
CAS_IN_EN_B => $44, -- in
CAS_IN_RDACCESS_A => $45, -- in
CAS_IN_RDACCESS_B => $46, -- in
CAS_IN_RDB_WR_A => $47, -- in
CAS_IN_RDB_WR_B => $48, -- in
CAS_IN_SBITERR_A => $49, -- in
CAS_IN_SBITERR_B => $50, -- in
CAS_OUT_ADDR_A => $51, -- out [22:0]
CAS_OUT_ADDR_B => $52, -- out [22:0]
CAS_OUT_BWE_A => $53, -- out [8:0]
CAS_OUT_BWE_B => $54, -- out [8:0]
CAS_OUT_DBITERR_A => $55, -- out
CAS_OUT_DBITERR_B => $56, -- out
CAS_OUT_DIN_A => $57, -- out [71:0]
CAS_OUT_DIN_B => $58, -- out [71:0]
CAS_OUT_DOUT_A => $59, -- out [71:0]
CAS_OUT_DOUT_B => $60, -- out [71:0]
CAS_OUT_EN_A => $61, -- out
CAS_OUT_EN_B => $62, -- out
CAS_OUT_RDACCESS_A => $63, -- out
CAS_OUT_RDACCESS_B => $64, -- out
CAS_OUT_RDB_WR_A => $65, -- out
CAS_OUT_RDB_WR_B => $66, -- out
CAS_OUT_SBITERR_A => $67, -- out
CAS_OUT_SBITERR_B => $68 -- out
);
"""
'URAM288E5':
'prefix': 'URAM288E5'
'body': """
${1:FileName}_I_Uram288e5_${2:0} : URAM288E5
generic map (
INIT_FILE => "NONE", -- string
BWE_MODE_A => "PARITY_INTERLEAVED", -- string
BWE_MODE_B => "PARITY_INTERLEAVED", -- string
READ_WIDTH_A => 72, -- integer
READ_WIDTH_B => 72, -- integer
WRITE_WIDTH_A => 72, -- integer
WRITE_WIDTH_B => 72, -- integer
IREG_PRE_A => "FALSE", -- string
IREG_PRE_B => "FALSE", -- string
OREG_A => "FALSE", -- string
OREG_B => "FALSE", -- string
OREG_ECC_A => "FALSE", -- string
OREG_ECC_B => "FALSE", -- string
REG_CAS_A => "FALSE", -- string
REG_CAS_B => "FALSE", -- string
RST_MODE_A => "SYNC", -- string
RST_MODE_B => "SYNC", -- string
SELF_ADDR_A => "000" & X"00", -- [10:0]
SELF_ADDR_B => "000" & X"00", -- [10:0]
SELF_MASK_A => "111" & X"FF", -- [10:0]
SELF_MASK_B => "111" & X"FF", -- [10:0]
USE_EXT_CE_A => "FALSE", -- string
USE_EXT_CE_B => "FALSE", -- string
CASCADE_ORDER_CTRL_A => "NONE", -- string
CASCADE_ORDER_CTRL_B => "NONE", -- string
CASCADE_ORDER_DATA_A => "NONE", -- string
CASCADE_ORDER_DATA_B => "NONE", -- string
AUTO_SLEEP_LATENCY => 8, -- integer
EN_AUTO_SLEEP_MODE => "FALSE", -- string
AVG_CONS_INACTIVE_CYCLES => 10, -- integer
EN_ECC_RD_A => "FALSE", -- string
EN_ECC_RD_B => "FALSE", -- string
EN_ECC_WR_A => "FALSE", -- string
EN_ECC_WR_B => "FALSE", -- string
MATRIX_ID => "NONE", -- string
NUM_UNIQUE_SELF_ADDR_A => 1, -- integer
NUM_UNIQUE_SELF_ADDR_B => 1, -- integer
NUM_URAM_IN_MATRIX => 1, -- integer
PR_SAVE_DATA => "FALSE", -- string
IS_CLK_INVERTED => '0', -- bit
IS_EN_A_INVERTED => '0', -- bit
IS_EN_B_INVERTED => '0', -- bit
IS_RDB_WR_A_INVERTED => '0', -- bit
IS_RDB_WR_B_INVERTED => '0', -- bit
IS_RST_A_INVERTED => '0', -- bit
IS_RST_B_INVERTED => '0' -- bit
)
port map (
DIN_A => $3, -- in [71:0]
ADDR_A => $4, -- in [25:0]
EN_A => $5, -- in
RDB_WR_A => $6, -- in
BWE_A => $7, -- in [8:0]
INJECT_SBITERR_A => $8, -- in
INJECT_DBITERR_A => $9, -- in
OREG_CE_A => $10, -- in
OREG_ECC_CE_A => $11, -- in
RST_A => $12, -- in
SLEEP => $13, -- in
CLK => $14, -- in
DIN_B => $15, -- in [71:0]
ADDR_B => $16, -- in [25:0]
EN_B => $17, -- in
RDB_WR_B => $18, -- in
BWE_B => $19, -- in [8:0]
INJECT_SBITERR_B => $20, -- in
INJECT_DBITERR_B => $21, -- in
OREG_CE_B => $22, -- in
OREG_ECC_CE_B => $23, -- in
RST_B => $24, -- in
DOUT_A => $25, -- out [71:0]
SBITERR_A => $26, -- out
DBITERR_A => $27, -- out
RDACCESS_A => $28, -- out
DOUT_B => $29, -- out [71:0]
SBITERR_B => $30, -- out
DBITERR_B => $31, -- out
RDACCESS_B => $32, -- out
CAS_IN_ADDR_A => $33, -- in [25:0]
CAS_IN_ADDR_B => $34, -- in [25:0]
CAS_IN_BWE_A => $35, -- in [8:0]
CAS_IN_BWE_B => $36, -- in [8:0]
CAS_IN_DBITERR_A => $37, -- in
CAS_IN_DBITERR_B => $38, -- in
CAS_IN_DIN_A => $39, -- in [71:0]
CAS_IN_DIN_B => $40, -- in [71:0]
CAS_IN_DOUT_A => $41, -- in [71:0]
CAS_IN_DOUT_B => $42, -- in [71:0]
CAS_IN_EN_A => $43, -- in
CAS_IN_EN_B => $44, -- in
CAS_IN_RDACCESS_A => $45, -- in
CAS_IN_RDACCESS_B => $46, -- in
CAS_IN_RDB_WR_A => $47, -- in
CAS_IN_RDB_WR_B => $48, -- in
CAS_IN_SBITERR_A => $49, -- in
CAS_IN_SBITERR_B => $50, -- in
CAS_OUT_ADDR_A => $51, -- out [25:0]
CAS_OUT_ADDR_B => $52, -- out [25:0]
CAS_OUT_BWE_A => $53, -- out [8:0]
CAS_OUT_BWE_B => $54, -- out [8:0]
CAS_OUT_DBITERR_A => $55, -- out
CAS_OUT_DBITERR_B => $56, -- out
CAS_OUT_DIN_A => $57, -- out [71:0]
CAS_OUT_DIN_B => $58, -- out [71:0]
CAS_OUT_DOUT_A => $59, -- out [71:0]
CAS_OUT_DOUT_B => $60, -- out [71:0]
CAS_OUT_EN_A => $61, -- out
CAS_OUT_EN_B => $62, -- out
CAS_OUT_RDACCESS_A => $63, -- out
CAS_OUT_RDACCESS_B => $64, -- out
CAS_OUT_RDB_WR_A => $65, -- out
CAS_OUT_RDB_WR_B => $66, -- out
CAS_OUT_SBITERR_A => $67, -- out
CAS_OUT_SBITERR_B => $68 -- out
);
"""
'USR_ACCESSE2':
'prefix': 'USR_ACCESSE2'
'body': """
${1:FileName}_I_Usr_Access_${2:0} : USR_ACCESSE2
port map (
CFGCLK => $3, -- out
DATA => $4, -- out [31:0]
DATAVALID => $5 -- out
);
"""
'XORCY':
'prefix': 'XORCY'
'body': """
$1 : XORCY
port map (
CI => $3, -- in
LI => $4, -- in
O => $5 -- out
);
"""
'XPLL':
'prefix': 'XPLL'
'body': """
${1:FileName}_I_Xpll_${2:0} : XPLL
generic map (
CLKIN_PERIOD => 0.000, -- real
REF_JITTER => 0.010, -- real
DIVCLK_DIVIDE => 1, -- integer
CLKFBOUT_MULT => 42, -- integer
CLKFBOUT_PHASE => 0.000, -- real
CLKOUT0_DIVIDE => 2, -- integer
CLKOUT0_DUTY_CYCLE => 0.500, -- real
CLKOUT0_PHASE => 0.000, -- real
CLKOUT0_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT1_DIVIDE => 2, -- integer
CLKOUT1_DUTY_CYCLE => 0.500, -- real
CLKOUT1_PHASE => 0.000, -- real
CLKOUT1_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT2_DIVIDE => 2, -- integer
CLKOUT2_DUTY_CYCLE => 0.500, -- real
CLKOUT2_PHASE => 0.000, -- real
CLKOUT2_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUT3_DIVIDE => 2, -- integer
CLKOUT3_DUTY_CYCLE => 0.500, -- real
CLKOUT3_PHASE => 0.000, -- real
CLKOUT3_PHASE_CTRL => "00", -- std_logic_vector[1:0]
CLKOUTPHY_DIVIDE => "DIV8", -- string
DESKEW_DELAY1 => 0, -- integer
DESKEW_DELAY2 => 0, -- integer
DESKEW_DELAY_EN1 => "FALSE", -- string
DESKEW_DELAY_EN2 => "FALSE", -- string
DESKEW_DELAY_PATH1 => "FALSE", -- string
DESKEW_DELAY_PATH2 => "FALSE", -- string
IS_CLKIN_INVERTED => '0', -- bit
IS_PSEN_INVERTED => '0', -- bit
IS_PSINCDEC_INVERTED => '0', -- bit
IS_PWRDWN_INVERTED => '0', -- bit
IS_RST_INVERTED => '0' -- bit
)
port map (
CLKIN1_DESKEW => $3, -- in
CLKFB1_DESKEW => $4, -- in
CLKFB2_DESKEW => $5, -- in
CLKIN2_DESKEW => $6, -- in
CLKIN => $7, -- in
RST => $8, -- in
PWRDWN => $9, -- in
CLKOUTPHYEN => $10, -- in
CLKOUT0 => $11, -- out
CLKOUT1 => $12, -- out
CLKOUT2 => $13, -- out
CLKOUT3 => $14, -- out
CLKOUTPHY => $15, -- out
PSCLK => $16, -- in
PSEN => $17, -- in
PSINCDEC => $18, -- in
PSDONE => $19, -- out
DCLK => $20, -- in
DEN => $21, -- in
DWE => $22, -- in
DADDR => $23, -- in [6:0]
DI => $24, -- in [15:0]
DO => $25, -- out [15:0]
DRDY => $26, -- out
RIU_CLK => $27, -- in
RIU_NIBBLE_SEL => $28, -- in
RIU_WR_EN => $29, -- in
RIU_ADDR => $30, -- in [7:0]
RIU_WR_DATA => $31, -- in [15:0]
RIU_RD_DATA => $32, -- out [15:0]
RIU_VALID => $33, -- out
LOCKED1_DESKEW => $34, -- out
LOCKED2_DESKEW => $35, -- out
LOCKED_FB => $36, -- out
LOCKED => $37 -- out
);
"""
'ZHOLD_DELAY':
'prefix': 'ZHOLD_DELAY'
'body': """
${1:FileName}_I_Zhld_Dly_${2:0} : ZHOLD_DELAY
generic map (
IS_DLYIN_INVERTED => '0', -- bit
ZHOLD_FABRIC => "DEFAULT", -- string
ZHOLD_IFF => "DEFAULT" -- string
)
port map (
DLYFABRIC => $3, -- out
DLYIFF => $4, -- out
DLYIN => $5 -- in
);
"""
|
[
{
"context": "module.exports =\n\tport: 4000,\n\tsecret: 'test',\n\tcookieSecret: 'test'\n",
"end": 44,
"score": 0.8594642877578735,
"start": 40,
"tag": "KEY",
"value": "test"
},
{
"context": "s =\n\tport: 4000,\n\tsecret: 'test',\n\tcookieSecret: 'test'\n",
"end": 67,
"score... | server/config/server-config.coffee | kuetemeier/Node-Express-Angular-Coffee-Bootstrap | 0 | module.exports =
port: 4000,
secret: 'test',
cookieSecret: 'test'
| 169100 | module.exports =
port: 4000,
secret: '<KEY>',
cookieSecret: '<KEY>'
| true | module.exports =
port: 4000,
secret: 'PI:KEY:<KEY>END_PI',
cookieSecret: 'PI:KEY:<KEY>END_PI'
|
[
{
"context": "iew Source code for spaced-comments rule\n# @author Gyandeep Singh\n###\n'use strict'\n\nlodash = require 'lodash'\nastUt",
"end": 82,
"score": 0.9998143315315247,
"start": 68,
"tag": "NAME",
"value": "Gyandeep Singh"
}
] | src/rules/spaced-comment.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Source code for spaced-comments rule
# @author Gyandeep Singh
###
'use strict'
lodash = require 'lodash'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Escapes the control characters of a given string.
# @param {string} s - A string to escape.
# @returns {string} An escaped string.
###
escape = (s) -> "(?:#{lodash.escapeRegExp s})"
###*
# Escapes the control characters of a given string.
# And adds a repeat flag.
# @param {string} s - A string to escape.
# @returns {string} An escaped string.
###
escapeAndRepeat = (s) -> "#{escape s}+"
###*
# Parses `markers` option.
# If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments.
# @param {string[]} [markers] - A marker list.
# @returns {string[]} A marker list.
###
parseMarkersOption = (markers) ->
# `*` is a marker for JSDoc comments.
return markers.concat '*' if markers.indexOf('*') is -1
markers
###*
# Creates string pattern for exceptions.
# Generated pattern:
#
# 1. A space or an exception pattern sequence.
#
# @param {string[]} exceptions - An exception pattern list.
# @returns {string} A regular expression string for exceptions.
###
createExceptionsPattern = (exceptions) ->
pattern = ''
###
# A space or an exception pattern sequence.
# [] ==> "\s"
# ["-"] ==> "(?:\s|\-+$)"
# ["-", "="] ==> "(?:\s|(?:\-+|=+)$)"
# ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24)
###
if exceptions.length is 0
# a space.
pattern += '\\s'
else
# a space or...
pattern += '(?:\\s|'
if exceptions.length is 1
# a sequence of the exception pattern.
pattern += escapeAndRepeat exceptions[0]
else
# a sequence of one of the exception patterns.
pattern += '(?:'
pattern += exceptions.map(escapeAndRepeat).join '|'
pattern += ')'
pattern += "(?:$|[#{Array.from(astUtils.LINEBREAKS).join ''}]))"
pattern
###*
# Creates RegExp object for `always` mode.
# Generated pattern for beginning of comment:
#
# 1. First, a marker or nothing.
# 2. Next, a space or an exception pattern sequence.
#
# @param {string[]} markers - A marker list.
# @param {string[]} exceptions - An exception pattern list.
# @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode.
###
createAlwaysStylePattern = (markers, exceptions) ->
pattern = '^'
###
# A marker or nothing.
# ["*"] ==> "\*?"
# ["*", "!"] ==> "(?:\*|!)?"
# ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F
###
if markers.length is 1
# the marker.
pattern += escape markers[0]
else
# one of markers.
pattern += '(?:'
pattern += markers.map(escape).join '|'
pattern += ')'
pattern += '?' # or nothing.
pattern += createExceptionsPattern exceptions
new RegExp pattern
###*
# Creates RegExp object for `never` mode.
# Generated pattern for beginning of comment:
#
# 1. First, a marker or nothing (captured).
# 2. Next, a space or a tab.
#
# @param {string[]} markers - A marker list.
# @returns {RegExp} A RegExp object for `never` mode.
###
createNeverStylePattern = (markers) ->
pattern = "^(#{markers.map(escape).join '|'})?[ \t]+"
new RegExp pattern
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'enforce consistent spacing after the `//` or `/*` in a comment'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/spaced-comment'
fixable: 'whitespace'
schema: [
enum: ['always', 'never']
,
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
line:
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
additionalProperties: no
block:
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
balanced:
type: 'boolean'
additionalProperties: no
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
# Unless the first option is never, require a space
requireSpace = context.options[0] isnt 'never'
###
# Parse the second options.
# If markers don't include `"*"`, it's added automatically for JSDoc
# comments.
###
config = context.options[1] or {}
balanced = config.block?.balanced
styleRules = ['block', 'line'].reduce(
(rule, type) ->
markers = parseMarkersOption(
config[type]?.markers or config.markers or []
)
exceptions = config[type]?.exceptions or config.exceptions or []
endNeverPattern = '[ \t]+$'
# Create RegExp object for valid patterns.
rule[type] =
beginRegex:
if requireSpace
createAlwaysStylePattern markers, exceptions
else
createNeverStylePattern markers
endRegex:
if balanced and requireSpace
new RegExp "#{createExceptionsPattern exceptions}$"
else
new RegExp endNeverPattern
hasExceptions: exceptions.length > 0
markers: new RegExp "^(#{markers.map(escape).join '|'})"
rule
,
{}
)
###*
# Reports a beginning spacing error with an appropriate message.
# @param {ASTNode} node - A comment node to check.
# @param {string} message - An error message to report.
# @param {Array} match - An array of match results for markers.
# @param {string} refChar - Character used for reference in the error message.
# @returns {void}
###
reportBegin = (node, message, match, refChar) ->
type = node.type.toLowerCase()
commentIdentifier = if type is 'block' then '###' else '#'
context.report {
node
fix: (fixer) ->
start = node.range[0]
end = start + commentIdentifier.length
if requireSpace
if match then end += match[0].length
return fixer.insertTextAfterRange [start, end], ' '
end += match[0].length
fixer.replaceTextRange(
[start, end]
commentIdentifier + (if match[1] then match[1] else '')
)
message
data: {refChar}
}
###*
# Reports an ending spacing error with an appropriate message.
# @param {ASTNode} node - A comment node to check.
# @param {string} message - An error message to report.
# @param {string} match - An array of the matched whitespace characters.
# @returns {void}
###
reportEnd = (node, message, match) ->
context.report {
node
fix: (fixer) ->
return fixer.insertTextAfterRange(
[node.range[0], node.range[1] - 3]
' '
) if requireSpace
end = node.range[1] - 3
start = end - match[0].length
fixer.replaceTextRange [start, end], ''
message
}
###*
# Reports a given comment if it's invalid.
# @param {ASTNode} node - a comment node to check.
# @returns {void}
###
checkCommentForSpace = (node) ->
type = node.type.toLowerCase()
rule = styleRules[type]
commentIdentifier = if type is 'block' then '###' else '#'
# Ignores empty comments.
return if node.value.length is 0
beginMatch = rule.beginRegex.exec node.value
endMatch = rule.endRegex.exec node.value
# Checks.
if requireSpace
unless beginMatch
hasMarker = rule.markers.exec node.value
marker =
if hasMarker
commentIdentifier + hasMarker[0]
else
commentIdentifier
if rule.hasExceptions
reportBegin(
node
"Expected exception block, space or tab after '{{refChar}}' in comment."
hasMarker
marker
)
else
reportBegin(
node
"Expected space or tab after '{{refChar}}' in comment."
hasMarker
marker
)
if balanced and type is 'block' and not endMatch
reportEnd node, "Expected space or tab before '###' in comment."
else
if beginMatch
unless beginMatch[1]
reportBegin(
node
"Unexpected space or tab after '{{refChar}}' in comment."
beginMatch
commentIdentifier
)
else
reportBegin(
node
'Unexpected space or tab after marker ({{refChar}}) in comment.'
beginMatch
beginMatch[1]
)
if balanced and type is 'block' and endMatch
reportEnd(
node
"Unexpected space or tab before '###' in comment."
endMatch
)
Program: ->
comments = sourceCode.getAllComments()
comments
.filter (token) -> token.type isnt 'Shebang'
.forEach checkCommentForSpace
| 150814 | ###*
# @fileoverview Source code for spaced-comments rule
# @author <NAME>
###
'use strict'
lodash = require 'lodash'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Escapes the control characters of a given string.
# @param {string} s - A string to escape.
# @returns {string} An escaped string.
###
escape = (s) -> "(?:#{lodash.escapeRegExp s})"
###*
# Escapes the control characters of a given string.
# And adds a repeat flag.
# @param {string} s - A string to escape.
# @returns {string} An escaped string.
###
escapeAndRepeat = (s) -> "#{escape s}+"
###*
# Parses `markers` option.
# If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments.
# @param {string[]} [markers] - A marker list.
# @returns {string[]} A marker list.
###
parseMarkersOption = (markers) ->
# `*` is a marker for JSDoc comments.
return markers.concat '*' if markers.indexOf('*') is -1
markers
###*
# Creates string pattern for exceptions.
# Generated pattern:
#
# 1. A space or an exception pattern sequence.
#
# @param {string[]} exceptions - An exception pattern list.
# @returns {string} A regular expression string for exceptions.
###
createExceptionsPattern = (exceptions) ->
pattern = ''
###
# A space or an exception pattern sequence.
# [] ==> "\s"
# ["-"] ==> "(?:\s|\-+$)"
# ["-", "="] ==> "(?:\s|(?:\-+|=+)$)"
# ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24)
###
if exceptions.length is 0
# a space.
pattern += '\\s'
else
# a space or...
pattern += '(?:\\s|'
if exceptions.length is 1
# a sequence of the exception pattern.
pattern += escapeAndRepeat exceptions[0]
else
# a sequence of one of the exception patterns.
pattern += '(?:'
pattern += exceptions.map(escapeAndRepeat).join '|'
pattern += ')'
pattern += "(?:$|[#{Array.from(astUtils.LINEBREAKS).join ''}]))"
pattern
###*
# Creates RegExp object for `always` mode.
# Generated pattern for beginning of comment:
#
# 1. First, a marker or nothing.
# 2. Next, a space or an exception pattern sequence.
#
# @param {string[]} markers - A marker list.
# @param {string[]} exceptions - An exception pattern list.
# @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode.
###
createAlwaysStylePattern = (markers, exceptions) ->
pattern = '^'
###
# A marker or nothing.
# ["*"] ==> "\*?"
# ["*", "!"] ==> "(?:\*|!)?"
# ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F
###
if markers.length is 1
# the marker.
pattern += escape markers[0]
else
# one of markers.
pattern += '(?:'
pattern += markers.map(escape).join '|'
pattern += ')'
pattern += '?' # or nothing.
pattern += createExceptionsPattern exceptions
new RegExp pattern
###*
# Creates RegExp object for `never` mode.
# Generated pattern for beginning of comment:
#
# 1. First, a marker or nothing (captured).
# 2. Next, a space or a tab.
#
# @param {string[]} markers - A marker list.
# @returns {RegExp} A RegExp object for `never` mode.
###
createNeverStylePattern = (markers) ->
pattern = "^(#{markers.map(escape).join '|'})?[ \t]+"
new RegExp pattern
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'enforce consistent spacing after the `//` or `/*` in a comment'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/spaced-comment'
fixable: 'whitespace'
schema: [
enum: ['always', 'never']
,
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
line:
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
additionalProperties: no
block:
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
balanced:
type: 'boolean'
additionalProperties: no
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
# Unless the first option is never, require a space
requireSpace = context.options[0] isnt 'never'
###
# Parse the second options.
# If markers don't include `"*"`, it's added automatically for JSDoc
# comments.
###
config = context.options[1] or {}
balanced = config.block?.balanced
styleRules = ['block', 'line'].reduce(
(rule, type) ->
markers = parseMarkersOption(
config[type]?.markers or config.markers or []
)
exceptions = config[type]?.exceptions or config.exceptions or []
endNeverPattern = '[ \t]+$'
# Create RegExp object for valid patterns.
rule[type] =
beginRegex:
if requireSpace
createAlwaysStylePattern markers, exceptions
else
createNeverStylePattern markers
endRegex:
if balanced and requireSpace
new RegExp "#{createExceptionsPattern exceptions}$"
else
new RegExp endNeverPattern
hasExceptions: exceptions.length > 0
markers: new RegExp "^(#{markers.map(escape).join '|'})"
rule
,
{}
)
###*
# Reports a beginning spacing error with an appropriate message.
# @param {ASTNode} node - A comment node to check.
# @param {string} message - An error message to report.
# @param {Array} match - An array of match results for markers.
# @param {string} refChar - Character used for reference in the error message.
# @returns {void}
###
reportBegin = (node, message, match, refChar) ->
type = node.type.toLowerCase()
commentIdentifier = if type is 'block' then '###' else '#'
context.report {
node
fix: (fixer) ->
start = node.range[0]
end = start + commentIdentifier.length
if requireSpace
if match then end += match[0].length
return fixer.insertTextAfterRange [start, end], ' '
end += match[0].length
fixer.replaceTextRange(
[start, end]
commentIdentifier + (if match[1] then match[1] else '')
)
message
data: {refChar}
}
###*
# Reports an ending spacing error with an appropriate message.
# @param {ASTNode} node - A comment node to check.
# @param {string} message - An error message to report.
# @param {string} match - An array of the matched whitespace characters.
# @returns {void}
###
reportEnd = (node, message, match) ->
context.report {
node
fix: (fixer) ->
return fixer.insertTextAfterRange(
[node.range[0], node.range[1] - 3]
' '
) if requireSpace
end = node.range[1] - 3
start = end - match[0].length
fixer.replaceTextRange [start, end], ''
message
}
###*
# Reports a given comment if it's invalid.
# @param {ASTNode} node - a comment node to check.
# @returns {void}
###
checkCommentForSpace = (node) ->
type = node.type.toLowerCase()
rule = styleRules[type]
commentIdentifier = if type is 'block' then '###' else '#'
# Ignores empty comments.
return if node.value.length is 0
beginMatch = rule.beginRegex.exec node.value
endMatch = rule.endRegex.exec node.value
# Checks.
if requireSpace
unless beginMatch
hasMarker = rule.markers.exec node.value
marker =
if hasMarker
commentIdentifier + hasMarker[0]
else
commentIdentifier
if rule.hasExceptions
reportBegin(
node
"Expected exception block, space or tab after '{{refChar}}' in comment."
hasMarker
marker
)
else
reportBegin(
node
"Expected space or tab after '{{refChar}}' in comment."
hasMarker
marker
)
if balanced and type is 'block' and not endMatch
reportEnd node, "Expected space or tab before '###' in comment."
else
if beginMatch
unless beginMatch[1]
reportBegin(
node
"Unexpected space or tab after '{{refChar}}' in comment."
beginMatch
commentIdentifier
)
else
reportBegin(
node
'Unexpected space or tab after marker ({{refChar}}) in comment.'
beginMatch
beginMatch[1]
)
if balanced and type is 'block' and endMatch
reportEnd(
node
"Unexpected space or tab before '###' in comment."
endMatch
)
Program: ->
comments = sourceCode.getAllComments()
comments
.filter (token) -> token.type isnt 'Shebang'
.forEach checkCommentForSpace
| true | ###*
# @fileoverview Source code for spaced-comments rule
# @author PI:NAME:<NAME>END_PI
###
'use strict'
lodash = require 'lodash'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Escapes the control characters of a given string.
# @param {string} s - A string to escape.
# @returns {string} An escaped string.
###
escape = (s) -> "(?:#{lodash.escapeRegExp s})"
###*
# Escapes the control characters of a given string.
# And adds a repeat flag.
# @param {string} s - A string to escape.
# @returns {string} An escaped string.
###
escapeAndRepeat = (s) -> "#{escape s}+"
###*
# Parses `markers` option.
# If markers don't include `"*"`, this adds `"*"` to allow JSDoc comments.
# @param {string[]} [markers] - A marker list.
# @returns {string[]} A marker list.
###
parseMarkersOption = (markers) ->
# `*` is a marker for JSDoc comments.
return markers.concat '*' if markers.indexOf('*') is -1
markers
###*
# Creates string pattern for exceptions.
# Generated pattern:
#
# 1. A space or an exception pattern sequence.
#
# @param {string[]} exceptions - An exception pattern list.
# @returns {string} A regular expression string for exceptions.
###
createExceptionsPattern = (exceptions) ->
pattern = ''
###
# A space or an exception pattern sequence.
# [] ==> "\s"
# ["-"] ==> "(?:\s|\-+$)"
# ["-", "="] ==> "(?:\s|(?:\-+|=+)$)"
# ["-", "=", "--=="] ==> "(?:\s|(?:\-+|=+|(?:\-\-==)+)$)" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5Cs%7C(%3F%3A%5C-%2B%7C%3D%2B%7C(%3F%3A%5C-%5C-%3D%3D)%2B)%24)
###
if exceptions.length is 0
# a space.
pattern += '\\s'
else
# a space or...
pattern += '(?:\\s|'
if exceptions.length is 1
# a sequence of the exception pattern.
pattern += escapeAndRepeat exceptions[0]
else
# a sequence of one of the exception patterns.
pattern += '(?:'
pattern += exceptions.map(escapeAndRepeat).join '|'
pattern += ')'
pattern += "(?:$|[#{Array.from(astUtils.LINEBREAKS).join ''}]))"
pattern
###*
# Creates RegExp object for `always` mode.
# Generated pattern for beginning of comment:
#
# 1. First, a marker or nothing.
# 2. Next, a space or an exception pattern sequence.
#
# @param {string[]} markers - A marker list.
# @param {string[]} exceptions - An exception pattern list.
# @returns {RegExp} A RegExp object for the beginning of a comment in `always` mode.
###
createAlwaysStylePattern = (markers, exceptions) ->
pattern = '^'
###
# A marker or nothing.
# ["*"] ==> "\*?"
# ["*", "!"] ==> "(?:\*|!)?"
# ["*", "/", "!<"] ==> "(?:\*|\/|(?:!<))?" ==> https://jex.im/regulex/#!embed=false&flags=&re=(%3F%3A%5C*%7C%5C%2F%7C(%3F%3A!%3C))%3F
###
if markers.length is 1
# the marker.
pattern += escape markers[0]
else
# one of markers.
pattern += '(?:'
pattern += markers.map(escape).join '|'
pattern += ')'
pattern += '?' # or nothing.
pattern += createExceptionsPattern exceptions
new RegExp pattern
###*
# Creates RegExp object for `never` mode.
# Generated pattern for beginning of comment:
#
# 1. First, a marker or nothing (captured).
# 2. Next, a space or a tab.
#
# @param {string[]} markers - A marker list.
# @returns {RegExp} A RegExp object for `never` mode.
###
createNeverStylePattern = (markers) ->
pattern = "^(#{markers.map(escape).join '|'})?[ \t]+"
new RegExp pattern
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'enforce consistent spacing after the `//` or `/*` in a comment'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/spaced-comment'
fixable: 'whitespace'
schema: [
enum: ['always', 'never']
,
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
line:
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
additionalProperties: no
block:
type: 'object'
properties:
exceptions:
type: 'array'
items:
type: 'string'
markers:
type: 'array'
items:
type: 'string'
balanced:
type: 'boolean'
additionalProperties: no
additionalProperties: no
]
create: (context) ->
sourceCode = context.getSourceCode()
# Unless the first option is never, require a space
requireSpace = context.options[0] isnt 'never'
###
# Parse the second options.
# If markers don't include `"*"`, it's added automatically for JSDoc
# comments.
###
config = context.options[1] or {}
balanced = config.block?.balanced
styleRules = ['block', 'line'].reduce(
(rule, type) ->
markers = parseMarkersOption(
config[type]?.markers or config.markers or []
)
exceptions = config[type]?.exceptions or config.exceptions or []
endNeverPattern = '[ \t]+$'
# Create RegExp object for valid patterns.
rule[type] =
beginRegex:
if requireSpace
createAlwaysStylePattern markers, exceptions
else
createNeverStylePattern markers
endRegex:
if balanced and requireSpace
new RegExp "#{createExceptionsPattern exceptions}$"
else
new RegExp endNeverPattern
hasExceptions: exceptions.length > 0
markers: new RegExp "^(#{markers.map(escape).join '|'})"
rule
,
{}
)
###*
# Reports a beginning spacing error with an appropriate message.
# @param {ASTNode} node - A comment node to check.
# @param {string} message - An error message to report.
# @param {Array} match - An array of match results for markers.
# @param {string} refChar - Character used for reference in the error message.
# @returns {void}
###
reportBegin = (node, message, match, refChar) ->
type = node.type.toLowerCase()
commentIdentifier = if type is 'block' then '###' else '#'
context.report {
node
fix: (fixer) ->
start = node.range[0]
end = start + commentIdentifier.length
if requireSpace
if match then end += match[0].length
return fixer.insertTextAfterRange [start, end], ' '
end += match[0].length
fixer.replaceTextRange(
[start, end]
commentIdentifier + (if match[1] then match[1] else '')
)
message
data: {refChar}
}
###*
# Reports an ending spacing error with an appropriate message.
# @param {ASTNode} node - A comment node to check.
# @param {string} message - An error message to report.
# @param {string} match - An array of the matched whitespace characters.
# @returns {void}
###
reportEnd = (node, message, match) ->
context.report {
node
fix: (fixer) ->
return fixer.insertTextAfterRange(
[node.range[0], node.range[1] - 3]
' '
) if requireSpace
end = node.range[1] - 3
start = end - match[0].length
fixer.replaceTextRange [start, end], ''
message
}
###*
# Reports a given comment if it's invalid.
# @param {ASTNode} node - a comment node to check.
# @returns {void}
###
checkCommentForSpace = (node) ->
type = node.type.toLowerCase()
rule = styleRules[type]
commentIdentifier = if type is 'block' then '###' else '#'
# Ignores empty comments.
return if node.value.length is 0
beginMatch = rule.beginRegex.exec node.value
endMatch = rule.endRegex.exec node.value
# Checks.
if requireSpace
unless beginMatch
hasMarker = rule.markers.exec node.value
marker =
if hasMarker
commentIdentifier + hasMarker[0]
else
commentIdentifier
if rule.hasExceptions
reportBegin(
node
"Expected exception block, space or tab after '{{refChar}}' in comment."
hasMarker
marker
)
else
reportBegin(
node
"Expected space or tab after '{{refChar}}' in comment."
hasMarker
marker
)
if balanced and type is 'block' and not endMatch
reportEnd node, "Expected space or tab before '###' in comment."
else
if beginMatch
unless beginMatch[1]
reportBegin(
node
"Unexpected space or tab after '{{refChar}}' in comment."
beginMatch
commentIdentifier
)
else
reportBegin(
node
'Unexpected space or tab after marker ({{refChar}}) in comment.'
beginMatch
beginMatch[1]
)
if balanced and type is 'block' and endMatch
reportEnd(
node
"Unexpected space or tab before '###' in comment."
endMatch
)
Program: ->
comments = sourceCode.getAllComments()
comments
.filter (token) -> token.type isnt 'Shebang'
.forEach checkCommentForSpace
|
[
{
"context": "iled', err\n\n genAPIKey: () ->\n key = new Buffer(16)\n uuid.v4(null, key)\n return key.to",
"end": 725,
"score": 0.9481974840164185,
"start": 716,
"tag": "KEY",
"value": "Buffer(16"
}
] | src/db/database.coffee | calzoneman/simplesnap | 3 | bookshelf = require 'bookshelf'
knex = require 'knex'
uuid = require 'uuid'
EventEmitter = require('events').EventEmitter
buildSchema = require './schema'
class Database extends EventEmitter
constructor: (@config) ->
@knex = knex(@config)
@bookshelf = bookshelf(@knex)
@ready = false
@models = require('./models')(@bookshelf)
if @knex.client == 'sqlite3'
@knex.raw('PRAGMA foreign_keys = ON;')
buildSchema(@knex).then =>
console.log 'Database initialized'
@ready = true
@emit 'ready'
.catch (err) ->
console.error 'Database initialization failed', err
genAPIKey: () ->
key = new Buffer(16)
uuid.v4(null, key)
return key.toString('base64')
genFileHash: (name) ->
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
hash = (str) ->
h = 0
for i of str
x = str.charCodeAt(i)
h = x + (h << 6) + (h << 16) - h
return h & 0x7fffffff
ts = Date.now()
ts = (ts << 1) + (hash(name) % ts)
ts = Math.abs(ts)
code = ''
while ts > 0
code += alphabet[ts % alphabet.length]
ts = Math.floor(ts / alphabet.length)
return code
addUser: () ->
if not @ready
throw new Error('Database has not been initialized yet')
User = @models.User
return User.forge(key: @genAPIKey()).save().tap((user) => @emit 'newuser', user.attributes)
addImage: (file, uploader_key = null) ->
data =
filename: [@genFileHash(file.filename), file.extension].join('.')
expires: Date.now() + file.expiration
if uploader_key
data.user_key = uploader_key
Image = @models.Image
return Image.forge(data).save().tap((image) => @emit 'newimage', image.attributes)
module.exports = Database
| 24720 | bookshelf = require 'bookshelf'
knex = require 'knex'
uuid = require 'uuid'
EventEmitter = require('events').EventEmitter
buildSchema = require './schema'
class Database extends EventEmitter
constructor: (@config) ->
@knex = knex(@config)
@bookshelf = bookshelf(@knex)
@ready = false
@models = require('./models')(@bookshelf)
if @knex.client == 'sqlite3'
@knex.raw('PRAGMA foreign_keys = ON;')
buildSchema(@knex).then =>
console.log 'Database initialized'
@ready = true
@emit 'ready'
.catch (err) ->
console.error 'Database initialization failed', err
genAPIKey: () ->
key = new <KEY>)
uuid.v4(null, key)
return key.toString('base64')
genFileHash: (name) ->
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
hash = (str) ->
h = 0
for i of str
x = str.charCodeAt(i)
h = x + (h << 6) + (h << 16) - h
return h & 0x7fffffff
ts = Date.now()
ts = (ts << 1) + (hash(name) % ts)
ts = Math.abs(ts)
code = ''
while ts > 0
code += alphabet[ts % alphabet.length]
ts = Math.floor(ts / alphabet.length)
return code
addUser: () ->
if not @ready
throw new Error('Database has not been initialized yet')
User = @models.User
return User.forge(key: @genAPIKey()).save().tap((user) => @emit 'newuser', user.attributes)
addImage: (file, uploader_key = null) ->
data =
filename: [@genFileHash(file.filename), file.extension].join('.')
expires: Date.now() + file.expiration
if uploader_key
data.user_key = uploader_key
Image = @models.Image
return Image.forge(data).save().tap((image) => @emit 'newimage', image.attributes)
module.exports = Database
| true | bookshelf = require 'bookshelf'
knex = require 'knex'
uuid = require 'uuid'
EventEmitter = require('events').EventEmitter
buildSchema = require './schema'
class Database extends EventEmitter
constructor: (@config) ->
@knex = knex(@config)
@bookshelf = bookshelf(@knex)
@ready = false
@models = require('./models')(@bookshelf)
if @knex.client == 'sqlite3'
@knex.raw('PRAGMA foreign_keys = ON;')
buildSchema(@knex).then =>
console.log 'Database initialized'
@ready = true
@emit 'ready'
.catch (err) ->
console.error 'Database initialization failed', err
genAPIKey: () ->
key = new PI:KEY:<KEY>END_PI)
uuid.v4(null, key)
return key.toString('base64')
genFileHash: (name) ->
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
hash = (str) ->
h = 0
for i of str
x = str.charCodeAt(i)
h = x + (h << 6) + (h << 16) - h
return h & 0x7fffffff
ts = Date.now()
ts = (ts << 1) + (hash(name) % ts)
ts = Math.abs(ts)
code = ''
while ts > 0
code += alphabet[ts % alphabet.length]
ts = Math.floor(ts / alphabet.length)
return code
addUser: () ->
if not @ready
throw new Error('Database has not been initialized yet')
User = @models.User
return User.forge(key: @genAPIKey()).save().tap((user) => @emit 'newuser', user.attributes)
addImage: (file, uploader_key = null) ->
data =
filename: [@genFileHash(file.filename), file.extension].join('.')
expires: Date.now() + file.expiration
if uploader_key
data.user_key = uploader_key
Image = @models.Image
return Image.forge(data).save().tap((image) => @emit 'newimage', image.attributes)
module.exports = Database
|
[
{
"context": "A256(\"s3\", kRegion);\n\tsignature_key = HmacSHA256(\"aws4_request\", kService);\n\n\tHmacSHA256 policy, signature_key\n\t",
"end": 2549,
"score": 0.8686345815658569,
"start": 2537,
"tag": "KEY",
"value": "aws4_request"
}
] | server/sign_request.coffee | jeanfredrik/meteor-s3 | 0 | Meteor.methods
_s3_sign: (ops={}) ->
@unblock()
# ops.expiration: the signature expires after x milliseconds | defaults to 30 minutes
# ops.path
# ops.file_type
# ops.file_name
# ops.file_size
# ops.acl
# ops.bucket
_.defaults ops,
expiration:1800000
path:""
bucket:S3.config.bucket
acl:"public-read"
region:S3.config.region
check ops,
expiration:Number
path:String
bucket:String
acl:String
region:String
file_type:String
file_name:String
file_size:Number
expiration = new Date Date.now() + ops.expiration
expiration = expiration.toISOString()
if _.isEmpty ops.path
key = "#{ops.file_name}"
else
key = "#{ops.path}/#{ops.file_name}"
meta_uuid = Meteor.uuid()
meta_date = "#{moment().format('YYYYMMDD')}T000000Z"
meta_credential = "#{S3.config.key}/#{moment().format('YYYYMMDD')}/#{ops.region}/s3/aws4_request"
policy =
"expiration":expiration
"conditions":[
["content-length-range",0,ops.file_size]
{"key":key}
{"bucket":ops.bucket}
{"Content-Type":ops.file_type}
{"Cache-Control":S3.config.cacheControl} if S3.config.cacheControl
{"acl":ops.acl}
# {"x-amz-server-side-encryption": "AES256"}
{"x-amz-algorithm": "AWS4-HMAC-SHA256"}
{"x-amz-credential": meta_credential}
{"x-amz-date": meta_date }
{"x-amz-meta-uuid": meta_uuid}
]
# Encode the policy
policy = new Buffer(JSON.stringify(policy), "utf-8").toString("base64")
# Sign the policy
signature = calculate_signature policy, ops.region
# Identify post_url
if ops.region is "us-east-1" or ops.region is "us-standard"
post_url = "https://s3.amazonaws.com/#{ops.bucket}"
else
post_url = "https://s3-#{ops.region}.amazonaws.com/#{ops.bucket}"
# Return results
policy:policy
signature:signature
access_key:S3.config.key
post_url:post_url
url:"#{post_url}/#{key}".replace("https://","http://")
secure_url:"#{post_url}/#{key}"
relative_url:"/#{key}"
bucket:ops.bucket
acl:ops.acl
key:key
file_type:ops.file_type
file_name:ops.file_name
meta_uuid:meta_uuid
meta_date:meta_date
meta_credential:meta_credential
cache_control:S3.config.cacheControl
# crypto = Npm.require("crypto")
Crypto = Npm.require "crypto-js"
moment = Npm.require "moment"
{HmacSHA256} = Crypto
calculate_signature = (policy, region) ->
kDate = HmacSHA256(moment().format("YYYYMMDD"), "AWS4" + S3.config.secret);
kRegion = HmacSHA256(region, kDate);
kService = HmacSHA256("s3", kRegion);
signature_key = HmacSHA256("aws4_request", kService);
HmacSHA256 policy, signature_key
.toString Crypto.enc.Hex
| 170051 | Meteor.methods
_s3_sign: (ops={}) ->
@unblock()
# ops.expiration: the signature expires after x milliseconds | defaults to 30 minutes
# ops.path
# ops.file_type
# ops.file_name
# ops.file_size
# ops.acl
# ops.bucket
_.defaults ops,
expiration:1800000
path:""
bucket:S3.config.bucket
acl:"public-read"
region:S3.config.region
check ops,
expiration:Number
path:String
bucket:String
acl:String
region:String
file_type:String
file_name:String
file_size:Number
expiration = new Date Date.now() + ops.expiration
expiration = expiration.toISOString()
if _.isEmpty ops.path
key = "#{ops.file_name}"
else
key = "#{ops.path}/#{ops.file_name}"
meta_uuid = Meteor.uuid()
meta_date = "#{moment().format('YYYYMMDD')}T000000Z"
meta_credential = "#{S3.config.key}/#{moment().format('YYYYMMDD')}/#{ops.region}/s3/aws4_request"
policy =
"expiration":expiration
"conditions":[
["content-length-range",0,ops.file_size]
{"key":key}
{"bucket":ops.bucket}
{"Content-Type":ops.file_type}
{"Cache-Control":S3.config.cacheControl} if S3.config.cacheControl
{"acl":ops.acl}
# {"x-amz-server-side-encryption": "AES256"}
{"x-amz-algorithm": "AWS4-HMAC-SHA256"}
{"x-amz-credential": meta_credential}
{"x-amz-date": meta_date }
{"x-amz-meta-uuid": meta_uuid}
]
# Encode the policy
policy = new Buffer(JSON.stringify(policy), "utf-8").toString("base64")
# Sign the policy
signature = calculate_signature policy, ops.region
# Identify post_url
if ops.region is "us-east-1" or ops.region is "us-standard"
post_url = "https://s3.amazonaws.com/#{ops.bucket}"
else
post_url = "https://s3-#{ops.region}.amazonaws.com/#{ops.bucket}"
# Return results
policy:policy
signature:signature
access_key:S3.config.key
post_url:post_url
url:"#{post_url}/#{key}".replace("https://","http://")
secure_url:"#{post_url}/#{key}"
relative_url:"/#{key}"
bucket:ops.bucket
acl:ops.acl
key:key
file_type:ops.file_type
file_name:ops.file_name
meta_uuid:meta_uuid
meta_date:meta_date
meta_credential:meta_credential
cache_control:S3.config.cacheControl
# crypto = Npm.require("crypto")
Crypto = Npm.require "crypto-js"
moment = Npm.require "moment"
{HmacSHA256} = Crypto
calculate_signature = (policy, region) ->
kDate = HmacSHA256(moment().format("YYYYMMDD"), "AWS4" + S3.config.secret);
kRegion = HmacSHA256(region, kDate);
kService = HmacSHA256("s3", kRegion);
signature_key = HmacSHA256("<KEY>", kService);
HmacSHA256 policy, signature_key
.toString Crypto.enc.Hex
| true | Meteor.methods
_s3_sign: (ops={}) ->
@unblock()
# ops.expiration: the signature expires after x milliseconds | defaults to 30 minutes
# ops.path
# ops.file_type
# ops.file_name
# ops.file_size
# ops.acl
# ops.bucket
_.defaults ops,
expiration:1800000
path:""
bucket:S3.config.bucket
acl:"public-read"
region:S3.config.region
check ops,
expiration:Number
path:String
bucket:String
acl:String
region:String
file_type:String
file_name:String
file_size:Number
expiration = new Date Date.now() + ops.expiration
expiration = expiration.toISOString()
if _.isEmpty ops.path
key = "#{ops.file_name}"
else
key = "#{ops.path}/#{ops.file_name}"
meta_uuid = Meteor.uuid()
meta_date = "#{moment().format('YYYYMMDD')}T000000Z"
meta_credential = "#{S3.config.key}/#{moment().format('YYYYMMDD')}/#{ops.region}/s3/aws4_request"
policy =
"expiration":expiration
"conditions":[
["content-length-range",0,ops.file_size]
{"key":key}
{"bucket":ops.bucket}
{"Content-Type":ops.file_type}
{"Cache-Control":S3.config.cacheControl} if S3.config.cacheControl
{"acl":ops.acl}
# {"x-amz-server-side-encryption": "AES256"}
{"x-amz-algorithm": "AWS4-HMAC-SHA256"}
{"x-amz-credential": meta_credential}
{"x-amz-date": meta_date }
{"x-amz-meta-uuid": meta_uuid}
]
# Encode the policy
policy = new Buffer(JSON.stringify(policy), "utf-8").toString("base64")
# Sign the policy
signature = calculate_signature policy, ops.region
# Identify post_url
if ops.region is "us-east-1" or ops.region is "us-standard"
post_url = "https://s3.amazonaws.com/#{ops.bucket}"
else
post_url = "https://s3-#{ops.region}.amazonaws.com/#{ops.bucket}"
# Return results
policy:policy
signature:signature
access_key:S3.config.key
post_url:post_url
url:"#{post_url}/#{key}".replace("https://","http://")
secure_url:"#{post_url}/#{key}"
relative_url:"/#{key}"
bucket:ops.bucket
acl:ops.acl
key:key
file_type:ops.file_type
file_name:ops.file_name
meta_uuid:meta_uuid
meta_date:meta_date
meta_credential:meta_credential
cache_control:S3.config.cacheControl
# crypto = Npm.require("crypto")
Crypto = Npm.require "crypto-js"
moment = Npm.require "moment"
{HmacSHA256} = Crypto
calculate_signature = (policy, region) ->
kDate = HmacSHA256(moment().format("YYYYMMDD"), "AWS4" + S3.config.secret);
kRegion = HmacSHA256(region, kDate);
kService = HmacSHA256("s3", kRegion);
signature_key = HmacSHA256("PI:KEY:<KEY>END_PI", kService);
HmacSHA256 policy, signature_key
.toString Crypto.enc.Hex
|
[
{
"context": "\n\ndescribe 'NotificationsHandler', ->\n\tuser_id = \"123nd3ijdks\"\n\tnotification_id = \"123njdskj9jlk\"\n\tnotification",
"end": 328,
"score": 0.7997351884841919,
"start": 317,
"tag": "USERNAME",
"value": "123nd3ijdks"
},
{
"context": "cribe \"markAsRead\", ->\n\t\t... | test/UnitTests/coffee/Notifications/NotificationsHandlerTests.coffee | bowlofstew/web-sharelatex | 0 | SandboxedModule = require('sandboxed-module')
assert = require('chai').assert
require('chai').should()
sinon = require('sinon')
modulePath = require('path').join __dirname, '../../../../app/js/Features/Notifications/NotificationsHandler.js'
_ = require('underscore')
describe 'NotificationsHandler', ->
user_id = "123nd3ijdks"
notification_id = "123njdskj9jlk"
notificationUrl = "notification.sharelatex.testing"
beforeEach ->
@request = sinon.stub().callsArgWith(1)
@handler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": apis:{notifications:{url:notificationUrl}}
"request":@request
'logger-sharelatex':
log:->
err:->
describe "getUserNotifications", ->
it 'should get unread notifications', (done)->
stubbedNotifications = [{_id: notification_id, user_id: user_id}]
@request.callsArgWith(1, null, {statusCode:200}, stubbedNotifications)
@handler.getUserNotifications user_id, (err, unreadNotifications)=>
stubbedNotifications.should.deep.equal unreadNotifications
getOpts =
uri: "#{notificationUrl}/user/#{user_id}"
json:true
timeout:1000
method: "GET"
@request.calledWith(getOpts).should.equal true
done()
it 'should return empty arrays if there are no notifications', ->
@request.callsArgWith(1, null, {statusCode:200}, null)
@handler.getUserNotifications user_id, (err, unreadNotifications)=>
unreadNotifications.length.should.equal 0
describe "markAsRead", ->
beforeEach ->
@key = "some key here"
it 'should send a delete request when a delete has been received to mark a notification', (done)->
@handler.markAsReadWithKey user_id, @key, =>
opts =
uri: "#{notificationUrl}/user/#{user_id}"
json:
key:@key
timeout:1000
method: "DELETE"
@request.calledWith(opts).should.equal true
done()
describe "createNotification", ->
beforeEach ->
@key = "some key here"
@messageOpts = {value:12344}
@templateKey = "renderThisHtml"
it "should post the message over", (done)->
@handler.createNotification user_id, @key, @templateKey, @messageOpts, =>
args = @request.args[0][0]
args.uri.should.equal "#{notificationUrl}/user/#{user_id}"
args.timeout.should.equal 1000
expectedJson = {key:@key, templateKey:@templateKey, messageOpts:@messageOpts}
assert.deepEqual(args.json, expectedJson)
done() | 223178 | SandboxedModule = require('sandboxed-module')
assert = require('chai').assert
require('chai').should()
sinon = require('sinon')
modulePath = require('path').join __dirname, '../../../../app/js/Features/Notifications/NotificationsHandler.js'
_ = require('underscore')
describe 'NotificationsHandler', ->
user_id = "123nd3ijdks"
notification_id = "123njdskj9jlk"
notificationUrl = "notification.sharelatex.testing"
beforeEach ->
@request = sinon.stub().callsArgWith(1)
@handler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": apis:{notifications:{url:notificationUrl}}
"request":@request
'logger-sharelatex':
log:->
err:->
describe "getUserNotifications", ->
it 'should get unread notifications', (done)->
stubbedNotifications = [{_id: notification_id, user_id: user_id}]
@request.callsArgWith(1, null, {statusCode:200}, stubbedNotifications)
@handler.getUserNotifications user_id, (err, unreadNotifications)=>
stubbedNotifications.should.deep.equal unreadNotifications
getOpts =
uri: "#{notificationUrl}/user/#{user_id}"
json:true
timeout:1000
method: "GET"
@request.calledWith(getOpts).should.equal true
done()
it 'should return empty arrays if there are no notifications', ->
@request.callsArgWith(1, null, {statusCode:200}, null)
@handler.getUserNotifications user_id, (err, unreadNotifications)=>
unreadNotifications.length.should.equal 0
describe "markAsRead", ->
beforeEach ->
@key = "<KEY>"
it 'should send a delete request when a delete has been received to mark a notification', (done)->
@handler.markAsReadWithKey user_id, @key, =>
opts =
uri: "#{notificationUrl}/user/#{user_id}"
json:
key:@key
timeout:1000
method: "DELETE"
@request.calledWith(opts).should.equal true
done()
describe "createNotification", ->
beforeEach ->
@key = "<KEY>"
@messageOpts = {value:12344}
@templateKey = "<KEY>"
it "should post the message over", (done)->
@handler.createNotification user_id, @key, @templateKey, @messageOpts, =>
args = @request.args[0][0]
args.uri.should.equal "#{notificationUrl}/user/#{user_id}"
args.timeout.should.equal 1000
expectedJson = {key:@key, templateKey:@templateKey, messageOpts:@messageOpts}
assert.deepEqual(args.json, expectedJson)
done() | true | SandboxedModule = require('sandboxed-module')
assert = require('chai').assert
require('chai').should()
sinon = require('sinon')
modulePath = require('path').join __dirname, '../../../../app/js/Features/Notifications/NotificationsHandler.js'
_ = require('underscore')
describe 'NotificationsHandler', ->
user_id = "123nd3ijdks"
notification_id = "123njdskj9jlk"
notificationUrl = "notification.sharelatex.testing"
beforeEach ->
@request = sinon.stub().callsArgWith(1)
@handler = SandboxedModule.require modulePath, requires:
"settings-sharelatex": apis:{notifications:{url:notificationUrl}}
"request":@request
'logger-sharelatex':
log:->
err:->
describe "getUserNotifications", ->
it 'should get unread notifications', (done)->
stubbedNotifications = [{_id: notification_id, user_id: user_id}]
@request.callsArgWith(1, null, {statusCode:200}, stubbedNotifications)
@handler.getUserNotifications user_id, (err, unreadNotifications)=>
stubbedNotifications.should.deep.equal unreadNotifications
getOpts =
uri: "#{notificationUrl}/user/#{user_id}"
json:true
timeout:1000
method: "GET"
@request.calledWith(getOpts).should.equal true
done()
it 'should return empty arrays if there are no notifications', ->
@request.callsArgWith(1, null, {statusCode:200}, null)
@handler.getUserNotifications user_id, (err, unreadNotifications)=>
unreadNotifications.length.should.equal 0
describe "markAsRead", ->
beforeEach ->
@key = "PI:KEY:<KEY>END_PI"
it 'should send a delete request when a delete has been received to mark a notification', (done)->
@handler.markAsReadWithKey user_id, @key, =>
opts =
uri: "#{notificationUrl}/user/#{user_id}"
json:
key:@key
timeout:1000
method: "DELETE"
@request.calledWith(opts).should.equal true
done()
describe "createNotification", ->
beforeEach ->
@key = "PI:KEY:<KEY>END_PI"
@messageOpts = {value:12344}
@templateKey = "PI:KEY:<KEY>END_PI"
it "should post the message over", (done)->
@handler.createNotification user_id, @key, @templateKey, @messageOpts, =>
args = @request.args[0][0]
args.uri.should.equal "#{notificationUrl}/user/#{user_id}"
args.timeout.should.equal 1000
expectedJson = {key:@key, templateKey:@templateKey, messageOpts:@messageOpts}
assert.deepEqual(args.json, expectedJson)
done() |
[
{
"context": " require set-dom\n#= require nitrolinks/utilities\n\n@nitro = ((document, window, pu, setDOM) ->\n getCsrfTok",
"end": 58,
"score": 0.8902931213378906,
"start": 52,
"tag": "USERNAME",
"value": "@nitro"
},
{
"context": "')\n\n saveState = (url, method, body) ->\n ke... | app/assets/javascripts/nitrolinks.coffee | asartalo/nitrolinks-rails | 0 | #= require set-dom
#= require nitrolinks/utilities
@nitro = ((document, window, pu, setDOM) ->
getCsrfToken = ->
pu.getContentOfElement('meta[name="csrf-token"]')
getCsrfParam = ->
pu.getContentOfElement('meta[name="csrf-param"]')
nitro = {
appHost: window.location.origin
csrfToken: getCsrfToken()
csrfParam: getCsrfParam()
}
# TODO: This holds too much information to just store in sessionStorage
cache = (key, value) ->
window.sessionStorage.setItem(key, JSON.stringify(value))
getCache = (key) ->
JSON.parse(window.sessionStorage.getItem(key))
getAppElement = ->
document.getElementsByTagName('html')[0]
isUrlAllowed = (url) ->
from = window.location
url.origin == nitro.appHost && isNewNavigation(from, url)
isNewNavigation = (fromUrl, toUrl) ->
if toUrl.pathname != fromUrl.pathname || toUrl.search != fromUrl.search
true
else
!isHashChanged(fromUrl, toUrl)
isHashChanged = (fromUrl, toUrl) ->
if toUrl.hash != fromUrl.hash
true
else
urlIsHashed(toUrl) || urlIsHashed(fromUrl)
urlIsHashed = (url) ->
url.toString().match(/#/)
urlPath = (urlStr) ->
urlPathFromUrl(new URL(urlStr))
urlPathFromUrl = (url) ->
if url.origin == url.toString()
url.pathname
else
url.toString().replace(url.origin, '')
hasEmptyHash = (url) ->
url.toString().match(/#/) && url.hash == ""
fullPath = (urlStr) ->
if urlStr.indexOf(nitro.appHost) != 0
"#{nitro.appHost}/#{urlStr.match(/^\/?(.+$)/)[1]}"
else
urlStr
pushTheState = (state, location) ->
window.history.pushState(state, null, location)
replaceTheState = (state, location) ->
window.history.replaceState(state, null, location)
onPopState = (fn) ->
window.addEventListener 'popstate',
(e) ->
state = e.state
return unless state
fn(getState(state))
pu.whenReady ->
state = window.history.state
if hasState(state) && !pu.isCurrentPageReloaded()
loadState(getState(state))
else
location = urlPath(window.location)
method = 'get'
appCode = getAppElement().outerHTML
renderState(preloadContent(appCode))
state = saveState(location, method, appCode)
replaceTheState(state, location)
pu.triggerEvent 'nitrolinks:load', url: location
pu.handleLinkClicks (url, e) ->
if isUrlAllowed(url)
e.preventDefault()
visit(url, method: 'get')
e.stopPropagation()
pu.handleFormSubmits (form, e) ->
url = new URL(form.action)
data = null
method = form.method.toLowerCase()
if method == 'get'
url.search = $(form).serialize()
else if method == 'post'
data = new FormData(form)
if isUrlAllowed(url)
e.preventDefault()
visit(url, method: form.method, body: data)
e.stopPropagation()
fetchComplete = (url, theOptions = {}) ->
options = pu.merge({method: 'get', pushState: true}, theOptions)
(response) ->
# return unless response.ok
method = options.method
pushState = options.pushState
response.text().then (contents) ->
pageSource = extractPageSource(contents)
unless pageSource
pu.triggerEvent 'nitrolinks:load-blank'
return
if response.headers.has("nitrolinks-location")
location = urlPath(response.headers.get("nitrolinks-location"))
else
location = urlPath(url)
state = saveState(location, method, pageSource)
renderState(preloadContent(pageSource))
pushTheState(state, location) if pushState
pu.triggerEvent 'nitrolinks:load-from-fetch', url: location
pu.triggerEvent 'nitrolinks:load', url: location
extractPageSource = (text) ->
code = text.trim()
match = code.match(/<html[^>]*>([\s\S]+)<\/html>/)
return null unless match
(match[0]).trim()
visit = (url, theOptions = {}) ->
options = pu.merge({method: 'get', pushState: true}, theOptions)
event = pu.triggerEvent 'nitrolinks:visit'
return if event.defaultPrevented
fetch(url, nitroFetchOptions(options)).then(
fetchComplete(url, options)
).catch( (error, a) ->
window.location = url
)
visitCached = (stateObj) ->
pu.triggerEvent 'nitrolinks:visit'
renderState(preloadContent(stateObj.content))
pu.triggerEvent 'nitrolinks:load-from-cache', url: stateObj.url
pu.triggerEvent 'nitrolinks:load', url: stateObj.url
nitroFetchOptions = (options) ->
headers = {
"nitrolinks-referrer": window.location.href
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
if options.method == 'post'
headers["x-csrf-token"] = getCsrfToken()
method: options.method
redirect: 'follow'
credentials: 'include'
body: options.body
headers: headers
loadState = (stateObj) ->
if stateObj.url
url = new URL(fullPath(stateObj.url))
else
url = false
if stateObj.content
visitCached(stateObj)
else if url && stateObj.method
visit(url, method: stateObj.method, pushState: false)
else if url
visit(url, method: 'get', pushState: false)
else
visit(window.location.href, method: 'get', pushState: false)
onPopState(loadState)
renderState = (content) ->
setDOM(getAppElement(), content)
preloadContent = (content) ->
# TODO: Is there a better way to do this?
content.replace('<html', '<html class="js"')
saveState = (url, method, body) ->
key = pu.uuid()
cache(key, url: url, method: method, body: body)
return key
getState = (state) ->
savedState = getCache(state)
if state && savedState
{
method: savedState.method
url: savedState.url
content: savedState.body
}
else
{
method: null
url: null
content: null
}
hasState = (state) ->
savedState = getCache(state)
state && savedState
parseState = (state) ->
match = (state || '').match(/^(\w+):(.+)$/)
method: match[1], url: match[2]
return {
}
)(document, window, pu, setDOM)
| 157957 | #= require set-dom
#= require nitrolinks/utilities
@nitro = ((document, window, pu, setDOM) ->
getCsrfToken = ->
pu.getContentOfElement('meta[name="csrf-token"]')
getCsrfParam = ->
pu.getContentOfElement('meta[name="csrf-param"]')
nitro = {
appHost: window.location.origin
csrfToken: getCsrfToken()
csrfParam: getCsrfParam()
}
# TODO: This holds too much information to just store in sessionStorage
cache = (key, value) ->
window.sessionStorage.setItem(key, JSON.stringify(value))
getCache = (key) ->
JSON.parse(window.sessionStorage.getItem(key))
getAppElement = ->
document.getElementsByTagName('html')[0]
isUrlAllowed = (url) ->
from = window.location
url.origin == nitro.appHost && isNewNavigation(from, url)
isNewNavigation = (fromUrl, toUrl) ->
if toUrl.pathname != fromUrl.pathname || toUrl.search != fromUrl.search
true
else
!isHashChanged(fromUrl, toUrl)
isHashChanged = (fromUrl, toUrl) ->
if toUrl.hash != fromUrl.hash
true
else
urlIsHashed(toUrl) || urlIsHashed(fromUrl)
urlIsHashed = (url) ->
url.toString().match(/#/)
urlPath = (urlStr) ->
urlPathFromUrl(new URL(urlStr))
urlPathFromUrl = (url) ->
if url.origin == url.toString()
url.pathname
else
url.toString().replace(url.origin, '')
hasEmptyHash = (url) ->
url.toString().match(/#/) && url.hash == ""
fullPath = (urlStr) ->
if urlStr.indexOf(nitro.appHost) != 0
"#{nitro.appHost}/#{urlStr.match(/^\/?(.+$)/)[1]}"
else
urlStr
pushTheState = (state, location) ->
window.history.pushState(state, null, location)
replaceTheState = (state, location) ->
window.history.replaceState(state, null, location)
onPopState = (fn) ->
window.addEventListener 'popstate',
(e) ->
state = e.state
return unless state
fn(getState(state))
pu.whenReady ->
state = window.history.state
if hasState(state) && !pu.isCurrentPageReloaded()
loadState(getState(state))
else
location = urlPath(window.location)
method = 'get'
appCode = getAppElement().outerHTML
renderState(preloadContent(appCode))
state = saveState(location, method, appCode)
replaceTheState(state, location)
pu.triggerEvent 'nitrolinks:load', url: location
pu.handleLinkClicks (url, e) ->
if isUrlAllowed(url)
e.preventDefault()
visit(url, method: 'get')
e.stopPropagation()
pu.handleFormSubmits (form, e) ->
url = new URL(form.action)
data = null
method = form.method.toLowerCase()
if method == 'get'
url.search = $(form).serialize()
else if method == 'post'
data = new FormData(form)
if isUrlAllowed(url)
e.preventDefault()
visit(url, method: form.method, body: data)
e.stopPropagation()
fetchComplete = (url, theOptions = {}) ->
options = pu.merge({method: 'get', pushState: true}, theOptions)
(response) ->
# return unless response.ok
method = options.method
pushState = options.pushState
response.text().then (contents) ->
pageSource = extractPageSource(contents)
unless pageSource
pu.triggerEvent 'nitrolinks:load-blank'
return
if response.headers.has("nitrolinks-location")
location = urlPath(response.headers.get("nitrolinks-location"))
else
location = urlPath(url)
state = saveState(location, method, pageSource)
renderState(preloadContent(pageSource))
pushTheState(state, location) if pushState
pu.triggerEvent 'nitrolinks:load-from-fetch', url: location
pu.triggerEvent 'nitrolinks:load', url: location
extractPageSource = (text) ->
code = text.trim()
match = code.match(/<html[^>]*>([\s\S]+)<\/html>/)
return null unless match
(match[0]).trim()
visit = (url, theOptions = {}) ->
options = pu.merge({method: 'get', pushState: true}, theOptions)
event = pu.triggerEvent 'nitrolinks:visit'
return if event.defaultPrevented
fetch(url, nitroFetchOptions(options)).then(
fetchComplete(url, options)
).catch( (error, a) ->
window.location = url
)
visitCached = (stateObj) ->
pu.triggerEvent 'nitrolinks:visit'
renderState(preloadContent(stateObj.content))
pu.triggerEvent 'nitrolinks:load-from-cache', url: stateObj.url
pu.triggerEvent 'nitrolinks:load', url: stateObj.url
nitroFetchOptions = (options) ->
headers = {
"nitrolinks-referrer": window.location.href
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
if options.method == 'post'
headers["x-csrf-token"] = getCsrfToken()
method: options.method
redirect: 'follow'
credentials: 'include'
body: options.body
headers: headers
loadState = (stateObj) ->
if stateObj.url
url = new URL(fullPath(stateObj.url))
else
url = false
if stateObj.content
visitCached(stateObj)
else if url && stateObj.method
visit(url, method: stateObj.method, pushState: false)
else if url
visit(url, method: 'get', pushState: false)
else
visit(window.location.href, method: 'get', pushState: false)
onPopState(loadState)
renderState = (content) ->
setDOM(getAppElement(), content)
preloadContent = (content) ->
# TODO: Is there a better way to do this?
content.replace('<html', '<html class="js"')
saveState = (url, method, body) ->
key = <KEY>
cache(key, url: url, method: method, body: body)
return key
getState = (state) ->
savedState = getCache(state)
if state && savedState
{
method: savedState.method
url: savedState.url
content: savedState.body
}
else
{
method: null
url: null
content: null
}
hasState = (state) ->
savedState = getCache(state)
state && savedState
parseState = (state) ->
match = (state || '').match(/^(\w+):(.+)$/)
method: match[1], url: match[2]
return {
}
)(document, window, pu, setDOM)
| true | #= require set-dom
#= require nitrolinks/utilities
@nitro = ((document, window, pu, setDOM) ->
getCsrfToken = ->
pu.getContentOfElement('meta[name="csrf-token"]')
getCsrfParam = ->
pu.getContentOfElement('meta[name="csrf-param"]')
nitro = {
appHost: window.location.origin
csrfToken: getCsrfToken()
csrfParam: getCsrfParam()
}
# TODO: This holds too much information to just store in sessionStorage
cache = (key, value) ->
window.sessionStorage.setItem(key, JSON.stringify(value))
getCache = (key) ->
JSON.parse(window.sessionStorage.getItem(key))
getAppElement = ->
document.getElementsByTagName('html')[0]
isUrlAllowed = (url) ->
from = window.location
url.origin == nitro.appHost && isNewNavigation(from, url)
isNewNavigation = (fromUrl, toUrl) ->
if toUrl.pathname != fromUrl.pathname || toUrl.search != fromUrl.search
true
else
!isHashChanged(fromUrl, toUrl)
isHashChanged = (fromUrl, toUrl) ->
if toUrl.hash != fromUrl.hash
true
else
urlIsHashed(toUrl) || urlIsHashed(fromUrl)
urlIsHashed = (url) ->
url.toString().match(/#/)
urlPath = (urlStr) ->
urlPathFromUrl(new URL(urlStr))
urlPathFromUrl = (url) ->
if url.origin == url.toString()
url.pathname
else
url.toString().replace(url.origin, '')
hasEmptyHash = (url) ->
url.toString().match(/#/) && url.hash == ""
fullPath = (urlStr) ->
if urlStr.indexOf(nitro.appHost) != 0
"#{nitro.appHost}/#{urlStr.match(/^\/?(.+$)/)[1]}"
else
urlStr
pushTheState = (state, location) ->
window.history.pushState(state, null, location)
replaceTheState = (state, location) ->
window.history.replaceState(state, null, location)
onPopState = (fn) ->
window.addEventListener 'popstate',
(e) ->
state = e.state
return unless state
fn(getState(state))
pu.whenReady ->
state = window.history.state
if hasState(state) && !pu.isCurrentPageReloaded()
loadState(getState(state))
else
location = urlPath(window.location)
method = 'get'
appCode = getAppElement().outerHTML
renderState(preloadContent(appCode))
state = saveState(location, method, appCode)
replaceTheState(state, location)
pu.triggerEvent 'nitrolinks:load', url: location
pu.handleLinkClicks (url, e) ->
if isUrlAllowed(url)
e.preventDefault()
visit(url, method: 'get')
e.stopPropagation()
pu.handleFormSubmits (form, e) ->
url = new URL(form.action)
data = null
method = form.method.toLowerCase()
if method == 'get'
url.search = $(form).serialize()
else if method == 'post'
data = new FormData(form)
if isUrlAllowed(url)
e.preventDefault()
visit(url, method: form.method, body: data)
e.stopPropagation()
fetchComplete = (url, theOptions = {}) ->
options = pu.merge({method: 'get', pushState: true}, theOptions)
(response) ->
# return unless response.ok
method = options.method
pushState = options.pushState
response.text().then (contents) ->
pageSource = extractPageSource(contents)
unless pageSource
pu.triggerEvent 'nitrolinks:load-blank'
return
if response.headers.has("nitrolinks-location")
location = urlPath(response.headers.get("nitrolinks-location"))
else
location = urlPath(url)
state = saveState(location, method, pageSource)
renderState(preloadContent(pageSource))
pushTheState(state, location) if pushState
pu.triggerEvent 'nitrolinks:load-from-fetch', url: location
pu.triggerEvent 'nitrolinks:load', url: location
extractPageSource = (text) ->
code = text.trim()
match = code.match(/<html[^>]*>([\s\S]+)<\/html>/)
return null unless match
(match[0]).trim()
visit = (url, theOptions = {}) ->
options = pu.merge({method: 'get', pushState: true}, theOptions)
event = pu.triggerEvent 'nitrolinks:visit'
return if event.defaultPrevented
fetch(url, nitroFetchOptions(options)).then(
fetchComplete(url, options)
).catch( (error, a) ->
window.location = url
)
visitCached = (stateObj) ->
pu.triggerEvent 'nitrolinks:visit'
renderState(preloadContent(stateObj.content))
pu.triggerEvent 'nitrolinks:load-from-cache', url: stateObj.url
pu.triggerEvent 'nitrolinks:load', url: stateObj.url
nitroFetchOptions = (options) ->
headers = {
"nitrolinks-referrer": window.location.href
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
if options.method == 'post'
headers["x-csrf-token"] = getCsrfToken()
method: options.method
redirect: 'follow'
credentials: 'include'
body: options.body
headers: headers
loadState = (stateObj) ->
if stateObj.url
url = new URL(fullPath(stateObj.url))
else
url = false
if stateObj.content
visitCached(stateObj)
else if url && stateObj.method
visit(url, method: stateObj.method, pushState: false)
else if url
visit(url, method: 'get', pushState: false)
else
visit(window.location.href, method: 'get', pushState: false)
onPopState(loadState)
renderState = (content) ->
setDOM(getAppElement(), content)
preloadContent = (content) ->
# TODO: Is there a better way to do this?
content.replace('<html', '<html class="js"')
saveState = (url, method, body) ->
key = PI:KEY:<KEY>END_PI
cache(key, url: url, method: method, body: body)
return key
getState = (state) ->
savedState = getCache(state)
if state && savedState
{
method: savedState.method
url: savedState.url
content: savedState.body
}
else
{
method: null
url: null
content: null
}
hasState = (state) ->
savedState = getCache(state)
state && savedState
parseState = (state) ->
match = (state || '').match(/^(\w+):(.+)$/)
method: match[1], url: match[2]
return {
}
)(document, window, pu, setDOM)
|
[
{
"context": " pic: encodeURI pic\n name: name\n link: url\n desc: c",
"end": 3561,
"score": 0.9767722487449646,
"start": 3557,
"tag": "NAME",
"value": "name"
}
] | API/src/scraper.coffee | codeforcologne/CutePetsCologne | 0 | cheerio = require 'cheerio'
request = require 'request'
express = require 'express'
NodeCache = require 'node-cache'
iconvlite = require 'iconv-lite'
fs = require 'fs'
_ = require 'underscore'
app = express()
cache = new NodeCache()
# Zollstock
zollstock_urls = ["http://www.tierheim-koeln-zollstock.de/tiervermittlung/katzen.html",
"http://www.tierheim-koeln-zollstock.de/tiervermittlung/hunde.html",
"http://www.tierheim-koeln-zollstock.de/tiervermittlung/nagetiere.html"];
zollstock_base_url = "http://www.tierheim-koeln-zollstock.de"
#Dellbrück
dellbrueck_urls = ["http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+kleine+Hunde+&f_funktion=Uebersicht",
"http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+gro%DFe+Hunde+&f_funktion=Uebersicht",
"http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+Katzen&f_funktion=Uebersicht"];
dellbrueck_base_url = "http://presenter.comedius.de/design/bmt_koeln_standard_10001.php"
dellbrueck_pic_url = "http://presenter.comedius.de/pic/bmt_koeln_d620d9faeeb43f717c893b5c818f1287"
get_zollstock_tier = (url)->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
$ = cheerio.load body
content = $('.animalDetail')
name = content.find('h1').first().text()
img = content.find('.lightbox-image').attr('href')
pic = zollstock_base_url + '/' + img
id = content.find('h1').attr('id')
content.find('h1').remove()
content.find('a').remove()
details =
id: id
pic: encodeURI pic
name: name
link: url
desc: content.find('.animalDescription p')
.text().trim().replace(/[\r|\n]+/g, '. ')
.replace(/\t+/g, ' ')
.trim()
f details
get_zollstock_urls = (url) ->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
urls = []
$ = cheerio.load body
$('.animalOverviewItem').each ->
elem = $(this)
detail_url = zollstock_base_url + elem.find('.more').attr('href')
console.log(detail_url)
urls.push detail_url
f urls
get_dellbrueck_tier = (url)->
new Promise (f, r) ->
request (uri: url, encoding: "ISO-8859-1"), (err, response, body) ->
if err
r err
$ = cheerio.load body
content = $('p[style="font-family:Verdana;font-size:13px;font-style:normal;font-weight:normal;color:#756d58;vertical-align:top"]').first()
name = content.find('b').first().text()
img = $('#bild_0').attr('src')
pic = ""
if (img)
start = img.lastIndexOf("/")
pic = dellbrueck_pic_url + img.substr(start)
start = url.indexOf("&f_aktueller_ds=")
id = url.substr(start+16)
end = id.indexOf("&")
id = id.substr(0, end)
content.find('b').remove()
details =
id: id
pic: encodeURI pic
name: name
link: url
desc: content
.contents()
.not('b')
.not('form')
.text().trim()
.replace(/[\r|\n]+/g, '. ')
.replace(/\t+/g, ' ')
.trim()
f details
get_dellbrueck_sub_urls = (url) ->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
sub_urls = []
$ = cheerio.load body
$('a#TextSeitenanzeige').each ->
elem = $(this)
detail_url = dellbrueck_base_url + elem.attr('href')
sub_urls.push detail_url
f sub_urls
get_dellbrueck_urls_for_page = (sub_url) ->
new Promise (f, r) ->
request sub_url, (err, response, body) ->
if err
r err
urls = []
$ = cheerio.load body
$('a[style="border-style:none;background-color:#ece9e2;vertical-align:top;font:normal 13px Verdana; color:#756d58"]').each ->
elem = $(this)
detail_url = dellbrueck_base_url + elem.attr('href')
urls.push detail_url
f urls
get_dellbrueck_urls = (url) ->
new Promise (f, r) ->
urls = []
p = []
get_dellbrueck_sub_urls url
.then (sub_urls) ->
for sub_url in sub_urls
p.push get_dellbrueck_urls_for_page sub_url
Promise.all p
.then (page_urls) ->
for page_url in page_urls
for animal_url in page_url
urls.push animal_url
.then () ->
f urls
get_zollstockdata = (tier_url)->
new Promise (f, r) ->
get_zollstock_urls tier_url
.then (urls) ->
p = []
for url in urls
console.log(url)
p.push get_zollstock_tier url
Promise.all p
.then (values) ->
f values
.catch (err) ->
r err
get_dellbrueckdata = (tier_url)->
new Promise (f, r) ->
get_dellbrueck_urls tier_url
.then (urls) ->
p = []
for url in urls
console.log(url)
p.push get_dellbrueck_tier url
Promise.all p
.then (values) ->
f values
.catch (err) ->
r err
get_data = ->
new Promise (f ,r) ->
p = []
iconvlite.extendNodeEncodings()
for url in zollstock_urls
p.push get_zollstockdata url
for url in dellbrueck_urls
p.push get_dellbrueckdata url
Promise.all p
.then (list_of_values) ->
values = _.union.apply null, list_of_values
cache.set('tiere', values, 60*60*24)
f values
.catch (err) ->
r err
# get a pet that was not posted yet
get_notPostedPet = ->
new Promise (f, r) ->
filename = '/var/cache/petscologne/posted_pets.json'
try
if fs.existsSync(filename)
postedPets = JSON.parse fs.readFileSync filename, 'utf8'
else
fs.writeFileSync filename, JSON.stringify []
postedPets = []
console.log('file does not exist')
catch err
r err
get_data().then (pets) ->
notPostedPets = []
for pet in pets
if pet.id not in postedPets
notPostedPets.push pet
if notPostedPets.length is 0
notPostedPets = pets
postedPets = []
random = Math.ceil Math.random()*notPostedPets.length-1
notPostedPet = notPostedPets[random]
postedPets.push notPostedPet.id
fs.writeFileSync filename, JSON.stringify postedPets
f notPostedPet
###
get_data().then (values) ->
console.log values.length
get_notPostedPet().then (pet) ->
console.log pet
###
# Return all pets
app.get '/', (req, res) ->
get_data()
.then (pets) ->
res.json pets
.catch (err) ->
console.error err
res.status(500).json(err)
# Return a random pet
app.get '/random', (req, res) ->
get_notPostedPet()
.then (pet) ->
res.json pet
.catch (err) ->
console.error err
res.status(500).json(err)
server = app.listen 3000, 'localhost', ->
host = server.address().address
host = if host.match /:/ then "[#{host}]" else host
port = server.address().port
console.log 'Listening at http://%s:%s', host, port
###
| 111967 | cheerio = require 'cheerio'
request = require 'request'
express = require 'express'
NodeCache = require 'node-cache'
iconvlite = require 'iconv-lite'
fs = require 'fs'
_ = require 'underscore'
app = express()
cache = new NodeCache()
# Zollstock
zollstock_urls = ["http://www.tierheim-koeln-zollstock.de/tiervermittlung/katzen.html",
"http://www.tierheim-koeln-zollstock.de/tiervermittlung/hunde.html",
"http://www.tierheim-koeln-zollstock.de/tiervermittlung/nagetiere.html"];
zollstock_base_url = "http://www.tierheim-koeln-zollstock.de"
#Dellbrück
dellbrueck_urls = ["http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+kleine+Hunde+&f_funktion=Uebersicht",
"http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+gro%DFe+Hunde+&f_funktion=Uebersicht",
"http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+Katzen&f_funktion=Uebersicht"];
dellbrueck_base_url = "http://presenter.comedius.de/design/bmt_koeln_standard_10001.php"
dellbrueck_pic_url = "http://presenter.comedius.de/pic/bmt_koeln_d620d9faeeb43f717c893b5c818f1287"
get_zollstock_tier = (url)->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
$ = cheerio.load body
content = $('.animalDetail')
name = content.find('h1').first().text()
img = content.find('.lightbox-image').attr('href')
pic = zollstock_base_url + '/' + img
id = content.find('h1').attr('id')
content.find('h1').remove()
content.find('a').remove()
details =
id: id
pic: encodeURI pic
name: name
link: url
desc: content.find('.animalDescription p')
.text().trim().replace(/[\r|\n]+/g, '. ')
.replace(/\t+/g, ' ')
.trim()
f details
get_zollstock_urls = (url) ->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
urls = []
$ = cheerio.load body
$('.animalOverviewItem').each ->
elem = $(this)
detail_url = zollstock_base_url + elem.find('.more').attr('href')
console.log(detail_url)
urls.push detail_url
f urls
get_dellbrueck_tier = (url)->
new Promise (f, r) ->
request (uri: url, encoding: "ISO-8859-1"), (err, response, body) ->
if err
r err
$ = cheerio.load body
content = $('p[style="font-family:Verdana;font-size:13px;font-style:normal;font-weight:normal;color:#756d58;vertical-align:top"]').first()
name = content.find('b').first().text()
img = $('#bild_0').attr('src')
pic = ""
if (img)
start = img.lastIndexOf("/")
pic = dellbrueck_pic_url + img.substr(start)
start = url.indexOf("&f_aktueller_ds=")
id = url.substr(start+16)
end = id.indexOf("&")
id = id.substr(0, end)
content.find('b').remove()
details =
id: id
pic: encodeURI pic
name: <NAME>
link: url
desc: content
.contents()
.not('b')
.not('form')
.text().trim()
.replace(/[\r|\n]+/g, '. ')
.replace(/\t+/g, ' ')
.trim()
f details
get_dellbrueck_sub_urls = (url) ->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
sub_urls = []
$ = cheerio.load body
$('a#TextSeitenanzeige').each ->
elem = $(this)
detail_url = dellbrueck_base_url + elem.attr('href')
sub_urls.push detail_url
f sub_urls
get_dellbrueck_urls_for_page = (sub_url) ->
new Promise (f, r) ->
request sub_url, (err, response, body) ->
if err
r err
urls = []
$ = cheerio.load body
$('a[style="border-style:none;background-color:#ece9e2;vertical-align:top;font:normal 13px Verdana; color:#756d58"]').each ->
elem = $(this)
detail_url = dellbrueck_base_url + elem.attr('href')
urls.push detail_url
f urls
get_dellbrueck_urls = (url) ->
new Promise (f, r) ->
urls = []
p = []
get_dellbrueck_sub_urls url
.then (sub_urls) ->
for sub_url in sub_urls
p.push get_dellbrueck_urls_for_page sub_url
Promise.all p
.then (page_urls) ->
for page_url in page_urls
for animal_url in page_url
urls.push animal_url
.then () ->
f urls
get_zollstockdata = (tier_url)->
new Promise (f, r) ->
get_zollstock_urls tier_url
.then (urls) ->
p = []
for url in urls
console.log(url)
p.push get_zollstock_tier url
Promise.all p
.then (values) ->
f values
.catch (err) ->
r err
get_dellbrueckdata = (tier_url)->
new Promise (f, r) ->
get_dellbrueck_urls tier_url
.then (urls) ->
p = []
for url in urls
console.log(url)
p.push get_dellbrueck_tier url
Promise.all p
.then (values) ->
f values
.catch (err) ->
r err
get_data = ->
new Promise (f ,r) ->
p = []
iconvlite.extendNodeEncodings()
for url in zollstock_urls
p.push get_zollstockdata url
for url in dellbrueck_urls
p.push get_dellbrueckdata url
Promise.all p
.then (list_of_values) ->
values = _.union.apply null, list_of_values
cache.set('tiere', values, 60*60*24)
f values
.catch (err) ->
r err
# get a pet that was not posted yet
get_notPostedPet = ->
new Promise (f, r) ->
filename = '/var/cache/petscologne/posted_pets.json'
try
if fs.existsSync(filename)
postedPets = JSON.parse fs.readFileSync filename, 'utf8'
else
fs.writeFileSync filename, JSON.stringify []
postedPets = []
console.log('file does not exist')
catch err
r err
get_data().then (pets) ->
notPostedPets = []
for pet in pets
if pet.id not in postedPets
notPostedPets.push pet
if notPostedPets.length is 0
notPostedPets = pets
postedPets = []
random = Math.ceil Math.random()*notPostedPets.length-1
notPostedPet = notPostedPets[random]
postedPets.push notPostedPet.id
fs.writeFileSync filename, JSON.stringify postedPets
f notPostedPet
###
get_data().then (values) ->
console.log values.length
get_notPostedPet().then (pet) ->
console.log pet
###
# Return all pets
app.get '/', (req, res) ->
get_data()
.then (pets) ->
res.json pets
.catch (err) ->
console.error err
res.status(500).json(err)
# Return a random pet
app.get '/random', (req, res) ->
get_notPostedPet()
.then (pet) ->
res.json pet
.catch (err) ->
console.error err
res.status(500).json(err)
server = app.listen 3000, 'localhost', ->
host = server.address().address
host = if host.match /:/ then "[#{host}]" else host
port = server.address().port
console.log 'Listening at http://%s:%s', host, port
###
| true | cheerio = require 'cheerio'
request = require 'request'
express = require 'express'
NodeCache = require 'node-cache'
iconvlite = require 'iconv-lite'
fs = require 'fs'
_ = require 'underscore'
app = express()
cache = new NodeCache()
# Zollstock
zollstock_urls = ["http://www.tierheim-koeln-zollstock.de/tiervermittlung/katzen.html",
"http://www.tierheim-koeln-zollstock.de/tiervermittlung/hunde.html",
"http://www.tierheim-koeln-zollstock.de/tiervermittlung/nagetiere.html"];
zollstock_base_url = "http://www.tierheim-koeln-zollstock.de"
#Dellbrück
dellbrueck_urls = ["http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+kleine+Hunde+&f_funktion=Uebersicht",
"http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+gro%DFe+Hunde+&f_funktion=Uebersicht",
"http://presenter.comedius.de/design/bmt_koeln_standard_10001.php?f_mandant=bmt_koeln_d620d9faeeb43f717c893b5c818f1287&f_bereich=Vermittlung+Katzen&f_funktion=Uebersicht"];
dellbrueck_base_url = "http://presenter.comedius.de/design/bmt_koeln_standard_10001.php"
dellbrueck_pic_url = "http://presenter.comedius.de/pic/bmt_koeln_d620d9faeeb43f717c893b5c818f1287"
get_zollstock_tier = (url)->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
$ = cheerio.load body
content = $('.animalDetail')
name = content.find('h1').first().text()
img = content.find('.lightbox-image').attr('href')
pic = zollstock_base_url + '/' + img
id = content.find('h1').attr('id')
content.find('h1').remove()
content.find('a').remove()
details =
id: id
pic: encodeURI pic
name: name
link: url
desc: content.find('.animalDescription p')
.text().trim().replace(/[\r|\n]+/g, '. ')
.replace(/\t+/g, ' ')
.trim()
f details
get_zollstock_urls = (url) ->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
urls = []
$ = cheerio.load body
$('.animalOverviewItem').each ->
elem = $(this)
detail_url = zollstock_base_url + elem.find('.more').attr('href')
console.log(detail_url)
urls.push detail_url
f urls
get_dellbrueck_tier = (url)->
new Promise (f, r) ->
request (uri: url, encoding: "ISO-8859-1"), (err, response, body) ->
if err
r err
$ = cheerio.load body
content = $('p[style="font-family:Verdana;font-size:13px;font-style:normal;font-weight:normal;color:#756d58;vertical-align:top"]').first()
name = content.find('b').first().text()
img = $('#bild_0').attr('src')
pic = ""
if (img)
start = img.lastIndexOf("/")
pic = dellbrueck_pic_url + img.substr(start)
start = url.indexOf("&f_aktueller_ds=")
id = url.substr(start+16)
end = id.indexOf("&")
id = id.substr(0, end)
content.find('b').remove()
details =
id: id
pic: encodeURI pic
name: PI:NAME:<NAME>END_PI
link: url
desc: content
.contents()
.not('b')
.not('form')
.text().trim()
.replace(/[\r|\n]+/g, '. ')
.replace(/\t+/g, ' ')
.trim()
f details
get_dellbrueck_sub_urls = (url) ->
new Promise (f, r) ->
request url, (err, response, body) ->
if err
r err
sub_urls = []
$ = cheerio.load body
$('a#TextSeitenanzeige').each ->
elem = $(this)
detail_url = dellbrueck_base_url + elem.attr('href')
sub_urls.push detail_url
f sub_urls
get_dellbrueck_urls_for_page = (sub_url) ->
new Promise (f, r) ->
request sub_url, (err, response, body) ->
if err
r err
urls = []
$ = cheerio.load body
$('a[style="border-style:none;background-color:#ece9e2;vertical-align:top;font:normal 13px Verdana; color:#756d58"]').each ->
elem = $(this)
detail_url = dellbrueck_base_url + elem.attr('href')
urls.push detail_url
f urls
get_dellbrueck_urls = (url) ->
new Promise (f, r) ->
urls = []
p = []
get_dellbrueck_sub_urls url
.then (sub_urls) ->
for sub_url in sub_urls
p.push get_dellbrueck_urls_for_page sub_url
Promise.all p
.then (page_urls) ->
for page_url in page_urls
for animal_url in page_url
urls.push animal_url
.then () ->
f urls
get_zollstockdata = (tier_url)->
new Promise (f, r) ->
get_zollstock_urls tier_url
.then (urls) ->
p = []
for url in urls
console.log(url)
p.push get_zollstock_tier url
Promise.all p
.then (values) ->
f values
.catch (err) ->
r err
get_dellbrueckdata = (tier_url)->
new Promise (f, r) ->
get_dellbrueck_urls tier_url
.then (urls) ->
p = []
for url in urls
console.log(url)
p.push get_dellbrueck_tier url
Promise.all p
.then (values) ->
f values
.catch (err) ->
r err
get_data = ->
new Promise (f ,r) ->
p = []
iconvlite.extendNodeEncodings()
for url in zollstock_urls
p.push get_zollstockdata url
for url in dellbrueck_urls
p.push get_dellbrueckdata url
Promise.all p
.then (list_of_values) ->
values = _.union.apply null, list_of_values
cache.set('tiere', values, 60*60*24)
f values
.catch (err) ->
r err
# get a pet that was not posted yet
get_notPostedPet = ->
new Promise (f, r) ->
filename = '/var/cache/petscologne/posted_pets.json'
try
if fs.existsSync(filename)
postedPets = JSON.parse fs.readFileSync filename, 'utf8'
else
fs.writeFileSync filename, JSON.stringify []
postedPets = []
console.log('file does not exist')
catch err
r err
get_data().then (pets) ->
notPostedPets = []
for pet in pets
if pet.id not in postedPets
notPostedPets.push pet
if notPostedPets.length is 0
notPostedPets = pets
postedPets = []
random = Math.ceil Math.random()*notPostedPets.length-1
notPostedPet = notPostedPets[random]
postedPets.push notPostedPet.id
fs.writeFileSync filename, JSON.stringify postedPets
f notPostedPet
###
get_data().then (values) ->
console.log values.length
get_notPostedPet().then (pet) ->
console.log pet
###
# Return all pets
app.get '/', (req, res) ->
get_data()
.then (pets) ->
res.json pets
.catch (err) ->
console.error err
res.status(500).json(err)
# Return a random pet
app.get '/random', (req, res) ->
get_notPostedPet()
.then (pet) ->
res.json pet
.catch (err) ->
console.error err
res.status(500).json(err)
server = app.listen 3000, 'localhost', ->
host = server.address().address
host = if host.match /:/ then "[#{host}]" else host
port = server.address().port
console.log 'Listening at http://%s:%s', host, port
###
|
[
{
"context": "ventData =\n tme: Date.now()\n projectToken: 'penguin'\n userID: userZooniverseId\n type: 'competit",
"end": 411,
"score": 0.9809897541999817,
"start": 404,
"tag": "PASSWORD",
"value": "penguin"
}
] | geordi.coffee | zooniverse/penguinwatch | 0 | $ = require 'jqueryify'
User = require 'zooniverse/models/user'
devServer = !!(location.host.match(/localhost:3665/))
geordiHost = if devServer then 'localhost:3030' else 'geordi.zooniverse.org'
geordiUrl = 'http://' + geordiHost + '/api/events/'
###
This will log a competition opt-in in the Geordi API
###
exports.logEvent = (userZooniverseId) ->
eventData =
tme: Date.now()
projectToken: 'penguin'
userID: userZooniverseId
type: 'competition'
relatedID: 'opt-in'
$.ajax
url: geordiUrl
type: 'POST'
contentType: 'application/json; charset=utf-8'
data: JSON.stringify eventData
dataType: 'json'
| 17390 | $ = require 'jqueryify'
User = require 'zooniverse/models/user'
devServer = !!(location.host.match(/localhost:3665/))
geordiHost = if devServer then 'localhost:3030' else 'geordi.zooniverse.org'
geordiUrl = 'http://' + geordiHost + '/api/events/'
###
This will log a competition opt-in in the Geordi API
###
exports.logEvent = (userZooniverseId) ->
eventData =
tme: Date.now()
projectToken: '<PASSWORD>'
userID: userZooniverseId
type: 'competition'
relatedID: 'opt-in'
$.ajax
url: geordiUrl
type: 'POST'
contentType: 'application/json; charset=utf-8'
data: JSON.stringify eventData
dataType: 'json'
| true | $ = require 'jqueryify'
User = require 'zooniverse/models/user'
devServer = !!(location.host.match(/localhost:3665/))
geordiHost = if devServer then 'localhost:3030' else 'geordi.zooniverse.org'
geordiUrl = 'http://' + geordiHost + '/api/events/'
###
This will log a competition opt-in in the Geordi API
###
exports.logEvent = (userZooniverseId) ->
eventData =
tme: Date.now()
projectToken: 'PI:PASSWORD:<PASSWORD>END_PI'
userID: userZooniverseId
type: 'competition'
relatedID: 'opt-in'
$.ajax
url: geordiUrl
type: 'POST'
contentType: 'application/json; charset=utf-8'
data: JSON.stringify eventData
dataType: 'json'
|
[
{
"context": "ef.name]\n service\n .where('name(en=\"Foo\")')\n .whereOperator('or')\n .page(2)",
"end": 6281,
"score": 0.7647959589958191,
"start": 6278,
"tag": "NAME",
"value": "Foo"
}
] | src/spec/client/client.spec.coffee | commercetools/sphere-node-sdk | 13 | _ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient, Rest, TaskQueue} = require '../../lib/main'
Config = require('../../config').config
describe 'SphereClient', ->
beforeEach ->
@client = new SphereClient config: Config
afterEach ->
@client = null
it 'should read credentials', ->
expect(Config.client_id).toBeDefined()
expect(Config.client_secret).toBeDefined()
expect(Config.project_key).toBeDefined()
it 'should initialize services', ->
expect(@client).toBeDefined()
expect(@client._rest).toBeDefined()
expect(@client._rest._options.headers['User-Agent']).toBe 'sphere-node-sdk'
expect(@client._task).toBeDefined()
expect(@client.cartDiscounts).toBeDefined()
expect(@client.carts).toBeDefined()
expect(@client.categories).toBeDefined()
expect(@client.channels).toBeDefined()
expect(@client.customObjects).toBeDefined()
expect(@client.customers).toBeDefined()
expect(@client.customerGroups).toBeDefined()
expect(@client.discountCodes).toBeDefined()
expect(@client.graphql).toBeDefined()
expect(@client.inventoryEntries).toBeDefined()
expect(@client.messages).toBeDefined()
expect(@client.orders).toBeDefined()
expect(@client.payments).toBeDefined()
expect(@client.products).toBeDefined()
expect(@client.productDiscounts).toBeDefined()
expect(@client.productProjections).toBeDefined()
expect(@client.productTypes).toBeDefined()
expect(@client.reviews).toBeDefined()
expect(@client.shippingMethods).toBeDefined()
expect(@client.states).toBeDefined()
expect(@client.taxCategories).toBeDefined()
expect(@client.types).toBeDefined()
expect(@client.zones).toBeDefined()
it 'should throw error if no credentials are given', ->
client = -> new SphereClient foo: 'bar'
expect(client).toThrow new Error('Missing credentials')
_.each ['client_id', 'client_secret', 'project_key'], (key) ->
it "should throw error if no '#{key}' is defined", ->
opt = _.clone(Config)
delete opt[key]
client = -> new SphereClient config: opt
expect(client).toThrow new Error("Missing '#{key}'")
it 'should initialize with given Rest', ->
existingRest = new Rest config: Config
client = new SphereClient rest: existingRest
expect(client._rest).toEqual existingRest
it 'should initialize with given TaskQueue', ->
existingTaskQueue = new TaskQueue
client = new SphereClient
config: Config
task: existingTaskQueue
expect(client._task).toEqual existingTaskQueue
it 'should set maxParallel requests globally', ->
@client.setMaxParallel(5)
expect(@client._task._maxParallel).toBe 5
it 'should throw if maxParallel < 1 or > 100', ->
expect(=> @client.setMaxParallel(0)).toThrow new Error 'MaxParallel must be a number between 1 and 100'
expect(=> @client.setMaxParallel(101)).toThrow new Error 'MaxParallel must be a number between 1 and 100'
it 'should not repeat request on error if repeater is disabled',(done) ->
client = new SphereClient {config: Config, enableRepeater: false}
callsMap = {
0: { statusCode: 500, message: 'ETIMEDOUT' }
1: { statusCode: 500, message: 'ETIMEDOUT' }
2: { statusCode: 200, message: 'success' }
}
callCount = 0
spyOn(client._rest, 'GET').andCallFake (resource, callback) ->
currentCall = callsMap[callCount]
callCount++
statusCode = currentCall.statusCode
message = currentCall.message
callback(null, { statusCode }, { message })
client.products.fetch()
.catch (err) ->
expect(client._rest.GET.calls.length).toEqual 1
expect(err.body.message).toEqual 'ETIMEDOUT'
done()
_.each [
{name: 'cartDiscounts', className: 'CartDiscountService', blacklist: []}
{name: 'carts', className: 'CartService', blacklist: []}
{name: 'categories', className: 'CategoryService', blacklist: []}
{name: 'channels', className: 'ChannelService', blacklist: []}
{name: 'customObjects', className: 'CustomObjectService', blacklist: []}
{name: 'customers', className: 'CustomerService', blacklist: []}
{name: 'customerGroups', className: 'CustomerGroupService', blacklist: []}
{name: 'discountCodes', className: 'DiscountCodeService', blacklist: []}
{name: 'inventoryEntries', className: 'InventoryEntryService', blacklist: []}
{name: 'messages', className: 'MessageService', blacklist: ['save', 'create', 'update', 'delete']}
{name: 'orders', className: 'OrderService', blacklist: ['delete']}
{name: 'payments', className: 'PaymentService', blacklist: []}
{name: 'products', className: 'ProductService', blacklist: []}
{name: 'productDiscounts', className: 'ProductDiscountService', blacklist: []}
{name: 'productProjections', className: 'ProductProjectionService', blacklist: ['save', 'create', 'update', 'delete']}
{name: 'productTypes', className: 'ProductTypeService', blacklist: []}
{name: 'reviews', className: 'ReviewService', blacklist: ['delete']}
{name: 'shippingMethods', className: 'ShippingMethodService', blacklist: []}
{name: 'states', className: 'StateService', blacklist: []}
{name: 'taxCategories', className: 'TaxCategoryService', blacklist: []}
{name: 'types', className: 'TypeService', blacklist: []}
{name: 'zones', className: 'ZoneService', blacklist: []}
], (serviceDef) ->
describe ":: #{serviceDef.name}", ->
ID = "1234-abcd-5678-efgh"
it 'should get service', ->
service = @client[serviceDef.name]
expect(service).toBeDefined()
expect(service.constructor.name).toBe(serviceDef.className)
it 'should enable statistic (headers)', ->
expect(@client[serviceDef.name]._stats.includeHeaders).toBe false
client = new SphereClient
config: Config
stats:
includeHeaders: true
expect(client[serviceDef.name]._stats.includeHeaders).toBe true
it 'should query resource', (done) ->
spyOn(@client._rest, "GET").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service
.where('name(en="Foo")')
.whereOperator('or')
.page(2)
.perPage(5)
.fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
it 'should get resource by id', (done) ->
spyOn(@client._rest, "GET").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.byId(ID).fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
if not _.contains(serviceDef.blacklist, 'save')
it 'should save new resource', (done) ->
spyOn(@client._rest, "POST").andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.save({foo: 'bar'}).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
if not _.contains(serviceDef.blacklist, 'delete')
it 'should delete resource', (done) ->
spyOn(@client._rest, "DELETE").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.byId('123-abc').delete(4).then (result) =>
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
expect(@client._rest.DELETE).toHaveBeenCalledWith "#{service._currentEndpoint}/123-abc?version=4", jasmine.any(Function)
done()
.catch (e) -> done(_.prettify(e))
| 211195 | _ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient, Rest, TaskQueue} = require '../../lib/main'
Config = require('../../config').config
describe 'SphereClient', ->
beforeEach ->
@client = new SphereClient config: Config
afterEach ->
@client = null
it 'should read credentials', ->
expect(Config.client_id).toBeDefined()
expect(Config.client_secret).toBeDefined()
expect(Config.project_key).toBeDefined()
it 'should initialize services', ->
expect(@client).toBeDefined()
expect(@client._rest).toBeDefined()
expect(@client._rest._options.headers['User-Agent']).toBe 'sphere-node-sdk'
expect(@client._task).toBeDefined()
expect(@client.cartDiscounts).toBeDefined()
expect(@client.carts).toBeDefined()
expect(@client.categories).toBeDefined()
expect(@client.channels).toBeDefined()
expect(@client.customObjects).toBeDefined()
expect(@client.customers).toBeDefined()
expect(@client.customerGroups).toBeDefined()
expect(@client.discountCodes).toBeDefined()
expect(@client.graphql).toBeDefined()
expect(@client.inventoryEntries).toBeDefined()
expect(@client.messages).toBeDefined()
expect(@client.orders).toBeDefined()
expect(@client.payments).toBeDefined()
expect(@client.products).toBeDefined()
expect(@client.productDiscounts).toBeDefined()
expect(@client.productProjections).toBeDefined()
expect(@client.productTypes).toBeDefined()
expect(@client.reviews).toBeDefined()
expect(@client.shippingMethods).toBeDefined()
expect(@client.states).toBeDefined()
expect(@client.taxCategories).toBeDefined()
expect(@client.types).toBeDefined()
expect(@client.zones).toBeDefined()
it 'should throw error if no credentials are given', ->
client = -> new SphereClient foo: 'bar'
expect(client).toThrow new Error('Missing credentials')
_.each ['client_id', 'client_secret', 'project_key'], (key) ->
it "should throw error if no '#{key}' is defined", ->
opt = _.clone(Config)
delete opt[key]
client = -> new SphereClient config: opt
expect(client).toThrow new Error("Missing '#{key}'")
it 'should initialize with given Rest', ->
existingRest = new Rest config: Config
client = new SphereClient rest: existingRest
expect(client._rest).toEqual existingRest
it 'should initialize with given TaskQueue', ->
existingTaskQueue = new TaskQueue
client = new SphereClient
config: Config
task: existingTaskQueue
expect(client._task).toEqual existingTaskQueue
it 'should set maxParallel requests globally', ->
@client.setMaxParallel(5)
expect(@client._task._maxParallel).toBe 5
it 'should throw if maxParallel < 1 or > 100', ->
expect(=> @client.setMaxParallel(0)).toThrow new Error 'MaxParallel must be a number between 1 and 100'
expect(=> @client.setMaxParallel(101)).toThrow new Error 'MaxParallel must be a number between 1 and 100'
it 'should not repeat request on error if repeater is disabled',(done) ->
client = new SphereClient {config: Config, enableRepeater: false}
callsMap = {
0: { statusCode: 500, message: 'ETIMEDOUT' }
1: { statusCode: 500, message: 'ETIMEDOUT' }
2: { statusCode: 200, message: 'success' }
}
callCount = 0
spyOn(client._rest, 'GET').andCallFake (resource, callback) ->
currentCall = callsMap[callCount]
callCount++
statusCode = currentCall.statusCode
message = currentCall.message
callback(null, { statusCode }, { message })
client.products.fetch()
.catch (err) ->
expect(client._rest.GET.calls.length).toEqual 1
expect(err.body.message).toEqual 'ETIMEDOUT'
done()
_.each [
{name: 'cartDiscounts', className: 'CartDiscountService', blacklist: []}
{name: 'carts', className: 'CartService', blacklist: []}
{name: 'categories', className: 'CategoryService', blacklist: []}
{name: 'channels', className: 'ChannelService', blacklist: []}
{name: 'customObjects', className: 'CustomObjectService', blacklist: []}
{name: 'customers', className: 'CustomerService', blacklist: []}
{name: 'customerGroups', className: 'CustomerGroupService', blacklist: []}
{name: 'discountCodes', className: 'DiscountCodeService', blacklist: []}
{name: 'inventoryEntries', className: 'InventoryEntryService', blacklist: []}
{name: 'messages', className: 'MessageService', blacklist: ['save', 'create', 'update', 'delete']}
{name: 'orders', className: 'OrderService', blacklist: ['delete']}
{name: 'payments', className: 'PaymentService', blacklist: []}
{name: 'products', className: 'ProductService', blacklist: []}
{name: 'productDiscounts', className: 'ProductDiscountService', blacklist: []}
{name: 'productProjections', className: 'ProductProjectionService', blacklist: ['save', 'create', 'update', 'delete']}
{name: 'productTypes', className: 'ProductTypeService', blacklist: []}
{name: 'reviews', className: 'ReviewService', blacklist: ['delete']}
{name: 'shippingMethods', className: 'ShippingMethodService', blacklist: []}
{name: 'states', className: 'StateService', blacklist: []}
{name: 'taxCategories', className: 'TaxCategoryService', blacklist: []}
{name: 'types', className: 'TypeService', blacklist: []}
{name: 'zones', className: 'ZoneService', blacklist: []}
], (serviceDef) ->
describe ":: #{serviceDef.name}", ->
ID = "1234-abcd-5678-efgh"
it 'should get service', ->
service = @client[serviceDef.name]
expect(service).toBeDefined()
expect(service.constructor.name).toBe(serviceDef.className)
it 'should enable statistic (headers)', ->
expect(@client[serviceDef.name]._stats.includeHeaders).toBe false
client = new SphereClient
config: Config
stats:
includeHeaders: true
expect(client[serviceDef.name]._stats.includeHeaders).toBe true
it 'should query resource', (done) ->
spyOn(@client._rest, "GET").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service
.where('name(en="<NAME>")')
.whereOperator('or')
.page(2)
.perPage(5)
.fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
it 'should get resource by id', (done) ->
spyOn(@client._rest, "GET").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.byId(ID).fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
if not _.contains(serviceDef.blacklist, 'save')
it 'should save new resource', (done) ->
spyOn(@client._rest, "POST").andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.save({foo: 'bar'}).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
if not _.contains(serviceDef.blacklist, 'delete')
it 'should delete resource', (done) ->
spyOn(@client._rest, "DELETE").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.byId('123-abc').delete(4).then (result) =>
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
expect(@client._rest.DELETE).toHaveBeenCalledWith "#{service._currentEndpoint}/123-abc?version=4", jasmine.any(Function)
done()
.catch (e) -> done(_.prettify(e))
| true | _ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient, Rest, TaskQueue} = require '../../lib/main'
Config = require('../../config').config
describe 'SphereClient', ->
beforeEach ->
@client = new SphereClient config: Config
afterEach ->
@client = null
it 'should read credentials', ->
expect(Config.client_id).toBeDefined()
expect(Config.client_secret).toBeDefined()
expect(Config.project_key).toBeDefined()
it 'should initialize services', ->
expect(@client).toBeDefined()
expect(@client._rest).toBeDefined()
expect(@client._rest._options.headers['User-Agent']).toBe 'sphere-node-sdk'
expect(@client._task).toBeDefined()
expect(@client.cartDiscounts).toBeDefined()
expect(@client.carts).toBeDefined()
expect(@client.categories).toBeDefined()
expect(@client.channels).toBeDefined()
expect(@client.customObjects).toBeDefined()
expect(@client.customers).toBeDefined()
expect(@client.customerGroups).toBeDefined()
expect(@client.discountCodes).toBeDefined()
expect(@client.graphql).toBeDefined()
expect(@client.inventoryEntries).toBeDefined()
expect(@client.messages).toBeDefined()
expect(@client.orders).toBeDefined()
expect(@client.payments).toBeDefined()
expect(@client.products).toBeDefined()
expect(@client.productDiscounts).toBeDefined()
expect(@client.productProjections).toBeDefined()
expect(@client.productTypes).toBeDefined()
expect(@client.reviews).toBeDefined()
expect(@client.shippingMethods).toBeDefined()
expect(@client.states).toBeDefined()
expect(@client.taxCategories).toBeDefined()
expect(@client.types).toBeDefined()
expect(@client.zones).toBeDefined()
it 'should throw error if no credentials are given', ->
client = -> new SphereClient foo: 'bar'
expect(client).toThrow new Error('Missing credentials')
_.each ['client_id', 'client_secret', 'project_key'], (key) ->
it "should throw error if no '#{key}' is defined", ->
opt = _.clone(Config)
delete opt[key]
client = -> new SphereClient config: opt
expect(client).toThrow new Error("Missing '#{key}'")
it 'should initialize with given Rest', ->
existingRest = new Rest config: Config
client = new SphereClient rest: existingRest
expect(client._rest).toEqual existingRest
it 'should initialize with given TaskQueue', ->
existingTaskQueue = new TaskQueue
client = new SphereClient
config: Config
task: existingTaskQueue
expect(client._task).toEqual existingTaskQueue
it 'should set maxParallel requests globally', ->
@client.setMaxParallel(5)
expect(@client._task._maxParallel).toBe 5
it 'should throw if maxParallel < 1 or > 100', ->
expect(=> @client.setMaxParallel(0)).toThrow new Error 'MaxParallel must be a number between 1 and 100'
expect(=> @client.setMaxParallel(101)).toThrow new Error 'MaxParallel must be a number between 1 and 100'
it 'should not repeat request on error if repeater is disabled',(done) ->
client = new SphereClient {config: Config, enableRepeater: false}
callsMap = {
0: { statusCode: 500, message: 'ETIMEDOUT' }
1: { statusCode: 500, message: 'ETIMEDOUT' }
2: { statusCode: 200, message: 'success' }
}
callCount = 0
spyOn(client._rest, 'GET').andCallFake (resource, callback) ->
currentCall = callsMap[callCount]
callCount++
statusCode = currentCall.statusCode
message = currentCall.message
callback(null, { statusCode }, { message })
client.products.fetch()
.catch (err) ->
expect(client._rest.GET.calls.length).toEqual 1
expect(err.body.message).toEqual 'ETIMEDOUT'
done()
_.each [
{name: 'cartDiscounts', className: 'CartDiscountService', blacklist: []}
{name: 'carts', className: 'CartService', blacklist: []}
{name: 'categories', className: 'CategoryService', blacklist: []}
{name: 'channels', className: 'ChannelService', blacklist: []}
{name: 'customObjects', className: 'CustomObjectService', blacklist: []}
{name: 'customers', className: 'CustomerService', blacklist: []}
{name: 'customerGroups', className: 'CustomerGroupService', blacklist: []}
{name: 'discountCodes', className: 'DiscountCodeService', blacklist: []}
{name: 'inventoryEntries', className: 'InventoryEntryService', blacklist: []}
{name: 'messages', className: 'MessageService', blacklist: ['save', 'create', 'update', 'delete']}
{name: 'orders', className: 'OrderService', blacklist: ['delete']}
{name: 'payments', className: 'PaymentService', blacklist: []}
{name: 'products', className: 'ProductService', blacklist: []}
{name: 'productDiscounts', className: 'ProductDiscountService', blacklist: []}
{name: 'productProjections', className: 'ProductProjectionService', blacklist: ['save', 'create', 'update', 'delete']}
{name: 'productTypes', className: 'ProductTypeService', blacklist: []}
{name: 'reviews', className: 'ReviewService', blacklist: ['delete']}
{name: 'shippingMethods', className: 'ShippingMethodService', blacklist: []}
{name: 'states', className: 'StateService', blacklist: []}
{name: 'taxCategories', className: 'TaxCategoryService', blacklist: []}
{name: 'types', className: 'TypeService', blacklist: []}
{name: 'zones', className: 'ZoneService', blacklist: []}
], (serviceDef) ->
describe ":: #{serviceDef.name}", ->
ID = "1234-abcd-5678-efgh"
it 'should get service', ->
service = @client[serviceDef.name]
expect(service).toBeDefined()
expect(service.constructor.name).toBe(serviceDef.className)
it 'should enable statistic (headers)', ->
expect(@client[serviceDef.name]._stats.includeHeaders).toBe false
client = new SphereClient
config: Config
stats:
includeHeaders: true
expect(client[serviceDef.name]._stats.includeHeaders).toBe true
it 'should query resource', (done) ->
spyOn(@client._rest, "GET").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service
.where('name(en="PI:NAME:<NAME>END_PI")')
.whereOperator('or')
.page(2)
.perPage(5)
.fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
it 'should get resource by id', (done) ->
spyOn(@client._rest, "GET").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.byId(ID).fetch().then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
if not _.contains(serviceDef.blacklist, 'save')
it 'should save new resource', (done) ->
spyOn(@client._rest, "POST").andCallFake (endpoint, payload, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.save({foo: 'bar'}).then (result) ->
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
done()
.catch (e) -> done(_.prettify(e))
if not _.contains(serviceDef.blacklist, 'delete')
it 'should delete resource', (done) ->
spyOn(@client._rest, "DELETE").andCallFake (endpoint, callback) -> callback(null, {statusCode: 200}, {foo: 'bar'})
service = @client[serviceDef.name]
service.byId('123-abc').delete(4).then (result) =>
expect(result.statusCode).toBe 200
expect(result.body).toEqual foo: 'bar'
expect(@client._rest.DELETE).toHaveBeenCalledWith "#{service._currentEndpoint}/123-abc?version=4", jasmine.any(Function)
done()
.catch (e) -> done(_.prettify(e))
|
[
{
"context": "angular: [\n { key: \"options.port\" }\n { key: \"desiredState.leds\" }\n]\n",
"end": 33,
"score": 0.7310256361961365,
"start": 21,
"tag": "KEY",
"value": "options.port"
},
{
"context": "angular: [\n { key: \"options.port\" }\n { key: \"desiredState.leds\" }\n]\n",
... | configs/default/form.cson | redaphid/meshblu-connector-blinky-tape | 0 | angular: [
{ key: "options.port" }
{ key: "desiredState.leds" }
]
| 71900 | angular: [
{ key: "<KEY>" }
{ key: "<KEY>" }
]
| true | angular: [
{ key: "PI:KEY:<KEY>END_PI" }
{ key: "PI:KEY:<KEY>END_PI" }
]
|
[
{
"context": "#####\n###\n Fit Composition 3D for MMD2AE\n (C) あかつきみさき(みくちぃP)\n\n このスクリプトについて\n このスクリプトはMMD2AEで出力した,nul",
"end": 70,
"score": 0.9962626695632935,
"start": 63,
"tag": "NAME",
"value": "あかつきみさき"
},
{
"context": "\n Fit Composition 3D for MMD2AE\n (C) あかつきみさき... | src/Fit Composition 3D for MMD2AE.coffee | MisakiAkatsuki/Fit-Composition-3D-for-MMD2AE | 0 | ##########
#######
###
Fit Composition 3D for MMD2AE
(C) あかつきみさき(みくちぃP)
このスクリプトについて
このスクリプトはMMD2AEで出力した,nullで親子付けされたカメラレイヤー専用のものです.
3Dレイヤーをアクティブカメラを使用して,コンポジションサイズにフィットするようにリサイズします.
使用方法
1.ファイル→スクリプト→スクリプトファイルの実行から実行.
動作環境
Adobe After Effects CS6以上
ライセンス
MIT License
バージョン情報
2016/11/07 Ver 1.2.0 Update
対応バージョンの変更.
2014/02/17 Ver 1.1.0 Update
方向がずれていた問題の修正.
2014/01/06 Ver 1.0.0 Release
###
######
#########
FC3D4MMD2AEData = ( ->
scriptName = "Fit Composition 3D for MMD2AE"
scriptURLName = "FitComposition3DforMMD2AE"
scriptVersionNumber = "1.2.0"
scriptURLVersion = 120
canRunVersionNum = 11.0
canRunVersionC = "CS6"
return{
getScriptName : -> scriptName
getScriptURLName : -> scriptURLName
getScriptVersionNumber: -> scriptVersionNumber
getCanRunVersionNum : -> canRunVersionNum
getCanRunVersionC : -> canRunVersionC
getGuid : -> guid
}
)()
ADBE_TRANSFORM_GROUP = "ADBE Transform Group"
ADBE_POSITION = "ADBE Position"
ADBE_SCALE = "ADBE Scale"
ADBE_ORIENTATION = "ADBE Orientation"
CAMERA_NAME = "MMD CAMERA"
parentNullX = CAMERA_NAME + " CONTROL X"
parentNullY = CAMERA_NAME + " CONTROL Y"
# 対象の名前のレイヤーが存在するか確認する
CompItem::hasTargetLayer = (targetName) ->
return @layer(targetName)?
###
起動しているAEの言語チェック
###
getLocalizedText = (str) ->
if app.language is Language.JAPANESE
str.jp
else
str.en
###
許容バージョンを渡し,実行できるか判別
###
runAEVersionCheck = (AEVersion) ->
if parseFloat(app.version) < AEVersion.getCanRunVersionNum()
alert "This script requires After Effects #{AEVersion.getCanRunVersionC()} or greater."
return false
else
return true
###
コンポジションにアクティブカメラが存在するか確認する関数
###
hasActiveCamera = (actComp) ->
return actComp.activeCamera?
###
コンポジションを選択しているか確認する関数
###
isCompActive = (selComp) ->
unless(selComp and selComp instanceof CompItem)
alert "Select Composition"
return false
else
return true
###
レイヤーを選択しているか確認する関数
###
isLayerSelected = (selLayers) ->
if selLayers.length is 0
alert "Select Layers"
return false
else
return true
entryFunc = () ->
# -------------------------------------------------------------------------
# アクティブカメラが存在しない場合,カメラを追加する.
unless hasActiveCamera actComp
actComp.layers.addCamera(FC3D4MMD2AEData.getScriptName(), [actComp.width/2, actComp.height/2])
unless actComp.hasTargetLayer(CAMERA_NAME)
CAMERA_NAME = prompt "MMD camera not found\nPut MMD camera layer's name", CAMERA_NAME
parentNullX = CAMERA_NAME + " CONTROL X"
parentNullY = CAMERA_NAME + " CONTROL Y"
return 0 unless CAMERA_NAME?
return 0 unless actComp.hasTargetLayer(CAMERA_NAME)
unless actComp.hasTargetLayer(parentNullX)
parentNullX = prompt "Control X not found\nPut Control X layer's name", parentNullX
return 0 unless parentNullX?
return 0 unless actComp.hasTargetLayer(parentNullX)
unless actComp.hasTargetLayer(parentNullY)
parentNullY = prompt "Control Y not found\nPut Control Y layer's name", CAMERA_NAME
return 0 unless parentNullY?
return 0 unless actComp.hasTargetLayer(parentNullY)
# -------------------------------------------------------------------------
for curLayer in [0...selLayers.length] by 1
# 対象のレイヤーがカメラかライトの場合は除外する
continue if selLayers[curLayer] instanceof CameraLayer or selLayers[curLayer] instanceof LightLayer
selLayers[curLayer].threeDLayer = true
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_POSITION).expression =
"thisComp.layer(\"#{CAMERA_NAME} CONTROL Y\").transform.position;"
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_SCALE).expression =
"""
var actCam = thisComp.activeCamera;
var camPointOfInterest = thisComp.layer("#{CAMERA_NAME} CONTROL X").transform.anchorPoint;
var camPosition = actCam.transform.position;
var camZoom = actCam.cameraOption.zoom;
var x = Math.abs(camPointOfInterest[0] - camPosition[0]);
var y = Math.abs(camPointOfInterest[1] - camPosition[1]);
var z = Math.abs(camPointOfInterest[2] - camPosition[2]);
range = Math.sqrt((x*x + y*y + z*z));
thisScale = range / camZoom * 100;
[thisScale, thisScale, thisScale]
"""
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_ORIENTATION).expression =
"""
var x = transform.orientation[0];
var y = transform.orientation[1];
var z = transform.orientation[2] + thisComp.layer(\"#{CAMERA_NAME} CONTROL X\").transform.zRotation;
[x, y, z]
"""
selLayers[curLayer].autoOrient = AutoOrientType.CAMERA_OR_POINT_OF_INTEREST
return 0
undoEntryFunc = (data) ->
app.beginUndoGroup data.getScriptName()
entryFunc()
app.endUndoGroup()
return 0
###
メイン処理開始
###
return 0 unless runAEVersionCheck FC3D4MMD2AEData
actComp = app.project.activeItem
return 0 unless isCompActive actComp
selLayers = actComp.selectedLayers
return 0 unless isLayerSelected selLayers
undoEntryFunc FC3D4MMD2AEData
return 0
| 21181 | ##########
#######
###
Fit Composition 3D for MMD2AE
(C) <NAME>(み<NAME>)
このスクリプトについて
このスクリプトはMMD2AEで出力した,nullで親子付けされたカメラレイヤー専用のものです.
3Dレイヤーをアクティブカメラを使用して,コンポジションサイズにフィットするようにリサイズします.
使用方法
1.ファイル→スクリプト→スクリプトファイルの実行から実行.
動作環境
Adobe After Effects CS6以上
ライセンス
MIT License
バージョン情報
2016/11/07 Ver 1.2.0 Update
対応バージョンの変更.
2014/02/17 Ver 1.1.0 Update
方向がずれていた問題の修正.
2014/01/06 Ver 1.0.0 Release
###
######
#########
FC3D4MMD2AEData = ( ->
scriptName = "Fit Composition 3D for MMD2AE"
scriptURLName = "FitComposition3DforMMD2AE"
scriptVersionNumber = "1.2.0"
scriptURLVersion = 120
canRunVersionNum = 11.0
canRunVersionC = "CS6"
return{
getScriptName : -> scriptName
getScriptURLName : -> scriptURLName
getScriptVersionNumber: -> scriptVersionNumber
getCanRunVersionNum : -> canRunVersionNum
getCanRunVersionC : -> canRunVersionC
getGuid : -> guid
}
)()
ADBE_TRANSFORM_GROUP = "ADBE Transform Group"
ADBE_POSITION = "ADBE Position"
ADBE_SCALE = "ADBE Scale"
ADBE_ORIENTATION = "ADBE Orientation"
CAMERA_NAME = "MMD CAMERA"
parentNullX = CAMERA_NAME + " CONTROL X"
parentNullY = CAMERA_NAME + " CONTROL Y"
# 対象の名前のレイヤーが存在するか確認する
CompItem::hasTargetLayer = (targetName) ->
return @layer(targetName)?
###
起動しているAEの言語チェック
###
getLocalizedText = (str) ->
if app.language is Language.JAPANESE
str.jp
else
str.en
###
許容バージョンを渡し,実行できるか判別
###
runAEVersionCheck = (AEVersion) ->
if parseFloat(app.version) < AEVersion.getCanRunVersionNum()
alert "This script requires After Effects #{AEVersion.getCanRunVersionC()} or greater."
return false
else
return true
###
コンポジションにアクティブカメラが存在するか確認する関数
###
hasActiveCamera = (actComp) ->
return actComp.activeCamera?
###
コンポジションを選択しているか確認する関数
###
isCompActive = (selComp) ->
unless(selComp and selComp instanceof CompItem)
alert "Select Composition"
return false
else
return true
###
レイヤーを選択しているか確認する関数
###
isLayerSelected = (selLayers) ->
if selLayers.length is 0
alert "Select Layers"
return false
else
return true
entryFunc = () ->
# -------------------------------------------------------------------------
# アクティブカメラが存在しない場合,カメラを追加する.
unless hasActiveCamera actComp
actComp.layers.addCamera(FC3D4MMD2AEData.getScriptName(), [actComp.width/2, actComp.height/2])
unless actComp.hasTargetLayer(CAMERA_NAME)
CAMERA_NAME = prompt "MMD camera not found\nPut MMD camera layer's name", CAMERA_NAME
parentNullX = CAMERA_NAME + " CONTROL X"
parentNullY = CAMERA_NAME + " CONTROL Y"
return 0 unless CAMERA_NAME?
return 0 unless actComp.hasTargetLayer(CAMERA_NAME)
unless actComp.hasTargetLayer(parentNullX)
parentNullX = prompt "Control X not found\nPut Control X layer's name", parentNullX
return 0 unless parentNullX?
return 0 unless actComp.hasTargetLayer(parentNullX)
unless actComp.hasTargetLayer(parentNullY)
parentNullY = prompt "Control Y not found\nPut Control Y layer's name", CAMERA_NAME
return 0 unless parentNullY?
return 0 unless actComp.hasTargetLayer(parentNullY)
# -------------------------------------------------------------------------
for curLayer in [0...selLayers.length] by 1
# 対象のレイヤーがカメラかライトの場合は除外する
continue if selLayers[curLayer] instanceof CameraLayer or selLayers[curLayer] instanceof LightLayer
selLayers[curLayer].threeDLayer = true
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_POSITION).expression =
"thisComp.layer(\"#{CAMERA_NAME} CONTROL Y\").transform.position;"
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_SCALE).expression =
"""
var actCam = thisComp.activeCamera;
var camPointOfInterest = thisComp.layer("#{CAMERA_NAME} CONTROL X").transform.anchorPoint;
var camPosition = actCam.transform.position;
var camZoom = actCam.cameraOption.zoom;
var x = Math.abs(camPointOfInterest[0] - camPosition[0]);
var y = Math.abs(camPointOfInterest[1] - camPosition[1]);
var z = Math.abs(camPointOfInterest[2] - camPosition[2]);
range = Math.sqrt((x*x + y*y + z*z));
thisScale = range / camZoom * 100;
[thisScale, thisScale, thisScale]
"""
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_ORIENTATION).expression =
"""
var x = transform.orientation[0];
var y = transform.orientation[1];
var z = transform.orientation[2] + thisComp.layer(\"#{CAMERA_NAME} CONTROL X\").transform.zRotation;
[x, y, z]
"""
selLayers[curLayer].autoOrient = AutoOrientType.CAMERA_OR_POINT_OF_INTEREST
return 0
undoEntryFunc = (data) ->
app.beginUndoGroup data.getScriptName()
entryFunc()
app.endUndoGroup()
return 0
###
メイン処理開始
###
return 0 unless runAEVersionCheck FC3D4MMD2AEData
actComp = app.project.activeItem
return 0 unless isCompActive actComp
selLayers = actComp.selectedLayers
return 0 unless isLayerSelected selLayers
undoEntryFunc FC3D4MMD2AEData
return 0
| true | ##########
#######
###
Fit Composition 3D for MMD2AE
(C) PI:NAME:<NAME>END_PI(みPI:NAME:<NAME>END_PI)
このスクリプトについて
このスクリプトはMMD2AEで出力した,nullで親子付けされたカメラレイヤー専用のものです.
3Dレイヤーをアクティブカメラを使用して,コンポジションサイズにフィットするようにリサイズします.
使用方法
1.ファイル→スクリプト→スクリプトファイルの実行から実行.
動作環境
Adobe After Effects CS6以上
ライセンス
MIT License
バージョン情報
2016/11/07 Ver 1.2.0 Update
対応バージョンの変更.
2014/02/17 Ver 1.1.0 Update
方向がずれていた問題の修正.
2014/01/06 Ver 1.0.0 Release
###
######
#########
FC3D4MMD2AEData = ( ->
scriptName = "Fit Composition 3D for MMD2AE"
scriptURLName = "FitComposition3DforMMD2AE"
scriptVersionNumber = "1.2.0"
scriptURLVersion = 120
canRunVersionNum = 11.0
canRunVersionC = "CS6"
return{
getScriptName : -> scriptName
getScriptURLName : -> scriptURLName
getScriptVersionNumber: -> scriptVersionNumber
getCanRunVersionNum : -> canRunVersionNum
getCanRunVersionC : -> canRunVersionC
getGuid : -> guid
}
)()
ADBE_TRANSFORM_GROUP = "ADBE Transform Group"
ADBE_POSITION = "ADBE Position"
ADBE_SCALE = "ADBE Scale"
ADBE_ORIENTATION = "ADBE Orientation"
CAMERA_NAME = "MMD CAMERA"
parentNullX = CAMERA_NAME + " CONTROL X"
parentNullY = CAMERA_NAME + " CONTROL Y"
# 対象の名前のレイヤーが存在するか確認する
CompItem::hasTargetLayer = (targetName) ->
return @layer(targetName)?
###
起動しているAEの言語チェック
###
getLocalizedText = (str) ->
if app.language is Language.JAPANESE
str.jp
else
str.en
###
許容バージョンを渡し,実行できるか判別
###
runAEVersionCheck = (AEVersion) ->
if parseFloat(app.version) < AEVersion.getCanRunVersionNum()
alert "This script requires After Effects #{AEVersion.getCanRunVersionC()} or greater."
return false
else
return true
###
コンポジションにアクティブカメラが存在するか確認する関数
###
hasActiveCamera = (actComp) ->
return actComp.activeCamera?
###
コンポジションを選択しているか確認する関数
###
isCompActive = (selComp) ->
unless(selComp and selComp instanceof CompItem)
alert "Select Composition"
return false
else
return true
###
レイヤーを選択しているか確認する関数
###
isLayerSelected = (selLayers) ->
if selLayers.length is 0
alert "Select Layers"
return false
else
return true
entryFunc = () ->
# -------------------------------------------------------------------------
# アクティブカメラが存在しない場合,カメラを追加する.
unless hasActiveCamera actComp
actComp.layers.addCamera(FC3D4MMD2AEData.getScriptName(), [actComp.width/2, actComp.height/2])
unless actComp.hasTargetLayer(CAMERA_NAME)
CAMERA_NAME = prompt "MMD camera not found\nPut MMD camera layer's name", CAMERA_NAME
parentNullX = CAMERA_NAME + " CONTROL X"
parentNullY = CAMERA_NAME + " CONTROL Y"
return 0 unless CAMERA_NAME?
return 0 unless actComp.hasTargetLayer(CAMERA_NAME)
unless actComp.hasTargetLayer(parentNullX)
parentNullX = prompt "Control X not found\nPut Control X layer's name", parentNullX
return 0 unless parentNullX?
return 0 unless actComp.hasTargetLayer(parentNullX)
unless actComp.hasTargetLayer(parentNullY)
parentNullY = prompt "Control Y not found\nPut Control Y layer's name", CAMERA_NAME
return 0 unless parentNullY?
return 0 unless actComp.hasTargetLayer(parentNullY)
# -------------------------------------------------------------------------
for curLayer in [0...selLayers.length] by 1
# 対象のレイヤーがカメラかライトの場合は除外する
continue if selLayers[curLayer] instanceof CameraLayer or selLayers[curLayer] instanceof LightLayer
selLayers[curLayer].threeDLayer = true
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_POSITION).expression =
"thisComp.layer(\"#{CAMERA_NAME} CONTROL Y\").transform.position;"
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_SCALE).expression =
"""
var actCam = thisComp.activeCamera;
var camPointOfInterest = thisComp.layer("#{CAMERA_NAME} CONTROL X").transform.anchorPoint;
var camPosition = actCam.transform.position;
var camZoom = actCam.cameraOption.zoom;
var x = Math.abs(camPointOfInterest[0] - camPosition[0]);
var y = Math.abs(camPointOfInterest[1] - camPosition[1]);
var z = Math.abs(camPointOfInterest[2] - camPosition[2]);
range = Math.sqrt((x*x + y*y + z*z));
thisScale = range / camZoom * 100;
[thisScale, thisScale, thisScale]
"""
selLayers[curLayer].property(ADBE_TRANSFORM_GROUP).property(ADBE_ORIENTATION).expression =
"""
var x = transform.orientation[0];
var y = transform.orientation[1];
var z = transform.orientation[2] + thisComp.layer(\"#{CAMERA_NAME} CONTROL X\").transform.zRotation;
[x, y, z]
"""
selLayers[curLayer].autoOrient = AutoOrientType.CAMERA_OR_POINT_OF_INTEREST
return 0
undoEntryFunc = (data) ->
app.beginUndoGroup data.getScriptName()
entryFunc()
app.endUndoGroup()
return 0
###
メイン処理開始
###
return 0 unless runAEVersionCheck FC3D4MMD2AEData
actComp = app.project.activeItem
return 0 unless isCompActive actComp
selLayers = actComp.selectedLayers
return 0 unless isLayerSelected selLayers
undoEntryFunc FC3D4MMD2AEData
return 0
|
[
{
"context": "->\n @hello = kb.observable(model, {key:'hello_greeting', localizer: kb.LocalizedStringLocalizer})\n ",
"end": 4801,
"score": 0.5290507078170776,
"start": 4793,
"tag": "USERNAME",
"value": "greeting"
},
{
"context": "Date(1940, 10, 9)\n model = new Contact(... | test/spec/plugins/localization_and_defaults.tests.coffee | metacommunications/knockback | 0 | assert = assert or require?('chai').assert
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
kb.Backbone.ModelRef or require?('backbone-modelref') if kb.Backbone
unless Globalize
Globalize = require?('../../lib/globalize')
require?('../../lib/globalize.culture.en-GB.js'); require?('../../lib/globalize.culture.fr-FR.js')
###############################
class LocaleManager
@prototype extends kb.Events # Mix in kb.Events so callers can subscribe
constructor: (locale_identifier, @translations_by_locale) ->
@setLocale(locale_identifier) if locale_identifier
get: (string_id, parameters) ->
culture_map = @translations_by_locale[@locale_identifier] if @locale_identifier
return '' if not culture_map
string = if culture_map.hasOwnProperty(string_id) then culture_map[string_id] else ''
return string if arguments == 1
string = string.replace("{#{index}}", arg) for arg, index in Array.prototype.slice.call(arguments, 1)
return string
getLocale: -> return @locale_identifier
setLocale: (locale_identifier) ->
@locale_identifier = locale_identifier
@trigger('change', this)
@trigger("change:#{key}", value) for key, value of (@translations_by_locale[@locale_identifier] or {})
return
getLocales: ->
locales = []
locales.push(string_id) for string_id, value of @translations_by_locale
return locales
class LocalizedString
constructor: (@string_id) ->
throw 'missing kb.locale_manager' unless kb.locale_manager
@string = kb.locale_manager.get(@string_id)
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
class LocalizedStringLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
super
return kb.utils.wrappedObservable(@)
read: (value) ->
return if (value.string_id) then kb.locale_manager.get(value.string_id) else ''
class kb.LocalizedStringLocalizer extends kb.LocalizedObservable
read: (value) ->
return if (value.string_id) then kb.locale_manager.get(value.string_id) else ''
# NOTE: dependency on globalize
class kb.LongDateLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
return super # return the observable instead of this
read: (value) ->
return Globalize.format(value, 'dd MMMM yyyy', kb.locale_manager.getLocale())
write: (localized_string, value) ->
new_value = Globalize.parseDate(localized_string, 'dd MMMM yyyy', kb.locale_manager.getLocale())
return kb.utils.wrappedObservable(@).resetToCurrent() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
# NOTE: dependency on globalize - notice the alternative formulation with extend
kb.ShortDateLocalizer = kb.LocalizedObservable.extend({
constructor: (value, options, view_model) ->
kb.LocalizedObservable.prototype.constructor.apply(this, arguments)
return kb.utils.wrappedObservable(@) # return the observable instead of this
read: (value) ->
return Globalize.format(value, Globalize.cultures[kb.locale_manager.getLocale()].calendars.standard.patterns.d, kb.locale_manager.getLocale())
write: (localized_string, value) ->
new_value = Globalize.parseDate(localized_string, Globalize.cultures[kb.locale_manager.getLocale()].calendars.standard.patterns.d, kb.locale_manager.getLocale())
return kb.utils.wrappedObservable(@).resetToCurrent() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
})
###############################
describe 'localized-observable @quick @localization', ->
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!Globalize, 'Globalize')
done()
locale_manager = new LocaleManager('en', {
'en':
formal_hello: 'Hello'
formal_goodbye: 'Goodbye'
informal_hello: 'Hi'
informal_goodbye: 'Bye'
'en-GB':
formal_hello: 'Good day sir'
formal_goodbye: 'Goodbye darling'
informal_hello: "Let's get a pint"
informal_goodbye: 'Toodles'
'fr-FR':
informal_hello: 'Bonjour'
informal_goodbye: 'Au revoir'
formal_hello: 'Bonjour'
formal_goodbye: 'Au revoir'
})
it 'Localized greeting', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModelGreeting = (model) ->
@hello = kb.observable(model, {key:'hello_greeting', localizer: kb.LocalizedStringLocalizer})
@goodbye = kb.observable(model, {key:'goodbye_greeting', localizer: kb.LocalizedStringLocalizer})
@
model = new Contact({hello_greeting: new LocalizedString('formal_hello'), goodbye_greeting: new LocalizedString('formal_goodbye')})
view_model = new ContactViewModelGreeting(model)
kb.locale_manager.setLocale('en')
assert.equal(view_model.hello(), 'Hello', "en: Hello")
assert.equal(view_model.goodbye(), 'Goodbye', "en: Goobye")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.hello(), 'Good day sir', "en-GB: Hello")
assert.equal(view_model.goodbye(), 'Goodbye darling', "en-GB: Goobye")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.hello(), 'Bonjour', "fr-FR: Hello")
assert.equal(view_model.goodbye(), 'Au revoir', "fr-FR: Goobye")
model.set({hello_greeting: new LocalizedString('informal_hello'), goodbye_greeting: new LocalizedString('informal_goodbye')})
kb.locale_manager.setLocale('en')
assert.equal(view_model.hello(), 'Hi', "en: Hello")
assert.equal(view_model.goodbye(), 'Bye', "en: Goobye")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.hello(), "Let's get a pint", "en-GB: Hello")
assert.equal(view_model.goodbye(), 'Toodles', "en-GB: Goobye")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.hello(), 'Bonjour', "fr-FR: Hello")
assert.equal(view_model.goodbye(), 'Au revoir', "fr-FR: Goobye")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# NOTE: dependency on globalize and knockback-defaults
class LongDateLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
super
return kb.utils.wrappedObservable(@)
read: (value) ->
return Globalize.format(value, 'dd MMMM yyyy', kb.locale_manager.getLocale())
write: (localized_string, value, observable) ->
new_value = Globalize.parseDate(localized_string, 'dd MMMM yyyy', kb.locale_manager.getLocale())
return observable.setToDefault() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
it 'Date and time with jquery.globalize', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
ContactViewModelDate = (model) ->
@date = kb.observable(model, {key:'date', localizer: kb.LongDateLocalizer}, this)
@
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'John', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'Localization with a changing key', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
# directly with the locale manager
greeting_key = ko.observable('formal_hello')
locale_manager_greeting = kb.observable(kb.locale_manager, {key:greeting_key})
kb.locale_manager.setLocale('en')
assert.equal(locale_manager_greeting(), 'Hello', "en: Hello")
kb.locale_manager.setLocale('en-GB')
assert.equal(locale_manager_greeting(), 'Good day sir', "en-GB: Hello")
greeting_key('formal_goodbye')
assert.equal(locale_manager_greeting(), 'Goodbye darling', "en-GB: Goodbye")
kb.locale_manager.setLocale('en')
assert.equal(locale_manager_greeting(), 'Goodbye', "en: Goodbye")
ContactViewModelGreeting = (model) ->
@greeting_key = ko.observable('hello_greeting')
@greeting = kb.observable(model, {key:@greeting_key, localizer: kb.LocalizedStringLocalizer})
return
model = new Contact({hello_greeting: new LocalizedString('formal_hello'), goodbye_greeting: new LocalizedString('formal_goodbye')})
view_model = new ContactViewModelGreeting(model)
assert.equal(view_model.greeting(), 'Hello', "en: Hello")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.greeting(), 'Good day sir', "en-GB: Hello")
view_model.greeting_key('goodbye_greeting')
assert.equal(view_model.greeting(), 'Goodbye darling', "en-GB: Goodbye")
kb.locale_manager.setLocale('en')
assert.equal(view_model.greeting(), 'Goodbye', "en: Goodbye")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '2. internals test (Coffeescript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['email', 'date']})
@email = (value) =>
if arguments.length
@_email(value)
else
return if not @_email() then 'your.name@yourplace.com' else @_email()
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'John', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), 'your.name@yourplace.com', "default message")
view_model._email('j@imagine.com')
assert.equal(view_model.email(), 'j@imagine.com', "received email")
view_model.email('john@imagine.com')
assert.equal(view_model.email(), 'john@imagine.com', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past John's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. internals test (Javascript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = kb.ViewModel.extend({
constructor: (model) ->
kb.ViewModel.prototype.constructor.call(this, model, {internals: ['email', 'date']})
@email = (value) =>
if arguments.length
@_email(value)
else
return if not @_email() then 'your.name@yourplace.com' else @_email()
@date = new kb.LongDateLocalizer(@_date)
return
})
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'John', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), 'your.name@yourplace.com', "default message")
view_model._email('j@imagine.com')
assert.equal(view_model._email(), 'j@imagine.com', "received email")
assert.equal(view_model.email(), 'j@imagine.com', "received email")
view_model.email('john@imagine.com')
assert.equal(view_model._email(), 'john@imagine.com', "received email")
assert.equal(view_model.email(), 'john@imagine.com', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past John's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Using kb.localizedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['date']})
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'John', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "John's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Using kb.localizedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['date']})
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'John', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "John's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '10. Nested custom view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model, options) ->
super(model, _.extend({internals: ['date']}, options))
@date = new kb.LongDateLocalizer(@_date)
john_birthdate = new Date(1940, 10, 9)
john = new Contact({name: 'John', date: new Date(john_birthdate.valueOf())})
paul_birthdate = new Date(1942, 6, 18)
paul = new Contact({name: 'Paul', date: new Date(paul_birthdate.valueOf())})
george_birthdate = new Date(1943, 2, 25)
george = new Contact({name: 'George', date: new Date(george_birthdate.valueOf())})
ringo_birthdate = new Date(1940, 7, 7)
ringo = new Contact({name: 'Ringo', date: new Date(ringo_birthdate.valueOf())})
major_duo = new kb.Collection([john, paul])
minor_duo = new kb.Collection([george, ringo])
nested_model = new kb.Model({
john: john
paul: paul
george: george
ringo: ringo
major_duo1: major_duo
major_duo2: major_duo
major_duo3: major_duo
minor_duo1: minor_duo
minor_duo2: minor_duo
minor_duo3: minor_duo
})
nested_view_model = kb.viewModel(nested_model, {
factories:
john: ContactViewModelDate
george: {create: (model, options) -> return new ContactViewModelDate(model, options)}
'major_duo1.models': ContactViewModelDate
'major_duo2.models': {create: (model, options) -> return new ContactViewModelDate(model, options)}
'major_duo3.models': {models_only: true}
'minor_duo1.models': kb.ViewModel
'minor_duo2.models': {create: (model, options) -> return new kb.ViewModel(model, options)}
})
validateContactViewModel = (view_model, name, birthdate) ->
model = kb.utils.wrappedModel(view_model)
assert.equal(view_model.name(), name, "#{name}: Name matches")
# set from the view model
kb.locale_manager.setLocale('en-GB')
formatted_date = new kb.LongDateLocalizer(birthdate)
assert.equal(view_model.date(), formatted_date(), "#{name}: Birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good")
assert.equal(current_date.getMonth(), 11, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model._date().getFullYear(), 1963, "#{name}: year is good")
assert.equal(view_model._date().getMonth(), 11, "#{name}: month is good")
assert.equal(view_model._date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
# set from the model
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), formatted_date(), "#{name}: Birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good")
assert.equal(current_date.getMonth(), 10, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model._date().getFullYear(), 1940, "#{name}: year is good")
assert.equal(view_model._date().getMonth(), 10, "#{name}: month is good")
assert.equal(view_model._date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
validateGenericViewModel = (view_model, name, birthdate) ->
assert.equal(view_model.name(), name, "#{name}: Name matches")
assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
validateModel = (model, name, birthdate) ->
assert.equal(model.get('name'), name, "#{name}: Name matches")
assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
# models
validateContactViewModel(nested_view_model.john(), 'John', john_birthdate)
validateGenericViewModel(nested_view_model.paul(), 'Paul', paul_birthdate)
validateContactViewModel(nested_view_model.george(), 'George', george_birthdate)
validateGenericViewModel(nested_view_model.ringo(), 'Ringo', ringo_birthdate)
# colllections
validateContactViewModel(nested_view_model.major_duo1()[0], 'John', john_birthdate)
validateContactViewModel(nested_view_model.major_duo1()[1], 'Paul', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo2()[0], 'John', john_birthdate)
validateContactViewModel(nested_view_model.major_duo2()[1], 'Paul', paul_birthdate)
validateModel(nested_view_model.major_duo3()[0], 'John', john_birthdate)
validateModel(nested_view_model.major_duo3()[1], 'Paul', paul_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[0], 'George', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[1], 'Ringo', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo2()[0], 'George', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo2()[1], 'Ringo', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[0], 'George', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[1], 'Ringo', ringo_birthdate)
# and cleanup after yourself when you are done.
kb.release(nested_view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '12. Prior kb.Observables functionality', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = (model) ->
@dynamic_observables = kb.viewModel(model, {keys: {
name: {key: 'name'}
number: 'number'
date: {key: 'date', localizer: kb.LongDateLocalizer}
name2: {key: 'name'}
}}, @)
return
model = new Contact({name: 'John', number: '555-555-5558', date: new Date(1940, 10, 9)})
view_model = new ContactViewModel(model)
# get
assert.equal(view_model.name(), 'John', "It is a name")
assert.equal(view_model.name2(), 'John', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
# set from the view model
assert.equal(model.get('name'), 'John', "Name not changed")
assert.equal(view_model.name(), 'John', "Name not changed")
assert.equal(view_model.name2(), 'John', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(model.get('name'), 'John', "Name not changed")
assert.equal(view_model.name(), 'John', "Name not changed")
assert.equal(view_model.name2(), 'John', "Name not changed")
# set from the model
model.set({name: 'Yoko', number: '818-818-8181'})
assert.equal(view_model.name(), 'Yoko', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '13. Bulk mode (array of keys)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
model = new Contact({name: 'John', number: '555-555-5558'})
view_model = kb.viewModel(model, ['name', 'number'])
# get
assert.equal(view_model.name(), 'John', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
kb.locale_manager.setLocale('fr-FR')
# set from the view model
view_model.name('Paul')
assert.equal(model.get('name'), 'Paul', "Name changed")
assert.equal(view_model.name(), 'Paul', "Name changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
# set from the model
model.set({name: 'Yoko', number: '818-818-8181'})
assert.equal(view_model.name(), 'Yoko', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
kb.locale_manager.setLocale('fr-FR')
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
describe 'defaults @quick @defaults', ->
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!Globalize, 'Globalize')
done()
locale_manager = new LocaleManager('en', {
'en': {loading: "Loading dude"}
'en-GB': {loading: "Loading sir"}
'fr-FR': {loading: "Chargement"}
})
if kb.Backbone
it '1. Standard use case: just enough to get the picture', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = (model) ->
@loading_message = new kb.LocalizedStringLocalizer(new LocalizedString('loading'))
@_auto = kb.viewModel(model, {keys: {
name: {key:'name', default: @loading_message}
number: {key:'number', default: @loading_message}
date: {key:'date', default: @loading_message, localizer: kb.ShortDateLocalizer}
}}, this)
@
collection = new Contacts()
model_ref = new kb.Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
collection.add(collection.parse({id: 'b4', name: 'John', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), 'John', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09/11/1940', "John's birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09/11/1940', "John's birthdate in France format")
# set from the view model
assert.equal(model.get('name'), 'John', "Name not changed")
assert.equal(view_model.name(), 'John', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10/12/1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: 'Yoko', number: '818-818-8181'})
assert.equal(view_model.name(), 'Yoko', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09/11/1940', "John's birthdate in France format")
view_model.date('10/11/1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# go back to loading state
collection.reset()
assert.equal(view_model.name(), 'Chargement', "Resets to default")
view_model._auto.setToDefault() # override default behavior and go back to loading state
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '2. Standard use case with kb.ViewModels', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number', 'date']})
@loading_message = new kb.LocalizedStringLocalizer(new LocalizedString('loading'))
@name = kb.defaultObservable(@_name, @loading_message)
@number = kb.defaultObservable(@_number, @loading_message)
@date = kb.defaultObservable(new kb.LongDateLocalizer(@_date), @loading_message)
collection = new Contacts()
model_ref = new kb.Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
collection.add(collection.parse({id: 'b4', name: 'John', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), 'John', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
# set from the view model
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: 'Yoko', number: '818-818-8181'})
assert.equal(view_model.name(), 'Yoko', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# go back to loading state
collection.reset()
assert.equal(view_model.name(), 'Chargement', "Resets to default")
kb.utils.setToDefault(view_model)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. internals test (Coffeescript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['email', 'date']})
@email = kb.defaultObservable(@_email, 'your.name@yourplace.com')
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'John', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), 'your.name@yourplace.com', "default message")
view_model._email('j@imagine.com')
assert.equal(view_model._email(), 'j@imagine.com', "received email")
assert.equal(view_model.email(), 'j@imagine.com', "received email")
view_model.email('john@imagine.com')
assert.equal(view_model._email(), 'john@imagine.com', "received email")
assert.equal(view_model.email(), 'john@imagine.com', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past John's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/114
it '4. 0 should not behave as null', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new Contact()
casebutton = kb.observable(model, {key:'casebutton', 'default': 99});
casecond = ko.computed ->
switch casebutton()
when 0 then return 'Open'
when 1 then return 'Closed'
else return 'Unknown'
assert.equal(casebutton(), 99)
assert.equal(casecond(), 'Unknown')
model.set({casebutton: 0})
assert.equal(casebutton(), 0)
assert.equal(casecond(), 'Open')
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
| 77135 | assert = assert or require?('chai').assert
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
kb.Backbone.ModelRef or require?('backbone-modelref') if kb.Backbone
unless Globalize
Globalize = require?('../../lib/globalize')
require?('../../lib/globalize.culture.en-GB.js'); require?('../../lib/globalize.culture.fr-FR.js')
###############################
class LocaleManager
@prototype extends kb.Events # Mix in kb.Events so callers can subscribe
constructor: (locale_identifier, @translations_by_locale) ->
@setLocale(locale_identifier) if locale_identifier
get: (string_id, parameters) ->
culture_map = @translations_by_locale[@locale_identifier] if @locale_identifier
return '' if not culture_map
string = if culture_map.hasOwnProperty(string_id) then culture_map[string_id] else ''
return string if arguments == 1
string = string.replace("{#{index}}", arg) for arg, index in Array.prototype.slice.call(arguments, 1)
return string
getLocale: -> return @locale_identifier
setLocale: (locale_identifier) ->
@locale_identifier = locale_identifier
@trigger('change', this)
@trigger("change:#{key}", value) for key, value of (@translations_by_locale[@locale_identifier] or {})
return
getLocales: ->
locales = []
locales.push(string_id) for string_id, value of @translations_by_locale
return locales
class LocalizedString
constructor: (@string_id) ->
throw 'missing kb.locale_manager' unless kb.locale_manager
@string = kb.locale_manager.get(@string_id)
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
class LocalizedStringLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
super
return kb.utils.wrappedObservable(@)
read: (value) ->
return if (value.string_id) then kb.locale_manager.get(value.string_id) else ''
class kb.LocalizedStringLocalizer extends kb.LocalizedObservable
read: (value) ->
return if (value.string_id) then kb.locale_manager.get(value.string_id) else ''
# NOTE: dependency on globalize
class kb.LongDateLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
return super # return the observable instead of this
read: (value) ->
return Globalize.format(value, 'dd MMMM yyyy', kb.locale_manager.getLocale())
write: (localized_string, value) ->
new_value = Globalize.parseDate(localized_string, 'dd MMMM yyyy', kb.locale_manager.getLocale())
return kb.utils.wrappedObservable(@).resetToCurrent() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
# NOTE: dependency on globalize - notice the alternative formulation with extend
kb.ShortDateLocalizer = kb.LocalizedObservable.extend({
constructor: (value, options, view_model) ->
kb.LocalizedObservable.prototype.constructor.apply(this, arguments)
return kb.utils.wrappedObservable(@) # return the observable instead of this
read: (value) ->
return Globalize.format(value, Globalize.cultures[kb.locale_manager.getLocale()].calendars.standard.patterns.d, kb.locale_manager.getLocale())
write: (localized_string, value) ->
new_value = Globalize.parseDate(localized_string, Globalize.cultures[kb.locale_manager.getLocale()].calendars.standard.patterns.d, kb.locale_manager.getLocale())
return kb.utils.wrappedObservable(@).resetToCurrent() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
})
###############################
describe 'localized-observable @quick @localization', ->
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!Globalize, 'Globalize')
done()
locale_manager = new LocaleManager('en', {
'en':
formal_hello: 'Hello'
formal_goodbye: 'Goodbye'
informal_hello: 'Hi'
informal_goodbye: 'Bye'
'en-GB':
formal_hello: 'Good day sir'
formal_goodbye: 'Goodbye darling'
informal_hello: "Let's get a pint"
informal_goodbye: 'Toodles'
'fr-FR':
informal_hello: 'Bonjour'
informal_goodbye: 'Au revoir'
formal_hello: 'Bonjour'
formal_goodbye: 'Au revoir'
})
it 'Localized greeting', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModelGreeting = (model) ->
@hello = kb.observable(model, {key:'hello_greeting', localizer: kb.LocalizedStringLocalizer})
@goodbye = kb.observable(model, {key:'goodbye_greeting', localizer: kb.LocalizedStringLocalizer})
@
model = new Contact({hello_greeting: new LocalizedString('formal_hello'), goodbye_greeting: new LocalizedString('formal_goodbye')})
view_model = new ContactViewModelGreeting(model)
kb.locale_manager.setLocale('en')
assert.equal(view_model.hello(), 'Hello', "en: Hello")
assert.equal(view_model.goodbye(), 'Goodbye', "en: Goobye")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.hello(), 'Good day sir', "en-GB: Hello")
assert.equal(view_model.goodbye(), 'Goodbye darling', "en-GB: Goobye")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.hello(), 'Bonjour', "fr-FR: Hello")
assert.equal(view_model.goodbye(), 'Au revoir', "fr-FR: Goobye")
model.set({hello_greeting: new LocalizedString('informal_hello'), goodbye_greeting: new LocalizedString('informal_goodbye')})
kb.locale_manager.setLocale('en')
assert.equal(view_model.hello(), 'Hi', "en: Hello")
assert.equal(view_model.goodbye(), 'Bye', "en: Goobye")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.hello(), "Let's get a pint", "en-GB: Hello")
assert.equal(view_model.goodbye(), 'Toodles', "en-GB: Goobye")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.hello(), 'Bonjour', "fr-FR: Hello")
assert.equal(view_model.goodbye(), 'Au revoir', "fr-FR: Goobye")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# NOTE: dependency on globalize and knockback-defaults
class LongDateLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
super
return kb.utils.wrappedObservable(@)
read: (value) ->
return Globalize.format(value, 'dd MMMM yyyy', kb.locale_manager.getLocale())
write: (localized_string, value, observable) ->
new_value = Globalize.parseDate(localized_string, 'dd MMMM yyyy', kb.locale_manager.getLocale())
return observable.setToDefault() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
it 'Date and time with jquery.globalize', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
ContactViewModelDate = (model) ->
@date = kb.observable(model, {key:'date', localizer: kb.LongDateLocalizer}, this)
@
birthdate = new Date(1940, 10, 9)
model = new Contact({name: '<NAME>', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "<NAME>'s birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'Localization with a changing key', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
# directly with the locale manager
greeting_key = ko.observable('form<KEY>')
locale_manager_greeting = kb.observable(kb.locale_manager, {key:greeting_key})
kb.locale_manager.setLocale('en')
assert.equal(locale_manager_greeting(), 'Hello', "en: Hello")
kb.locale_manager.setLocale('en-GB')
assert.equal(locale_manager_greeting(), 'Good day sir', "en-GB: Hello")
greeting_key('<KEY>')
assert.equal(locale_manager_greeting(), 'Goodbye darling', "en-GB: Goodbye")
kb.locale_manager.setLocale('en')
assert.equal(locale_manager_greeting(), 'Goodbye', "en: Goodbye")
ContactViewModelGreeting = (model) ->
@greeting_key = ko.observable('hello_greeting')
@greeting = kb.observable(model, {key:@greeting_key, localizer: kb.LocalizedStringLocalizer})
return
model = new Contact({hello_greeting: new LocalizedString('formal_hello'), goodbye_greeting: new LocalizedString('formal_goodbye')})
view_model = new ContactViewModelGreeting(model)
assert.equal(view_model.greeting(), 'Hello', "en: Hello")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.greeting(), 'Good day sir', "en-GB: Hello")
view_model.greeting_key('goodbye_greeting')
assert.equal(view_model.greeting(), 'Goodbye darling', "en-GB: Goodbye")
kb.locale_manager.setLocale('en')
assert.equal(view_model.greeting(), 'Goodbye', "en: Goodbye")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '2. internals test (Coffeescript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['email', 'date']})
@email = (value) =>
if arguments.length
@_email(value)
else
return if not @_email() then '<EMAIL>' else @_email()
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: '<NAME>', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), '<EMAIL>', "default message")
view_model._email('<EMAIL>')
assert.equal(view_model.email(), '<EMAIL>', "received email")
view_model.email('<EMAIL>')
assert.equal(view_model.email(), '<EMAIL>', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "<NAME>'s birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past John's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. internals test (Javascript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = kb.ViewModel.extend({
constructor: (model) ->
kb.ViewModel.prototype.constructor.call(this, model, {internals: ['email', 'date']})
@email = (value) =>
if arguments.length
@_email(value)
else
return if not @_email() then '<EMAIL>' else @_email()
@date = new kb.LongDateLocalizer(@_date)
return
})
birthdate = new Date(1940, 10, 9)
model = new Contact({name: '<NAME>', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), '<EMAIL>', "default message")
view_model._email('<EMAIL>')
assert.equal(view_model._email(), '<EMAIL>', "received email")
assert.equal(view_model.email(), '<EMAIL>', "received email")
view_model.email('<EMAIL>')
assert.equal(view_model._email(), '<EMAIL>', "received email")
assert.equal(view_model.email(), '<EMAIL>', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past <NAME>'s birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Using kb.localizedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['date']})
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: '<NAME>', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "<NAME>'s birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "<NAME>'s birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Using kb.localizedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['date']})
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: '<NAME>', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "<NAME>'s birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "<NAME>'s birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '10. Nested custom view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model, options) ->
super(model, _.extend({internals: ['date']}, options))
@date = new kb.LongDateLocalizer(@_date)
john_birthdate = new Date(1940, 10, 9)
john = new Contact({name: '<NAME>', date: new Date(john_birthdate.valueOf())})
paul_birthdate = new Date(1942, 6, 18)
paul = new Contact({name: '<NAME>', date: new Date(paul_birthdate.valueOf())})
george_birthdate = new Date(1943, 2, 25)
george = new Contact({name: '<NAME>', date: new Date(george_birthdate.valueOf())})
ringo_birthdate = new Date(1940, 7, 7)
ringo = new Contact({name: '<NAME>', date: new Date(ringo_birthdate.valueOf())})
major_duo = new kb.Collection([john, paul])
minor_duo = new kb.Collection([george, ringo])
nested_model = new kb.Model({
john: john
paul: paul
george: george
ringo: ringo
major_duo1: major_duo
major_duo2: major_duo
major_duo3: major_duo
minor_duo1: minor_duo
minor_duo2: minor_duo
minor_duo3: minor_duo
})
nested_view_model = kb.viewModel(nested_model, {
factories:
john: ContactViewModelDate
george: {create: (model, options) -> return new ContactViewModelDate(model, options)}
'major_duo1.models': ContactViewModelDate
'major_duo2.models': {create: (model, options) -> return new ContactViewModelDate(model, options)}
'major_duo3.models': {models_only: true}
'minor_duo1.models': kb.ViewModel
'minor_duo2.models': {create: (model, options) -> return new kb.ViewModel(model, options)}
})
validateContactViewModel = (view_model, name, birthdate) ->
model = kb.utils.wrappedModel(view_model)
assert.equal(view_model.name(), name, "#{name}: Name matches")
# set from the view model
kb.locale_manager.setLocale('en-GB')
formatted_date = new kb.LongDateLocalizer(birthdate)
assert.equal(view_model.date(), formatted_date(), "#{name}: Birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good")
assert.equal(current_date.getMonth(), 11, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model._date().getFullYear(), 1963, "#{name}: year is good")
assert.equal(view_model._date().getMonth(), 11, "#{name}: month is good")
assert.equal(view_model._date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
# set from the model
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), formatted_date(), "#{name}: Birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good")
assert.equal(current_date.getMonth(), 10, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model._date().getFullYear(), 1940, "#{name}: year is good")
assert.equal(view_model._date().getMonth(), 10, "#{name}: month is good")
assert.equal(view_model._date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
validateGenericViewModel = (view_model, name, birthdate) ->
assert.equal(view_model.name(), name, "#{name}: Name matches")
assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
validateModel = (model, name, birthdate) ->
assert.equal(model.get('name'), name, "#{name}: Name matches")
assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
# models
validateContactViewModel(nested_view_model.john(), '<NAME>', john_birthdate)
validateGenericViewModel(nested_view_model.paul(), '<NAME>', paul_birthdate)
validateContactViewModel(nested_view_model.george(), '<NAME>', george_birthdate)
validateGenericViewModel(nested_view_model.ringo(), '<NAME>', ringo_birthdate)
# colllections
validateContactViewModel(nested_view_model.major_duo1()[0], '<NAME>', john_birthdate)
validateContactViewModel(nested_view_model.major_duo1()[1], '<NAME>', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo2()[0], '<NAME>', john_birthdate)
validateContactViewModel(nested_view_model.major_duo2()[1], '<NAME>', paul_birthdate)
validateModel(nested_view_model.major_duo3()[0], '<NAME>', john_birthdate)
validateModel(nested_view_model.major_duo3()[1], '<NAME>', paul_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[0], 'George', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[1], 'Ringo', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo2()[0], 'Ge<NAME>', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo2()[1], '<NAME>', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[0], '<NAME>', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[1], '<NAME>', ringo_birthdate)
# and cleanup after yourself when you are done.
kb.release(nested_view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '12. Prior kb.Observables functionality', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = (model) ->
@dynamic_observables = kb.viewModel(model, {keys: {
name: {key: 'name'}
number: 'number'
date: {key: 'date', localizer: kb.LongDateLocalizer}
name2: {key: 'name'}
}}, @)
return
model = new Contact({name: '<NAME>', number: '555-555-5558', date: new Date(1940, 10, 9)})
view_model = new ContactViewModel(model)
# get
assert.equal(view_model.name(), '<NAME>', "It is a name")
assert.equal(view_model.name2(), '<NAME>', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "<NAME>'s birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
# set from the view model
assert.equal(model.get('name'), '<NAME>', "Name not changed")
assert.equal(view_model.name(), '<NAME>', "Name not changed")
assert.equal(view_model.name2(), '<NAME>', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(model.get('name'), '<NAME>', "Name not changed")
assert.equal(view_model.name(), '<NAME>', "Name not changed")
assert.equal(view_model.name2(), '<NAME>', "Name not changed")
# set from the model
model.set({name: '<NAME>', number: '818-818-8181'})
assert.equal(view_model.name(), '<NAME>', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '13. Bulk mode (array of keys)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
model = new Contact({name: '<NAME>', number: '555-555-5558'})
view_model = kb.viewModel(model, ['name', 'number'])
# get
assert.equal(view_model.name(), '<NAME>', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
kb.locale_manager.setLocale('fr-FR')
# set from the view model
view_model.name('<NAME>')
assert.equal(model.get('name'), '<NAME>', "Name changed")
assert.equal(view_model.name(), '<NAME>', "Name changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
# set from the model
model.set({name: '<NAME>', number: '818-818-8181'})
assert.equal(view_model.name(), '<NAME>', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
kb.locale_manager.setLocale('fr-FR')
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
describe 'defaults @quick @defaults', ->
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!Globalize, 'Globalize')
done()
locale_manager = new LocaleManager('en', {
'en': {loading: "Loading dude"}
'en-GB': {loading: "Loading sir"}
'fr-FR': {loading: "Chargement"}
})
if kb.Backbone
it '1. Standard use case: just enough to get the picture', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = (model) ->
@loading_message = new kb.LocalizedStringLocalizer(new LocalizedString('loading'))
@_auto = kb.viewModel(model, {keys: {
name: {key:'name', default: @loading_message}
number: {key:'number', default: @loading_message}
date: {key:'date', default: @loading_message, localizer: kb.ShortDateLocalizer}
}}, this)
@
collection = new Contacts()
model_ref = new kb.Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
collection.add(collection.parse({id: 'b4', name: '<NAME>', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), '<NAME>', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09/11/1940', "<NAME>'s birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09/11/1940', "<NAME>'s birthdate in France format")
# set from the view model
assert.equal(model.get('name'), '<NAME>', "Name not changed")
assert.equal(view_model.name(), '<NAME>', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10/12/1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: '<NAME>', number: '818-818-8181'})
assert.equal(view_model.name(), '<NAME>', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09/11/1940', "<NAME>'s birthdate in France format")
view_model.date('10/11/1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# go back to loading state
collection.reset()
assert.equal(view_model.name(), 'Chargement', "Resets to default")
view_model._auto.setToDefault() # override default behavior and go back to loading state
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '2. Standard use case with kb.ViewModels', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number', 'date']})
@loading_message = new kb.LocalizedStringLocalizer(new LocalizedString('loading'))
@name = kb.defaultObservable(@_name, @loading_message)
@number = kb.defaultObservable(@_number, @loading_message)
@date = kb.defaultObservable(new kb.LongDateLocalizer(@_date), @loading_message)
collection = new Contacts()
model_ref = new kb.Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
collection.add(collection.parse({id: 'b4', name: '<NAME>', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), '<NAME>', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "<NAME>'s birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
# set from the view model
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: '<NAME>', number: '818-818-8181'})
assert.equal(view_model.name(), '<NAME>', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# go back to loading state
collection.reset()
assert.equal(view_model.name(), 'Chargement', "Resets to default")
kb.utils.setToDefault(view_model)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. internals test (Coffeescript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['email', 'date']})
@email = kb.defaultObservable(@_email, '<EMAIL>')
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: '<NAME>', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), '<EMAIL>', "default message")
view_model._email('<EMAIL>')
assert.equal(view_model._email(), '<EMAIL>', "received email")
assert.equal(view_model.email(), '<EMAIL>', "received email")
view_model.email('<EMAIL>')
assert.equal(view_model._email(), '<EMAIL>', "received email")
assert.equal(view_model.email(), '<EMAIL>', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "<NAME>'s birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past <NAME>'s birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/114
it '4. 0 should not behave as null', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new Contact()
casebutton = kb.observable(model, {key:'casebutton', 'default': 99});
casecond = ko.computed ->
switch casebutton()
when 0 then return 'Open'
when 1 then return 'Closed'
else return 'Unknown'
assert.equal(casebutton(), 99)
assert.equal(casecond(), 'Unknown')
model.set({casebutton: 0})
assert.equal(casebutton(), 0)
assert.equal(casecond(), 'Open')
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
| true | assert = assert or require?('chai').assert
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
kb.Backbone.ModelRef or require?('backbone-modelref') if kb.Backbone
unless Globalize
Globalize = require?('../../lib/globalize')
require?('../../lib/globalize.culture.en-GB.js'); require?('../../lib/globalize.culture.fr-FR.js')
###############################
class LocaleManager
@prototype extends kb.Events # Mix in kb.Events so callers can subscribe
constructor: (locale_identifier, @translations_by_locale) ->
@setLocale(locale_identifier) if locale_identifier
get: (string_id, parameters) ->
culture_map = @translations_by_locale[@locale_identifier] if @locale_identifier
return '' if not culture_map
string = if culture_map.hasOwnProperty(string_id) then culture_map[string_id] else ''
return string if arguments == 1
string = string.replace("{#{index}}", arg) for arg, index in Array.prototype.slice.call(arguments, 1)
return string
getLocale: -> return @locale_identifier
setLocale: (locale_identifier) ->
@locale_identifier = locale_identifier
@trigger('change', this)
@trigger("change:#{key}", value) for key, value of (@translations_by_locale[@locale_identifier] or {})
return
getLocales: ->
locales = []
locales.push(string_id) for string_id, value of @translations_by_locale
return locales
class LocalizedString
constructor: (@string_id) ->
throw 'missing kb.locale_manager' unless kb.locale_manager
@string = kb.locale_manager.get(@string_id)
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
class LocalizedStringLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
super
return kb.utils.wrappedObservable(@)
read: (value) ->
return if (value.string_id) then kb.locale_manager.get(value.string_id) else ''
class kb.LocalizedStringLocalizer extends kb.LocalizedObservable
read: (value) ->
return if (value.string_id) then kb.locale_manager.get(value.string_id) else ''
# NOTE: dependency on globalize
class kb.LongDateLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
return super # return the observable instead of this
read: (value) ->
return Globalize.format(value, 'dd MMMM yyyy', kb.locale_manager.getLocale())
write: (localized_string, value) ->
new_value = Globalize.parseDate(localized_string, 'dd MMMM yyyy', kb.locale_manager.getLocale())
return kb.utils.wrappedObservable(@).resetToCurrent() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
# NOTE: dependency on globalize - notice the alternative formulation with extend
kb.ShortDateLocalizer = kb.LocalizedObservable.extend({
constructor: (value, options, view_model) ->
kb.LocalizedObservable.prototype.constructor.apply(this, arguments)
return kb.utils.wrappedObservable(@) # return the observable instead of this
read: (value) ->
return Globalize.format(value, Globalize.cultures[kb.locale_manager.getLocale()].calendars.standard.patterns.d, kb.locale_manager.getLocale())
write: (localized_string, value) ->
new_value = Globalize.parseDate(localized_string, Globalize.cultures[kb.locale_manager.getLocale()].calendars.standard.patterns.d, kb.locale_manager.getLocale())
return kb.utils.wrappedObservable(@).resetToCurrent() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
})
###############################
describe 'localized-observable @quick @localization', ->
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!Globalize, 'Globalize')
done()
locale_manager = new LocaleManager('en', {
'en':
formal_hello: 'Hello'
formal_goodbye: 'Goodbye'
informal_hello: 'Hi'
informal_goodbye: 'Bye'
'en-GB':
formal_hello: 'Good day sir'
formal_goodbye: 'Goodbye darling'
informal_hello: "Let's get a pint"
informal_goodbye: 'Toodles'
'fr-FR':
informal_hello: 'Bonjour'
informal_goodbye: 'Au revoir'
formal_hello: 'Bonjour'
formal_goodbye: 'Au revoir'
})
it 'Localized greeting', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModelGreeting = (model) ->
@hello = kb.observable(model, {key:'hello_greeting', localizer: kb.LocalizedStringLocalizer})
@goodbye = kb.observable(model, {key:'goodbye_greeting', localizer: kb.LocalizedStringLocalizer})
@
model = new Contact({hello_greeting: new LocalizedString('formal_hello'), goodbye_greeting: new LocalizedString('formal_goodbye')})
view_model = new ContactViewModelGreeting(model)
kb.locale_manager.setLocale('en')
assert.equal(view_model.hello(), 'Hello', "en: Hello")
assert.equal(view_model.goodbye(), 'Goodbye', "en: Goobye")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.hello(), 'Good day sir', "en-GB: Hello")
assert.equal(view_model.goodbye(), 'Goodbye darling', "en-GB: Goobye")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.hello(), 'Bonjour', "fr-FR: Hello")
assert.equal(view_model.goodbye(), 'Au revoir', "fr-FR: Goobye")
model.set({hello_greeting: new LocalizedString('informal_hello'), goodbye_greeting: new LocalizedString('informal_goodbye')})
kb.locale_manager.setLocale('en')
assert.equal(view_model.hello(), 'Hi', "en: Hello")
assert.equal(view_model.goodbye(), 'Bye', "en: Goobye")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.hello(), "Let's get a pint", "en-GB: Hello")
assert.equal(view_model.goodbye(), 'Toodles', "en-GB: Goobye")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.hello(), 'Bonjour', "fr-FR: Hello")
assert.equal(view_model.goodbye(), 'Au revoir', "fr-FR: Goobye")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# NOTE: dependency on globalize and knockback-defaults
class LongDateLocalizer extends kb.LocalizedObservable
constructor: (value, options, view_model) ->
super
return kb.utils.wrappedObservable(@)
read: (value) ->
return Globalize.format(value, 'dd MMMM yyyy', kb.locale_manager.getLocale())
write: (localized_string, value, observable) ->
new_value = Globalize.parseDate(localized_string, 'dd MMMM yyyy', kb.locale_manager.getLocale())
return observable.setToDefault() if not (new_value and _.isDate(new_value)) # reset if invalid
value.setTime(new_value.valueOf())
it 'Date and time with jquery.globalize', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
ContactViewModelDate = (model) ->
@date = kb.observable(model, {key:'date', localizer: kb.LongDateLocalizer}, this)
@
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "PI:NAME:<NAME>END_PI's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'Localization with a changing key', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
# directly with the locale manager
greeting_key = ko.observable('formPI:KEY:<KEY>END_PI')
locale_manager_greeting = kb.observable(kb.locale_manager, {key:greeting_key})
kb.locale_manager.setLocale('en')
assert.equal(locale_manager_greeting(), 'Hello', "en: Hello")
kb.locale_manager.setLocale('en-GB')
assert.equal(locale_manager_greeting(), 'Good day sir', "en-GB: Hello")
greeting_key('PI:KEY:<KEY>END_PI')
assert.equal(locale_manager_greeting(), 'Goodbye darling', "en-GB: Goodbye")
kb.locale_manager.setLocale('en')
assert.equal(locale_manager_greeting(), 'Goodbye', "en: Goodbye")
ContactViewModelGreeting = (model) ->
@greeting_key = ko.observable('hello_greeting')
@greeting = kb.observable(model, {key:@greeting_key, localizer: kb.LocalizedStringLocalizer})
return
model = new Contact({hello_greeting: new LocalizedString('formal_hello'), goodbye_greeting: new LocalizedString('formal_goodbye')})
view_model = new ContactViewModelGreeting(model)
assert.equal(view_model.greeting(), 'Hello', "en: Hello")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.greeting(), 'Good day sir', "en-GB: Hello")
view_model.greeting_key('goodbye_greeting')
assert.equal(view_model.greeting(), 'Goodbye darling', "en-GB: Goodbye")
kb.locale_manager.setLocale('en')
assert.equal(view_model.greeting(), 'Goodbye', "en: Goodbye")
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '2. internals test (Coffeescript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['email', 'date']})
@email = (value) =>
if arguments.length
@_email(value)
else
return if not @_email() then 'PI:EMAIL:<EMAIL>END_PI' else @_email()
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "default message")
view_model._email('PI:EMAIL:<EMAIL>END_PI')
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
view_model.email('PI:EMAIL:<EMAIL>END_PI')
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "PI:NAME:<NAME>END_PI's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past John's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. internals test (Javascript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = kb.ViewModel.extend({
constructor: (model) ->
kb.ViewModel.prototype.constructor.call(this, model, {internals: ['email', 'date']})
@email = (value) =>
if arguments.length
@_email(value)
else
return if not @_email() then 'PI:EMAIL:<EMAIL>END_PI' else @_email()
@date = new kb.LongDateLocalizer(@_date)
return
})
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "default message")
view_model._email('PI:EMAIL:<EMAIL>END_PI')
assert.equal(view_model._email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
view_model.email('PI:EMAIL:<EMAIL>END_PI')
assert.equal(view_model._email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past PI:NAME:<NAME>END_PI's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Using kb.localizedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['date']})
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "PI:NAME:<NAME>END_PI's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '7. Using kb.localizedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['date']})
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModelDate(model)
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "PI:NAME:<NAME>END_PI's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '10. Nested custom view models', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModelDate extends kb.ViewModel
constructor: (model, options) ->
super(model, _.extend({internals: ['date']}, options))
@date = new kb.LongDateLocalizer(@_date)
john_birthdate = new Date(1940, 10, 9)
john = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(john_birthdate.valueOf())})
paul_birthdate = new Date(1942, 6, 18)
paul = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(paul_birthdate.valueOf())})
george_birthdate = new Date(1943, 2, 25)
george = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(george_birthdate.valueOf())})
ringo_birthdate = new Date(1940, 7, 7)
ringo = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(ringo_birthdate.valueOf())})
major_duo = new kb.Collection([john, paul])
minor_duo = new kb.Collection([george, ringo])
nested_model = new kb.Model({
john: john
paul: paul
george: george
ringo: ringo
major_duo1: major_duo
major_duo2: major_duo
major_duo3: major_duo
minor_duo1: minor_duo
minor_duo2: minor_duo
minor_duo3: minor_duo
})
nested_view_model = kb.viewModel(nested_model, {
factories:
john: ContactViewModelDate
george: {create: (model, options) -> return new ContactViewModelDate(model, options)}
'major_duo1.models': ContactViewModelDate
'major_duo2.models': {create: (model, options) -> return new ContactViewModelDate(model, options)}
'major_duo3.models': {models_only: true}
'minor_duo1.models': kb.ViewModel
'minor_duo2.models': {create: (model, options) -> return new kb.ViewModel(model, options)}
})
validateContactViewModel = (view_model, name, birthdate) ->
model = kb.utils.wrappedModel(view_model)
assert.equal(view_model.name(), name, "#{name}: Name matches")
# set from the view model
kb.locale_manager.setLocale('en-GB')
formatted_date = new kb.LongDateLocalizer(birthdate)
assert.equal(view_model.date(), formatted_date(), "#{name}: Birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "#{name}: year is good")
assert.equal(current_date.getMonth(), 11, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model._date().getFullYear(), 1963, "#{name}: year is good")
assert.equal(view_model._date().getMonth(), 11, "#{name}: month is good")
assert.equal(view_model._date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
# set from the model
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), formatted_date(), "#{name}: Birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "#{name}: year is good")
assert.equal(current_date.getMonth(), 10, "#{name}: month is good")
assert.equal(current_date.getDate(), 10, "#{name}: day is good")
assert.equal(view_model._date().getFullYear(), 1940, "#{name}: year is good")
assert.equal(view_model._date().getMonth(), 10, "#{name}: month is good")
assert.equal(view_model._date().getDate(), 10, "#{name}: day is good")
model.set({date: new Date(birthdate.valueOf())}) # restore birthdate
validateGenericViewModel = (view_model, name, birthdate) ->
assert.equal(view_model.name(), name, "#{name}: Name matches")
assert.equal(view_model.date().valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
validateModel = (model, name, birthdate) ->
assert.equal(model.get('name'), name, "#{name}: Name matches")
assert.equal(model.get('date').valueOf(), birthdate.valueOf(), "#{name}: Birthdate matches")
# models
validateContactViewModel(nested_view_model.john(), 'PI:NAME:<NAME>END_PI', john_birthdate)
validateGenericViewModel(nested_view_model.paul(), 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateContactViewModel(nested_view_model.george(), 'PI:NAME:<NAME>END_PI', george_birthdate)
validateGenericViewModel(nested_view_model.ringo(), 'PI:NAME:<NAME>END_PI', ringo_birthdate)
# colllections
validateContactViewModel(nested_view_model.major_duo1()[0], 'PI:NAME:<NAME>END_PI', john_birthdate)
validateContactViewModel(nested_view_model.major_duo1()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateContactViewModel(nested_view_model.major_duo2()[0], 'PI:NAME:<NAME>END_PI', john_birthdate)
validateContactViewModel(nested_view_model.major_duo2()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateModel(nested_view_model.major_duo3()[0], 'PI:NAME:<NAME>END_PI', john_birthdate)
validateModel(nested_view_model.major_duo3()[1], 'PI:NAME:<NAME>END_PI', paul_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[0], 'George', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo1()[1], 'Ringo', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo2()[0], 'GePI:NAME:<NAME>END_PI', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo2()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[0], 'PI:NAME:<NAME>END_PI', george_birthdate)
validateGenericViewModel(nested_view_model.minor_duo3()[1], 'PI:NAME:<NAME>END_PI', ringo_birthdate)
# and cleanup after yourself when you are done.
kb.release(nested_view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '12. Prior kb.Observables functionality', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = (model) ->
@dynamic_observables = kb.viewModel(model, {keys: {
name: {key: 'name'}
number: 'number'
date: {key: 'date', localizer: kb.LongDateLocalizer}
name2: {key: 'name'}
}}, @)
return
model = new Contact({name: 'PI:NAME:<NAME>END_PI', number: '555-555-5558', date: new Date(1940, 10, 9)})
view_model = new ContactViewModel(model)
# get
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "It is a name")
assert.equal(view_model.name2(), 'PI:NAME:<NAME>END_PI', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "PI:NAME:<NAME>END_PI's birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
# set from the view model
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "Name not changed")
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name not changed")
assert.equal(view_model.name2(), 'PI:NAME:<NAME>END_PI', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "Name not changed")
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name not changed")
assert.equal(view_model.name2(), 'PI:NAME:<NAME>END_PI', "Name not changed")
# set from the model
model.set({name: 'PI:NAME:<NAME>END_PI', number: '818-818-8181'})
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '13. Bulk mode (array of keys)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
model = new Contact({name: 'PI:NAME:<NAME>END_PI', number: '555-555-5558'})
view_model = kb.viewModel(model, ['name', 'number'])
# get
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
kb.locale_manager.setLocale('fr-FR')
# set from the view model
view_model.name('PI:NAME:<NAME>END_PI')
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
# set from the model
model.set({name: 'PI:NAME:<NAME>END_PI', number: '818-818-8181'})
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
kb.locale_manager.setLocale('fr-FR')
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
describe 'defaults @quick @defaults', ->
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!Globalize, 'Globalize')
done()
locale_manager = new LocaleManager('en', {
'en': {loading: "Loading dude"}
'en-GB': {loading: "Loading sir"}
'fr-FR': {loading: "Chargement"}
})
if kb.Backbone
it '1. Standard use case: just enough to get the picture', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
ContactViewModel = (model) ->
@loading_message = new kb.LocalizedStringLocalizer(new LocalizedString('loading'))
@_auto = kb.viewModel(model, {keys: {
name: {key:'name', default: @loading_message}
number: {key:'number', default: @loading_message}
date: {key:'date', default: @loading_message, localizer: kb.ShortDateLocalizer}
}}, this)
@
collection = new Contacts()
model_ref = new kb.Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
collection.add(collection.parse({id: 'b4', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09/11/1940', "PI:NAME:<NAME>END_PI's birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09/11/1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
# set from the view model
assert.equal(model.get('name'), 'PI:NAME:<NAME>END_PI', "Name not changed")
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name not changed")
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10/12/1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: 'PI:NAME:<NAME>END_PI', number: '818-818-8181'})
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09/11/1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
view_model.date('10/11/1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# go back to loading state
collection.reset()
assert.equal(view_model.name(), 'Chargement', "Resets to default")
view_model._auto.setToDefault() # override default behavior and go back to loading state
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '2. Standard use case with kb.ViewModels', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number', 'date']})
@loading_message = new kb.LocalizedStringLocalizer(new LocalizedString('loading'))
@name = kb.defaultObservable(@_name, @loading_message)
@number = kb.defaultObservable(@_number, @loading_message)
@date = kb.defaultObservable(new kb.LongDateLocalizer(@_date), @loading_message)
collection = new Contacts()
model_ref = new kb.Backbone.ModelRef(collection, 'b4')
view_model = new ContactViewModel(model_ref)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
collection.add(collection.parse({id: 'b4', name: 'PI:NAME:<NAME>END_PI', number: '555-555-5558', date: new Date(1940, 10, 9)}))
model = collection.get('b4')
# get
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "It is a name")
assert.equal(view_model.number(), '555-555-5558', "Not so interesting number")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "PI:NAME:<NAME>END_PI's birthdate in Great Britain format")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
# set from the view model
view_model.number('9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '9222-222-222', "Number was changed")
kb.locale_manager.setLocale('en-GB')
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# set from the model
model.set({name: 'PI:NAME:<NAME>END_PI', number: '818-818-8181'})
assert.equal(view_model.name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.number(), '818-818-8181', "Number was changed")
model.set({date: new Date(1940, 10, 9)})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "John's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
# go back to loading state
collection.reset()
assert.equal(view_model.name(), 'Chargement', "Resets to default")
kb.utils.setToDefault(view_model)
kb.locale_manager.setLocale('en')
assert.equal(view_model.name(), 'Loading dude', "Is that what we want to convey?")
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.name(), 'Loading sir', "Maybe too formal")
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.name(), 'Chargement', "Localize from day one. Good!")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '3. internals test (Coffeescript inheritance)', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
kb.locale_manager = locale_manager
class ContactViewModel extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['email', 'date']})
@email = kb.defaultObservable(@_email, 'PI:EMAIL:<EMAIL>END_PI')
@date = new kb.LongDateLocalizer(@_date)
birthdate = new Date(1940, 10, 9)
model = new Contact({name: 'PI:NAME:<NAME>END_PI', date: new Date(birthdate.valueOf())})
view_model = new ContactViewModel(model)
# check email
assert.equal(view_model._email(), undefined, "no email")
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "default message")
view_model._email('PI:EMAIL:<EMAIL>END_PI')
assert.equal(view_model._email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
view_model.email('PI:EMAIL:<EMAIL>END_PI')
assert.equal(view_model._email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
assert.equal(view_model.email(), 'PI:EMAIL:<EMAIL>END_PI', "received email")
# set from the view model
kb.locale_manager.setLocale('en-GB')
assert.equal(view_model.date(), '09 November 1940', "John's birthdate in Great Britain format")
view_model.date('10 December 1963')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1963, "year is good")
assert.equal(current_date.getMonth(), 11, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1963, "year is good")
assert.equal(view_model._date().getMonth(), 11, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the model
model.set({date: new Date(birthdate.valueOf())})
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '09 novembre 1940', "PI:NAME:<NAME>END_PI's birthdate in France format")
view_model.date('10 novembre 1940')
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# set from the automatically-generated date observable
view_model.date(new Date(birthdate.valueOf()))
kb.locale_manager.setLocale('fr-FR')
assert.equal(view_model.date(), '10 novembre 1940', "One past PI:NAME:<NAME>END_PI's birthdate in France format")
current_date = model.get('date')
assert.equal(current_date.getFullYear(), 1940, "year is good")
assert.equal(current_date.getMonth(), 10, "month is good")
assert.equal(current_date.getDate(), 10, "day is good")
assert.equal(view_model._date().getFullYear(), 1940, "year is good")
assert.equal(view_model._date().getMonth(), 10, "month is good")
assert.equal(view_model._date().getDate(), 10, "day is good")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
# https://github.com/kmalakoff/knockback/issues/114
it '4. 0 should not behave as null', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
model = new Contact()
casebutton = kb.observable(model, {key:'casebutton', 'default': 99});
casecond = ko.computed ->
switch casebutton()
when 0 then return 'Open'
when 1 then return 'Closed'
else return 'Unknown'
assert.equal(casebutton(), 99)
assert.equal(casecond(), 'Unknown')
model.set({casebutton: 0})
assert.equal(casebutton(), 0)
assert.equal(casecond(), 'Open')
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
|
[
{
"context": " options.tagName = 'a'\n options.title = niceName\n options.href = link or '#'\n opt",
"end": 2429,
"score": 0.8740706443786621,
"start": 2425,
"tag": "NAME",
"value": "nice"
}
] | client/activity/lib/views/activityinputhelperview.coffee | ezgikaysi/koding | 1 | _ = require 'lodash'
kd = require 'kd'
KDCustomHTMLView = kd.CustomHTMLView
CustomLinkView = require 'app/customlinkview'
module.exports = class ActivityInputHelperView extends KDCustomHTMLView
helpMap =
mysql :
niceName : 'MySQL'
tooltip :
title : 'Open your terminal and type <code>help mysql</code>'
phpmyadmin :
niceName : 'phpMyAdmin'
tooltip :
title : 'Open your terminal and type <code>help phpmyadmin</code>'
"vm size" :
pattern : 'vm\\ssize|vm\\sconfig'
niceName : 'VM config'
tooltip :
title : 'Open your terminal and type <code>help specs</code>'
"vm down" :
pattern : 'vm\\sdown|vm\\snot\\sworking|vm\\sis\\snot\\sworking'
niceName : 'non-working VM'
tooltip :
title : 'You can go to your environments and try to restart your VM'
help :
niceName : 'Help!!!'
tooltip :
title : "You don't need to type help in your post, just ask your question."
wordpress :
niceName : 'WordPress'
link : 'https://koding.com/docs/topic/wordpress'
constructor: (options = {}, data) ->
options.cssClass ?= 'help-container hidden'
options.partial ?= 'Need help with:'
super options, data
@currentHelperNames = []
getPattern: ->
helpKeys = Object.keys helpMap
///#{(helpMap[key].pattern or key for key in helpKeys).join('|')}///gi
checkForCommonQuestions: kd.utils.throttle 200, (val)->
@hideAllHelpers()
pattern = @getPattern()
match = pattern.exec val
matches = []
while match isnt null
matches.push match[0] if match
match = pattern.exec val
@addHelper keyword for keyword in matches
addHelper: (val) ->
@show()
unless helpMap[val.toLowerCase()]
for own key, item of helpMap when item.pattern
if ///#{item.pattern}///i.test val
val = key
break
return if val in @currentHelperNames
{niceName, link, tooltip} = helpMap[val.toLowerCase()]
Klass = KDCustomHTMLView
options =
tagName : 'span'
partial : niceName
if tooltip
options.tooltip = _.extend {}, tooltip
options.tooltip.cssClass = 'activity-helper'
options.tooltip.placement = 'bottom'
if link
Klass = CustomLinkView
options.tagName = 'a'
options.title = niceName
options.href = link or '#'
options.target = if link?[0] isnt '/' then '_blank' else ''
@addSubView new Klass options
@currentHelperNames.push val
hideAllHelpers:->
@hide()
@destroySubViews()
@currentHelperNames = []
| 217395 | _ = require 'lodash'
kd = require 'kd'
KDCustomHTMLView = kd.CustomHTMLView
CustomLinkView = require 'app/customlinkview'
module.exports = class ActivityInputHelperView extends KDCustomHTMLView
helpMap =
mysql :
niceName : 'MySQL'
tooltip :
title : 'Open your terminal and type <code>help mysql</code>'
phpmyadmin :
niceName : 'phpMyAdmin'
tooltip :
title : 'Open your terminal and type <code>help phpmyadmin</code>'
"vm size" :
pattern : 'vm\\ssize|vm\\sconfig'
niceName : 'VM config'
tooltip :
title : 'Open your terminal and type <code>help specs</code>'
"vm down" :
pattern : 'vm\\sdown|vm\\snot\\sworking|vm\\sis\\snot\\sworking'
niceName : 'non-working VM'
tooltip :
title : 'You can go to your environments and try to restart your VM'
help :
niceName : 'Help!!!'
tooltip :
title : "You don't need to type help in your post, just ask your question."
wordpress :
niceName : 'WordPress'
link : 'https://koding.com/docs/topic/wordpress'
constructor: (options = {}, data) ->
options.cssClass ?= 'help-container hidden'
options.partial ?= 'Need help with:'
super options, data
@currentHelperNames = []
getPattern: ->
helpKeys = Object.keys helpMap
///#{(helpMap[key].pattern or key for key in helpKeys).join('|')}///gi
checkForCommonQuestions: kd.utils.throttle 200, (val)->
@hideAllHelpers()
pattern = @getPattern()
match = pattern.exec val
matches = []
while match isnt null
matches.push match[0] if match
match = pattern.exec val
@addHelper keyword for keyword in matches
addHelper: (val) ->
@show()
unless helpMap[val.toLowerCase()]
for own key, item of helpMap when item.pattern
if ///#{item.pattern}///i.test val
val = key
break
return if val in @currentHelperNames
{niceName, link, tooltip} = helpMap[val.toLowerCase()]
Klass = KDCustomHTMLView
options =
tagName : 'span'
partial : niceName
if tooltip
options.tooltip = _.extend {}, tooltip
options.tooltip.cssClass = 'activity-helper'
options.tooltip.placement = 'bottom'
if link
Klass = CustomLinkView
options.tagName = 'a'
options.title = <NAME>Name
options.href = link or '#'
options.target = if link?[0] isnt '/' then '_blank' else ''
@addSubView new Klass options
@currentHelperNames.push val
hideAllHelpers:->
@hide()
@destroySubViews()
@currentHelperNames = []
| true | _ = require 'lodash'
kd = require 'kd'
KDCustomHTMLView = kd.CustomHTMLView
CustomLinkView = require 'app/customlinkview'
module.exports = class ActivityInputHelperView extends KDCustomHTMLView
helpMap =
mysql :
niceName : 'MySQL'
tooltip :
title : 'Open your terminal and type <code>help mysql</code>'
phpmyadmin :
niceName : 'phpMyAdmin'
tooltip :
title : 'Open your terminal and type <code>help phpmyadmin</code>'
"vm size" :
pattern : 'vm\\ssize|vm\\sconfig'
niceName : 'VM config'
tooltip :
title : 'Open your terminal and type <code>help specs</code>'
"vm down" :
pattern : 'vm\\sdown|vm\\snot\\sworking|vm\\sis\\snot\\sworking'
niceName : 'non-working VM'
tooltip :
title : 'You can go to your environments and try to restart your VM'
help :
niceName : 'Help!!!'
tooltip :
title : "You don't need to type help in your post, just ask your question."
wordpress :
niceName : 'WordPress'
link : 'https://koding.com/docs/topic/wordpress'
constructor: (options = {}, data) ->
options.cssClass ?= 'help-container hidden'
options.partial ?= 'Need help with:'
super options, data
@currentHelperNames = []
getPattern: ->
helpKeys = Object.keys helpMap
///#{(helpMap[key].pattern or key for key in helpKeys).join('|')}///gi
checkForCommonQuestions: kd.utils.throttle 200, (val)->
@hideAllHelpers()
pattern = @getPattern()
match = pattern.exec val
matches = []
while match isnt null
matches.push match[0] if match
match = pattern.exec val
@addHelper keyword for keyword in matches
addHelper: (val) ->
@show()
unless helpMap[val.toLowerCase()]
for own key, item of helpMap when item.pattern
if ///#{item.pattern}///i.test val
val = key
break
return if val in @currentHelperNames
{niceName, link, tooltip} = helpMap[val.toLowerCase()]
Klass = KDCustomHTMLView
options =
tagName : 'span'
partial : niceName
if tooltip
options.tooltip = _.extend {}, tooltip
options.tooltip.cssClass = 'activity-helper'
options.tooltip.placement = 'bottom'
if link
Klass = CustomLinkView
options.tagName = 'a'
options.title = PI:NAME:<NAME>END_PIName
options.href = link or '#'
options.target = if link?[0] isnt '/' then '_blank' else ''
@addSubView new Klass options
@currentHelperNames.push val
hideAllHelpers:->
@hide()
@destroySubViews()
@currentHelperNames = []
|
[
{
"context": ")\n\nStaticTeams = {\n mystic : {\n name : \"Mystic\"\n leader : \"Blanche\"\n color : \"blue",
"end": 88,
"score": 0.9972367882728577,
"start": 82,
"tag": "NAME",
"value": "Mystic"
},
{
"context": "tic : {\n name : \"Mystic\"\n lea... | src/pokemon-go/teams.coffee | technogeek00/hipchat-pokemon-go | 3 | database = require('../database')
StaticTeams = {
mystic : {
name : "Mystic"
leader : "Blanche"
color : "blue"
mascot : "Articuno"
}
valor : {
name : "Valor"
leader : "Candela"
color : "red"
mascot : "Moltres"
}
instinct : {
name : "Instinct"
leader : "Spark"
color : "yellow"
mascot : "Zapados"
}
}
module.exports = Teams = {
get : (name, cb) ->
name = name.toLowerCase()
unless StaticTeams[name]?
return cb("Invalid team name")
return cb(null, StaticTeams[name])
getMembers : (name, cb) ->
Teams.get(name, (err, info) ->
return cb(err) if err?
database.query("SELECT name, mention, home FROM `trainers` WHERE `team` = ? ORDER BY name", [info.name], (err, rows) ->
return cb(err) if err?
members = ({
name : row.name,
mention : row.mention,
home : row.home
} for row in rows)
cb(null, info, members)
)
)
join : (name, trainer, cb) ->
Teams.get(name, (err, info) ->
return cb(err) if err?
database.query("UPDATE trainers SET team = ? WHERE user_id = ?", [name, trainer.id], (err, rows) ->
return cb(err) if err?
cb(null, {
team : info
trainer : trainer
})
)
)
} | 72154 | database = require('../database')
StaticTeams = {
mystic : {
name : "<NAME>"
leader : "<NAME>"
color : "blue"
mascot : "<NAME>"
}
valor : {
name : "<NAME>"
leader : "<NAME>"
color : "red"
mascot : "M<NAME>"
}
instinct : {
name : "<NAME>"
leader : "<NAME>"
color : "yellow"
mascot : "Zapados"
}
}
module.exports = Teams = {
get : (name, cb) ->
name = name.toLowerCase()
unless StaticTeams[name]?
return cb("Invalid team name")
return cb(null, StaticTeams[name])
getMembers : (name, cb) ->
Teams.get(name, (err, info) ->
return cb(err) if err?
database.query("SELECT name, mention, home FROM `trainers` WHERE `team` = ? ORDER BY name", [info.name], (err, rows) ->
return cb(err) if err?
members = ({
name : row.name,
mention : row.mention,
home : row.home
} for row in rows)
cb(null, info, members)
)
)
join : (name, trainer, cb) ->
Teams.get(name, (err, info) ->
return cb(err) if err?
database.query("UPDATE trainers SET team = ? WHERE user_id = ?", [name, trainer.id], (err, rows) ->
return cb(err) if err?
cb(null, {
team : info
trainer : trainer
})
)
)
} | true | database = require('../database')
StaticTeams = {
mystic : {
name : "PI:NAME:<NAME>END_PI"
leader : "PI:NAME:<NAME>END_PI"
color : "blue"
mascot : "PI:NAME:<NAME>END_PI"
}
valor : {
name : "PI:NAME:<NAME>END_PI"
leader : "PI:NAME:<NAME>END_PI"
color : "red"
mascot : "MPI:NAME:<NAME>END_PI"
}
instinct : {
name : "PI:NAME:<NAME>END_PI"
leader : "PI:NAME:<NAME>END_PI"
color : "yellow"
mascot : "Zapados"
}
}
module.exports = Teams = {
get : (name, cb) ->
name = name.toLowerCase()
unless StaticTeams[name]?
return cb("Invalid team name")
return cb(null, StaticTeams[name])
getMembers : (name, cb) ->
Teams.get(name, (err, info) ->
return cb(err) if err?
database.query("SELECT name, mention, home FROM `trainers` WHERE `team` = ? ORDER BY name", [info.name], (err, rows) ->
return cb(err) if err?
members = ({
name : row.name,
mention : row.mention,
home : row.home
} for row in rows)
cb(null, info, members)
)
)
join : (name, trainer, cb) ->
Teams.get(name, (err, info) ->
return cb(err) if err?
database.query("UPDATE trainers SET team = ? WHERE user_id = ?", [name, trainer.id], (err, rows) ->
return cb(err) if err?
cb(null, {
team : info
trainer : trainer
})
)
)
} |
[
{
"context": "firing-multiple-times\n # debouncing function from John Hann\n # http://unscriptable.com/index.php/2009/03/20/",
"end": 3186,
"score": 0.9971752166748047,
"start": 3177,
"tag": "NAME",
"value": "John Hann"
}
] | otto.client.misc.coffee | ferguson/otto | 16 | ###############
### client side (body of otto.client.misc.coffee served as /otto.misc.js)
###############
global.otto.client.misc = ->
window.otto = window.otto || {}
# on demand client side modules
otto.client = otto.client || {}
otto.load_module = (modulename, callback) ->
if not otto.client[modulename]
console.log "loading module #{modulename}"
$.getScript "/otto.client.#{modulename}.js", ->
console.log "module #{modulename} loaded"
if callback
callback()
else
if callback
callback()
otto.call_module = (modulename, methodname, args...) ->
otto.load_module modulename, ->
console.log "calling otto.client.#{modulename}.#{methodname}(args...)"
otto.client[modulename][methodname](args...)
otto.call_module_ifloaded = (modulename, methodname, args...) ->
# only call the module if it is already loaded, otherwise do nothing
if otto.client[modulename] # don't trigger a automatic module load
otto.call_module modulename, methodname, args...
else
console.log "ignoring call to unloaded module otto.client.#{modulename}.#{methodname}(args...)"
otto.ismoduleloaded = (modulename) ->
return otto.client[modulename]?
# client side version of node's nextTick
window.nextTick = (func) -> setTimeout(func, 0)
# coffeescript friendly version of setTimeout and setInterval
window.timeoutSet = (ms, func) -> setTimeout(func, ms)
window.intervalSet = (ms, func) -> setInterval(func, ms)
$.fn.scrollToBottom = ->
this.animate scrollTop: this.prop('scrollHeight') - this.height(), 100
otto.autosize_clear_cache = -> otto.$autosize_elements_cache = false
otto.autosize_clear_cache()
otto.autosize_adjust = ->
console.log 'autosize_adjust'
if !otto.$autosize_elements_cache
otto.$autosize_elements_cache = $('.autosize')
otto.$autosize_elements_cache.each (index, element) ->
$element = $ element
maxFontSize = $element.data('autosize-max') || $element.height()-4
minFontSize = $element.data('autosize-min') || Math.round($element.height/2)-4
rightMargin = $element.data('autosize-right-margin') || 0
fontSize = maxFontSize
#while size > minFontSize and element.scrollWidth > element.offsetWidth
# $element.css 'font-size': "#{fontSize}px"
desiredWidth = $element.parent().width()
$resizer = $element.clone()
$resizer.css
'display': 'inline'
'white-space': 'nowrap'
'width': 'auto'
'font-size': "#{fontSize}px"
$resizer.insertAfter($element)
while fontSize > minFontSize and $resizer.width() > desiredWidth
fontSize = fontSize - 1
$resizer.css 'font-size': "#{fontSize}px"
# adjust the top so the text stays centered in the div
heightAdjust = 0
if fontSize > minFontSize
heightAdjust = (maxFontSize - fontSize) / 2
$resizer.remove()
$element.css
'font-size': "#{fontSize}px"
'top': "#{heightAdjust}px"
# from http://stackoverflow.com/questions/6658517/window-resize-in-jquery-firing-multiple-times
# debouncing function from John Hann
# http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
# usage:
# $(window).smartresize ->
# code that takes it easy...
do ($ = jQuery, sr = 'smartresize') ->
debounce = (func, threshold, execAsap) ->
timeout = null
debounced = ->
obj = this
args = arguments
delayed = ->
if not execAsap
func.apply(obj, args)
timeout = null
if timeout
clearTimeout timeout
else if execAsap
func.apply(obj, args)
timeout = setTimeout(delayed, threshold || 50)
return debounced
# smartresize
$.fn[sr] = (fn) ->
return if fn then this.bind('resize', debounce(fn)) else this.trigger(sr)
| 168148 | ###############
### client side (body of otto.client.misc.coffee served as /otto.misc.js)
###############
global.otto.client.misc = ->
window.otto = window.otto || {}
# on demand client side modules
otto.client = otto.client || {}
otto.load_module = (modulename, callback) ->
if not otto.client[modulename]
console.log "loading module #{modulename}"
$.getScript "/otto.client.#{modulename}.js", ->
console.log "module #{modulename} loaded"
if callback
callback()
else
if callback
callback()
otto.call_module = (modulename, methodname, args...) ->
otto.load_module modulename, ->
console.log "calling otto.client.#{modulename}.#{methodname}(args...)"
otto.client[modulename][methodname](args...)
otto.call_module_ifloaded = (modulename, methodname, args...) ->
# only call the module if it is already loaded, otherwise do nothing
if otto.client[modulename] # don't trigger a automatic module load
otto.call_module modulename, methodname, args...
else
console.log "ignoring call to unloaded module otto.client.#{modulename}.#{methodname}(args...)"
otto.ismoduleloaded = (modulename) ->
return otto.client[modulename]?
# client side version of node's nextTick
window.nextTick = (func) -> setTimeout(func, 0)
# coffeescript friendly version of setTimeout and setInterval
window.timeoutSet = (ms, func) -> setTimeout(func, ms)
window.intervalSet = (ms, func) -> setInterval(func, ms)
$.fn.scrollToBottom = ->
this.animate scrollTop: this.prop('scrollHeight') - this.height(), 100
otto.autosize_clear_cache = -> otto.$autosize_elements_cache = false
otto.autosize_clear_cache()
otto.autosize_adjust = ->
console.log 'autosize_adjust'
if !otto.$autosize_elements_cache
otto.$autosize_elements_cache = $('.autosize')
otto.$autosize_elements_cache.each (index, element) ->
$element = $ element
maxFontSize = $element.data('autosize-max') || $element.height()-4
minFontSize = $element.data('autosize-min') || Math.round($element.height/2)-4
rightMargin = $element.data('autosize-right-margin') || 0
fontSize = maxFontSize
#while size > minFontSize and element.scrollWidth > element.offsetWidth
# $element.css 'font-size': "#{fontSize}px"
desiredWidth = $element.parent().width()
$resizer = $element.clone()
$resizer.css
'display': 'inline'
'white-space': 'nowrap'
'width': 'auto'
'font-size': "#{fontSize}px"
$resizer.insertAfter($element)
while fontSize > minFontSize and $resizer.width() > desiredWidth
fontSize = fontSize - 1
$resizer.css 'font-size': "#{fontSize}px"
# adjust the top so the text stays centered in the div
heightAdjust = 0
if fontSize > minFontSize
heightAdjust = (maxFontSize - fontSize) / 2
$resizer.remove()
$element.css
'font-size': "#{fontSize}px"
'top': "#{heightAdjust}px"
# from http://stackoverflow.com/questions/6658517/window-resize-in-jquery-firing-multiple-times
# debouncing function from <NAME>
# http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
# usage:
# $(window).smartresize ->
# code that takes it easy...
do ($ = jQuery, sr = 'smartresize') ->
debounce = (func, threshold, execAsap) ->
timeout = null
debounced = ->
obj = this
args = arguments
delayed = ->
if not execAsap
func.apply(obj, args)
timeout = null
if timeout
clearTimeout timeout
else if execAsap
func.apply(obj, args)
timeout = setTimeout(delayed, threshold || 50)
return debounced
# smartresize
$.fn[sr] = (fn) ->
return if fn then this.bind('resize', debounce(fn)) else this.trigger(sr)
| true | ###############
### client side (body of otto.client.misc.coffee served as /otto.misc.js)
###############
global.otto.client.misc = ->
window.otto = window.otto || {}
# on demand client side modules
otto.client = otto.client || {}
otto.load_module = (modulename, callback) ->
if not otto.client[modulename]
console.log "loading module #{modulename}"
$.getScript "/otto.client.#{modulename}.js", ->
console.log "module #{modulename} loaded"
if callback
callback()
else
if callback
callback()
otto.call_module = (modulename, methodname, args...) ->
otto.load_module modulename, ->
console.log "calling otto.client.#{modulename}.#{methodname}(args...)"
otto.client[modulename][methodname](args...)
otto.call_module_ifloaded = (modulename, methodname, args...) ->
# only call the module if it is already loaded, otherwise do nothing
if otto.client[modulename] # don't trigger a automatic module load
otto.call_module modulename, methodname, args...
else
console.log "ignoring call to unloaded module otto.client.#{modulename}.#{methodname}(args...)"
otto.ismoduleloaded = (modulename) ->
return otto.client[modulename]?
# client side version of node's nextTick
window.nextTick = (func) -> setTimeout(func, 0)
# coffeescript friendly version of setTimeout and setInterval
window.timeoutSet = (ms, func) -> setTimeout(func, ms)
window.intervalSet = (ms, func) -> setInterval(func, ms)
$.fn.scrollToBottom = ->
this.animate scrollTop: this.prop('scrollHeight') - this.height(), 100
otto.autosize_clear_cache = -> otto.$autosize_elements_cache = false
otto.autosize_clear_cache()
otto.autosize_adjust = ->
console.log 'autosize_adjust'
if !otto.$autosize_elements_cache
otto.$autosize_elements_cache = $('.autosize')
otto.$autosize_elements_cache.each (index, element) ->
$element = $ element
maxFontSize = $element.data('autosize-max') || $element.height()-4
minFontSize = $element.data('autosize-min') || Math.round($element.height/2)-4
rightMargin = $element.data('autosize-right-margin') || 0
fontSize = maxFontSize
#while size > minFontSize and element.scrollWidth > element.offsetWidth
# $element.css 'font-size': "#{fontSize}px"
desiredWidth = $element.parent().width()
$resizer = $element.clone()
$resizer.css
'display': 'inline'
'white-space': 'nowrap'
'width': 'auto'
'font-size': "#{fontSize}px"
$resizer.insertAfter($element)
while fontSize > minFontSize and $resizer.width() > desiredWidth
fontSize = fontSize - 1
$resizer.css 'font-size': "#{fontSize}px"
# adjust the top so the text stays centered in the div
heightAdjust = 0
if fontSize > minFontSize
heightAdjust = (maxFontSize - fontSize) / 2
$resizer.remove()
$element.css
'font-size': "#{fontSize}px"
'top': "#{heightAdjust}px"
# from http://stackoverflow.com/questions/6658517/window-resize-in-jquery-firing-multiple-times
# debouncing function from PI:NAME:<NAME>END_PI
# http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
# usage:
# $(window).smartresize ->
# code that takes it easy...
do ($ = jQuery, sr = 'smartresize') ->
debounce = (func, threshold, execAsap) ->
timeout = null
debounced = ->
obj = this
args = arguments
delayed = ->
if not execAsap
func.apply(obj, args)
timeout = null
if timeout
clearTimeout timeout
else if execAsap
func.apply(obj, args)
timeout = setTimeout(delayed, threshold || 50)
return debounced
# smartresize
$.fn[sr] = (fn) ->
return if fn then this.bind('resize', debounce(fn)) else this.trigger(sr)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9993112683296204,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/pummel/test-net-pingpong-delay.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.
pingPongTest = (port, host, on_complete) ->
N = 100
DELAY = 1
count = 0
client_ended = false
server = net.createServer(
allowHalfOpen: true
, (socket) ->
socket.setEncoding "utf8"
socket.on "data", (data) ->
console.log data
assert.equal "PING", data
assert.equal "open", socket.readyState
assert.equal true, count <= N
setTimeout (->
assert.equal "open", socket.readyState
socket.write "PONG"
return
), DELAY
return
socket.on "timeout", ->
common.debug "server-side timeout!!"
assert.equal false, true
return
socket.on "end", ->
console.log "server-side socket EOF"
assert.equal "writeOnly", socket.readyState
socket.end()
return
socket.on "close", (had_error) ->
console.log "server-side socket.end"
assert.equal false, had_error
assert.equal "closed", socket.readyState
socket.server.close()
return
return
)
server.listen port, host, ->
client = net.createConnection(port, host)
client.setEncoding "utf8"
client.on "connect", ->
assert.equal "open", client.readyState
client.write "PING"
return
client.on "data", (data) ->
console.log data
assert.equal "PONG", data
assert.equal "open", client.readyState
setTimeout (->
assert.equal "open", client.readyState
if count++ < N
client.write "PING"
else
console.log "closing client"
client.end()
client_ended = true
return
), DELAY
return
client.on "timeout", ->
common.debug "client-side timeout!!"
assert.equal false, true
return
client.on "close", ->
console.log "client.end"
assert.equal N + 1, count
assert.ok client_ended
on_complete() if on_complete
tests_run += 1
return
return
return
common = require("../common")
assert = require("assert")
net = require("net")
tests_run = 0
pingPongTest common.PORT
process.on "exit", ->
assert.equal 1, tests_run
return
| 130986 | # 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.
pingPongTest = (port, host, on_complete) ->
N = 100
DELAY = 1
count = 0
client_ended = false
server = net.createServer(
allowHalfOpen: true
, (socket) ->
socket.setEncoding "utf8"
socket.on "data", (data) ->
console.log data
assert.equal "PING", data
assert.equal "open", socket.readyState
assert.equal true, count <= N
setTimeout (->
assert.equal "open", socket.readyState
socket.write "PONG"
return
), DELAY
return
socket.on "timeout", ->
common.debug "server-side timeout!!"
assert.equal false, true
return
socket.on "end", ->
console.log "server-side socket EOF"
assert.equal "writeOnly", socket.readyState
socket.end()
return
socket.on "close", (had_error) ->
console.log "server-side socket.end"
assert.equal false, had_error
assert.equal "closed", socket.readyState
socket.server.close()
return
return
)
server.listen port, host, ->
client = net.createConnection(port, host)
client.setEncoding "utf8"
client.on "connect", ->
assert.equal "open", client.readyState
client.write "PING"
return
client.on "data", (data) ->
console.log data
assert.equal "PONG", data
assert.equal "open", client.readyState
setTimeout (->
assert.equal "open", client.readyState
if count++ < N
client.write "PING"
else
console.log "closing client"
client.end()
client_ended = true
return
), DELAY
return
client.on "timeout", ->
common.debug "client-side timeout!!"
assert.equal false, true
return
client.on "close", ->
console.log "client.end"
assert.equal N + 1, count
assert.ok client_ended
on_complete() if on_complete
tests_run += 1
return
return
return
common = require("../common")
assert = require("assert")
net = require("net")
tests_run = 0
pingPongTest common.PORT
process.on "exit", ->
assert.equal 1, tests_run
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.
pingPongTest = (port, host, on_complete) ->
N = 100
DELAY = 1
count = 0
client_ended = false
server = net.createServer(
allowHalfOpen: true
, (socket) ->
socket.setEncoding "utf8"
socket.on "data", (data) ->
console.log data
assert.equal "PING", data
assert.equal "open", socket.readyState
assert.equal true, count <= N
setTimeout (->
assert.equal "open", socket.readyState
socket.write "PONG"
return
), DELAY
return
socket.on "timeout", ->
common.debug "server-side timeout!!"
assert.equal false, true
return
socket.on "end", ->
console.log "server-side socket EOF"
assert.equal "writeOnly", socket.readyState
socket.end()
return
socket.on "close", (had_error) ->
console.log "server-side socket.end"
assert.equal false, had_error
assert.equal "closed", socket.readyState
socket.server.close()
return
return
)
server.listen port, host, ->
client = net.createConnection(port, host)
client.setEncoding "utf8"
client.on "connect", ->
assert.equal "open", client.readyState
client.write "PING"
return
client.on "data", (data) ->
console.log data
assert.equal "PONG", data
assert.equal "open", client.readyState
setTimeout (->
assert.equal "open", client.readyState
if count++ < N
client.write "PING"
else
console.log "closing client"
client.end()
client_ended = true
return
), DELAY
return
client.on "timeout", ->
common.debug "client-side timeout!!"
assert.equal false, true
return
client.on "close", ->
console.log "client.end"
assert.equal N + 1, count
assert.ok client_ended
on_complete() if on_complete
tests_run += 1
return
return
return
common = require("../common")
assert = require("assert")
net = require("net")
tests_run = 0
pingPongTest common.PORT
process.on "exit", ->
assert.equal 1, tests_run
return
|
[
{
"context": "quire 'when'\n\nwordsKey = () -> '[[APP-wordbank]]::stefano@stefanomasini.com::words'\n\nexports.buildDatabase = (redisDb) ->\n ",
"end": 106,
"score": 0.9989364147186279,
"start": 81,
"tag": "EMAIL",
"value": "stefano@stefanomasini.com"
}
] | database.coffee | stefanomasini/wordbank | 0 | _ = require 'lodash'
when_ = require 'when'
wordsKey = () -> '[[APP-wordbank]]::stefano@stefanomasini.com::words'
exports.buildDatabase = (redisDb) ->
saveChanges: (changes) ->
if changes.length == 0
return when_.resolve()
changesDict = _.zipObject([c.src, JSON.stringify(c)] for c in changes)
redisDb.hmset wordsKey(), changesDict
deleteWords: (words) ->
if words.length == 0
return when_.resolve()
redisDb.hdel wordsKey(), words
getWords: () ->
redisDb.hgetall(wordsKey())
.then (res) ->
return (JSON.parse(v) for v in _.values(res))
| 199387 | _ = require 'lodash'
when_ = require 'when'
wordsKey = () -> '[[APP-wordbank]]::<EMAIL>::words'
exports.buildDatabase = (redisDb) ->
saveChanges: (changes) ->
if changes.length == 0
return when_.resolve()
changesDict = _.zipObject([c.src, JSON.stringify(c)] for c in changes)
redisDb.hmset wordsKey(), changesDict
deleteWords: (words) ->
if words.length == 0
return when_.resolve()
redisDb.hdel wordsKey(), words
getWords: () ->
redisDb.hgetall(wordsKey())
.then (res) ->
return (JSON.parse(v) for v in _.values(res))
| true | _ = require 'lodash'
when_ = require 'when'
wordsKey = () -> '[[APP-wordbank]]::PI:EMAIL:<EMAIL>END_PI::words'
exports.buildDatabase = (redisDb) ->
saveChanges: (changes) ->
if changes.length == 0
return when_.resolve()
changesDict = _.zipObject([c.src, JSON.stringify(c)] for c in changes)
redisDb.hmset wordsKey(), changesDict
deleteWords: (words) ->
if words.length == 0
return when_.resolve()
redisDb.hdel wordsKey(), words
getWords: () ->
redisDb.hgetall(wordsKey())
.then (res) ->
return (JSON.parse(v) for v in _.values(res))
|
[
{
"context": " asked: true\n id: requestId\n userId: @userId\n stop: stop\n notificationService.notifyAb",
"end": 1593,
"score": 0.9995142817497253,
"start": 1586,
"tag": "USERNAME",
"value": "@userId"
},
{
"context": " //\n from: request.userEm... | src/packages/carpool-service/server/server.coffee | ArnoldasSid/vilnius-carpool | 11 | @notificationService = new NotificationService
tripsMatcher = new TripsMatcher
Meteor.startup ->
tripsMatcher.start()
process.on 'exit', ->
tripsMatcher.stop()
rad = (x) ->
x * Math.PI / 180
getDistance = (p1, p2) ->
R = 6378137
dLat = rad(p2[1] - (p1[1]))
dLong = rad(p2[0] - (p1[0]))
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p1[1])) * Math.cos(rad(p2[1])) * Math.sin(dLong / 2) * Math.sin(dLong / 2)
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
d = R * c
Meteor.methods
sendMessage: (from, to, message)->
messageId = ChatHistory.insert({
message: message,
to: to,
from: from
});
notificationService.notify "message", "New message", to, {
from: from,
messageId: messageId,
text: message
}
removeTrip: (id) ->
notificationService.removeTripNotifications id
Trips.remove
_id: id
owner: Meteor.userId()
requestRide: (tripId, fromLoc) ->
requestId = undefined
stop = undefined
trip = undefined
da [ 'trip-request' ], 'Request to join trip ' + tripId + ':', fromLoc
trip = Trips.findOne(tripId)
if fromLoc
stop = _(trip.stops).min (item) ->
getDistance fromLoc, item.loc
da [ 'trip-request' ], 'Closest stop ' + tripId + ':', stop
else
da [ 'trip-request' ], 'Rider loc is not know - opt for point A'
stop = trip.fromLoc
requestId = getRandomString('ABCDEFGHIKLMNOPQRSTUVWXY0123456789', 5)
Trips.update { _id: tripId }, $addToSet: requests:
asked: true
id: requestId
userId: @userId
stop: stop
notificationService.notifyAboutTrip 'request', trip.owner, trip, requestId
acceptRequest: (invitationId, response) ->
request = undefined
trip = undefined
trip = Trips.findOne('requests.id': invitationId)
request = _.findWhere(trip.requests, id: invitationId)
da [ 'trip-request' ], 'Accept request from ' + request.userId + ' to join trip ' + invitationId
### // 49
user = Meteor.user() //
#d(response+" invitation for trip:"+tripId+" user:",user); //
tripOwner = Meteor.users.findOne(trip.owner) //
d 'Responding to invitation to trip owner:' + response, tripOwner //
inviter = getUserEmail(tripOwner) //
request = _.find(trip.requests, (item) -> //
item.id == invitationId //
) //
emailText = 'Proposal to join the trip ' + trip.fromStreet + ' ' + trip.fromHouse + '-' + trip.toStreet + ' ' + trip.toHouse + '\n' + 'was accepted by ' + request.userEmail
Email.send //
from: request.userEmail or 'spastai@gmail.com' //
to: inviter //
subject: 'Trip invitation accepted' //
text: emailText //
###
Trips.update { 'requests.id': invitationId }, $set: 'requests.$.response': response
notificationService.notifyAboutTrip 'confirmation', request.userId, trip, invitationId
| 31542 | @notificationService = new NotificationService
tripsMatcher = new TripsMatcher
Meteor.startup ->
tripsMatcher.start()
process.on 'exit', ->
tripsMatcher.stop()
rad = (x) ->
x * Math.PI / 180
getDistance = (p1, p2) ->
R = 6378137
dLat = rad(p2[1] - (p1[1]))
dLong = rad(p2[0] - (p1[0]))
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p1[1])) * Math.cos(rad(p2[1])) * Math.sin(dLong / 2) * Math.sin(dLong / 2)
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
d = R * c
Meteor.methods
sendMessage: (from, to, message)->
messageId = ChatHistory.insert({
message: message,
to: to,
from: from
});
notificationService.notify "message", "New message", to, {
from: from,
messageId: messageId,
text: message
}
removeTrip: (id) ->
notificationService.removeTripNotifications id
Trips.remove
_id: id
owner: Meteor.userId()
requestRide: (tripId, fromLoc) ->
requestId = undefined
stop = undefined
trip = undefined
da [ 'trip-request' ], 'Request to join trip ' + tripId + ':', fromLoc
trip = Trips.findOne(tripId)
if fromLoc
stop = _(trip.stops).min (item) ->
getDistance fromLoc, item.loc
da [ 'trip-request' ], 'Closest stop ' + tripId + ':', stop
else
da [ 'trip-request' ], 'Rider loc is not know - opt for point A'
stop = trip.fromLoc
requestId = getRandomString('ABCDEFGHIKLMNOPQRSTUVWXY0123456789', 5)
Trips.update { _id: tripId }, $addToSet: requests:
asked: true
id: requestId
userId: @userId
stop: stop
notificationService.notifyAboutTrip 'request', trip.owner, trip, requestId
acceptRequest: (invitationId, response) ->
request = undefined
trip = undefined
trip = Trips.findOne('requests.id': invitationId)
request = _.findWhere(trip.requests, id: invitationId)
da [ 'trip-request' ], 'Accept request from ' + request.userId + ' to join trip ' + invitationId
### // 49
user = Meteor.user() //
#d(response+" invitation for trip:"+tripId+" user:",user); //
tripOwner = Meteor.users.findOne(trip.owner) //
d 'Responding to invitation to trip owner:' + response, tripOwner //
inviter = getUserEmail(tripOwner) //
request = _.find(trip.requests, (item) -> //
item.id == invitationId //
) //
emailText = 'Proposal to join the trip ' + trip.fromStreet + ' ' + trip.fromHouse + '-' + trip.toStreet + ' ' + trip.toHouse + '\n' + 'was accepted by ' + request.userEmail
Email.send //
from: request.userEmail or '<EMAIL>' //
to: inviter //
subject: 'Trip invitation accepted' //
text: emailText //
###
Trips.update { 'requests.id': invitationId }, $set: 'requests.$.response': response
notificationService.notifyAboutTrip 'confirmation', request.userId, trip, invitationId
| true | @notificationService = new NotificationService
tripsMatcher = new TripsMatcher
Meteor.startup ->
tripsMatcher.start()
process.on 'exit', ->
tripsMatcher.stop()
rad = (x) ->
x * Math.PI / 180
getDistance = (p1, p2) ->
R = 6378137
dLat = rad(p2[1] - (p1[1]))
dLong = rad(p2[0] - (p1[0]))
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(rad(p1[1])) * Math.cos(rad(p2[1])) * Math.sin(dLong / 2) * Math.sin(dLong / 2)
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
d = R * c
Meteor.methods
sendMessage: (from, to, message)->
messageId = ChatHistory.insert({
message: message,
to: to,
from: from
});
notificationService.notify "message", "New message", to, {
from: from,
messageId: messageId,
text: message
}
removeTrip: (id) ->
notificationService.removeTripNotifications id
Trips.remove
_id: id
owner: Meteor.userId()
requestRide: (tripId, fromLoc) ->
requestId = undefined
stop = undefined
trip = undefined
da [ 'trip-request' ], 'Request to join trip ' + tripId + ':', fromLoc
trip = Trips.findOne(tripId)
if fromLoc
stop = _(trip.stops).min (item) ->
getDistance fromLoc, item.loc
da [ 'trip-request' ], 'Closest stop ' + tripId + ':', stop
else
da [ 'trip-request' ], 'Rider loc is not know - opt for point A'
stop = trip.fromLoc
requestId = getRandomString('ABCDEFGHIKLMNOPQRSTUVWXY0123456789', 5)
Trips.update { _id: tripId }, $addToSet: requests:
asked: true
id: requestId
userId: @userId
stop: stop
notificationService.notifyAboutTrip 'request', trip.owner, trip, requestId
acceptRequest: (invitationId, response) ->
request = undefined
trip = undefined
trip = Trips.findOne('requests.id': invitationId)
request = _.findWhere(trip.requests, id: invitationId)
da [ 'trip-request' ], 'Accept request from ' + request.userId + ' to join trip ' + invitationId
### // 49
user = Meteor.user() //
#d(response+" invitation for trip:"+tripId+" user:",user); //
tripOwner = Meteor.users.findOne(trip.owner) //
d 'Responding to invitation to trip owner:' + response, tripOwner //
inviter = getUserEmail(tripOwner) //
request = _.find(trip.requests, (item) -> //
item.id == invitationId //
) //
emailText = 'Proposal to join the trip ' + trip.fromStreet + ' ' + trip.fromHouse + '-' + trip.toStreet + ' ' + trip.toHouse + '\n' + 'was accepted by ' + request.userEmail
Email.send //
from: request.userEmail or 'PI:EMAIL:<EMAIL>END_PI' //
to: inviter //
subject: 'Trip invitation accepted' //
text: emailText //
###
Trips.update { 'requests.id': invitationId }, $set: 'requests.$.response': response
notificationService.notifyAboutTrip 'confirmation', request.userId, trip, invitationId
|
[
{
"context": "\n config =\n id: 'test'\n name: 'test device'\n host: 'localhost'\n interval: 200\n",
"end": 422,
"score": 0.7624341249465942,
"start": 411,
"tag": "NAME",
"value": "test device"
}
] | test/hongkongpollution-test.coffee | hongkongkiwi/pimatic-hongkongpollution | 0 | chai = require 'chai'
chai.should()
env = {
require: require,
plugins: require '../../pimatic/lib/plugins'
}
# env = {
# require: require,
# logger: require '../../pimatic/lib/logger',
# }
#
# env.devices = require '../../pimatic/lib/devices'
# env.framework = require '../../pimatic/lib/framework'
# env.plugins = require '../../pimatic/lib/plugins'
config =
id: 'test'
name: 'test device'
host: 'localhost'
interval: 200
retries: 1
timeout: 2001
plugin = (require '../hongkongpollution') env
#HKPollutionAQHICurrentDevice = require "../devices/pollution-current-device' env
describe 'Pollution Current Device', ->
#urrentDevice = new HKPollutionAQHICurrentDevice()
# it 'should be an object', ->
# currentDevice.should.exist
| 18401 | chai = require 'chai'
chai.should()
env = {
require: require,
plugins: require '../../pimatic/lib/plugins'
}
# env = {
# require: require,
# logger: require '../../pimatic/lib/logger',
# }
#
# env.devices = require '../../pimatic/lib/devices'
# env.framework = require '../../pimatic/lib/framework'
# env.plugins = require '../../pimatic/lib/plugins'
config =
id: 'test'
name: '<NAME>'
host: 'localhost'
interval: 200
retries: 1
timeout: 2001
plugin = (require '../hongkongpollution') env
#HKPollutionAQHICurrentDevice = require "../devices/pollution-current-device' env
describe 'Pollution Current Device', ->
#urrentDevice = new HKPollutionAQHICurrentDevice()
# it 'should be an object', ->
# currentDevice.should.exist
| true | chai = require 'chai'
chai.should()
env = {
require: require,
plugins: require '../../pimatic/lib/plugins'
}
# env = {
# require: require,
# logger: require '../../pimatic/lib/logger',
# }
#
# env.devices = require '../../pimatic/lib/devices'
# env.framework = require '../../pimatic/lib/framework'
# env.plugins = require '../../pimatic/lib/plugins'
config =
id: 'test'
name: 'PI:NAME:<NAME>END_PI'
host: 'localhost'
interval: 200
retries: 1
timeout: 2001
plugin = (require '../hongkongpollution') env
#HKPollutionAQHICurrentDevice = require "../devices/pollution-current-device' env
describe 'Pollution Current Device', ->
#urrentDevice = new HKPollutionAQHICurrentDevice()
# it 'should be an object', ->
# currentDevice.should.exist
|
[
{
"context": " {\n ship: 'X-Wing'\n pilot: \"Luke Skywalker\"\n upgrades: [\n \"Treffsi",
"end": 581,
"score": 0.9419658184051514,
"start": 567,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": " \"Aufklärungs-Experte\... | tests/test_translation_de.coffee | strikegun/xwing | 0 | common = require './common'
common.setup()
casper.test.begin "German translations: Rebel", (test) ->
common.waitForStartup('#rebel-builder')
common.setGameType('#rebel-builder', 'epic')
common.selectLanguage('Deutsch')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: "Anfängerpilot"
upgrades: [
"Protonen-Torpedos"
"R2 Astromechdroide"
"Verbesserte Schilde"
]
}
{
ship: 'X-Wing'
pilot: "Luke Skywalker"
upgrades: [
"Treffsicherheit"
null
"R2-D2"
null
]
}
{
ship: 'YT-1300'
pilot: "Chewbacca"
upgrades: [
"Das Feuer auf mich ziehen"
"Angriffsraketen"
"Geheimagent"
"Aufklärungs-Experte"
"Millennium Falke"
"Verbessertes Triebwerk"
]
}
{
ship: 'Medium-Transporter GR-75'
pilot: 'Medium-Transporter GR-75'
upgrades: [
'WED-15 Reparaturdroide'
'Jan Dodonna'
'Störsender (Fracht)'
'Schildprojektor'
'Erweiterter Ladebereich'
'Quantum Storm'
'Umrüstung für den Kampfeinsatz'
]
}
])
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'Luke Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'Luke Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'R2-D2 (Crew)')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'R2-D2 (Crew)')
common.assertTotalPoints(test, '#rebel-builder', 183)
common.selectLanguage('English')
common.assertShipTypeIs(test, '#rebel-builder', 1, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade')
common.assertShipTypeIs(test, '#rebel-builder', 2, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 2, 'Luke Skywalker')
common.assertUpgradeInSlot(test, '#rebel-builder', 2, 1, 'Marksmanship')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 2)
common.assertUpgradeInSlot(test, '#rebel-builder', 2, 3, 'R2-D2')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 4)
common.assertShipTypeIs(test, '#rebel-builder', 3, 'YT-1300')
common.assertPilotIs(test, '#rebel-builder', 3, 'Chewbacca')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Draw Their Fire')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 2, 'Assault Missiles')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Intelligence Agent')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 4, 'Recon Specialist')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 5, 'Millennium Falcon')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 6, 'Engine Upgrade')
common.assertShipTypeIs(test, '#rebel-builder', 4, 'GR-75 Medium Transport')
common.assertPilotIs(test, '#rebel-builder', 4, 'GR-75 Medium Transport')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 1, 'WED-15 Repair Droid')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 2, 'Jan Dodonna')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 3, 'Frequency Jammer')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 4, 'Shield Projector')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 5, 'Expanded Cargo Hold')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 6, 'Quantum Storm')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 7, 'Combat Retrofit')
common.assertTotalPoints(test, '#rebel-builder', 183)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "German translations: Imperial", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.selectLanguage('Deutsch')
common.createList('#empire-builder', [
{
ship: 'TIE-Abfangjäger'
pilot: "Pilot der Alpha-Staffel"
upgrades: [
null
"Tarnvorrichtung"
]
}
{
ship: 'TIE-Jäger'
pilot: "Pilot der Akademie"
upgrades: [
null
]
}
{
ship: 'TIE-Abfangjäger'
pilot: "Soontir Fel"
upgrades: [
null
"TIE der Roten Garde"
"Verbesserte Hülle"
"Verbesserte Schilde"
]
}
])
common.assertTotalPoints(test, '#empire-builder', 67)
common.selectLanguage('English')
common.assertShipTypeIs(test, '#empire-builder', 1, 'TIE Interceptor')
common.assertPilotIs(test, '#empire-builder', 1, 'Alpha Squadron Pilot')
common.assertUpgradeInSlot(test, '#empire-builder', 1, 2, 'Stealth Device')
common.assertShipTypeIs(test, '#empire-builder', 2, 'TIE Fighter')
common.assertPilotIs(test, '#empire-builder', 2, 'Academy Pilot')
common.assertShipTypeIs(test, '#empire-builder', 3, 'TIE Interceptor')
common.assertPilotIs(test, '#empire-builder', 3, 'Soontir Fel')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 2, 'Royal Guard TIE')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 3, 'Hull Upgrade')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 4, 'Shield Upgrade')
common.assertTotalPoints(test, '#empire-builder', 67)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
| 47649 | common = require './common'
common.setup()
casper.test.begin "German translations: Rebel", (test) ->
common.waitForStartup('#rebel-builder')
common.setGameType('#rebel-builder', 'epic')
common.selectLanguage('Deutsch')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: "Anfängerpilot"
upgrades: [
"Protonen-Torpedos"
"R2 Astromechdroide"
"Verbesserte Schilde"
]
}
{
ship: 'X-Wing'
pilot: "<NAME>"
upgrades: [
"Treffsicherheit"
null
"R2-D2"
null
]
}
{
ship: 'YT-1300'
pilot: "Chewbacca"
upgrades: [
"Das Feuer auf mich ziehen"
"Angriffsraketen"
"Geheimagent"
"Aufklärungs-Experte"
"<NAME>"
"Verbessertes Triebwerk"
]
}
{
ship: 'Medium-Transporter GR-75'
pilot: 'Medium-Transporter GR-75'
upgrades: [
'WED-15 Reparaturdroide'
'<NAME>'
'Störsender (Fracht)'
'Schildprojektor'
'Erweiterter Ladebereich'
'Quantum Storm'
'Umrüstung für den Kampfeinsatz'
]
}
])
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'Lu<NAME> Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", '<NAME> Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'R2-D2 (Crew)')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'R2-D2 (Crew)')
common.assertTotalPoints(test, '#rebel-builder', 183)
common.selectLanguage('English')
common.assertShipTypeIs(test, '#rebel-builder', 1, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade')
common.assertShipTypeIs(test, '#rebel-builder', 2, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 2, 'Lu<NAME>walker')
common.assertUpgradeInSlot(test, '#rebel-builder', 2, 1, 'Marksmanship')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 2)
common.assertUpgradeInSlot(test, '#rebel-builder', 2, 3, 'R2-D2')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 4)
common.assertShipTypeIs(test, '#rebel-builder', 3, 'YT-1300')
common.assertPilotIs(test, '#rebel-builder', 3, 'Chewbacca')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Draw Their Fire')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 2, 'Assault Missiles')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Intelligence Agent')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 4, 'Recon Specialist')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 5, 'Millennium Falcon')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 6, 'Engine Upgrade')
common.assertShipTypeIs(test, '#rebel-builder', 4, 'GR-75 Medium Transport')
common.assertPilotIs(test, '#rebel-builder', 4, 'GR-75 Medium Transport')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 1, 'WED-15 Repair Droid')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 2, '<NAME>')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 3, 'Frequency Jammer')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 4, 'Shield Projector')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 5, 'Expanded Cargo Hold')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 6, 'Quantum Storm')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 7, 'Combat Retrofit')
common.assertTotalPoints(test, '#rebel-builder', 183)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "German translations: Imperial", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.selectLanguage('Deutsch')
common.createList('#empire-builder', [
{
ship: 'TIE-Abfangjäger'
pilot: "Pilot der Alpha-Staffel"
upgrades: [
null
"Tarnvorrichtung"
]
}
{
ship: 'TIE-Jäger'
pilot: "Pilot der Akademie"
upgrades: [
null
]
}
{
ship: 'TIE-Abfangjäger'
pilot: "<NAME>"
upgrades: [
null
"TIE der Roten Garde"
"Verbesserte Hülle"
"Verbesserte Sch<NAME>"
]
}
])
common.assertTotalPoints(test, '#empire-builder', 67)
common.selectLanguage('English')
common.assertShipTypeIs(test, '#empire-builder', 1, 'TIE Interceptor')
common.assertPilotIs(test, '#empire-builder', 1, 'Alpha Squadron Pilot')
common.assertUpgradeInSlot(test, '#empire-builder', 1, 2, 'Stealth Device')
common.assertShipTypeIs(test, '#empire-builder', 2, 'TIE Fighter')
common.assertPilotIs(test, '#empire-builder', 2, 'Academy Pilot')
common.assertShipTypeIs(test, '#empire-builder', 3, 'TIE Interceptor')
common.assertPilotIs(test, '#empire-builder', 3, '<NAME>')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 2, 'Royal Guard TIE')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 3, 'Hull Upgrade')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 4, 'Shield Upgrade')
common.assertTotalPoints(test, '#empire-builder', 67)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
| true | common = require './common'
common.setup()
casper.test.begin "German translations: Rebel", (test) ->
common.waitForStartup('#rebel-builder')
common.setGameType('#rebel-builder', 'epic')
common.selectLanguage('Deutsch')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: "Anfängerpilot"
upgrades: [
"Protonen-Torpedos"
"R2 Astromechdroide"
"Verbesserte Schilde"
]
}
{
ship: 'X-Wing'
pilot: "PI:NAME:<NAME>END_PI"
upgrades: [
"Treffsicherheit"
null
"R2-D2"
null
]
}
{
ship: 'YT-1300'
pilot: "Chewbacca"
upgrades: [
"Das Feuer auf mich ziehen"
"Angriffsraketen"
"Geheimagent"
"Aufklärungs-Experte"
"PI:NAME:<NAME>END_PI"
"Verbessertes Triebwerk"
]
}
{
ship: 'Medium-Transporter GR-75'
pilot: 'Medium-Transporter GR-75'
upgrades: [
'WED-15 Reparaturdroide'
'PI:NAME:<NAME>END_PI'
'Störsender (Fracht)'
'Schildprojektor'
'Erweiterter Ladebereich'
'Quantum Storm'
'Umrüstung für den Kampfeinsatz'
]
}
])
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'LuPI:NAME:<NAME>END_PI Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'PI:NAME:<NAME>END_PI Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 3)}", 'R2-D2 (Crew)')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex(3, 4)}", 'R2-D2 (Crew)')
common.assertTotalPoints(test, '#rebel-builder', 183)
common.selectLanguage('English')
common.assertShipTypeIs(test, '#rebel-builder', 1, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 1, 'Rookie Pilot')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 1, 'Proton Torpedoes')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 2, 'R2 Astromech')
common.assertUpgradeInSlot(test, '#rebel-builder', 1, 3, 'Shield Upgrade')
common.assertShipTypeIs(test, '#rebel-builder', 2, 'X-Wing')
common.assertPilotIs(test, '#rebel-builder', 2, 'LuPI:NAME:<NAME>END_PIwalker')
common.assertUpgradeInSlot(test, '#rebel-builder', 2, 1, 'Marksmanship')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 2)
common.assertUpgradeInSlot(test, '#rebel-builder', 2, 3, 'R2-D2')
common.assertNoUpgradeInSlot(test, '#rebel-builder', 2, 4)
common.assertShipTypeIs(test, '#rebel-builder', 3, 'YT-1300')
common.assertPilotIs(test, '#rebel-builder', 3, 'Chewbacca')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 1, 'Draw Their Fire')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 2, 'Assault Missiles')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 3, 'Intelligence Agent')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 4, 'Recon Specialist')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 5, 'Millennium Falcon')
common.assertUpgradeInSlot(test, '#rebel-builder', 3, 6, 'Engine Upgrade')
common.assertShipTypeIs(test, '#rebel-builder', 4, 'GR-75 Medium Transport')
common.assertPilotIs(test, '#rebel-builder', 4, 'GR-75 Medium Transport')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 1, 'WED-15 Repair Droid')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 2, 'PI:NAME:<NAME>END_PI')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 3, 'Frequency Jammer')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 4, 'Shield Projector')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 5, 'Expanded Cargo Hold')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 6, 'Quantum Storm')
common.assertUpgradeInSlot(test, '#rebel-builder', 4, 7, 'Combat Retrofit')
common.assertTotalPoints(test, '#rebel-builder', 183)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
casper.test.begin "German translations: Imperial", (test) ->
common.waitForStartup('#rebel-builder')
common.openEmpireBuilder()
common.selectLanguage('Deutsch')
common.createList('#empire-builder', [
{
ship: 'TIE-Abfangjäger'
pilot: "Pilot der Alpha-Staffel"
upgrades: [
null
"Tarnvorrichtung"
]
}
{
ship: 'TIE-Jäger'
pilot: "Pilot der Akademie"
upgrades: [
null
]
}
{
ship: 'TIE-Abfangjäger'
pilot: "PI:NAME:<NAME>END_PI"
upgrades: [
null
"TIE der Roten Garde"
"Verbesserte Hülle"
"Verbesserte SchPI:NAME:<NAME>END_PI"
]
}
])
common.assertTotalPoints(test, '#empire-builder', 67)
common.selectLanguage('English')
common.assertShipTypeIs(test, '#empire-builder', 1, 'TIE Interceptor')
common.assertPilotIs(test, '#empire-builder', 1, 'Alpha Squadron Pilot')
common.assertUpgradeInSlot(test, '#empire-builder', 1, 2, 'Stealth Device')
common.assertShipTypeIs(test, '#empire-builder', 2, 'TIE Fighter')
common.assertPilotIs(test, '#empire-builder', 2, 'Academy Pilot')
common.assertShipTypeIs(test, '#empire-builder', 3, 'TIE Interceptor')
common.assertPilotIs(test, '#empire-builder', 3, 'PI:NAME:<NAME>END_PI')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 2, 'Royal Guard TIE')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 3, 'Hull Upgrade')
common.assertUpgradeInSlot(test, '#empire-builder', 3, 4, 'Shield Upgrade')
common.assertTotalPoints(test, '#empire-builder', 67)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
common.removeShip('#empire-builder', 1)
.run ->
test.done()
|
[
{
"context": "ttp://www.dropzonejs.com)\n# \n# Copyright (c) 2012, Matias Meno \n# \n# Permission is hereby granted, free of char",
"end": 105,
"score": 0.9998675584793091,
"start": 94,
"tag": "NAME",
"value": "Matias Meno"
},
{
"context": "t Chrome versions.\n # See https://gi... | src/dropzone.coffee | fpena06/dropzone | 1 | ###
#
# More info at [www.dropzonejs.com](http://www.dropzonejs.com)
#
# Copyright (c) 2012, Matias Meno
#
# 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.
#
###
# Dependencies
Em = Emitter ? require "emitter" # Can't be the same name because it will lead to a local variable
noop = ->
class Dropzone extends Em
###
This is a list of all available events you can register on a dropzone object.
You can register an event handler like this:
dropzone.on("dragEnter", function() { });
###
events: [
"drop"
"dragstart"
"dragend"
"dragenter"
"dragover"
"dragleave"
"selectedfiles"
"addedfile"
"removedfile"
"thumbnail"
"error"
"errormultiple"
"processing"
"processingmultiple"
"uploadprogress"
"totaluploadprogress"
"sending"
"sendingmultiple"
"success"
"successmultiple"
"canceled"
"canceledmultiple"
"complete"
"completemultiple"
"reset"
"maxfilesexceeded"
"maxfilesreached"
]
defaultOptions:
url: null
method: "post"
withCredentials: no
parallelUploads: 2
uploadMultiple: no # Whether to send multiple files in one request.
maxFilesize: 256 # in MB
paramName: "file" # The name of the file param that gets transferred.
createImageThumbnails: true
maxThumbnailFilesize: 10 # in MB. When the filename exceeds this limit, the thumbnail will not be generated.
thumbnailWidth: 100
thumbnailHeight: 100
# Can be used to limit the maximum number of files that will be handled
# by this Dropzone
maxFiles: null
# Can be an object of additional parameters to transfer to the server.
# This is the same as adding hidden input fields in the form element.
params: { }
# If true, the dropzone will present a file selector when clicked.
clickable: yes
# Whether hidden files in directories should be ignored.
ignoreHiddenFiles: yes
# You can set accepted mime types here.
#
# The default implementation of the `accept()` function will check this
# property, and if the Dropzone is clickable this will be used as
# `accept` attribute.
#
# This is a comma separated list of mime types or extensions. E.g.:
#
# audio/*,video/*,image/png,.pdf
#
# See https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept
# for a reference.
acceptedFiles: null
# @deprecated
# Use acceptedFiles instead.
acceptedMimeTypes: null
# If false, files will be added to the queue but the queu will not be
# processed automatically.
# This can be useful if you need some additional user input before sending
# files (or if you want want all files sent at once).
# If you're ready to send the file simply call myDropzone.processQueue()
autoProcessQueue: on
# If true, Dropzone will add a link to each file preview to cancel/remove
# the upload.
# See dictCancelUpload and dictRemoveFile to use different words.
addRemoveLinks: no
# A CSS selector or HTML element for the file previews container.
# If null, the dropzone element itself will be used
previewsContainer: null
# Dictionary
# The text used before any files are dropped
dictDefaultMessage: "Drop files here to upload"
# The text that replaces the default message text it the browser is not supported
dictFallbackMessage: "Your browser does not support drag'n'drop file uploads."
# The text that will be added before the fallback form
# If null, no text will be added at all.
dictFallbackText: "Please use the fallback form below to upload your files like in the olden days."
# If the filesize is too big.
dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: {{maxFilesize}}MB."
# If the file doesn't match the file type.
dictInvalidFileType: "You can't upload files of this type."
# If the server response was invalid.
dictResponseError: "Server responded with {{statusCode}} code."
# If used, the text to be used for the cancel upload link.
dictCancelUpload: "Cancel upload"
# If used, the text to be used for confirmation when cancelling upload.
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?"
# If used, the text to be used to remove a file.
dictRemoveFile: "Remove file"
# If this is not null, then the user will be prompted before removing a file.
dictRemoveFileConfirmation: null
# Displayed when the maxFiles have been exceeded
dictMaxFilesExceeded: "You can only upload {{maxFiles}} files."
# If `done()` is called without argument the file is accepted
# If you call it with an error message, the file is rejected
# (This allows for asynchronous validation).
accept: (file, done) -> done()
# Called when dropzone initialized
# You can add event listeners here
init: -> noop
# Used to debug dropzone and force the fallback form.
forceFallback: off
# Called when the browser does not support drag and drop
fallback: ->
# This code should pass in IE7... :(
@element.className = "#{@element.className} dz-browser-not-supported"
for child in @element.getElementsByTagName "div"
if /(^| )dz-message($| )/.test child.className
messageElement = child
child.className = "dz-message" # Removes the 'dz-default' class
continue
unless messageElement
messageElement = Dropzone.createElement """<div class="dz-message"><span></span></div>"""
@element.appendChild messageElement
span = messageElement.getElementsByTagName("span")[0]
span.textContent = @options.dictFallbackMessage if span
@element.appendChild @getFallbackForm()
# Gets called to calculate the thumbnail dimensions.
#
# You can use file.width, file.height, options.thumbnailWidth and
# options.thumbnailHeight to calculate the dimensions.
#
# The dimensions are going to be used like this:
#
# var info = @options.resize.call(this, file);
# ctx.drawImage(img, info.srcX, info.srcY, info.srcWidth, info.srcHeight, info.trgX, info.trgY, info.trgWidth, info.trgHeight);
#
# srcX, srcy, trgX and trgY can be omitted (in which case 0 is assumed).
# trgWidth and trgHeight can be omitted (in which case the options.thumbnailWidth / options.thumbnailHeight are used)
resize: (file) ->
info =
srcX: 0
srcY: 0
srcWidth: file.width
srcHeight: file.height
srcRatio = file.width / file.height
trgRatio = @options.thumbnailWidth / @options.thumbnailHeight
if file.height < @options.thumbnailHeight or file.width < @options.thumbnailWidth
# This image is smaller than the canvas
info.trgHeight = info.srcHeight
info.trgWidth = info.srcWidth
else
# Image is bigger and needs rescaling
if srcRatio > trgRatio
info.srcHeight = file.height
info.srcWidth = info.srcHeight * trgRatio
else
info.srcWidth = file.width
info.srcHeight = info.srcWidth / trgRatio
info.srcX = (file.width - info.srcWidth) / 2
info.srcY = (file.height - info.srcHeight) / 2
return info
###
Those functions register themselves to the events on init and handle all
the user interface specific stuff. Overwriting them won't break the upload
but can break the way it's displayed.
You can overwrite them if you don't like the default behavior. If you just
want to add an additional event handler, register it on the dropzone object
and don't overwrite those options.
###
# Those are self explanatory and simply concern the DragnDrop.
drop: (e) -> @element.classList.remove "dz-drag-hover"
dragstart: noop
dragend: (e) -> @element.classList.remove "dz-drag-hover"
dragenter: (e) -> @element.classList.add "dz-drag-hover"
dragover: (e) -> @element.classList.add "dz-drag-hover"
dragleave: (e) -> @element.classList.remove "dz-drag-hover"
# Called whenever files are dropped or selected
selectedfiles: (files) ->
@element.classList.add "dz-started" if @element == @previewsContainer
# Called whenever there are no files left in the dropzone anymore, and the
# dropzone should be displayed as if in the initial state.
reset: ->
@element.classList.remove "dz-started"
# Called when a file is added to the queue
# Receives `file`
addedfile: (file) ->
file.previewElement = Dropzone.createElement @options.previewTemplate.trim()
file.previewTemplate = file.previewElement # Backwards compatibility
@previewsContainer.appendChild file.previewElement
node.textContent = file.name for node in file.previewElement.querySelectorAll("[data-dz-name]")
node.innerHTML = @filesize file.size for node in file.previewElement.querySelectorAll("[data-dz-size]")
if @options.addRemoveLinks
file._removeLink = Dropzone.createElement """<a class="dz-remove" href="javascript:undefined;">#{@options.dictRemoveFile}</a>"""
file._removeLink.addEventListener "click", (e) =>
e.preventDefault()
e.stopPropagation()
if file.status == Dropzone.UPLOADING
Dropzone.confirm @options.dictCancelUploadConfirmation, => @removeFile file
else
if @options.dictRemoveFileConfirmation
Dropzone.confirm @options.dictRemoveFileConfirmation, => @removeFile file
else
@removeFile file
file.previewElement.appendChild file._removeLink
# Called whenever a file is removed.
removedfile: (file) ->
file.previewElement?.parentNode.removeChild file.previewElement
@_updateMaxFilesReachedClass()
# Called when a thumbnail has been generated
# Receives `file` and `dataUrl`
thumbnail: (file, dataUrl) ->
file.previewElement.classList.remove "dz-file-preview"
file.previewElement.classList.add "dz-image-preview"
for thumbnailElement in file.previewElement.querySelectorAll("[data-dz-thumbnail]")
thumbnailElement.alt = file.name
thumbnailElement.src = dataUrl
# Called whenever an error occurs
# Receives `file` and `message`
error: (file, message) ->
file.previewElement.classList.add "dz-error"
node.textContent = message for node in file.previewElement.querySelectorAll("[data-dz-errormessage]")
errormultiple: noop
# Called when a file gets processed. Since there is a cue, not all added
# files are processed immediately.
# Receives `file`
processing: (file) ->
file.previewElement.classList.add "dz-processing"
file._removeLink.textContent = @options.dictCancelUpload if file._removeLink
processingmultiple: noop
# Called whenever the upload progress gets updated.
# Receives `file`, `progress` (percentage 0-100) and `bytesSent`.
# To get the total number of bytes of the file, use `file.size`
uploadprogress: (file, progress, bytesSent) ->
node.style.width = "#{progress}%" for node in file.previewElement.querySelectorAll("[data-dz-uploadprogress]")
# Called whenever the total upload progress gets updated.
# Called with totalUploadProgress (0-100), totalBytes and totalBytesSent
totaluploadprogress: noop
# Called just before the file is sent. Gets the `xhr` object as second
# parameter, so you can modify it (for example to add a CSRF token) and a
# `formData` object to add additional information.
sending: noop
sendingmultiple: noop
# When the complete upload is finished and successfull
# Receives `file`
success: (file) ->
file.previewElement.classList.add "dz-success"
successmultiple: noop
# When the upload is canceled.
canceled: (file) -> @emit "error", file, "Upload canceled."
canceledmultiple: noop
# When the upload is finished, either with success or an error.
# Receives `file`
complete: (file) ->
file._removeLink.textContent = @options.dictRemoveFile if file._removeLink
completemultiple: noop
maxfilesexceeded: noop
maxfilesreached: noop
# This template will be chosen when a new file is dropped.
previewTemplate: """
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-filename"><span data-dz-name></span></div>
<div class="dz-size" data-dz-size></div>
<img data-dz-thumbnail />
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
</div>
"""
# global utility
extend = (target, objects...) ->
for object in objects
target[key] = val for key, val of object
target
constructor: (@element, options) ->
# For backwards compatibility since the version was in the prototype previously
@version = Dropzone.version
@defaultOptions.previewTemplate = @defaultOptions.previewTemplate.replace /\n*/g, ""
@clickableElements = [ ]
@listeners = [ ]
@files = [] # All files
@element = document.querySelector @element if typeof @element == "string"
# Not checking if instance of HTMLElement or Element since IE9 is extremely weird.
throw new Error "Invalid dropzone element." unless @element and @element.nodeType?
throw new Error "Dropzone already attached." if @element.dropzone
# Now add this dropzone to the instances.
Dropzone.instances.push @
# Put the dropzone inside the element itself.
@element.dropzone = @
elementOptions = Dropzone.optionsForElement(@element) ? { }
@options = extend { }, @defaultOptions, elementOptions, options ? { }
# If the browser failed, just call the fallback and leave
return @options.fallback.call this if @options.forceFallback or !Dropzone.isBrowserSupported()
# @options.url = @element.getAttribute "action" unless @options.url?
@options.url = @element.getAttribute "action" unless @options.url?
throw new Error "No URL provided." unless @options.url
throw new Error "You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated." if @options.acceptedFiles and @options.acceptedMimeTypes
# Backwards compatibility
if @options.acceptedMimeTypes
@options.acceptedFiles = @options.acceptedMimeTypes
delete @options.acceptedMimeTypes
@options.method = @options.method.toUpperCase()
if (fallback = @getExistingFallback()) and fallback.parentNode
# Remove the fallback
fallback.parentNode.removeChild fallback
if @options.previewsContainer
@previewsContainer = Dropzone.getElement @options.previewsContainer, "previewsContainer"
else
@previewsContainer = @element
if @options.clickable
if @options.clickable == yes
@clickableElements = [ @element ]
else
@clickableElements = Dropzone.getElements @options.clickable, "clickable"
@init()
# Returns all files that have been accepted
getAcceptedFiles: -> file for file in @files when file.accepted
# Returns all files that have been rejected
# Not sure when that's going to be useful, but added for completeness.
getRejectedFiles: -> file for file in @files when not file.accepted
# Returns all files that are in the queue
getQueuedFiles: -> file for file in @files when file.status == Dropzone.QUEUED
getUploadingFiles: -> file for file in @files when file.status == Dropzone.UPLOADING
init: ->
# In case it isn't set already
@element.setAttribute("enctype", "multipart/form-data") if @element.tagName == "form"
if @element.classList.contains("dropzone") and !@element.querySelector(".dz-message")
@element.appendChild Dropzone.createElement """<div class="dz-default dz-message"><span>#{@options.dictDefaultMessage}</span></div>"""
if @clickableElements.length
setupHiddenFileInput = =>
document.body.removeChild @hiddenFileInput if @hiddenFileInput
@hiddenFileInput = document.createElement "input"
@hiddenFileInput.setAttribute "type", "file"
@hiddenFileInput.setAttribute "multiple", "multiple" if !@options.maxFiles? || @options.maxFiles > 1
@hiddenFileInput.setAttribute "accept", @options.acceptedFiles if @options.acceptedFiles?
# Not setting `display="none"` because some browsers don't accept clicks
# on elements that aren't displayed.
@hiddenFileInput.style.visibility = "hidden"
@hiddenFileInput.style.position = "absolute"
@hiddenFileInput.style.top = "0"
@hiddenFileInput.style.left = "0"
@hiddenFileInput.style.height = "0"
@hiddenFileInput.style.width = "0"
document.body.appendChild @hiddenFileInput
@hiddenFileInput.addEventListener "change", =>
files = @hiddenFileInput.files
if files.length
@emit "selectedfiles", files
@handleFiles files
setupHiddenFileInput()
setupHiddenFileInput()
@URL = window.URL ? window.webkitURL
# Setup all event listeners on the Dropzone object itself.
# They're not in @setupEventListeners() because they shouldn't be removed
# again when the dropzone gets disabled.
@on eventName, @options[eventName] for eventName in @events
@on "uploadprogress", => @updateTotalUploadProgress()
@on "removedfile", => @updateTotalUploadProgress()
@on "canceled", (file) => @emit "complete", file
noPropagation = (e) ->
e.stopPropagation()
if e.preventDefault
e.preventDefault()
else
e.returnValue = false
# Create the listeners
@listeners = [
{
element: @element
events:
"dragstart": (e) =>
@emit "dragstart", e
"dragenter": (e) =>
noPropagation e
@emit "dragenter", e
"dragover": (e) =>
# Makes it possible to drag files from chrome's download bar
# http://stackoverflow.com/questions/19526430/drag-and-drop-file-uploads-from-chrome-downloads-bar
efct = e.dataTransfer.effectAllowed
e.dataTransfer.dropEffect = if 'move' == efct or 'linkMove' == efct then 'move' else 'copy'
noPropagation e
@emit "dragover", e
"dragleave": (e) =>
@emit "dragleave", e
"drop": (e) =>
noPropagation e
@drop e
"dragend": (e) =>
@emit "dragend", e
}
]
@clickableElements.forEach (clickableElement) =>
@listeners.push
element: clickableElement
events:
"click": (evt) =>
# Only the actual dropzone or the message element should trigger file selection
if (clickableElement != @element) or (evt.target == @element or Dropzone.elementInside evt.target, @element.querySelector ".dz-message")
@hiddenFileInput.click() # Forward the click
@enable()
@options.init.call @
# Not fully tested yet
destroy: ->
@disable()
@removeAllFiles true
if @hiddenFileInput?.parentNode
@hiddenFileInput.parentNode.removeChild @hiddenFileInput
@hiddenFileInput = null
delete @element.dropzone
updateTotalUploadProgress: ->
totalBytesSent = 0
totalBytes = 0
acceptedFiles = @getAcceptedFiles()
if acceptedFiles.length
for file in @getAcceptedFiles()
totalBytesSent += file.upload.bytesSent
totalBytes += file.upload.total
totalUploadProgress = 100 * totalBytesSent / totalBytes
else
totalUploadProgress = 100
@emit "totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent
# Returns a form that can be used as fallback if the browser does not support DragnDrop
#
# If the dropzone is already a form, only the input field and button are returned. Otherwise a complete form element is provided.
# This code has to pass in IE7 :(
getFallbackForm: ->
return existingFallback if existingFallback = @getExistingFallback()
fieldsString = """<div class="dz-fallback">"""
fieldsString += """<p>#{@options.dictFallbackText}</p>""" if @options.dictFallbackText
fieldsString += """<input type="file" name="#{@options.paramName}#{if @options.uploadMultiple then "[]" else ""}" #{if @options.uploadMultiple then 'multiple="multiple"' } /><input type="submit" value="Upload!"></div>"""
fields = Dropzone.createElement fieldsString
if @element.tagName isnt "FORM"
form = Dropzone.createElement("""<form action="#{@options.url}" enctype="multipart/form-data" method="#{@options.method}"></form>""")
form.appendChild fields
else
# Make sure that the enctype and method attributes are set properly
@element.setAttribute "enctype", "multipart/form-data"
@element.setAttribute "method", @options.method
form ? fields
# Returns the fallback elements if they exist already
#
# This code has to pass in IE7 :(
getExistingFallback: ->
getFallback = (elements) -> return el for el in elements when /(^| )fallback($| )/.test el.className
for tagName in [ "div", "form" ]
return fallback if fallback = getFallback @element.getElementsByTagName tagName
# Activates all listeners stored in @listeners
setupEventListeners: ->
for elementListeners in @listeners
elementListeners.element.addEventListener event, listener, false for event, listener of elementListeners.events
# Deactivates all listeners stored in @listeners
removeEventListeners: ->
for elementListeners in @listeners
elementListeners.element.removeEventListener event, listener, false for event, listener of elementListeners.events
# Removes all event listeners and cancels all files in the queue or being processed.
disable: ->
@clickableElements.forEach (element) -> element.classList.remove "dz-clickable"
@removeEventListeners()
@cancelUpload file for file in @files
enable: ->
@clickableElements.forEach (element) -> element.classList.add "dz-clickable"
@setupEventListeners()
# Returns a nicely formatted filesize
filesize: (size) ->
if size >= 100000000000
size = size / 100000000000
string = "TB"
else if size >= 100000000
size = size / 100000000
string = "GB"
else if size >= 100000
size = size / 100000
string = "MB"
else if size >= 100
size = size / 100
string = "KB"
else
size = size * 10
string = "b"
"<strong>#{Math.round(size)/10}</strong> #{string}"
# Adds or removes the `dz-max-files-reached` class from the form.
_updateMaxFilesReachedClass: ->
if @options.maxFiles and @getAcceptedFiles().length >= @options.maxFiles
@emit 'maxfilesreached', @files if @getAcceptedFiles().length == @options.maxFiles
@element.classList.add "dz-max-files-reached"
else
@element.classList.remove "dz-max-files-reached"
drop: (e) ->
return unless e.dataTransfer
@emit "drop", e
files = e.dataTransfer.files
@emit "selectedfiles", files
# Even if it's a folder, files.length will contain the folders.
if files.length
items = e.dataTransfer.items
if items and items.length and (items[0].webkitGetAsEntry? or items[0].getAsEntry?)
# The browser supports dropping of folders, so handle items instead of files
@handleItems items
else
@handleFiles files
return
handleFiles: (files) ->
@addFile file for file in files
# When a folder is dropped, items must be handled instead of files.
handleItems: (items) ->
for item in items
if item.webkitGetAsEntry?
entry = item.webkitGetAsEntry()
if entry.isFile
@addFile item.getAsFile()
else if entry.isDirectory
@addDirectory entry, entry.name
else
@addFile item.getAsFile()
return
# If `done()` is called without argument the file is accepted
# If you call it with an error message, the file is rejected
# (This allows for asynchronous validation)
#
# This function checks the filesize, and if the file.type passes the
# `acceptedFiles` check.
accept: (file, done) ->
if file.size > @options.maxFilesize * 1024 * 1024
done @options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", @options.maxFilesize)
else unless Dropzone.isValidFile file, @options.acceptedFiles
done @options.dictInvalidFileType
else if @options.maxFiles and @getAcceptedFiles().length >= @options.maxFiles
done @options.dictMaxFilesExceeded.replace "{{maxFiles}}", @options.maxFiles
@emit "maxfilesexceeded", file
else
@options.accept.call this, file, done
addFile: (file) ->
file.upload =
progress: 0
# Setting the total upload size to file.size for the beginning
# It's actual different than the size to be transmitted.
total: file.size
bytesSent: 0
@files.push file
file.status = Dropzone.ADDED
@emit "addedfile", file
@createThumbnail file if @options.createImageThumbnails and file.type.match(/image.*/) and file.size <= @options.maxThumbnailFilesize * 1024 * 1024
@accept file, (error) =>
if error
file.accepted = false
@_errorProcessing [ file ], error # Will set the file.status
else
@enqueueFile file # Will set .accepted = true
@_updateMaxFilesReachedClass()
# Wrapper for enqueuFile
enqueueFiles: (files) -> @enqueueFile file for file in files; null
enqueueFile: (file) ->
file.accepted = true
if file.status == Dropzone.ADDED
file.status = Dropzone.QUEUED
if @options.autoProcessQueue
setTimeout (=> @processQueue()), 1 # Deferring the call
else
throw new Error "This file can't be queued because it has already been processed or was rejected."
# Used to read a directory, and call addFile() with every file found.
addDirectory: (entry, path) ->
dirReader = entry.createReader()
entriesReader = (entries) =>
for entry in entries
if entry.isFile
entry.file (file) =>
return if @options.ignoreHiddenFiles and file.name.substring(0, 1) is '.'
file.fullPath = "#{path}/#{file.name}"
@addFile file
else if entry.isDirectory
@addDirectory entry, "#{path}/#{entry.name}"
return
dirReader.readEntries entriesReader, (error) -> console?.log? error
# Can be called by the user to remove a file
removeFile: (file) ->
@cancelUpload file if file.status == Dropzone.UPLOADING
@files = without @files, file
@emit "removedfile", file
@emit "reset" if @files.length == 0
# Removes all files that aren't currently processed from the list
removeAllFiles: (cancelIfNecessary = off) ->
# Create a copy of files since removeFile() changes the @files array.
for file in @files.slice()
@removeFile file if file.status != Dropzone.UPLOADING || cancelIfNecessary
return null
createThumbnail: (file) ->
fileReader = new FileReader
fileReader.onload = =>
# Not using `new Image` here because of a bug in latest Chrome versions.
# See https://github.com/enyo/dropzone/pull/226
img = document.createElement "img"
img.onload = =>
file.width = img.width
file.height = img.height
resizeInfo = @options.resize.call @, file
resizeInfo.trgWidth ?= @options.thumbnailWidth
resizeInfo.trgHeight ?= @options.thumbnailHeight
canvas = document.createElement "canvas"
ctx = canvas.getContext "2d"
canvas.width = resizeInfo.trgWidth
canvas.height = resizeInfo.trgHeight
ctx.drawImage img, resizeInfo.srcX ? 0, resizeInfo.srcY ? 0, resizeInfo.srcWidth, resizeInfo.srcHeight, resizeInfo.trgX ? 0, resizeInfo.trgY ? 0, resizeInfo.trgWidth, resizeInfo.trgHeight
thumbnail = canvas.toDataURL "image/png"
@emit "thumbnail", file, thumbnail
img.src = fileReader.result
fileReader.readAsDataURL file
# Goes through the queue and processes files if there aren't too many already.
processQueue: ->
parallelUploads = @options.parallelUploads
processingLength = @getUploadingFiles().length
i = processingLength
# There are already at least as many files uploading than should be
return if processingLength >= parallelUploads
queuedFiles = @getQueuedFiles()
return unless queuedFiles.length > 0
if @options.uploadMultiple
# The files should be uploaded in one request
@processFiles queuedFiles.slice 0, (parallelUploads - processingLength)
else
while i < parallelUploads
return unless queuedFiles.length # Nothing left to process
@processFile queuedFiles.shift()
i++
# Wrapper for `processFiles`
processFile: (file) -> @processFiles [ file ]
# Loads the file, then calls finishedLoading()
processFiles: (files) ->
for file in files
file.processing = yes # Backwards compatibility
file.status = Dropzone.UPLOADING
@emit "processing", file
@emit "processingmultiple", files if @options.uploadMultiple
@uploadFiles files
_getFilesWithXhr: (xhr) -> files = (file for file in @files when file.xhr == xhr)
# Cancels the file upload and sets the status to CANCELED
# **if** the file is actually being uploaded.
# If it's still in the queue, the file is being removed from it and the status
# set to CANCELED.
cancelUpload: (file) ->
if file.status == Dropzone.UPLOADING
groupedFiles = @_getFilesWithXhr file.xhr
groupedFile.status = Dropzone.CANCELED for groupedFile in groupedFiles
file.xhr.abort()
@emit "canceled", groupedFile for groupedFile in groupedFiles
@emit "canceledmultiple", groupedFiles if @options.uploadMultiple
else if file.status in [ Dropzone.ADDED, Dropzone.QUEUED ]
file.status = Dropzone.CANCELED
@emit "canceled", file
@emit "canceledmultiple", [ file ] if @options.uploadMultiple
@processQueue() if @options.autoProcessQueue
# Wrapper for uploadFiles()
uploadFile: (file) -> @uploadFiles [ file ]
uploadFiles: (files) ->
xhr = new XMLHttpRequest()
# Put the xhr object in the file objects to be able to reference it later.
file.xhr = xhr for file in files
xhr.open @options.method, @options.url, true
# Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179
xhr.withCredentials = !!@options.withCredentials
response = null
handleError = =>
for file in files
@_errorProcessing files, response || @options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr
updateProgress = (e) =>
if e?
progress = 100 * e.loaded / e.total
for file in files
file.upload =
progress: progress
total: e.total
bytesSent: e.loaded
else
# Called when the file finished uploading
allFilesFinished = yes
progress = 100
for file in files
allFilesFinished = no unless file.upload.progress == 100 and file.upload.bytesSent == file.upload.total
file.upload.progress = progress
file.upload.bytesSent = file.upload.total
# Nothing to do, all files already at 100%
return if allFilesFinished
for file in files
@emit "uploadprogress", file, progress, file.upload.bytesSent
xhr.onload = (e) =>
return if files[0].status == Dropzone.CANCELED
return unless xhr.readyState is 4
response = xhr.responseText
if xhr.getResponseHeader("content-type") and ~xhr.getResponseHeader("content-type").indexOf "application/json"
try
response = JSON.parse response
catch e
response = "Invalid JSON response from server."
updateProgress()
unless 200 <= xhr.status < 300
handleError()
else
@_finished files, response, e
xhr.onerror = =>
return if files[0].status == Dropzone.CANCELED
handleError()
# Some browsers do not have the .upload property
progressObj = xhr.upload ? xhr
progressObj.onprogress = updateProgress
headers =
"Accept": "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest",
extend headers, @options.headers if @options.headers
xhr.setRequestHeader headerName, headerValue for headerName, headerValue of headers
formData = new FormData()
# Adding all @options parameters
formData.append key, value for key, value of @options.params if @options.params
# Let the user add additional data if necessary
@emit "sending", file, xhr, formData for file in files
@emit "sendingmultiple", files, xhr, formData if @options.uploadMultiple
# Take care of other input elements
if @element.tagName == "FORM"
for input in @element.querySelectorAll "input, textarea, select, button"
inputName = input.getAttribute "name"
inputType = input.getAttribute "type"
if !inputType or (inputType.toLowerCase() not in [ "checkbox", "radio" ]) or input.checked
formData.append inputName, input.value
# Finally add the file
# Has to be last because some servers (eg: S3) expect the file to be the
# last parameter
formData.append "#{@options.paramName}#{if @options.uploadMultiple then "[]" else ""}", file, file.name for file in files
xhr.send formData
# Called internally when processing is finished.
# Individual callbacks have to be called in the appropriate sections.
_finished: (files, responseText, e) ->
for file in files
file.status = Dropzone.SUCCESS
@emit "success", file, responseText, e
@emit "complete", file
if @options.uploadMultiple
@emit "successmultiple", files, responseText, e
@emit "completemultiple", files
@processQueue() if @options.autoProcessQueue
# Called internally when processing is finished.
# Individual callbacks have to be called in the appropriate sections.
_errorProcessing: (files, message, xhr) ->
for file in files
file.status = Dropzone.ERROR
@emit "error", file, message, xhr
@emit "complete", file
if @options.uploadMultiple
@emit "errormultiple", files, message, xhr
@emit "completemultiple", files
@processQueue() if @options.autoProcessQueue
Dropzone.version = "3.7.4-dev"
# This is a map of options for your different dropzones. Add configurations
# to this object for your different dropzone elemens.
#
# Example:
#
# Dropzone.options.myDropzoneElementId = { maxFilesize: 1 };
#
# To disable autoDiscover for a specific element, you can set `false` as an option:
#
# Dropzone.options.myDisabledElementId = false;
#
# And in html:
#
# <form action="/upload" id="my-dropzone-element-id" class="dropzone"></form>
Dropzone.options = { }
# Returns the options for an element or undefined if none available.
Dropzone.optionsForElement = (element) ->
# Get the `Dropzone.options.elementId` for this element if it exists
if element.id then Dropzone.options[camelize element.id] else undefined
# Holds a list of all dropzone instances
Dropzone.instances = [ ]
# Returns the dropzone for given element if any
Dropzone.forElement = (element) ->
element = document.querySelector element if typeof element == "string"
throw new Error "No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone." unless element?.dropzone?
return element.dropzone
# Set to false if you don't want Dropzone to automatically find and attach to .dropzone elements.
Dropzone.autoDiscover = on
# Looks for all .dropzone elements and creates a dropzone for them
Dropzone.discover = ->
if document.querySelectorAll
dropzones = document.querySelectorAll ".dropzone"
else
dropzones = [ ]
# IE :(
checkElements = (elements) ->
for el in elements
dropzones.push el if /(^| )dropzone($| )/.test el.className
checkElements document.getElementsByTagName "div"
checkElements document.getElementsByTagName "form"
for dropzone in dropzones
# Create a dropzone unless auto discover has been disabled for specific element
new Dropzone dropzone unless Dropzone.optionsForElement(dropzone) == false
# Since the whole Drag'n'Drop API is pretty new, some browsers implement it,
# but not correctly.
# So I created a blacklist of userAgents. Yes, yes. Browser sniffing, I know.
# But what to do when browsers *theoretically* support an API, but crash
# when using it.
#
# This is a list of regular expressions tested against navigator.userAgent
#
# ** It should only be used on browser that *do* support the API, but
# incorrectly **
#
Dropzone.blacklistedBrowsers = [
# The mac os version of opera 12 seems to have a problem with the File drag'n'drop API.
/opera.*Macintosh.*version\/12/i
# /MSIE\ 10/i
]
# Checks if the browser is supported
Dropzone.isBrowserSupported = ->
capableBrowser = yes
if window.File and window.FileReader and window.FileList and window.Blob and window.FormData and document.querySelector
unless "classList" of document.createElement "a"
capableBrowser = no
else
# The browser supports the API, but may be blacklisted.
for regex in Dropzone.blacklistedBrowsers
if regex.test navigator.userAgent
capableBrowser = no
continue
else
capableBrowser = no
capableBrowser
# Returns an array without the rejected item
without = (list, rejectedItem) -> item for item in list when item isnt rejectedItem
# abc-def_ghi -> abcDefGhi
camelize = (str) -> str.replace /[\-_](\w)/g, (match) -> match[1].toUpperCase()
# Creates an element from string
Dropzone.createElement = (string) ->
div = document.createElement "div"
div.innerHTML = string
div.childNodes[0]
# Tests if given element is inside (or simply is) the container
Dropzone.elementInside = (element, container) ->
return yes if element == container # Coffeescript doesn't support do/while loops
return yes while element = element.parentNode when element == container
return no
Dropzone.getElement = (el, name) ->
if typeof el == "string"
element = document.querySelector el
else if el.nodeType?
element = el
throw new Error "Invalid `#{name}` option provided. Please provide a CSS selector or a plain HTML element." unless element?
return element
Dropzone.getElements = (els, name) ->
if els instanceof Array
elements = [ ]
try
elements.push @getElement el, name for el in els
catch e
elements = null
else if typeof els == "string"
elements = [ ]
elements.push el for el in document.querySelectorAll els
else if els.nodeType?
elements = [ els ]
throw new Error "Invalid `#{name}` option provided. Please provide a CSS selector, a plain HTML element or a list of those." unless elements? and elements.length
return elements
# Asks the user the question and calls accepted or rejected accordingly
#
# The default implementation just uses `window.confirm` and then calls the
# appropriate callback.
Dropzone.confirm = (question, accepted, rejected) ->
if window.confirm question
accepted()
else if rejected?
rejected()
# Validates the mime type like this:
#
# https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept
Dropzone.isValidFile = (file, acceptedFiles) ->
return yes unless acceptedFiles # If there are no accepted mime types, it's OK
acceptedFiles = acceptedFiles.split ","
mimeType = file.type
baseMimeType = mimeType.replace /\/.*$/, ""
for validType in acceptedFiles
validType = validType.trim()
if validType.charAt(0) == "."
return yes if file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) != -1
else if /\/\*$/.test validType
# This is something like a image/* mime type
return yes if baseMimeType == validType.replace /\/.*$/, ""
else
return yes if mimeType == validType
return no
# Augment jQuery
if jQuery?
jQuery.fn.dropzone = (options) ->
this.each -> new Dropzone this, options
if module?
module.exports = Dropzone
else
window.Dropzone = Dropzone
# Dropzone file status codes
Dropzone.ADDED = "added"
Dropzone.QUEUED = "queued"
# For backwards compatibility. Now, if a file is accepted, it's either queued
# or uploading.
Dropzone.ACCEPTED = Dropzone.QUEUED
Dropzone.UPLOADING = "uploading"
Dropzone.PROCESSING = Dropzone.UPLOADING # alias
Dropzone.CANCELED = "canceled"
Dropzone.ERROR = "error"
Dropzone.SUCCESS = "success"
###
# contentloaded.js
#
# Author: Diego Perini (diego.perini at gmail.com)
# Summary: cross-browser wrapper for DOMContentLoaded
# Updated: 20101020
# License: MIT
# Version: 1.2
#
# URL:
# http://javascript.nwbox.com/ContentLoaded/
# http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
###
# @win window reference
# @fn function reference
contentLoaded = (win, fn) ->
done = false
top = true
doc = win.document
root = doc.documentElement
add = (if doc.addEventListener then "addEventListener" else "attachEvent")
rem = (if doc.addEventListener then "removeEventListener" else "detachEvent")
pre = (if doc.addEventListener then "" else "on")
init = (e) ->
return if e.type is "readystatechange" and doc.readyState isnt "complete"
((if e.type is "load" then win else doc))[rem] pre + e.type, init, false
fn.call win, e.type or e if not done and (done = true)
poll = ->
try
root.doScroll "left"
catch e
setTimeout poll, 50
return
init "poll"
unless doc.readyState is "complete"
if doc.createEventObject and root.doScroll
try
top = not win.frameElement
poll() if top
doc[add] pre + "DOMContentLoaded", init, false
doc[add] pre + "readystatechange", init, false
win[add] pre + "load", init, false
# As a single function to be able to write tests.
Dropzone._autoDiscoverFunction = -> Dropzone.discover() if Dropzone.autoDiscover
contentLoaded window, Dropzone._autoDiscoverFunction
| 225149 | ###
#
# More info at [www.dropzonejs.com](http://www.dropzonejs.com)
#
# Copyright (c) 2012, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###
# Dependencies
Em = Emitter ? require "emitter" # Can't be the same name because it will lead to a local variable
noop = ->
class Dropzone extends Em
###
This is a list of all available events you can register on a dropzone object.
You can register an event handler like this:
dropzone.on("dragEnter", function() { });
###
events: [
"drop"
"dragstart"
"dragend"
"dragenter"
"dragover"
"dragleave"
"selectedfiles"
"addedfile"
"removedfile"
"thumbnail"
"error"
"errormultiple"
"processing"
"processingmultiple"
"uploadprogress"
"totaluploadprogress"
"sending"
"sendingmultiple"
"success"
"successmultiple"
"canceled"
"canceledmultiple"
"complete"
"completemultiple"
"reset"
"maxfilesexceeded"
"maxfilesreached"
]
defaultOptions:
url: null
method: "post"
withCredentials: no
parallelUploads: 2
uploadMultiple: no # Whether to send multiple files in one request.
maxFilesize: 256 # in MB
paramName: "file" # The name of the file param that gets transferred.
createImageThumbnails: true
maxThumbnailFilesize: 10 # in MB. When the filename exceeds this limit, the thumbnail will not be generated.
thumbnailWidth: 100
thumbnailHeight: 100
# Can be used to limit the maximum number of files that will be handled
# by this Dropzone
maxFiles: null
# Can be an object of additional parameters to transfer to the server.
# This is the same as adding hidden input fields in the form element.
params: { }
# If true, the dropzone will present a file selector when clicked.
clickable: yes
# Whether hidden files in directories should be ignored.
ignoreHiddenFiles: yes
# You can set accepted mime types here.
#
# The default implementation of the `accept()` function will check this
# property, and if the Dropzone is clickable this will be used as
# `accept` attribute.
#
# This is a comma separated list of mime types or extensions. E.g.:
#
# audio/*,video/*,image/png,.pdf
#
# See https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept
# for a reference.
acceptedFiles: null
# @deprecated
# Use acceptedFiles instead.
acceptedMimeTypes: null
# If false, files will be added to the queue but the queu will not be
# processed automatically.
# This can be useful if you need some additional user input before sending
# files (or if you want want all files sent at once).
# If you're ready to send the file simply call myDropzone.processQueue()
autoProcessQueue: on
# If true, Dropzone will add a link to each file preview to cancel/remove
# the upload.
# See dictCancelUpload and dictRemoveFile to use different words.
addRemoveLinks: no
# A CSS selector or HTML element for the file previews container.
# If null, the dropzone element itself will be used
previewsContainer: null
# Dictionary
# The text used before any files are dropped
dictDefaultMessage: "Drop files here to upload"
# The text that replaces the default message text it the browser is not supported
dictFallbackMessage: "Your browser does not support drag'n'drop file uploads."
# The text that will be added before the fallback form
# If null, no text will be added at all.
dictFallbackText: "Please use the fallback form below to upload your files like in the olden days."
# If the filesize is too big.
dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: {{maxFilesize}}MB."
# If the file doesn't match the file type.
dictInvalidFileType: "You can't upload files of this type."
# If the server response was invalid.
dictResponseError: "Server responded with {{statusCode}} code."
# If used, the text to be used for the cancel upload link.
dictCancelUpload: "Cancel upload"
# If used, the text to be used for confirmation when cancelling upload.
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?"
# If used, the text to be used to remove a file.
dictRemoveFile: "Remove file"
# If this is not null, then the user will be prompted before removing a file.
dictRemoveFileConfirmation: null
# Displayed when the maxFiles have been exceeded
dictMaxFilesExceeded: "You can only upload {{maxFiles}} files."
# If `done()` is called without argument the file is accepted
# If you call it with an error message, the file is rejected
# (This allows for asynchronous validation).
accept: (file, done) -> done()
# Called when dropzone initialized
# You can add event listeners here
init: -> noop
# Used to debug dropzone and force the fallback form.
forceFallback: off
# Called when the browser does not support drag and drop
fallback: ->
# This code should pass in IE7... :(
@element.className = "#{@element.className} dz-browser-not-supported"
for child in @element.getElementsByTagName "div"
if /(^| )dz-message($| )/.test child.className
messageElement = child
child.className = "dz-message" # Removes the 'dz-default' class
continue
unless messageElement
messageElement = Dropzone.createElement """<div class="dz-message"><span></span></div>"""
@element.appendChild messageElement
span = messageElement.getElementsByTagName("span")[0]
span.textContent = @options.dictFallbackMessage if span
@element.appendChild @getFallbackForm()
# Gets called to calculate the thumbnail dimensions.
#
# You can use file.width, file.height, options.thumbnailWidth and
# options.thumbnailHeight to calculate the dimensions.
#
# The dimensions are going to be used like this:
#
# var info = @options.resize.call(this, file);
# ctx.drawImage(img, info.srcX, info.srcY, info.srcWidth, info.srcHeight, info.trgX, info.trgY, info.trgWidth, info.trgHeight);
#
# srcX, srcy, trgX and trgY can be omitted (in which case 0 is assumed).
# trgWidth and trgHeight can be omitted (in which case the options.thumbnailWidth / options.thumbnailHeight are used)
resize: (file) ->
info =
srcX: 0
srcY: 0
srcWidth: file.width
srcHeight: file.height
srcRatio = file.width / file.height
trgRatio = @options.thumbnailWidth / @options.thumbnailHeight
if file.height < @options.thumbnailHeight or file.width < @options.thumbnailWidth
# This image is smaller than the canvas
info.trgHeight = info.srcHeight
info.trgWidth = info.srcWidth
else
# Image is bigger and needs rescaling
if srcRatio > trgRatio
info.srcHeight = file.height
info.srcWidth = info.srcHeight * trgRatio
else
info.srcWidth = file.width
info.srcHeight = info.srcWidth / trgRatio
info.srcX = (file.width - info.srcWidth) / 2
info.srcY = (file.height - info.srcHeight) / 2
return info
###
Those functions register themselves to the events on init and handle all
the user interface specific stuff. Overwriting them won't break the upload
but can break the way it's displayed.
You can overwrite them if you don't like the default behavior. If you just
want to add an additional event handler, register it on the dropzone object
and don't overwrite those options.
###
# Those are self explanatory and simply concern the DragnDrop.
drop: (e) -> @element.classList.remove "dz-drag-hover"
dragstart: noop
dragend: (e) -> @element.classList.remove "dz-drag-hover"
dragenter: (e) -> @element.classList.add "dz-drag-hover"
dragover: (e) -> @element.classList.add "dz-drag-hover"
dragleave: (e) -> @element.classList.remove "dz-drag-hover"
# Called whenever files are dropped or selected
selectedfiles: (files) ->
@element.classList.add "dz-started" if @element == @previewsContainer
# Called whenever there are no files left in the dropzone anymore, and the
# dropzone should be displayed as if in the initial state.
reset: ->
@element.classList.remove "dz-started"
# Called when a file is added to the queue
# Receives `file`
addedfile: (file) ->
file.previewElement = Dropzone.createElement @options.previewTemplate.trim()
file.previewTemplate = file.previewElement # Backwards compatibility
@previewsContainer.appendChild file.previewElement
node.textContent = file.name for node in file.previewElement.querySelectorAll("[data-dz-name]")
node.innerHTML = @filesize file.size for node in file.previewElement.querySelectorAll("[data-dz-size]")
if @options.addRemoveLinks
file._removeLink = Dropzone.createElement """<a class="dz-remove" href="javascript:undefined;">#{@options.dictRemoveFile}</a>"""
file._removeLink.addEventListener "click", (e) =>
e.preventDefault()
e.stopPropagation()
if file.status == Dropzone.UPLOADING
Dropzone.confirm @options.dictCancelUploadConfirmation, => @removeFile file
else
if @options.dictRemoveFileConfirmation
Dropzone.confirm @options.dictRemoveFileConfirmation, => @removeFile file
else
@removeFile file
file.previewElement.appendChild file._removeLink
# Called whenever a file is removed.
removedfile: (file) ->
file.previewElement?.parentNode.removeChild file.previewElement
@_updateMaxFilesReachedClass()
# Called when a thumbnail has been generated
# Receives `file` and `dataUrl`
thumbnail: (file, dataUrl) ->
file.previewElement.classList.remove "dz-file-preview"
file.previewElement.classList.add "dz-image-preview"
for thumbnailElement in file.previewElement.querySelectorAll("[data-dz-thumbnail]")
thumbnailElement.alt = file.name
thumbnailElement.src = dataUrl
# Called whenever an error occurs
# Receives `file` and `message`
error: (file, message) ->
file.previewElement.classList.add "dz-error"
node.textContent = message for node in file.previewElement.querySelectorAll("[data-dz-errormessage]")
errormultiple: noop
# Called when a file gets processed. Since there is a cue, not all added
# files are processed immediately.
# Receives `file`
processing: (file) ->
file.previewElement.classList.add "dz-processing"
file._removeLink.textContent = @options.dictCancelUpload if file._removeLink
processingmultiple: noop
# Called whenever the upload progress gets updated.
# Receives `file`, `progress` (percentage 0-100) and `bytesSent`.
# To get the total number of bytes of the file, use `file.size`
uploadprogress: (file, progress, bytesSent) ->
node.style.width = "#{progress}%" for node in file.previewElement.querySelectorAll("[data-dz-uploadprogress]")
# Called whenever the total upload progress gets updated.
# Called with totalUploadProgress (0-100), totalBytes and totalBytesSent
totaluploadprogress: noop
# Called just before the file is sent. Gets the `xhr` object as second
# parameter, so you can modify it (for example to add a CSRF token) and a
# `formData` object to add additional information.
sending: noop
sendingmultiple: noop
# When the complete upload is finished and successfull
# Receives `file`
success: (file) ->
file.previewElement.classList.add "dz-success"
successmultiple: noop
# When the upload is canceled.
canceled: (file) -> @emit "error", file, "Upload canceled."
canceledmultiple: noop
# When the upload is finished, either with success or an error.
# Receives `file`
complete: (file) ->
file._removeLink.textContent = @options.dictRemoveFile if file._removeLink
completemultiple: noop
maxfilesexceeded: noop
maxfilesreached: noop
# This template will be chosen when a new file is dropped.
previewTemplate: """
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-filename"><span data-dz-name></span></div>
<div class="dz-size" data-dz-size></div>
<img data-dz-thumbnail />
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
</div>
"""
# global utility
extend = (target, objects...) ->
for object in objects
target[key] = val for key, val of object
target
constructor: (@element, options) ->
# For backwards compatibility since the version was in the prototype previously
@version = Dropzone.version
@defaultOptions.previewTemplate = @defaultOptions.previewTemplate.replace /\n*/g, ""
@clickableElements = [ ]
@listeners = [ ]
@files = [] # All files
@element = document.querySelector @element if typeof @element == "string"
# Not checking if instance of HTMLElement or Element since IE9 is extremely weird.
throw new Error "Invalid dropzone element." unless @element and @element.nodeType?
throw new Error "Dropzone already attached." if @element.dropzone
# Now add this dropzone to the instances.
Dropzone.instances.push @
# Put the dropzone inside the element itself.
@element.dropzone = @
elementOptions = Dropzone.optionsForElement(@element) ? { }
@options = extend { }, @defaultOptions, elementOptions, options ? { }
# If the browser failed, just call the fallback and leave
return @options.fallback.call this if @options.forceFallback or !Dropzone.isBrowserSupported()
# @options.url = @element.getAttribute "action" unless @options.url?
@options.url = @element.getAttribute "action" unless @options.url?
throw new Error "No URL provided." unless @options.url
throw new Error "You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated." if @options.acceptedFiles and @options.acceptedMimeTypes
# Backwards compatibility
if @options.acceptedMimeTypes
@options.acceptedFiles = @options.acceptedMimeTypes
delete @options.acceptedMimeTypes
@options.method = @options.method.toUpperCase()
if (fallback = @getExistingFallback()) and fallback.parentNode
# Remove the fallback
fallback.parentNode.removeChild fallback
if @options.previewsContainer
@previewsContainer = Dropzone.getElement @options.previewsContainer, "previewsContainer"
else
@previewsContainer = @element
if @options.clickable
if @options.clickable == yes
@clickableElements = [ @element ]
else
@clickableElements = Dropzone.getElements @options.clickable, "clickable"
@init()
# Returns all files that have been accepted
getAcceptedFiles: -> file for file in @files when file.accepted
# Returns all files that have been rejected
# Not sure when that's going to be useful, but added for completeness.
getRejectedFiles: -> file for file in @files when not file.accepted
# Returns all files that are in the queue
getQueuedFiles: -> file for file in @files when file.status == Dropzone.QUEUED
getUploadingFiles: -> file for file in @files when file.status == Dropzone.UPLOADING
init: ->
# In case it isn't set already
@element.setAttribute("enctype", "multipart/form-data") if @element.tagName == "form"
if @element.classList.contains("dropzone") and !@element.querySelector(".dz-message")
@element.appendChild Dropzone.createElement """<div class="dz-default dz-message"><span>#{@options.dictDefaultMessage}</span></div>"""
if @clickableElements.length
setupHiddenFileInput = =>
document.body.removeChild @hiddenFileInput if @hiddenFileInput
@hiddenFileInput = document.createElement "input"
@hiddenFileInput.setAttribute "type", "file"
@hiddenFileInput.setAttribute "multiple", "multiple" if !@options.maxFiles? || @options.maxFiles > 1
@hiddenFileInput.setAttribute "accept", @options.acceptedFiles if @options.acceptedFiles?
# Not setting `display="none"` because some browsers don't accept clicks
# on elements that aren't displayed.
@hiddenFileInput.style.visibility = "hidden"
@hiddenFileInput.style.position = "absolute"
@hiddenFileInput.style.top = "0"
@hiddenFileInput.style.left = "0"
@hiddenFileInput.style.height = "0"
@hiddenFileInput.style.width = "0"
document.body.appendChild @hiddenFileInput
@hiddenFileInput.addEventListener "change", =>
files = @hiddenFileInput.files
if files.length
@emit "selectedfiles", files
@handleFiles files
setupHiddenFileInput()
setupHiddenFileInput()
@URL = window.URL ? window.webkitURL
# Setup all event listeners on the Dropzone object itself.
# They're not in @setupEventListeners() because they shouldn't be removed
# again when the dropzone gets disabled.
@on eventName, @options[eventName] for eventName in @events
@on "uploadprogress", => @updateTotalUploadProgress()
@on "removedfile", => @updateTotalUploadProgress()
@on "canceled", (file) => @emit "complete", file
noPropagation = (e) ->
e.stopPropagation()
if e.preventDefault
e.preventDefault()
else
e.returnValue = false
# Create the listeners
@listeners = [
{
element: @element
events:
"dragstart": (e) =>
@emit "dragstart", e
"dragenter": (e) =>
noPropagation e
@emit "dragenter", e
"dragover": (e) =>
# Makes it possible to drag files from chrome's download bar
# http://stackoverflow.com/questions/19526430/drag-and-drop-file-uploads-from-chrome-downloads-bar
efct = e.dataTransfer.effectAllowed
e.dataTransfer.dropEffect = if 'move' == efct or 'linkMove' == efct then 'move' else 'copy'
noPropagation e
@emit "dragover", e
"dragleave": (e) =>
@emit "dragleave", e
"drop": (e) =>
noPropagation e
@drop e
"dragend": (e) =>
@emit "dragend", e
}
]
@clickableElements.forEach (clickableElement) =>
@listeners.push
element: clickableElement
events:
"click": (evt) =>
# Only the actual dropzone or the message element should trigger file selection
if (clickableElement != @element) or (evt.target == @element or Dropzone.elementInside evt.target, @element.querySelector ".dz-message")
@hiddenFileInput.click() # Forward the click
@enable()
@options.init.call @
# Not fully tested yet
destroy: ->
@disable()
@removeAllFiles true
if @hiddenFileInput?.parentNode
@hiddenFileInput.parentNode.removeChild @hiddenFileInput
@hiddenFileInput = null
delete @element.dropzone
updateTotalUploadProgress: ->
totalBytesSent = 0
totalBytes = 0
acceptedFiles = @getAcceptedFiles()
if acceptedFiles.length
for file in @getAcceptedFiles()
totalBytesSent += file.upload.bytesSent
totalBytes += file.upload.total
totalUploadProgress = 100 * totalBytesSent / totalBytes
else
totalUploadProgress = 100
@emit "totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent
# Returns a form that can be used as fallback if the browser does not support DragnDrop
#
# If the dropzone is already a form, only the input field and button are returned. Otherwise a complete form element is provided.
# This code has to pass in IE7 :(
getFallbackForm: ->
return existingFallback if existingFallback = @getExistingFallback()
fieldsString = """<div class="dz-fallback">"""
fieldsString += """<p>#{@options.dictFallbackText}</p>""" if @options.dictFallbackText
fieldsString += """<input type="file" name="#{@options.paramName}#{if @options.uploadMultiple then "[]" else ""}" #{if @options.uploadMultiple then 'multiple="multiple"' } /><input type="submit" value="Upload!"></div>"""
fields = Dropzone.createElement fieldsString
if @element.tagName isnt "FORM"
form = Dropzone.createElement("""<form action="#{@options.url}" enctype="multipart/form-data" method="#{@options.method}"></form>""")
form.appendChild fields
else
# Make sure that the enctype and method attributes are set properly
@element.setAttribute "enctype", "multipart/form-data"
@element.setAttribute "method", @options.method
form ? fields
# Returns the fallback elements if they exist already
#
# This code has to pass in IE7 :(
getExistingFallback: ->
getFallback = (elements) -> return el for el in elements when /(^| )fallback($| )/.test el.className
for tagName in [ "div", "form" ]
return fallback if fallback = getFallback @element.getElementsByTagName tagName
# Activates all listeners stored in @listeners
setupEventListeners: ->
for elementListeners in @listeners
elementListeners.element.addEventListener event, listener, false for event, listener of elementListeners.events
# Deactivates all listeners stored in @listeners
removeEventListeners: ->
for elementListeners in @listeners
elementListeners.element.removeEventListener event, listener, false for event, listener of elementListeners.events
# Removes all event listeners and cancels all files in the queue or being processed.
disable: ->
@clickableElements.forEach (element) -> element.classList.remove "dz-clickable"
@removeEventListeners()
@cancelUpload file for file in @files
enable: ->
@clickableElements.forEach (element) -> element.classList.add "dz-clickable"
@setupEventListeners()
# Returns a nicely formatted filesize
filesize: (size) ->
if size >= 100000000000
size = size / 100000000000
string = "TB"
else if size >= 100000000
size = size / 100000000
string = "GB"
else if size >= 100000
size = size / 100000
string = "MB"
else if size >= 100
size = size / 100
string = "KB"
else
size = size * 10
string = "b"
"<strong>#{Math.round(size)/10}</strong> #{string}"
# Adds or removes the `dz-max-files-reached` class from the form.
_updateMaxFilesReachedClass: ->
if @options.maxFiles and @getAcceptedFiles().length >= @options.maxFiles
@emit 'maxfilesreached', @files if @getAcceptedFiles().length == @options.maxFiles
@element.classList.add "dz-max-files-reached"
else
@element.classList.remove "dz-max-files-reached"
drop: (e) ->
return unless e.dataTransfer
@emit "drop", e
files = e.dataTransfer.files
@emit "selectedfiles", files
# Even if it's a folder, files.length will contain the folders.
if files.length
items = e.dataTransfer.items
if items and items.length and (items[0].webkitGetAsEntry? or items[0].getAsEntry?)
# The browser supports dropping of folders, so handle items instead of files
@handleItems items
else
@handleFiles files
return
handleFiles: (files) ->
@addFile file for file in files
# When a folder is dropped, items must be handled instead of files.
handleItems: (items) ->
for item in items
if item.webkitGetAsEntry?
entry = item.webkitGetAsEntry()
if entry.isFile
@addFile item.getAsFile()
else if entry.isDirectory
@addDirectory entry, entry.name
else
@addFile item.getAsFile()
return
# If `done()` is called without argument the file is accepted
# If you call it with an error message, the file is rejected
# (This allows for asynchronous validation)
#
# This function checks the filesize, and if the file.type passes the
# `acceptedFiles` check.
accept: (file, done) ->
if file.size > @options.maxFilesize * 1024 * 1024
done @options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", @options.maxFilesize)
else unless Dropzone.isValidFile file, @options.acceptedFiles
done @options.dictInvalidFileType
else if @options.maxFiles and @getAcceptedFiles().length >= @options.maxFiles
done @options.dictMaxFilesExceeded.replace "{{maxFiles}}", @options.maxFiles
@emit "maxfilesexceeded", file
else
@options.accept.call this, file, done
addFile: (file) ->
file.upload =
progress: 0
# Setting the total upload size to file.size for the beginning
# It's actual different than the size to be transmitted.
total: file.size
bytesSent: 0
@files.push file
file.status = Dropzone.ADDED
@emit "addedfile", file
@createThumbnail file if @options.createImageThumbnails and file.type.match(/image.*/) and file.size <= @options.maxThumbnailFilesize * 1024 * 1024
@accept file, (error) =>
if error
file.accepted = false
@_errorProcessing [ file ], error # Will set the file.status
else
@enqueueFile file # Will set .accepted = true
@_updateMaxFilesReachedClass()
# Wrapper for enqueuFile
enqueueFiles: (files) -> @enqueueFile file for file in files; null
enqueueFile: (file) ->
file.accepted = true
if file.status == Dropzone.ADDED
file.status = Dropzone.QUEUED
if @options.autoProcessQueue
setTimeout (=> @processQueue()), 1 # Deferring the call
else
throw new Error "This file can't be queued because it has already been processed or was rejected."
# Used to read a directory, and call addFile() with every file found.
addDirectory: (entry, path) ->
dirReader = entry.createReader()
entriesReader = (entries) =>
for entry in entries
if entry.isFile
entry.file (file) =>
return if @options.ignoreHiddenFiles and file.name.substring(0, 1) is '.'
file.fullPath = "#{path}/#{file.name}"
@addFile file
else if entry.isDirectory
@addDirectory entry, "#{path}/#{entry.name}"
return
dirReader.readEntries entriesReader, (error) -> console?.log? error
# Can be called by the user to remove a file
removeFile: (file) ->
@cancelUpload file if file.status == Dropzone.UPLOADING
@files = without @files, file
@emit "removedfile", file
@emit "reset" if @files.length == 0
# Removes all files that aren't currently processed from the list
removeAllFiles: (cancelIfNecessary = off) ->
# Create a copy of files since removeFile() changes the @files array.
for file in @files.slice()
@removeFile file if file.status != Dropzone.UPLOADING || cancelIfNecessary
return null
createThumbnail: (file) ->
fileReader = new FileReader
fileReader.onload = =>
# Not using `new Image` here because of a bug in latest Chrome versions.
# See https://github.com/enyo/dropzone/pull/226
img = document.createElement "img"
img.onload = =>
file.width = img.width
file.height = img.height
resizeInfo = @options.resize.call @, file
resizeInfo.trgWidth ?= @options.thumbnailWidth
resizeInfo.trgHeight ?= @options.thumbnailHeight
canvas = document.createElement "canvas"
ctx = canvas.getContext "2d"
canvas.width = resizeInfo.trgWidth
canvas.height = resizeInfo.trgHeight
ctx.drawImage img, resizeInfo.srcX ? 0, resizeInfo.srcY ? 0, resizeInfo.srcWidth, resizeInfo.srcHeight, resizeInfo.trgX ? 0, resizeInfo.trgY ? 0, resizeInfo.trgWidth, resizeInfo.trgHeight
thumbnail = canvas.toDataURL "image/png"
@emit "thumbnail", file, thumbnail
img.src = fileReader.result
fileReader.readAsDataURL file
# Goes through the queue and processes files if there aren't too many already.
processQueue: ->
parallelUploads = @options.parallelUploads
processingLength = @getUploadingFiles().length
i = processingLength
# There are already at least as many files uploading than should be
return if processingLength >= parallelUploads
queuedFiles = @getQueuedFiles()
return unless queuedFiles.length > 0
if @options.uploadMultiple
# The files should be uploaded in one request
@processFiles queuedFiles.slice 0, (parallelUploads - processingLength)
else
while i < parallelUploads
return unless queuedFiles.length # Nothing left to process
@processFile queuedFiles.shift()
i++
# Wrapper for `processFiles`
processFile: (file) -> @processFiles [ file ]
# Loads the file, then calls finishedLoading()
processFiles: (files) ->
for file in files
file.processing = yes # Backwards compatibility
file.status = Dropzone.UPLOADING
@emit "processing", file
@emit "processingmultiple", files if @options.uploadMultiple
@uploadFiles files
_getFilesWithXhr: (xhr) -> files = (file for file in @files when file.xhr == xhr)
# Cancels the file upload and sets the status to CANCELED
# **if** the file is actually being uploaded.
# If it's still in the queue, the file is being removed from it and the status
# set to CANCELED.
cancelUpload: (file) ->
if file.status == Dropzone.UPLOADING
groupedFiles = @_getFilesWithXhr file.xhr
groupedFile.status = Dropzone.CANCELED for groupedFile in groupedFiles
file.xhr.abort()
@emit "canceled", groupedFile for groupedFile in groupedFiles
@emit "canceledmultiple", groupedFiles if @options.uploadMultiple
else if file.status in [ Dropzone.ADDED, Dropzone.QUEUED ]
file.status = Dropzone.CANCELED
@emit "canceled", file
@emit "canceledmultiple", [ file ] if @options.uploadMultiple
@processQueue() if @options.autoProcessQueue
# Wrapper for uploadFiles()
uploadFile: (file) -> @uploadFiles [ file ]
uploadFiles: (files) ->
xhr = new XMLHttpRequest()
# Put the xhr object in the file objects to be able to reference it later.
file.xhr = xhr for file in files
xhr.open @options.method, @options.url, true
# Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179
xhr.withCredentials = !!@options.withCredentials
response = null
handleError = =>
for file in files
@_errorProcessing files, response || @options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr
updateProgress = (e) =>
if e?
progress = 100 * e.loaded / e.total
for file in files
file.upload =
progress: progress
total: e.total
bytesSent: e.loaded
else
# Called when the file finished uploading
allFilesFinished = yes
progress = 100
for file in files
allFilesFinished = no unless file.upload.progress == 100 and file.upload.bytesSent == file.upload.total
file.upload.progress = progress
file.upload.bytesSent = file.upload.total
# Nothing to do, all files already at 100%
return if allFilesFinished
for file in files
@emit "uploadprogress", file, progress, file.upload.bytesSent
xhr.onload = (e) =>
return if files[0].status == Dropzone.CANCELED
return unless xhr.readyState is 4
response = xhr.responseText
if xhr.getResponseHeader("content-type") and ~xhr.getResponseHeader("content-type").indexOf "application/json"
try
response = JSON.parse response
catch e
response = "Invalid JSON response from server."
updateProgress()
unless 200 <= xhr.status < 300
handleError()
else
@_finished files, response, e
xhr.onerror = =>
return if files[0].status == Dropzone.CANCELED
handleError()
# Some browsers do not have the .upload property
progressObj = xhr.upload ? xhr
progressObj.onprogress = updateProgress
headers =
"Accept": "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest",
extend headers, @options.headers if @options.headers
xhr.setRequestHeader headerName, headerValue for headerName, headerValue of headers
formData = new FormData()
# Adding all @options parameters
formData.append key, value for key, value of @options.params if @options.params
# Let the user add additional data if necessary
@emit "sending", file, xhr, formData for file in files
@emit "sendingmultiple", files, xhr, formData if @options.uploadMultiple
# Take care of other input elements
if @element.tagName == "FORM"
for input in @element.querySelectorAll "input, textarea, select, button"
inputName = input.getAttribute "name"
inputType = input.getAttribute "type"
if !inputType or (inputType.toLowerCase() not in [ "checkbox", "radio" ]) or input.checked
formData.append inputName, input.value
# Finally add the file
# Has to be last because some servers (eg: S3) expect the file to be the
# last parameter
formData.append "#{@options.paramName}#{if @options.uploadMultiple then "[]" else ""}", file, file.name for file in files
xhr.send formData
# Called internally when processing is finished.
# Individual callbacks have to be called in the appropriate sections.
_finished: (files, responseText, e) ->
for file in files
file.status = Dropzone.SUCCESS
@emit "success", file, responseText, e
@emit "complete", file
if @options.uploadMultiple
@emit "successmultiple", files, responseText, e
@emit "completemultiple", files
@processQueue() if @options.autoProcessQueue
# Called internally when processing is finished.
# Individual callbacks have to be called in the appropriate sections.
_errorProcessing: (files, message, xhr) ->
for file in files
file.status = Dropzone.ERROR
@emit "error", file, message, xhr
@emit "complete", file
if @options.uploadMultiple
@emit "errormultiple", files, message, xhr
@emit "completemultiple", files
@processQueue() if @options.autoProcessQueue
Dropzone.version = "3.7.4-dev"
# This is a map of options for your different dropzones. Add configurations
# to this object for your different dropzone elemens.
#
# Example:
#
# Dropzone.options.myDropzoneElementId = { maxFilesize: 1 };
#
# To disable autoDiscover for a specific element, you can set `false` as an option:
#
# Dropzone.options.myDisabledElementId = false;
#
# And in html:
#
# <form action="/upload" id="my-dropzone-element-id" class="dropzone"></form>
Dropzone.options = { }
# Returns the options for an element or undefined if none available.
Dropzone.optionsForElement = (element) ->
# Get the `Dropzone.options.elementId` for this element if it exists
if element.id then Dropzone.options[camelize element.id] else undefined
# Holds a list of all dropzone instances
Dropzone.instances = [ ]
# Returns the dropzone for given element if any
Dropzone.forElement = (element) ->
element = document.querySelector element if typeof element == "string"
throw new Error "No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone." unless element?.dropzone?
return element.dropzone
# Set to false if you don't want Dropzone to automatically find and attach to .dropzone elements.
Dropzone.autoDiscover = on
# Looks for all .dropzone elements and creates a dropzone for them
Dropzone.discover = ->
if document.querySelectorAll
dropzones = document.querySelectorAll ".dropzone"
else
dropzones = [ ]
# IE :(
checkElements = (elements) ->
for el in elements
dropzones.push el if /(^| )dropzone($| )/.test el.className
checkElements document.getElementsByTagName "div"
checkElements document.getElementsByTagName "form"
for dropzone in dropzones
# Create a dropzone unless auto discover has been disabled for specific element
new Dropzone dropzone unless Dropzone.optionsForElement(dropzone) == false
# Since the whole Drag'n'Drop API is pretty new, some browsers implement it,
# but not correctly.
# So I created a blacklist of userAgents. Yes, yes. Browser sniffing, I know.
# But what to do when browsers *theoretically* support an API, but crash
# when using it.
#
# This is a list of regular expressions tested against navigator.userAgent
#
# ** It should only be used on browser that *do* support the API, but
# incorrectly **
#
Dropzone.blacklistedBrowsers = [
# The mac os version of opera 12 seems to have a problem with the File drag'n'drop API.
/opera.*Macintosh.*version\/12/i
# /MSIE\ 10/i
]
# Checks if the browser is supported
Dropzone.isBrowserSupported = ->
capableBrowser = yes
if window.File and window.FileReader and window.FileList and window.Blob and window.FormData and document.querySelector
unless "classList" of document.createElement "a"
capableBrowser = no
else
# The browser supports the API, but may be blacklisted.
for regex in Dropzone.blacklistedBrowsers
if regex.test navigator.userAgent
capableBrowser = no
continue
else
capableBrowser = no
capableBrowser
# Returns an array without the rejected item
without = (list, rejectedItem) -> item for item in list when item isnt rejectedItem
# abc-def_ghi -> abcDefGhi
camelize = (str) -> str.replace /[\-_](\w)/g, (match) -> match[1].toUpperCase()
# Creates an element from string
Dropzone.createElement = (string) ->
div = document.createElement "div"
div.innerHTML = string
div.childNodes[0]
# Tests if given element is inside (or simply is) the container
Dropzone.elementInside = (element, container) ->
return yes if element == container # Coffeescript doesn't support do/while loops
return yes while element = element.parentNode when element == container
return no
Dropzone.getElement = (el, name) ->
if typeof el == "string"
element = document.querySelector el
else if el.nodeType?
element = el
throw new Error "Invalid `#{name}` option provided. Please provide a CSS selector or a plain HTML element." unless element?
return element
Dropzone.getElements = (els, name) ->
if els instanceof Array
elements = [ ]
try
elements.push @getElement el, name for el in els
catch e
elements = null
else if typeof els == "string"
elements = [ ]
elements.push el for el in document.querySelectorAll els
else if els.nodeType?
elements = [ els ]
throw new Error "Invalid `#{name}` option provided. Please provide a CSS selector, a plain HTML element or a list of those." unless elements? and elements.length
return elements
# Asks the user the question and calls accepted or rejected accordingly
#
# The default implementation just uses `window.confirm` and then calls the
# appropriate callback.
Dropzone.confirm = (question, accepted, rejected) ->
if window.confirm question
accepted()
else if rejected?
rejected()
# Validates the mime type like this:
#
# https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept
Dropzone.isValidFile = (file, acceptedFiles) ->
return yes unless acceptedFiles # If there are no accepted mime types, it's OK
acceptedFiles = acceptedFiles.split ","
mimeType = file.type
baseMimeType = mimeType.replace /\/.*$/, ""
for validType in acceptedFiles
validType = validType.trim()
if validType.charAt(0) == "."
return yes if file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) != -1
else if /\/\*$/.test validType
# This is something like a image/* mime type
return yes if baseMimeType == validType.replace /\/.*$/, ""
else
return yes if mimeType == validType
return no
# Augment jQuery
if jQuery?
jQuery.fn.dropzone = (options) ->
this.each -> new Dropzone this, options
if module?
module.exports = Dropzone
else
window.Dropzone = Dropzone
# Dropzone file status codes
Dropzone.ADDED = "added"
Dropzone.QUEUED = "queued"
# For backwards compatibility. Now, if a file is accepted, it's either queued
# or uploading.
Dropzone.ACCEPTED = Dropzone.QUEUED
Dropzone.UPLOADING = "uploading"
Dropzone.PROCESSING = Dropzone.UPLOADING # alias
Dropzone.CANCELED = "canceled"
Dropzone.ERROR = "error"
Dropzone.SUCCESS = "success"
###
# contentloaded.js
#
# Author: <NAME> (<EMAIL>)
# Summary: cross-browser wrapper for DOMContentLoaded
# Updated: 20101020
# License: MIT
# Version: 1.2
#
# URL:
# http://javascript.nwbox.com/ContentLoaded/
# http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
###
# @win window reference
# @fn function reference
contentLoaded = (win, fn) ->
done = false
top = true
doc = win.document
root = doc.documentElement
add = (if doc.addEventListener then "addEventListener" else "attachEvent")
rem = (if doc.addEventListener then "removeEventListener" else "detachEvent")
pre = (if doc.addEventListener then "" else "on")
init = (e) ->
return if e.type is "readystatechange" and doc.readyState isnt "complete"
((if e.type is "load" then win else doc))[rem] pre + e.type, init, false
fn.call win, e.type or e if not done and (done = true)
poll = ->
try
root.doScroll "left"
catch e
setTimeout poll, 50
return
init "poll"
unless doc.readyState is "complete"
if doc.createEventObject and root.doScroll
try
top = not win.frameElement
poll() if top
doc[add] pre + "DOMContentLoaded", init, false
doc[add] pre + "readystatechange", init, false
win[add] pre + "load", init, false
# As a single function to be able to write tests.
Dropzone._autoDiscoverFunction = -> Dropzone.discover() if Dropzone.autoDiscover
contentLoaded window, Dropzone._autoDiscoverFunction
| true | ###
#
# More info at [www.dropzonejs.com](http://www.dropzonejs.com)
#
# Copyright (c) 2012, PI:NAME:<NAME>END_PI
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
###
# Dependencies
Em = Emitter ? require "emitter" # Can't be the same name because it will lead to a local variable
noop = ->
class Dropzone extends Em
###
This is a list of all available events you can register on a dropzone object.
You can register an event handler like this:
dropzone.on("dragEnter", function() { });
###
events: [
"drop"
"dragstart"
"dragend"
"dragenter"
"dragover"
"dragleave"
"selectedfiles"
"addedfile"
"removedfile"
"thumbnail"
"error"
"errormultiple"
"processing"
"processingmultiple"
"uploadprogress"
"totaluploadprogress"
"sending"
"sendingmultiple"
"success"
"successmultiple"
"canceled"
"canceledmultiple"
"complete"
"completemultiple"
"reset"
"maxfilesexceeded"
"maxfilesreached"
]
defaultOptions:
url: null
method: "post"
withCredentials: no
parallelUploads: 2
uploadMultiple: no # Whether to send multiple files in one request.
maxFilesize: 256 # in MB
paramName: "file" # The name of the file param that gets transferred.
createImageThumbnails: true
maxThumbnailFilesize: 10 # in MB. When the filename exceeds this limit, the thumbnail will not be generated.
thumbnailWidth: 100
thumbnailHeight: 100
# Can be used to limit the maximum number of files that will be handled
# by this Dropzone
maxFiles: null
# Can be an object of additional parameters to transfer to the server.
# This is the same as adding hidden input fields in the form element.
params: { }
# If true, the dropzone will present a file selector when clicked.
clickable: yes
# Whether hidden files in directories should be ignored.
ignoreHiddenFiles: yes
# You can set accepted mime types here.
#
# The default implementation of the `accept()` function will check this
# property, and if the Dropzone is clickable this will be used as
# `accept` attribute.
#
# This is a comma separated list of mime types or extensions. E.g.:
#
# audio/*,video/*,image/png,.pdf
#
# See https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept
# for a reference.
acceptedFiles: null
# @deprecated
# Use acceptedFiles instead.
acceptedMimeTypes: null
# If false, files will be added to the queue but the queu will not be
# processed automatically.
# This can be useful if you need some additional user input before sending
# files (or if you want want all files sent at once).
# If you're ready to send the file simply call myDropzone.processQueue()
autoProcessQueue: on
# If true, Dropzone will add a link to each file preview to cancel/remove
# the upload.
# See dictCancelUpload and dictRemoveFile to use different words.
addRemoveLinks: no
# A CSS selector or HTML element for the file previews container.
# If null, the dropzone element itself will be used
previewsContainer: null
# Dictionary
# The text used before any files are dropped
dictDefaultMessage: "Drop files here to upload"
# The text that replaces the default message text it the browser is not supported
dictFallbackMessage: "Your browser does not support drag'n'drop file uploads."
# The text that will be added before the fallback form
# If null, no text will be added at all.
dictFallbackText: "Please use the fallback form below to upload your files like in the olden days."
# If the filesize is too big.
dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: {{maxFilesize}}MB."
# If the file doesn't match the file type.
dictInvalidFileType: "You can't upload files of this type."
# If the server response was invalid.
dictResponseError: "Server responded with {{statusCode}} code."
# If used, the text to be used for the cancel upload link.
dictCancelUpload: "Cancel upload"
# If used, the text to be used for confirmation when cancelling upload.
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?"
# If used, the text to be used to remove a file.
dictRemoveFile: "Remove file"
# If this is not null, then the user will be prompted before removing a file.
dictRemoveFileConfirmation: null
# Displayed when the maxFiles have been exceeded
dictMaxFilesExceeded: "You can only upload {{maxFiles}} files."
# If `done()` is called without argument the file is accepted
# If you call it with an error message, the file is rejected
# (This allows for asynchronous validation).
accept: (file, done) -> done()
# Called when dropzone initialized
# You can add event listeners here
init: -> noop
# Used to debug dropzone and force the fallback form.
forceFallback: off
# Called when the browser does not support drag and drop
fallback: ->
# This code should pass in IE7... :(
@element.className = "#{@element.className} dz-browser-not-supported"
for child in @element.getElementsByTagName "div"
if /(^| )dz-message($| )/.test child.className
messageElement = child
child.className = "dz-message" # Removes the 'dz-default' class
continue
unless messageElement
messageElement = Dropzone.createElement """<div class="dz-message"><span></span></div>"""
@element.appendChild messageElement
span = messageElement.getElementsByTagName("span")[0]
span.textContent = @options.dictFallbackMessage if span
@element.appendChild @getFallbackForm()
# Gets called to calculate the thumbnail dimensions.
#
# You can use file.width, file.height, options.thumbnailWidth and
# options.thumbnailHeight to calculate the dimensions.
#
# The dimensions are going to be used like this:
#
# var info = @options.resize.call(this, file);
# ctx.drawImage(img, info.srcX, info.srcY, info.srcWidth, info.srcHeight, info.trgX, info.trgY, info.trgWidth, info.trgHeight);
#
# srcX, srcy, trgX and trgY can be omitted (in which case 0 is assumed).
# trgWidth and trgHeight can be omitted (in which case the options.thumbnailWidth / options.thumbnailHeight are used)
resize: (file) ->
info =
srcX: 0
srcY: 0
srcWidth: file.width
srcHeight: file.height
srcRatio = file.width / file.height
trgRatio = @options.thumbnailWidth / @options.thumbnailHeight
if file.height < @options.thumbnailHeight or file.width < @options.thumbnailWidth
# This image is smaller than the canvas
info.trgHeight = info.srcHeight
info.trgWidth = info.srcWidth
else
# Image is bigger and needs rescaling
if srcRatio > trgRatio
info.srcHeight = file.height
info.srcWidth = info.srcHeight * trgRatio
else
info.srcWidth = file.width
info.srcHeight = info.srcWidth / trgRatio
info.srcX = (file.width - info.srcWidth) / 2
info.srcY = (file.height - info.srcHeight) / 2
return info
###
Those functions register themselves to the events on init and handle all
the user interface specific stuff. Overwriting them won't break the upload
but can break the way it's displayed.
You can overwrite them if you don't like the default behavior. If you just
want to add an additional event handler, register it on the dropzone object
and don't overwrite those options.
###
# Those are self explanatory and simply concern the DragnDrop.
drop: (e) -> @element.classList.remove "dz-drag-hover"
dragstart: noop
dragend: (e) -> @element.classList.remove "dz-drag-hover"
dragenter: (e) -> @element.classList.add "dz-drag-hover"
dragover: (e) -> @element.classList.add "dz-drag-hover"
dragleave: (e) -> @element.classList.remove "dz-drag-hover"
# Called whenever files are dropped or selected
selectedfiles: (files) ->
@element.classList.add "dz-started" if @element == @previewsContainer
# Called whenever there are no files left in the dropzone anymore, and the
# dropzone should be displayed as if in the initial state.
reset: ->
@element.classList.remove "dz-started"
# Called when a file is added to the queue
# Receives `file`
addedfile: (file) ->
file.previewElement = Dropzone.createElement @options.previewTemplate.trim()
file.previewTemplate = file.previewElement # Backwards compatibility
@previewsContainer.appendChild file.previewElement
node.textContent = file.name for node in file.previewElement.querySelectorAll("[data-dz-name]")
node.innerHTML = @filesize file.size for node in file.previewElement.querySelectorAll("[data-dz-size]")
if @options.addRemoveLinks
file._removeLink = Dropzone.createElement """<a class="dz-remove" href="javascript:undefined;">#{@options.dictRemoveFile}</a>"""
file._removeLink.addEventListener "click", (e) =>
e.preventDefault()
e.stopPropagation()
if file.status == Dropzone.UPLOADING
Dropzone.confirm @options.dictCancelUploadConfirmation, => @removeFile file
else
if @options.dictRemoveFileConfirmation
Dropzone.confirm @options.dictRemoveFileConfirmation, => @removeFile file
else
@removeFile file
file.previewElement.appendChild file._removeLink
# Called whenever a file is removed.
removedfile: (file) ->
file.previewElement?.parentNode.removeChild file.previewElement
@_updateMaxFilesReachedClass()
# Called when a thumbnail has been generated
# Receives `file` and `dataUrl`
thumbnail: (file, dataUrl) ->
file.previewElement.classList.remove "dz-file-preview"
file.previewElement.classList.add "dz-image-preview"
for thumbnailElement in file.previewElement.querySelectorAll("[data-dz-thumbnail]")
thumbnailElement.alt = file.name
thumbnailElement.src = dataUrl
# Called whenever an error occurs
# Receives `file` and `message`
error: (file, message) ->
file.previewElement.classList.add "dz-error"
node.textContent = message for node in file.previewElement.querySelectorAll("[data-dz-errormessage]")
errormultiple: noop
# Called when a file gets processed. Since there is a cue, not all added
# files are processed immediately.
# Receives `file`
processing: (file) ->
file.previewElement.classList.add "dz-processing"
file._removeLink.textContent = @options.dictCancelUpload if file._removeLink
processingmultiple: noop
# Called whenever the upload progress gets updated.
# Receives `file`, `progress` (percentage 0-100) and `bytesSent`.
# To get the total number of bytes of the file, use `file.size`
uploadprogress: (file, progress, bytesSent) ->
node.style.width = "#{progress}%" for node in file.previewElement.querySelectorAll("[data-dz-uploadprogress]")
# Called whenever the total upload progress gets updated.
# Called with totalUploadProgress (0-100), totalBytes and totalBytesSent
totaluploadprogress: noop
# Called just before the file is sent. Gets the `xhr` object as second
# parameter, so you can modify it (for example to add a CSRF token) and a
# `formData` object to add additional information.
sending: noop
sendingmultiple: noop
# When the complete upload is finished and successfull
# Receives `file`
success: (file) ->
file.previewElement.classList.add "dz-success"
successmultiple: noop
# When the upload is canceled.
canceled: (file) -> @emit "error", file, "Upload canceled."
canceledmultiple: noop
# When the upload is finished, either with success or an error.
# Receives `file`
complete: (file) ->
file._removeLink.textContent = @options.dictRemoveFile if file._removeLink
completemultiple: noop
maxfilesexceeded: noop
maxfilesreached: noop
# This template will be chosen when a new file is dropped.
previewTemplate: """
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-filename"><span data-dz-name></span></div>
<div class="dz-size" data-dz-size></div>
<img data-dz-thumbnail />
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
</div>
"""
# global utility
extend = (target, objects...) ->
for object in objects
target[key] = val for key, val of object
target
constructor: (@element, options) ->
# For backwards compatibility since the version was in the prototype previously
@version = Dropzone.version
@defaultOptions.previewTemplate = @defaultOptions.previewTemplate.replace /\n*/g, ""
@clickableElements = [ ]
@listeners = [ ]
@files = [] # All files
@element = document.querySelector @element if typeof @element == "string"
# Not checking if instance of HTMLElement or Element since IE9 is extremely weird.
throw new Error "Invalid dropzone element." unless @element and @element.nodeType?
throw new Error "Dropzone already attached." if @element.dropzone
# Now add this dropzone to the instances.
Dropzone.instances.push @
# Put the dropzone inside the element itself.
@element.dropzone = @
elementOptions = Dropzone.optionsForElement(@element) ? { }
@options = extend { }, @defaultOptions, elementOptions, options ? { }
# If the browser failed, just call the fallback and leave
return @options.fallback.call this if @options.forceFallback or !Dropzone.isBrowserSupported()
# @options.url = @element.getAttribute "action" unless @options.url?
@options.url = @element.getAttribute "action" unless @options.url?
throw new Error "No URL provided." unless @options.url
throw new Error "You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated." if @options.acceptedFiles and @options.acceptedMimeTypes
# Backwards compatibility
if @options.acceptedMimeTypes
@options.acceptedFiles = @options.acceptedMimeTypes
delete @options.acceptedMimeTypes
@options.method = @options.method.toUpperCase()
if (fallback = @getExistingFallback()) and fallback.parentNode
# Remove the fallback
fallback.parentNode.removeChild fallback
if @options.previewsContainer
@previewsContainer = Dropzone.getElement @options.previewsContainer, "previewsContainer"
else
@previewsContainer = @element
if @options.clickable
if @options.clickable == yes
@clickableElements = [ @element ]
else
@clickableElements = Dropzone.getElements @options.clickable, "clickable"
@init()
# Returns all files that have been accepted
getAcceptedFiles: -> file for file in @files when file.accepted
# Returns all files that have been rejected
# Not sure when that's going to be useful, but added for completeness.
getRejectedFiles: -> file for file in @files when not file.accepted
# Returns all files that are in the queue
getQueuedFiles: -> file for file in @files when file.status == Dropzone.QUEUED
getUploadingFiles: -> file for file in @files when file.status == Dropzone.UPLOADING
init: ->
# In case it isn't set already
@element.setAttribute("enctype", "multipart/form-data") if @element.tagName == "form"
if @element.classList.contains("dropzone") and !@element.querySelector(".dz-message")
@element.appendChild Dropzone.createElement """<div class="dz-default dz-message"><span>#{@options.dictDefaultMessage}</span></div>"""
if @clickableElements.length
setupHiddenFileInput = =>
document.body.removeChild @hiddenFileInput if @hiddenFileInput
@hiddenFileInput = document.createElement "input"
@hiddenFileInput.setAttribute "type", "file"
@hiddenFileInput.setAttribute "multiple", "multiple" if !@options.maxFiles? || @options.maxFiles > 1
@hiddenFileInput.setAttribute "accept", @options.acceptedFiles if @options.acceptedFiles?
# Not setting `display="none"` because some browsers don't accept clicks
# on elements that aren't displayed.
@hiddenFileInput.style.visibility = "hidden"
@hiddenFileInput.style.position = "absolute"
@hiddenFileInput.style.top = "0"
@hiddenFileInput.style.left = "0"
@hiddenFileInput.style.height = "0"
@hiddenFileInput.style.width = "0"
document.body.appendChild @hiddenFileInput
@hiddenFileInput.addEventListener "change", =>
files = @hiddenFileInput.files
if files.length
@emit "selectedfiles", files
@handleFiles files
setupHiddenFileInput()
setupHiddenFileInput()
@URL = window.URL ? window.webkitURL
# Setup all event listeners on the Dropzone object itself.
# They're not in @setupEventListeners() because they shouldn't be removed
# again when the dropzone gets disabled.
@on eventName, @options[eventName] for eventName in @events
@on "uploadprogress", => @updateTotalUploadProgress()
@on "removedfile", => @updateTotalUploadProgress()
@on "canceled", (file) => @emit "complete", file
noPropagation = (e) ->
e.stopPropagation()
if e.preventDefault
e.preventDefault()
else
e.returnValue = false
# Create the listeners
@listeners = [
{
element: @element
events:
"dragstart": (e) =>
@emit "dragstart", e
"dragenter": (e) =>
noPropagation e
@emit "dragenter", e
"dragover": (e) =>
# Makes it possible to drag files from chrome's download bar
# http://stackoverflow.com/questions/19526430/drag-and-drop-file-uploads-from-chrome-downloads-bar
efct = e.dataTransfer.effectAllowed
e.dataTransfer.dropEffect = if 'move' == efct or 'linkMove' == efct then 'move' else 'copy'
noPropagation e
@emit "dragover", e
"dragleave": (e) =>
@emit "dragleave", e
"drop": (e) =>
noPropagation e
@drop e
"dragend": (e) =>
@emit "dragend", e
}
]
@clickableElements.forEach (clickableElement) =>
@listeners.push
element: clickableElement
events:
"click": (evt) =>
# Only the actual dropzone or the message element should trigger file selection
if (clickableElement != @element) or (evt.target == @element or Dropzone.elementInside evt.target, @element.querySelector ".dz-message")
@hiddenFileInput.click() # Forward the click
@enable()
@options.init.call @
# Not fully tested yet
destroy: ->
@disable()
@removeAllFiles true
if @hiddenFileInput?.parentNode
@hiddenFileInput.parentNode.removeChild @hiddenFileInput
@hiddenFileInput = null
delete @element.dropzone
updateTotalUploadProgress: ->
totalBytesSent = 0
totalBytes = 0
acceptedFiles = @getAcceptedFiles()
if acceptedFiles.length
for file in @getAcceptedFiles()
totalBytesSent += file.upload.bytesSent
totalBytes += file.upload.total
totalUploadProgress = 100 * totalBytesSent / totalBytes
else
totalUploadProgress = 100
@emit "totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent
# Returns a form that can be used as fallback if the browser does not support DragnDrop
#
# If the dropzone is already a form, only the input field and button are returned. Otherwise a complete form element is provided.
# This code has to pass in IE7 :(
getFallbackForm: ->
return existingFallback if existingFallback = @getExistingFallback()
fieldsString = """<div class="dz-fallback">"""
fieldsString += """<p>#{@options.dictFallbackText}</p>""" if @options.dictFallbackText
fieldsString += """<input type="file" name="#{@options.paramName}#{if @options.uploadMultiple then "[]" else ""}" #{if @options.uploadMultiple then 'multiple="multiple"' } /><input type="submit" value="Upload!"></div>"""
fields = Dropzone.createElement fieldsString
if @element.tagName isnt "FORM"
form = Dropzone.createElement("""<form action="#{@options.url}" enctype="multipart/form-data" method="#{@options.method}"></form>""")
form.appendChild fields
else
# Make sure that the enctype and method attributes are set properly
@element.setAttribute "enctype", "multipart/form-data"
@element.setAttribute "method", @options.method
form ? fields
# Returns the fallback elements if they exist already
#
# This code has to pass in IE7 :(
getExistingFallback: ->
getFallback = (elements) -> return el for el in elements when /(^| )fallback($| )/.test el.className
for tagName in [ "div", "form" ]
return fallback if fallback = getFallback @element.getElementsByTagName tagName
# Activates all listeners stored in @listeners
setupEventListeners: ->
for elementListeners in @listeners
elementListeners.element.addEventListener event, listener, false for event, listener of elementListeners.events
# Deactivates all listeners stored in @listeners
removeEventListeners: ->
for elementListeners in @listeners
elementListeners.element.removeEventListener event, listener, false for event, listener of elementListeners.events
# Removes all event listeners and cancels all files in the queue or being processed.
disable: ->
@clickableElements.forEach (element) -> element.classList.remove "dz-clickable"
@removeEventListeners()
@cancelUpload file for file in @files
enable: ->
@clickableElements.forEach (element) -> element.classList.add "dz-clickable"
@setupEventListeners()
# Returns a nicely formatted filesize
filesize: (size) ->
if size >= 100000000000
size = size / 100000000000
string = "TB"
else if size >= 100000000
size = size / 100000000
string = "GB"
else if size >= 100000
size = size / 100000
string = "MB"
else if size >= 100
size = size / 100
string = "KB"
else
size = size * 10
string = "b"
"<strong>#{Math.round(size)/10}</strong> #{string}"
# Adds or removes the `dz-max-files-reached` class from the form.
_updateMaxFilesReachedClass: ->
if @options.maxFiles and @getAcceptedFiles().length >= @options.maxFiles
@emit 'maxfilesreached', @files if @getAcceptedFiles().length == @options.maxFiles
@element.classList.add "dz-max-files-reached"
else
@element.classList.remove "dz-max-files-reached"
drop: (e) ->
return unless e.dataTransfer
@emit "drop", e
files = e.dataTransfer.files
@emit "selectedfiles", files
# Even if it's a folder, files.length will contain the folders.
if files.length
items = e.dataTransfer.items
if items and items.length and (items[0].webkitGetAsEntry? or items[0].getAsEntry?)
# The browser supports dropping of folders, so handle items instead of files
@handleItems items
else
@handleFiles files
return
handleFiles: (files) ->
@addFile file for file in files
# When a folder is dropped, items must be handled instead of files.
handleItems: (items) ->
for item in items
if item.webkitGetAsEntry?
entry = item.webkitGetAsEntry()
if entry.isFile
@addFile item.getAsFile()
else if entry.isDirectory
@addDirectory entry, entry.name
else
@addFile item.getAsFile()
return
# If `done()` is called without argument the file is accepted
# If you call it with an error message, the file is rejected
# (This allows for asynchronous validation)
#
# This function checks the filesize, and if the file.type passes the
# `acceptedFiles` check.
accept: (file, done) ->
if file.size > @options.maxFilesize * 1024 * 1024
done @options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", @options.maxFilesize)
else unless Dropzone.isValidFile file, @options.acceptedFiles
done @options.dictInvalidFileType
else if @options.maxFiles and @getAcceptedFiles().length >= @options.maxFiles
done @options.dictMaxFilesExceeded.replace "{{maxFiles}}", @options.maxFiles
@emit "maxfilesexceeded", file
else
@options.accept.call this, file, done
addFile: (file) ->
file.upload =
progress: 0
# Setting the total upload size to file.size for the beginning
# It's actual different than the size to be transmitted.
total: file.size
bytesSent: 0
@files.push file
file.status = Dropzone.ADDED
@emit "addedfile", file
@createThumbnail file if @options.createImageThumbnails and file.type.match(/image.*/) and file.size <= @options.maxThumbnailFilesize * 1024 * 1024
@accept file, (error) =>
if error
file.accepted = false
@_errorProcessing [ file ], error # Will set the file.status
else
@enqueueFile file # Will set .accepted = true
@_updateMaxFilesReachedClass()
# Wrapper for enqueuFile
enqueueFiles: (files) -> @enqueueFile file for file in files; null
enqueueFile: (file) ->
file.accepted = true
if file.status == Dropzone.ADDED
file.status = Dropzone.QUEUED
if @options.autoProcessQueue
setTimeout (=> @processQueue()), 1 # Deferring the call
else
throw new Error "This file can't be queued because it has already been processed or was rejected."
# Used to read a directory, and call addFile() with every file found.
addDirectory: (entry, path) ->
dirReader = entry.createReader()
entriesReader = (entries) =>
for entry in entries
if entry.isFile
entry.file (file) =>
return if @options.ignoreHiddenFiles and file.name.substring(0, 1) is '.'
file.fullPath = "#{path}/#{file.name}"
@addFile file
else if entry.isDirectory
@addDirectory entry, "#{path}/#{entry.name}"
return
dirReader.readEntries entriesReader, (error) -> console?.log? error
# Can be called by the user to remove a file
removeFile: (file) ->
@cancelUpload file if file.status == Dropzone.UPLOADING
@files = without @files, file
@emit "removedfile", file
@emit "reset" if @files.length == 0
# Removes all files that aren't currently processed from the list
removeAllFiles: (cancelIfNecessary = off) ->
# Create a copy of files since removeFile() changes the @files array.
for file in @files.slice()
@removeFile file if file.status != Dropzone.UPLOADING || cancelIfNecessary
return null
createThumbnail: (file) ->
fileReader = new FileReader
fileReader.onload = =>
# Not using `new Image` here because of a bug in latest Chrome versions.
# See https://github.com/enyo/dropzone/pull/226
img = document.createElement "img"
img.onload = =>
file.width = img.width
file.height = img.height
resizeInfo = @options.resize.call @, file
resizeInfo.trgWidth ?= @options.thumbnailWidth
resizeInfo.trgHeight ?= @options.thumbnailHeight
canvas = document.createElement "canvas"
ctx = canvas.getContext "2d"
canvas.width = resizeInfo.trgWidth
canvas.height = resizeInfo.trgHeight
ctx.drawImage img, resizeInfo.srcX ? 0, resizeInfo.srcY ? 0, resizeInfo.srcWidth, resizeInfo.srcHeight, resizeInfo.trgX ? 0, resizeInfo.trgY ? 0, resizeInfo.trgWidth, resizeInfo.trgHeight
thumbnail = canvas.toDataURL "image/png"
@emit "thumbnail", file, thumbnail
img.src = fileReader.result
fileReader.readAsDataURL file
# Goes through the queue and processes files if there aren't too many already.
processQueue: ->
parallelUploads = @options.parallelUploads
processingLength = @getUploadingFiles().length
i = processingLength
# There are already at least as many files uploading than should be
return if processingLength >= parallelUploads
queuedFiles = @getQueuedFiles()
return unless queuedFiles.length > 0
if @options.uploadMultiple
# The files should be uploaded in one request
@processFiles queuedFiles.slice 0, (parallelUploads - processingLength)
else
while i < parallelUploads
return unless queuedFiles.length # Nothing left to process
@processFile queuedFiles.shift()
i++
# Wrapper for `processFiles`
processFile: (file) -> @processFiles [ file ]
# Loads the file, then calls finishedLoading()
processFiles: (files) ->
for file in files
file.processing = yes # Backwards compatibility
file.status = Dropzone.UPLOADING
@emit "processing", file
@emit "processingmultiple", files if @options.uploadMultiple
@uploadFiles files
_getFilesWithXhr: (xhr) -> files = (file for file in @files when file.xhr == xhr)
# Cancels the file upload and sets the status to CANCELED
# **if** the file is actually being uploaded.
# If it's still in the queue, the file is being removed from it and the status
# set to CANCELED.
cancelUpload: (file) ->
if file.status == Dropzone.UPLOADING
groupedFiles = @_getFilesWithXhr file.xhr
groupedFile.status = Dropzone.CANCELED for groupedFile in groupedFiles
file.xhr.abort()
@emit "canceled", groupedFile for groupedFile in groupedFiles
@emit "canceledmultiple", groupedFiles if @options.uploadMultiple
else if file.status in [ Dropzone.ADDED, Dropzone.QUEUED ]
file.status = Dropzone.CANCELED
@emit "canceled", file
@emit "canceledmultiple", [ file ] if @options.uploadMultiple
@processQueue() if @options.autoProcessQueue
# Wrapper for uploadFiles()
uploadFile: (file) -> @uploadFiles [ file ]
uploadFiles: (files) ->
xhr = new XMLHttpRequest()
# Put the xhr object in the file objects to be able to reference it later.
file.xhr = xhr for file in files
xhr.open @options.method, @options.url, true
# Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179
xhr.withCredentials = !!@options.withCredentials
response = null
handleError = =>
for file in files
@_errorProcessing files, response || @options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr
updateProgress = (e) =>
if e?
progress = 100 * e.loaded / e.total
for file in files
file.upload =
progress: progress
total: e.total
bytesSent: e.loaded
else
# Called when the file finished uploading
allFilesFinished = yes
progress = 100
for file in files
allFilesFinished = no unless file.upload.progress == 100 and file.upload.bytesSent == file.upload.total
file.upload.progress = progress
file.upload.bytesSent = file.upload.total
# Nothing to do, all files already at 100%
return if allFilesFinished
for file in files
@emit "uploadprogress", file, progress, file.upload.bytesSent
xhr.onload = (e) =>
return if files[0].status == Dropzone.CANCELED
return unless xhr.readyState is 4
response = xhr.responseText
if xhr.getResponseHeader("content-type") and ~xhr.getResponseHeader("content-type").indexOf "application/json"
try
response = JSON.parse response
catch e
response = "Invalid JSON response from server."
updateProgress()
unless 200 <= xhr.status < 300
handleError()
else
@_finished files, response, e
xhr.onerror = =>
return if files[0].status == Dropzone.CANCELED
handleError()
# Some browsers do not have the .upload property
progressObj = xhr.upload ? xhr
progressObj.onprogress = updateProgress
headers =
"Accept": "application/json",
"Cache-Control": "no-cache",
"X-Requested-With": "XMLHttpRequest",
extend headers, @options.headers if @options.headers
xhr.setRequestHeader headerName, headerValue for headerName, headerValue of headers
formData = new FormData()
# Adding all @options parameters
formData.append key, value for key, value of @options.params if @options.params
# Let the user add additional data if necessary
@emit "sending", file, xhr, formData for file in files
@emit "sendingmultiple", files, xhr, formData if @options.uploadMultiple
# Take care of other input elements
if @element.tagName == "FORM"
for input in @element.querySelectorAll "input, textarea, select, button"
inputName = input.getAttribute "name"
inputType = input.getAttribute "type"
if !inputType or (inputType.toLowerCase() not in [ "checkbox", "radio" ]) or input.checked
formData.append inputName, input.value
# Finally add the file
# Has to be last because some servers (eg: S3) expect the file to be the
# last parameter
formData.append "#{@options.paramName}#{if @options.uploadMultiple then "[]" else ""}", file, file.name for file in files
xhr.send formData
# Called internally when processing is finished.
# Individual callbacks have to be called in the appropriate sections.
_finished: (files, responseText, e) ->
for file in files
file.status = Dropzone.SUCCESS
@emit "success", file, responseText, e
@emit "complete", file
if @options.uploadMultiple
@emit "successmultiple", files, responseText, e
@emit "completemultiple", files
@processQueue() if @options.autoProcessQueue
# Called internally when processing is finished.
# Individual callbacks have to be called in the appropriate sections.
_errorProcessing: (files, message, xhr) ->
for file in files
file.status = Dropzone.ERROR
@emit "error", file, message, xhr
@emit "complete", file
if @options.uploadMultiple
@emit "errormultiple", files, message, xhr
@emit "completemultiple", files
@processQueue() if @options.autoProcessQueue
Dropzone.version = "3.7.4-dev"
# This is a map of options for your different dropzones. Add configurations
# to this object for your different dropzone elemens.
#
# Example:
#
# Dropzone.options.myDropzoneElementId = { maxFilesize: 1 };
#
# To disable autoDiscover for a specific element, you can set `false` as an option:
#
# Dropzone.options.myDisabledElementId = false;
#
# And in html:
#
# <form action="/upload" id="my-dropzone-element-id" class="dropzone"></form>
Dropzone.options = { }
# Returns the options for an element or undefined if none available.
Dropzone.optionsForElement = (element) ->
# Get the `Dropzone.options.elementId` for this element if it exists
if element.id then Dropzone.options[camelize element.id] else undefined
# Holds a list of all dropzone instances
Dropzone.instances = [ ]
# Returns the dropzone for given element if any
Dropzone.forElement = (element) ->
element = document.querySelector element if typeof element == "string"
throw new Error "No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone." unless element?.dropzone?
return element.dropzone
# Set to false if you don't want Dropzone to automatically find and attach to .dropzone elements.
Dropzone.autoDiscover = on
# Looks for all .dropzone elements and creates a dropzone for them
Dropzone.discover = ->
if document.querySelectorAll
dropzones = document.querySelectorAll ".dropzone"
else
dropzones = [ ]
# IE :(
checkElements = (elements) ->
for el in elements
dropzones.push el if /(^| )dropzone($| )/.test el.className
checkElements document.getElementsByTagName "div"
checkElements document.getElementsByTagName "form"
for dropzone in dropzones
# Create a dropzone unless auto discover has been disabled for specific element
new Dropzone dropzone unless Dropzone.optionsForElement(dropzone) == false
# Since the whole Drag'n'Drop API is pretty new, some browsers implement it,
# but not correctly.
# So I created a blacklist of userAgents. Yes, yes. Browser sniffing, I know.
# But what to do when browsers *theoretically* support an API, but crash
# when using it.
#
# This is a list of regular expressions tested against navigator.userAgent
#
# ** It should only be used on browser that *do* support the API, but
# incorrectly **
#
Dropzone.blacklistedBrowsers = [
# The mac os version of opera 12 seems to have a problem with the File drag'n'drop API.
/opera.*Macintosh.*version\/12/i
# /MSIE\ 10/i
]
# Checks if the browser is supported
Dropzone.isBrowserSupported = ->
capableBrowser = yes
if window.File and window.FileReader and window.FileList and window.Blob and window.FormData and document.querySelector
unless "classList" of document.createElement "a"
capableBrowser = no
else
# The browser supports the API, but may be blacklisted.
for regex in Dropzone.blacklistedBrowsers
if regex.test navigator.userAgent
capableBrowser = no
continue
else
capableBrowser = no
capableBrowser
# Returns an array without the rejected item
without = (list, rejectedItem) -> item for item in list when item isnt rejectedItem
# abc-def_ghi -> abcDefGhi
camelize = (str) -> str.replace /[\-_](\w)/g, (match) -> match[1].toUpperCase()
# Creates an element from string
Dropzone.createElement = (string) ->
div = document.createElement "div"
div.innerHTML = string
div.childNodes[0]
# Tests if given element is inside (or simply is) the container
Dropzone.elementInside = (element, container) ->
return yes if element == container # Coffeescript doesn't support do/while loops
return yes while element = element.parentNode when element == container
return no
Dropzone.getElement = (el, name) ->
if typeof el == "string"
element = document.querySelector el
else if el.nodeType?
element = el
throw new Error "Invalid `#{name}` option provided. Please provide a CSS selector or a plain HTML element." unless element?
return element
Dropzone.getElements = (els, name) ->
if els instanceof Array
elements = [ ]
try
elements.push @getElement el, name for el in els
catch e
elements = null
else if typeof els == "string"
elements = [ ]
elements.push el for el in document.querySelectorAll els
else if els.nodeType?
elements = [ els ]
throw new Error "Invalid `#{name}` option provided. Please provide a CSS selector, a plain HTML element or a list of those." unless elements? and elements.length
return elements
# Asks the user the question and calls accepted or rejected accordingly
#
# The default implementation just uses `window.confirm` and then calls the
# appropriate callback.
Dropzone.confirm = (question, accepted, rejected) ->
if window.confirm question
accepted()
else if rejected?
rejected()
# Validates the mime type like this:
#
# https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept
Dropzone.isValidFile = (file, acceptedFiles) ->
return yes unless acceptedFiles # If there are no accepted mime types, it's OK
acceptedFiles = acceptedFiles.split ","
mimeType = file.type
baseMimeType = mimeType.replace /\/.*$/, ""
for validType in acceptedFiles
validType = validType.trim()
if validType.charAt(0) == "."
return yes if file.name.toLowerCase().indexOf(validType.toLowerCase(), file.name.length - validType.length) != -1
else if /\/\*$/.test validType
# This is something like a image/* mime type
return yes if baseMimeType == validType.replace /\/.*$/, ""
else
return yes if mimeType == validType
return no
# Augment jQuery
if jQuery?
jQuery.fn.dropzone = (options) ->
this.each -> new Dropzone this, options
if module?
module.exports = Dropzone
else
window.Dropzone = Dropzone
# Dropzone file status codes
Dropzone.ADDED = "added"
Dropzone.QUEUED = "queued"
# For backwards compatibility. Now, if a file is accepted, it's either queued
# or uploading.
Dropzone.ACCEPTED = Dropzone.QUEUED
Dropzone.UPLOADING = "uploading"
Dropzone.PROCESSING = Dropzone.UPLOADING # alias
Dropzone.CANCELED = "canceled"
Dropzone.ERROR = "error"
Dropzone.SUCCESS = "success"
###
# contentloaded.js
#
# Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# Summary: cross-browser wrapper for DOMContentLoaded
# Updated: 20101020
# License: MIT
# Version: 1.2
#
# URL:
# http://javascript.nwbox.com/ContentLoaded/
# http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE
###
# @win window reference
# @fn function reference
contentLoaded = (win, fn) ->
done = false
top = true
doc = win.document
root = doc.documentElement
add = (if doc.addEventListener then "addEventListener" else "attachEvent")
rem = (if doc.addEventListener then "removeEventListener" else "detachEvent")
pre = (if doc.addEventListener then "" else "on")
init = (e) ->
return if e.type is "readystatechange" and doc.readyState isnt "complete"
((if e.type is "load" then win else doc))[rem] pre + e.type, init, false
fn.call win, e.type or e if not done and (done = true)
poll = ->
try
root.doScroll "left"
catch e
setTimeout poll, 50
return
init "poll"
unless doc.readyState is "complete"
if doc.createEventObject and root.doScroll
try
top = not win.frameElement
poll() if top
doc[add] pre + "DOMContentLoaded", init, false
doc[add] pre + "readystatechange", init, false
win[add] pre + "load", init, false
# As a single function to be able to write tests.
Dropzone._autoDiscoverFunction = -> Dropzone.discover() if Dropzone.autoDiscover
contentLoaded window, Dropzone._autoDiscoverFunction
|
[
{
"context": " (no longer strictly required)\n\t# @param\t{String}\tusername\t\tUser's username\n\t# @param\t{String}\tpassword\t\tUse",
"end": 4272,
"score": 0.9522994756698608,
"start": 4264,
"tag": "USERNAME",
"value": "username"
},
{
"context": "r strictly required)\n\t# @param\t... | server/lib/data_access/users.coffee | willroberts/duelyst | 5 | Promise = require 'bluebird'
util = require 'util'
crypto = require 'crypto'
FirebasePromises = require '../firebase_promises'
DuelystFirebase = require '../duelyst_firebase_module'
fbUtil = require '../../../app/common/utils/utils_firebase.js'
Logger = require '../../../app/common/logger.coffee'
colors = require 'colors'
validator = require 'validator'
uuid = require 'node-uuid'
moment = require 'moment'
_ = require 'underscore'
SyncModule = require './sync'
MigrationsModule = require './migrations'
InventoryModule = require './inventory'
QuestsModule = require './quests'
GamesModule = require './games'
RiftModule = require './rift'
RiftModule = require './gauntlet'
CosmeticChestsModule = require './cosmetic_chests'
CONFIG = require '../../../app/common/config.js'
Errors = require '../custom_errors'
mail = require '../../mailer'
knex = require("../data_access/knex")
config = require '../../../config/config.js'
generatePushId = require '../../../app/common/generate_push_id'
DataAccessHelpers = require('./helpers')
hashHelpers = require '../hash_helpers.coffee'
Promise.promisifyAll(mail)
AnalyticsUtil = require '../../../app/common/analyticsUtil.coffee'
{version} = require '../../../version.json'
# redis
{Redis, Jobs, GameManager} = require '../../redis/'
# SDK imports
SDK = require '../../../app/sdk'
Cards = require '../../../app/sdk/cards/cardsLookupComplete'
CardSetFactory = require '../../../app/sdk/cards/cardSetFactory'
RankFactory = require '../../../app/sdk/rank/rankFactory'
Entity = require '../../../app/sdk/entities/entity'
QuestFactory = require '../../../app/sdk/quests/questFactory'
QuestType = require '../../../app/sdk/quests/questTypeLookup'
GameType = require '../../../app/sdk/gameType'
GameFormat = require '../../../app/sdk/gameFormat'
UtilsGameSession = require '../../../app/common/utils/utils_game_session.coffee'
NewPlayerProgressionHelper = require '../../../app/sdk/progression/newPlayerProgressionHelper'
NewPlayerProgressionStageEnum = require '../../../app/sdk/progression/newPlayerProgressionStageEnum'
NewPlayerProgressionModuleLookup = require '../../../app/sdk/progression/newPlayerProgressionModuleLookup'
{Redis, Jobs} = require '../../redis/'
class UsersModule
###*
# MAX number of daily games to count for play rewards.
# @public
###
@DAILY_REWARD_GAME_CAP: 200
###*
# Hours until FWOTD is available again.
# @public
###
@DAILY_WIN_CYCLE_HOURS: 22
###*
# Retrieve an active and valid global referral code.
# @public
# @param {String} code Referral Code
# @return {Promise} Promise that will return true or throw InvalidReferralCodeError exception .
###
@getValidReferralCode: (code) ->
# validate referral code and force it to lower case
code = code?.toLowerCase().trim()
if not validator.isLength(code,4)
return Promise.reject(new Errors.InvalidReferralCodeError("invalid referral code"))
MOMENT_NOW_UTC = moment().utc()
# we check if the referral code is a UUID so that anyone accidentally using invite codes doesn't error out
if validator.isUUID(code)
return Promise.resolve({})
return knex("referral_codes").where('code',code).first()
.then (referralCodeRow)->
if referralCodeRow? and
referralCodeRow?.is_active and
(!referralCodeRow?.signup_limit? or referralCodeRow?.signup_count < referralCodeRow?.signup_limit) and
(!referralCodeRow?.expires_at? or moment.utc(referralCodeRow?.expires_at).isAfter(MOMENT_NOW_UTC))
return referralCodeRow
else
throw new Errors.InvalidReferralCodeError("referral code not found")
###*
# Check if an invite code is valid.
# @public
# @param {String} inviteCode Invite Code
# @return {Promise} Promise that will return true or throw InvalidInviteCodeError exception .
###
@isValidInviteCode: (inviteCode,cb) ->
inviteCode ?= null
return knex("invite_codes").where('code',inviteCode).first()
.then (codeRow)->
if !config.get("inviteCodesActive") || codeRow? || inviteCode is "kumite14" || inviteCode is "keysign789"
return true
else
throw new Errors.InvalidInviteCodeError("Invalid Invite Code")
###*
# Create a user record for the specified parameters.
# @public
# @param {String} email User's email (no longer strictly required)
# @param {String} username User's username
# @param {String} password User's password
# @param {String} inviteCode Invite code used
# @return {Promise} Promise that will return the userId on completion.
###
@createNewUser: (email = null,username,password,inviteCode = 'kumite14',referralCode,campaignData,registrationSource = null)->
# validate referral code and force it to lower case
referralCode = referralCode?.toLowerCase().trim()
if referralCode? and not validator.isLength(referralCode,3)
return Promise.reject(new Errors.InvalidReferralCodeError("invalid referral code"))
if email then email = email.toLowerCase()
userId = generatePushId()
username = username.toLowerCase()
inviteCode ?= null
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
return knex("invite_codes").where('code',inviteCode).first()
.bind this_obj
.then (inviteCodeRow)->
if config.get("inviteCodesActive") and !inviteCodeRow and inviteCode != "kumite14" and inviteCode != "keysign789"
throw new Errors.InvalidInviteCodeError("Invite code not found")
referralCodePromise = Promise.resolve(null)
# we check if the referral code is a UUID so that anyone accidentally using invite codes doesn't error out
if referralCode? and not validator.isUUID(referralCode)
referralCodePromise = UsersModule.getValidReferralCode(referralCode)
return Promise.all([
UsersModule.userIdForEmail(email),
UsersModule.userIdForUsername(username),
referralCodePromise
])
.spread (idForEmail,idForUsername,referralCodeRow)->
if idForEmail
throw new Errors.AlreadyExistsError("Email already registered")
if idForUsername
throw new Errors.AlreadyExistsError("Username not available")
@.referralCodeRow = referralCodeRow
return hashHelpers.generateHash(password)
.then (passwordHash)->
return knex.transaction (tx) =>
userRecord =
id:userId
email:email # email maybe equals null here
username:username
password:passwordHash
created_at:MOMENT_NOW_UTC.toDate()
if registrationSource
userRecord.registration_source = registrationSource
if config.get("inviteCodesActive")
userRecord.invite_code = inviteCode
# Add campaign data to userRecord
if campaignData?
userRecord.campaign_source ?= campaignData.campaign_source
userRecord.campaign_medium ?= campaignData.campaign_medium
userRecord.campaign_term ?= campaignData.campaign_term
userRecord.campaign_content ?= campaignData.campaign_content
userRecord.campaign_name ?= campaignData.campaign_name
userRecord.referrer ?= campaignData.referrer
updateReferralCodePromise = Promise.resolve()
if @.referralCodeRow?
Logger.module("USERS").debug "createNewUser() -> using referral code #{referralCode.yellow} for user #{userId.blue} ", @.referralCodeRow.params
userRecord.referral_code = referralCode
updateReferralCodePromise = knex("referral_codes").where('code',referralCode).increment('signup_count',1).transacting(tx)
if @.referralCodeRow.params?.gold
userRecord.wallet_gold ?= 0
userRecord.wallet_gold += @.referralCodeRow.params?.gold
if @.referralCodeRow.params?.spirit
userRecord.wallet_spirit ?= 0
userRecord.wallet_spirit += @.referralCodeRow.params?.spirit
Promise.all([
# user record
knex('users').insert(userRecord).transacting(tx),
# update referal code table
updateReferralCodePromise
])
.bind this_obj
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
# collect all the firebase update promises here
allPromises = []
userData = {
id: userId
username: username
created_at: MOMENT_NOW_UTC.valueOf()
presence: {
rank: 30
username: username
status: "offline"
}
tx_counter: {
count:0
}
# all new users have accepted EULA before signing up
hasAcceptedEula: false
hasAcceptedSteamEula: false
}
starting_gold = @.referralCodeRow?.params?.gold || 0
starting_spirit = @.referralCodeRow?.params?.spirit || 0
allPromises.push(FirebasePromises.set(rootRef.child('users').child(userId),userData))
allPromises.push(FirebasePromises.set(rootRef.child('username-index').child(username),userId))
allPromises.push(FirebasePromises.set(rootRef.child('user-inventory').child(userId).child('wallet'),{
gold_amount:starting_gold
spirit_amount:starting_spirit
}))
return Promise.all(allPromises)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
if config.get("inviteCodesActive")
return knex("invite_codes").where('code',inviteCode).delete()
.then ()->
# if email then mail.sendSignupAsync(username, email, verifyToken)
# NOTE: don't send registration notifications at large volume, and also since they contain PID
# mail.sendNotificationAsync("New Registration", "#{email} has registered with #{username}.")
return Promise.resolve(userId)
###*
# Delete a newly created user record in the event of partial registration.
# @public
# @param {String} userId User's ID
# @return {Promise} Promise that will return the userId on completion.
###
@deleteNewUser: (userId) ->
username = null
return @userDataForId(userId)
.then (userRow) ->
if !userRow
throw new Errors.NotFoundError()
username = userRow.username
return knex("users").where('id',userId).delete()
.then () -> return DuelystFirebase.connect().getRootRef()
.then (rootRef) ->
promises = [
FirebasePromises.remove(rootRef.child('users').child(userId)),
FirebasePromises.remove(rootRef.child('user-inventory').child(userId))
]
if username
promises.push(FirebasePromises.remove(rootRef.child('username-index').child(username)))
return Promise.all(promises)
###*
# Change a user's username.
# It will skip gold check if the username has never been set (currently null)
# @public
# @param {String} userId User ID
# @param {String} username New username
# @param {Moment} systemTime Pass in the current system time to override clock. Used mostly for testing.
# @return {Promise} Promise that will return on completion.
###
@changeUsername: (userId,newUsername,forceItForNoGold=false,systemTime)->
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
return UsersModule.userIdForUsername(newUsername)
.bind {}
.then (existingUserId)->
if existingUserId
throw new Errors.AlreadyExistsError("Username already exists")
else
return knex.transaction (tx)->
knex("users").where('id',userId).first('username','username_updated_at','wallet_gold').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
# we should have a user
if !userRow
throw new Errors.NotFoundError()
# let's figure out if we're allowed to change the username and how much it should cost
# if username was null, price stays 0
price = 0
if not forceItForNoGold and userRow.username_updated_at and userRow.username
price = 100
timeSinceLastChange = moment.duration(MOMENT_NOW_UTC.diff(moment.utc(userRow.username_updated_at)))
if timeSinceLastChange.asMonths() < 1.0
throw new Errors.InvalidRequestError("Username can't be changed twice in one month")
@.price = price
@.oldUsername = userRow.username
if price > 0 and userRow.wallet_gold < price
throw new Errors.InsufficientFundsError("Insufficient gold to update username")
allUpdates = []
# if username was null, we skip setting the updated_at flag since it is being set for first time
if !@.oldUsername
userUpdateParams =
username:newUsername
else
userUpdateParams =
username:newUsername
username_updated_at:MOMENT_NOW_UTC.toDate()
if price > 0
userUpdateParams.wallet_gold = userRow.wallet_gold-price
userUpdateParams.wallet_updated_at = MOMENT_NOW_UTC.toDate()
userCurrencyLogItem =
id: generatePushId()
user_id: userId
gold: -price
memo: "username change"
created_at: MOMENT_NOW_UTC.toDate()
allUpdates.push knex("user_currency_log").insert(userCurrencyLogItem).transacting(tx)
allUpdates.push knex("users").where('id',userId).update(userUpdateParams).transacting(tx)
return Promise.all(allUpdates)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
updateWalletData = (walletData)=>
walletData ?= {}
walletData.gold_amount ?= 0
walletData.gold_amount -= @.price
walletData.updated_at = MOMENT_NOW_UTC.valueOf()
return walletData
allPromises = [
FirebasePromises.set(rootRef.child('username-index').child(newUsername),userId)
FirebasePromises.set(rootRef.child('users').child(userId).child('presence').child('username'),newUsername)
]
# if username was null, we skip setting the updated_at flag since it is being set for first time
# and there is no old index to remove
if !@.oldUsername
allPromises.push(FirebasePromises.update(rootRef.child('users').child(userId),{username: newUsername}))
else
allPromises.push(FirebasePromises.remove(rootRef.child('username-index').child(@.oldUsername)))
allPromises.push(FirebasePromises.update(rootRef.child('users').child(userId),{username: newUsername, username_updated_at:MOMENT_NOW_UTC.valueOf()}))
if @.price > 0
allPromises.push FirebasePromises.safeTransaction(rootRef.child("user-inventory").child(userId).child("wallet"),updateWalletData)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
###*
# Change a user's email address.
# @public
# @param {String} userId User ID
# @param {String} newEmail New email
# @param {Moment} systemTime Pass in the current system time to override clock. Used mostly for testing.
# @return {Promise} Promise that will return on completion.
###
@changeEmail: (userId,newEmail,systemTime)->
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
return UsersModule.userIdForEmail(newEmail)
.bind {}
.then (existingUserId)->
if existingUserId
throw new Errors.AlreadyExistsError("Email already exists")
else
return knex.transaction (tx)->
knex("users").where('id',userId).first('email').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
# we should have a user
if !userRow
throw new Errors.NotFoundError()
@.oldEmail = userRow.email
userUpdateParams =
email:newEmail
return knex("users").where('id',userId).update(userUpdateParams).transacting(tx)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
###*
# Mark a user record as having verified email.
# @public
# @param {String} token Verification Token
# @return {Promise} Promise that will return on completion.
###
@verifyEmailUsingToken: (token)->
MOMENT_NOW_UTC = moment().utc()
return knex("email_verify_tokens").first().where('verify_token',token)
.bind {}
.then (tokenRow)->
@.tokenRow = tokenRow
unless tokenRow?.created_at
throw new Errors.NotFoundError()
duration = moment.duration(moment().utc().valueOf() - moment.utc(tokenRow?.created_at).valueOf())
if duration.asDays() < 1
return Promise.all([
knex('users').where('id',tokenRow.user_id).update({ email_verified_at: MOMENT_NOW_UTC.toDate() }) # mark user as verified
knex('email_verify_tokens').where('user_id',tokenRow.user_id).delete() # delete all user's verify tokens
])
else
throw new Errors.NotFoundError()
###*
# Change a user's password.
# @public
# @param {String} userId User ID
# @param {String} oldPassword Old password
# @param {String} newPassword New password
# @return {Promise} Promise that will return on completion.
###
@changePassword: (userId,oldPassword,newPassword)->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx)->
knex("users").where('id',userId).first('password').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
return hashHelpers.comparePassword(oldPassword, userRow.password)
.then (match) ->
if (!match)
throw new Errors.BadPasswordError()
else
return hashHelpers.generateHash(newPassword)
.then (hash) ->
knex("users").where('id',userId).update({
password:hash
password_updated_at:MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Google Play ID to a User
# @public
# @param {String} userId User ID
# @param {String} googlePlayId User's Google Play ID
# @return {Promise} Promise that will return on completion
###
@associateGooglePlayId: (userId, googlePlayId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
google_play_id: googlePlayId
google_play_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Google Play ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateGooglePlayId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
google_play_id: null
google_play_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Gamecenter ID to a user
# @public
# @param {String} userId User ID
# @param {String} gamecenterId User's Gamecenter Id
# @return {Promise} Promise that will return on completion
###
@associateGameCenterId: (userId, gameCenterId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
gamecenter_id: gameCenterId
gamecenter_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Gamecenter ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateGameCenterId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
gamecenter_id: null
gamecenter_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Steam ID to a User
# @public
# @param {String} userId User ID
# @param {String} steamId User's Steam ID as returned from steam.coffee authenticateUserTicket
# @return {Promise} Promise that will return on completion.
###
@associateSteamId: (userId, steamId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
steam_id: steamId
steam_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Steam ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateSteamId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
steam_id: null
steam_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Get user data for id.
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return the user data on completion.
###
@userDataForId: (userId)->
return knex("users").first().where('id',userId)
###*
# Get user data for email.
# @public
# @param {String} email User Email
# @return {Promise} Promise that will return the user data on completion.
###
@userDataForEmail: (email)->
return knex("users").first().where('email',email)
###*
# Intended to be called on login/reload to bump session counter and check transaction counter to update user caches / initiate any hot copies.
# @public
# @param {String} userId User ID
# @param {Object} userData User data if previously loaded
# @return {Promise} Promise that will return synced when done
###
@bumpSessionCountAndSyncDataIfNeeded: (userId,userData=null,systemTime=null)->
MOMENT_NOW_UTC = systemTime || moment().utc()
startPromise = null
if userData
startPromise = Promise.resolve(userData)
else
startPromise = knex("users").where('id',userId).first('id','created_at','session_count','last_session_at','last_session_version')
return startPromise
.then (userData)->
@.userData = userData
if not @.userData?
throw new Errors.NotFoundError("User not found")
# Check if user needs to have emotes migrated to cosmetics inventory
return MigrationsModule.checkIfUserNeedsMigrateEmotes20160708(@.userData)
.then (userNeedsMigrateEmotes) ->
if userNeedsMigrateEmotes
return MigrationsModule.userMigrateEmotes20160708(userId,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then () ->
return MigrationsModule.checkIfUserNeedsPrismaticBackfillReward(@.userData)
.then (userNeedsPrismaticBackfill) ->
if userNeedsPrismaticBackfill
return MigrationsModule.userBackfillPrismaticRewards(userId,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then ()-> # migrate user charge counts for purchase limits
return MigrationsModule.checkIfUserNeedsChargeCountsMigration(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userCreateChargeCountsMigration(userId)
else
return Promise.resolve()
.then ()->
return MigrationsModule.checkIfUserNeedsIncompleteGauntletRefund(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userIncompleteGauntletRefund(userId)
else
return Promise.resolve()
.then ()->
return MigrationsModule.checkIfUserNeedsUnlockableOrbsRefund(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userUnlockableOrbsRefund(userId)
else
return Promise.resolve()
.then () ->
lastSessionTime = moment.utc(@.userData.last_session_at).valueOf() || 0
duration = moment.duration(MOMENT_NOW_UTC.valueOf() - lastSessionTime)
if moment.utc(@.userData.created_at).isBefore(moment.utc("2016-06-18")) and moment.utc(@.userData.last_session_at).isBefore(moment.utc("2016-06-18"))
Logger.module("UsersModule").debug "bumpSessionCountAndSyncDataIfNeeded() -> starting inventory achievements for user - #{userId.blue}."
# Kick off job to update achievements
Jobs.create("update-user-achievements",
name: "Update User Inventory Achievements"
title: util.format("User %s :: Update Inventory Achievements", userId)
userId: userId
inventoryChanged: true
).removeOnComplete(true).save()
if duration.asHours() > 2
return knex("users").where('id',userId).update(
session_count: @.userData.session_count+1
last_session_at: MOMENT_NOW_UTC.toDate()
)
else
return Promise.resolve()
.then ()->
# Update a user's last seen session if needed
if not @.userData.last_session_version? or @.userData.last_session_version != version
return knex("users").where('id',userId).update(
last_session_version: version
)
else
return Promise.resolve()
.then ()->
return SyncModule.syncUserDataIfTrasactionCountMismatched(userId,@.userData)
.then (synced)->
# # Job: Sync user buddy data
# Jobs.create("data-sync-user-buddy-list",
# name: "Sync User Buddy Data"
# title: util.format("User %s :: Sync Buddies", userId)
# userId: userId
# ).removeOnComplete(true).save()
return synced
###*
# Intended to be called on login/reload to fire off a job which tracks cohort data for given user
# @public
# @param {String} userId User ID
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise.resolve() for now since all handling is done in job
###
@createDaysSeenOnJob: (userId,systemTime) ->
MOMENT_NOW_UTC = systemTime || moment().utc()
Jobs.create("update-user-seen-on",
name: "Update User Seen On"
title: util.format("User %s :: Update Seen On", userId)
userId: userId
userSeenOn: MOMENT_NOW_UTC.valueOf()
).removeOnComplete(true).save()
return Promise.resolve()
###*
# Intended to be called on login/reload to fire off a job which tracks cohort data for given user
# @public
# @param {String} userId User ID
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise.resolve() for now since all handling is done in job
###
@createSteamFriendsSyncJob: (userId, friendSteamIds) ->
Jobs.create("data-sync-steam-friends",
name: "Sync Steam Friends"
title: util.format("User %s :: Sync Steam Friends", userId)
userId: userId
friendsSteamIds: friendSteamIds
).removeOnComplete(true).save()
return Promise.resolve()
###*
# Updates the users row if they have newly logged in on a set day
# @public
# @param {String} userId User ID
# @param {Moment} userSeenOn Moment representing the time the user was seen (at point of log in)
# @return {Promise} Promise that completes when user's days seen is updated (if needed)
###
@updateDaysSeen: (userId,userSeenOn) ->
return knex.first('created_at','seen_on_days').from('users').where('id',userId)
.then (userRow) ->
recordedDayIndex = AnalyticsUtil.recordedDayIndexForRegistrationAndSeenOn(moment.utc(userRow.created_at),userSeenOn)
if not recordedDayIndex?
return Promise.resolve()
else
userSeenOnDays = userRow.seen_on_days || []
needsUpdate = false
if not _.contains(userSeenOnDays,recordedDayIndex)
needsUpdate = true
userSeenOnDays.push(recordedDayIndex)
# perform update if needed
if needsUpdate
return knex('users').where({'id':userId}).update({seen_on_days:userSeenOnDays})
else
return Promise.resolve()
###*
# Get the user ID for the specified email.
# @public
# @param {String} email User's email
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForEmail: (email, callback) ->
if !email then return Promise.resolve(null).nodeify(callback)
return knex.first('id').from('users').where('email',email)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified username.
# @public
# @param {String} username User's username (CaSE in-sensitive)
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForUsername: (username, callback) ->
# usernames are ALWAYS lowercase, so when searching downcase by default
username = username?.toLowerCase()
return knex.first('id').from('users').where('username',username)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Steam ID.
# Reference steam.coffee's authenticateUserTicket
# @public
# @param {String} steamId User's Steam ID as returned from steam.coffee authenticateUserTicket
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForSteamId: (steamId, callback) ->
return knex.first('id').from('users').where('steam_id',steamId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Google Play ID.
# @public
# @param {String} googlePlayId User's Google Play ID
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForGooglePlayId: (googlePlayId, callback) ->
return knex.first('id').from('users').where('google_play_id',googlePlayId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Gamecenter ID.
# @public
# @param {String} gameCenterId User's Gamecenter ID
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForGameCenterId: (gameCenterId, callback) ->
return knex.first('id').from('users').where('gamecenter_id',gameCenterId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Validate that a deck is valid and that the user is allowed to play it.
# @public
# @param {String} userId User ID.
# @param {Array} deck Array of card objects with at least card IDs.
# @param {String} gameType game type (see SDK.GameType)
# @param {Boolean} [forceValidation=false] Force validation regardless of ENV. Useful for unit tests.
# @return {Promise} Promise that will resolve if the deck is valid and throw an "InvalidDeckError" otherwise
###
@isAllowedToUseDeck: (userId,deck,gameType, ticketId, forceValidation) ->
# userId must be defined
if !userId || !deck
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid user ID or deck parameter - #{userId.blue}.".red
return Promise.reject(new Errors.InvalidDeckError("invalid user ID or deck - #{userId}"))
# on DEV + STAGING environments, always allow any deck
if !forceValidation and config.get('allCardsAvailable')
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> valid deck because this environment allows all cards ALL_CARDS_AVAILABLE = #{config.get('allCardsAvailable')} - #{userId.blue}.".green
return Promise.resolve(true)
# check for valid general
deckFactionId = null
generalId = deck[0]?.id
if generalId?
generalCard = SDK.GameSession.getCardCaches().getCardById(generalId)
if not generalCard?.isGeneral
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> first card in the deck must be a general - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("First card in the deck must be a general"))
else
deckFactionId = generalCard.factionId
if gameType == GameType.Gauntlet
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> Allowing ANY arena deck for now - #{userId.blue}.".green
return Promise.resolve(true)
else if ticketId? && gameType == GameType.Friendly
# # Validate a friendly rift deck
# return RiftModule.getRiftRunDeck(userId,ticketId)
# .then (riftDeck) ->
# sortedDeckIds = _.sortBy(_.map(deck,(cardObject) -> return cardObject.id),(id) -> return id)
# sortedRiftDeckIds = _.sortBy(riftDeck,(id)-> return id)
# if (sortedDeckIds.length != sortedRiftDeckIds.length)
# return Promise.reject(new Errors.InvalidDeckError("Friendly rift deck has incorrect card count: " + sortedDeckIds.length))
#
# for i in [0...sortedDeckIds.length]
# if sortedDeckIds[i] != sortedRiftDeckIds[i]
# return Promise.reject(new Errors.InvalidDeckError("Friendly rift deck has incorrect cards"))
#
# return Promise.resolve(true)
# Validate a friendly gauntlet deck
decksExpireMoment = moment.utc().subtract(CONFIG.DAYS_BEFORE_GAUNTLET_DECK_EXPIRES,"days")
currentDeckPromise = knex("user_gauntlet_run").first("deck").where("user_id",userId).andWhere("ticket_id",ticketId)
oldDeckPromise = knex("user_gauntlet_run_complete").first("deck","ended_at").where("user_id",userId).andWhere("id",ticketId).andWhere("ended_at",">",decksExpireMoment.toDate())
return Promise.all([currentDeckPromise,oldDeckPromise])
.spread (currentRunRow,completedRunRow) ->
matchingRunRow = null
if (currentRunRow?)
matchingRunRow = currentRunRow
else if (completedRunRow?)
matchingRunRow = completedRunRow
else
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has no matching recent run, ticket_id: " + ticketId))
gauntletDeck = matchingRunRow.deck
sortedDeckIds = _.sortBy(_.map(deck,(cardObject) -> return cardObject.id),(id) -> return id)
sortedGauntletDeckIds = _.sortBy(gauntletDeck,(id)-> return id)
if (sortedDeckIds.length != sortedGauntletDeckIds.length)
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has incorrect card count: " + sortedDeckIds.length))
for i in [0...sortedDeckIds.length]
if sortedDeckIds[i] != sortedGauntletDeckIds[i]
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has incorrect cards"))
return Promise.resolve(true)
else if gameType # allow all other game modes
cardsToValidateAgainstInventory = []
cardSkinsToValidateAgainstInventory = []
basicsOnly = true
for card in deck
cardId = card.id
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if sdkCard.rarityId != SDK.Rarity.Fixed
basicsOnly = false
if sdkCard.factionId != deckFactionId && sdkCard.factionId != SDK.Factions.Neutral
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> found a card with faction #{sdkCard.factionId} that doesn't belong in a #{deckFactionId} faction deck - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Deck has cards from more than one faction"))
if (sdkCard.rarityId != SDK.Rarity.Fixed and sdkCard.rarityId != SDK.Rarity.TokenUnit) || sdkCard.getIsUnlockable()
cardSkinId = SDK.Cards.getCardSkinIdForCardId(cardId)
if cardSkinId?
# add skin to validate against inventory
if !_.contains(cardSkinsToValidateAgainstInventory, cardSkinId)
cardSkinsToValidateAgainstInventory.push(cardSkinId)
# add unskinned card to validate against inventory if needed
unskinnedCardId = SDK.Cards.getNonSkinnedCardId(cardId)
unskinnedSDKCard = SDK.GameSession.getCardCaches().getIsSkinned(false).getCardById(unskinnedCardId)
if unskinnedSDKCard.getRarityId() != SDK.Rarity.Fixed and unskinnedSDKCard.getRarityId() != SDK.Rarity.TokenUnit
cardsToValidateAgainstInventory.push(unskinnedCardId)
else
# add card to validate against inventory
cardsToValidateAgainstInventory.push(card.id)
# starter decks must contain all cards in level 0 faction starter deck
# normal decks must match exact deck size
maxDeckSize = if CONFIG.DECK_SIZE_INCLUDES_GENERAL then CONFIG.MAX_DECK_SIZE else CONFIG.MAX_DECK_SIZE + 1
if basicsOnly
if deck.length < CONFIG.MIN_BASICS_DECK_SIZE
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid starter deck (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Starter decks must have at least #{CONFIG.MIN_BASICS_DECK_SIZE} cards!"))
else if deck.length > maxDeckSize
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid starter deck (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Starter decks must not have more than #{maxDeckSize} cards!"))
else if deck.length != maxDeckSize
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid deck length (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Deck must have #{maxDeckSize} cards"))
# ensure that player has no more than 3 of a base card (normal + prismatic) in deck
cardCountsById = _.countBy(deck, (cardData) ->
return Cards.getBaseCardId(cardData.id)
)
for k,v of cardCountsById
if v > 3
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 3 of a card"))
# Ensure that player doesn't have any cards that are in development, hidden in collection, and only one general
gameSessionCards = _.map(deck, (cardData) ->
cardId = cardData.id
return SDK.GameSession.getCardCaches().getCardById(cardId)
)
generalCount = 0
for gameSessionCard in gameSessionCards
if gameSessionCard instanceof Entity and gameSessionCard.getIsGeneral()
generalCount += 1
if not gameSessionCard.getIsAvailable(null, forceValidation)
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are not yet available - player #{userId.blue}.".red
return Promise.reject(new Errors.NotFoundError("Deck has cards that are not yet available"))
if gameSessionCard.getIsHiddenInCollection()
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are in hidden to collection - player #{userId.blue}.".red
return Promise.reject(new Errors.InvalidDeckError("Deck has cards that are in hidden to collection"))
if (gameSessionCard.getIsLegacy() || CardSetFactory.cardSetForIdentifier(gameSessionCard.getCardSetId()).isLegacy?) and GameType.getGameFormatForGameType(gameType) == GameFormat.Standard
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are in LEGACY format but game mode is STANDARD format"
return Promise.reject(new Errors.InvalidDeckError("Game Mode is STANDARD but deck contains LEGACY card"))
if generalCount != 1
return Promise.reject(new Errors.InvalidDeckError("Deck has " + generalCount + " generals"))
# ensure that player has no more than 1 of a mythron card (normal + prismatic) in deck
mythronCardCountsById = _.countBy(gameSessionCards, (card) ->
if card.getRarityId() == SDK.Rarity.Mythron
return Cards.getBaseCardId(card.getId())
else
return -1
)
for k,v of mythronCardCountsById
if k != '-1' and v > 1
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 1 of a mythron card"))
# ensure that player has no more than 1 trial card total
trialCardCount = _.countBy(gameSessionCards, (card) ->
baseCardId = Cards.getBaseCardId(card.getId())
if baseCardId in [Cards.Faction1.RightfulHeir, Cards.Faction2.DarkHeart, Cards.Faction3.KeeperOfAges, Cards.Faction4.DemonOfEternity, Cards.Faction5.Dinomancer, Cards.Faction6.VanarQuest, Cards.Neutral.Singleton]
return 'trialCard'
else
return -1
)
for k,v of trialCardCount
if k != '-1' and v > 1
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 1 total trial card"))
# setup method to validate cards against user inventory
validateCards = () ->
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> doesUserHaveCards -> #{cardsToValidateAgainstInventory.length} cards to validate - #{userId.blue}.".green
# if we're playing basic cards only, mark deck as valid, and only check against inventory otherwise
if cardsToValidateAgainstInventory.length == 0
return Promise.resolve(true)
else
return InventoryModule.isAllowedToUseCards(Promise.resolve(), knex, userId, cardsToValidateAgainstInventory)
# setup method to validate skins against user inventory
validateSkins = () ->
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> doesUserHaveSkins -> #{cardSkinsToValidateAgainstInventory.length} skins to validate - #{userId.blue}.".green
if cardSkinsToValidateAgainstInventory.length == 0
return Promise.resolve(true)
else
return InventoryModule.isAllowedToUseCosmetics(Promise.resolve(), knex, userId, cardSkinsToValidateAgainstInventory, SDK.CosmeticsTypeLookup.CardSkin)
return Promise.all([
validateCards(),
validateSkins()
])
else
return Promise.reject(new Error("Unknown game type: #{gameType}"))
###*
# Creates a blank faction progression (0 XP) record for a user. This is used to mark a faction as "unlocked".
# @public
# @param {String} userId User ID for which to update.
# @param {String} factionId Faction ID for which to update.
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@createFactionProgressionRecord: (userId,factionId,gameId,gameType,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not createFactionProgressionRecord(): invalid user ID - #{userId}"))
# factionId must be defined
if !factionId
return Promise.reject(new Error("Can not createFactionProgressionRecord(): invalid faction ID - #{factionId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx('users').where('id',userId).first('id').forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).first().forUpdate()
])
.spread (userRow,factionProgressionRow)->
if factionProgressionRow
throw new Errors.AlreadyExistsError()
# faction progression row
factionProgressionRow ?= { user_id:userId, faction_id:factionId }
@.factionProgressionRow = factionProgressionRow
factionProgressionRow.xp ?= 0
factionProgressionRow.game_count ?= 0
factionProgressionRow.unscored_count ?= 0
factionProgressionRow.loss_count ?= 0
factionProgressionRow.win_count ?= 0
factionProgressionRow.draw_count ?= 0
factionProgressionRow.single_player_win_count ?= 0
factionProgressionRow.friendly_win_count ?= 0
factionProgressionRow.xp_earned ?= 0
factionProgressionRow.updated_at = MOMENT_NOW_UTC.toDate()
factionProgressionRow.last_game_id = gameId
factionProgressionRow.level = SDK.FactionProgression.levelForXP(factionProgressionRow.xp)
# reward row
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"faction unlock"
game_id:gameId
unlocked_faction_id:factionId
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
return Promise.all([
tx('user_faction_progression').insert(factionProgressionRow)
tx("user_rewards").insert(rewardData)
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
])
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
delete @.factionProgressionRow.user_id
@.factionProgressionRow.updated_at = moment.utc(@.factionProgressionRow.updated_at).valueOf()
return FirebasePromises.set(rootRef.child('user-faction-progression').child(userId).child(factionId).child('stats'),@.factionProgressionRow)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "createFactionProgressionRecord() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
return txPromise
###*
# Update a user's per-faction progression metrics based on the outcome of a ranked game
# @public
# @param {String} userId User ID for which to update.
# @param {String} factionId Faction ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserFactionProgressionWithGameOutcome: (userId,factionId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserFactionProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# factionId must be defined
if !factionId
return Promise.reject(new Error("Can not updateUserFactionProgressionWithGameOutcome(): invalid faction ID - #{factionId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").first('id','is_bot').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).first().forUpdate()
])
.spread (userRow,factionProgressionRow)->
# Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> ACQUIRED LOCK ON #{userId}".yellow
@userRow = userRow
allPromises = []
needsInsert = _.isUndefined(factionProgressionRow)
factionProgressionRow ?= {user_id:userId,faction_id:factionId}
@.factionProgressionRow = factionProgressionRow
factionProgressionRow.xp ?= 0
factionProgressionRow.game_count ?= 0
factionProgressionRow.unscored_count ?= 0
factionProgressionRow.loss_count ?= 0
factionProgressionRow.win_count ?= 0
factionProgressionRow.draw_count ?= 0
factionProgressionRow.single_player_win_count ?= 0
factionProgressionRow.friendly_win_count ?= 0
factionProgressionRow.level ?= 0
# faction xp progression for single player and friendly games is capped at 10
# levels are indexed from 0 so we check 9 here instead of 10
if (gameType == GameType.SinglePlayer or gameType == GameType.BossBattle or gameType == GameType.Friendly) and factionProgressionRow.level >= 9
throw new Errors.MaxFactionXPForSinglePlayerReachedError()
# grab the default xp earned for a win/loss
# xp_earned = if isWinner then SDK.FactionProgression.winXP else SDK.FactionProgression.lossXP
xp_earned = SDK.FactionProgression.xpEarnedForGameOutcome(isWinner, factionProgressionRow.level)
# if this game should not earn XP for some reason (early concede for example)
if isUnscored then xp_earned = 0
xp = factionProgressionRow.xp
game_count = factionProgressionRow.game_count
win_count = factionProgressionRow.win_count
xp_cap = SDK.FactionProgression.totalXPForLevel(SDK.FactionProgression.maxLevel)
# do not commit transaction if we're at the max level
if (SDK.FactionProgression.levelForXP(xp) >= SDK.FactionProgression.maxLevel)
xp_earned = 0
# make sure user can't earn XP over cap
else if (xp_cap - xp < xp_earned)
xp_earned = xp_cap - xp
factionProgressionRow.xp_earned = xp_earned
factionProgressionRow.updated_at = MOMENT_NOW_UTC.toDate()
factionProgressionRow.last_game_id = gameId
if isUnscored
unscored_count = factionProgressionRow.unscored_count
factionProgressionRow.unscored_count += 1
else
factionProgressionRow.xp = xp + xp_earned
factionProgressionRow.level = SDK.FactionProgression.levelForXP(factionProgressionRow.xp)
factionProgressionRow.game_count += 1
if isDraw
factionProgressionRow.draw_count += 1
else if isWinner
factionProgressionRow.win_count += 1
if gameType == GameType.SinglePlayer or gameType == GameType.BossBattle
factionProgressionRow.single_player_win_count += 1
if gameType == GameType.Friendly
factionProgressionRow.friendly_win_count += 1
else
factionProgressionRow.loss_count += 1
# Logger.module("UsersModule").debug factionProgressionRow
if needsInsert
allPromises.push knex('user_faction_progression').insert(factionProgressionRow).transacting(tx)
else
allPromises.push knex('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).update(factionProgressionRow).transacting(tx)
if !isUnscored and not @.factionProgressionRow.xp_earned > 0
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> F#{factionId} MAX level reached"
# update the user game params
@.updateUserGameParams =
faction_xp: @.factionProgressionRow.xp
faction_xp_earned: 0
allPromises.push knex("user_games").where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
else
level = SDK.FactionProgression.levelForXP(@.factionProgressionRow.xp)
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> At F#{factionId} L:#{level} [#{@.factionProgressionRow.xp}] earned #{@.factionProgressionRow.xp_earned} for G:#{gameId}"
progressData = {
user_id:userId
faction_id:factionId
xp_earned:@.factionProgressionRow.xp_earned
is_winner:isWinner || false
is_draw:isDraw || false
game_id:gameId
created_at:MOMENT_NOW_UTC.toDate()
is_scored:!isUnscored
}
@.updateUserGameParams =
faction_xp: @.factionProgressionRow.xp - @.factionProgressionRow.xp_earned
faction_xp_earned: @.factionProgressionRow.xp_earned
allPromises.push knex("user_faction_progression_events").insert(progressData).transacting(tx)
allPromises.push knex("user_games").where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
return Promise.all(allPromises)
.then ()->
allPromises = []
if (!isUnscored and @.factionProgressionRow) and SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned)
# Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> LEVELED up"
factionName = SDK.FactionFactory.factionForIdentifier(factionId).devName
level = SDK.FactionProgression.levelForXP(@.factionProgressionRow.xp)
rewardData = SDK.FactionProgression.rewardDataForLevel(factionId,level)
@.rewardRows = []
if rewardData?
rewardRowData =
id: generatePushId()
user_id: userId
reward_category: 'faction xp'
reward_type: "#{factionName} L#{level}"
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread:true
@.rewardRows.push(rewardRowData)
rewardData.created_at = MOMENT_NOW_UTC.valueOf()
rewardData.level = level
# update inventory
earnRewardInventoryPromise = null
if rewardData.gold?
rewardRowData.gold = rewardData.gold
# update wallet
earnRewardInventoryPromise = InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,"#{factionName} L#{level}",gameId)
else if rewardData.spirit?
rewardRowData.spirit = rewardData.spirit
# update wallet
earnRewardInventoryPromise = InventoryModule.giveUserSpirit(txPromise,tx,userId,rewardData.spirit,"#{factionName} L#{level}",gameId)
else if rewardData.cards?
cardIds = []
_.each(rewardData.cards,(c)->
_.times c.count, ()->
cardIds.push(c.id)
)
rewardRowData.cards = cardIds
# give cards
earnRewardInventoryPromise = InventoryModule.giveUserCards(txPromise,tx,userId,cardIds,'faction xp',gameId,"#{factionName} L#{level}")
else if rewardData.booster_packs?
rewardRowData.spirit_orbs = rewardData.booster_packs
# TODO: what about more than 1 booster pack?
earnRewardInventoryPromise = InventoryModule.addBoosterPackToUser(txPromise,tx,userId,1,"faction xp","#{factionName} L#{level}",{factionId:factionId,level:level,gameId:gameId})
else if rewardData.emotes?
rewardRowData.cosmetics = []
# update emotes inventory
emotes_promises = []
for emote_id in rewardData.emotes
rewardRowData.cosmetics.push(emote_id)
allPromises.push InventoryModule.giveUserCosmeticId(txPromise, tx, userId, emote_id, "faction xp reward", rewardRowData.id,null, MOMENT_NOW_UTC)
earnRewardInventoryPromise = Promise.all(emotes_promises)
# resolve master promise whan reward is saved and inventory updated
allPromises = allPromises.concat [
knex("user_rewards").insert(rewardRowData).transacting(tx),
earnRewardInventoryPromise,
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardRowData.id)
]
# let's see if we need to add any faction ribbons for this user
winCountForRibbons = @.factionProgressionRow.win_count - (@.factionProgressionRow.single_player_win_count + @.factionProgressionRow.friendly_win_count)
if isWinner and winCountForRibbons > 0 and winCountForRibbons % 100 == 0 and not @.userRow.is_bot
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} earned WIN RIBBON for faction #{factionId}"
ribbonId = "f#{factionId}_champion"
rewardRowData =
id: generatePushId()
user_id: userId
reward_category: 'ribbon'
reward_type: "#{factionName} wins"
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
ribbons:[ribbonId]
is_unread:true
# looks like the user earned a faction ribbon!
ribbon =
user_id:userId
ribbon_id:ribbonId
game_id:gameId
created_at:MOMENT_NOW_UTC.toDate()
@.ribbon = ribbon
allPromises = allPromises.concat [
knex("user_ribbons").insert(ribbon).transacting(tx)
knex("user_rewards").insert(rewardRowData).transacting(tx),
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardRowData.id)
]
return Promise.all(allPromises)
.then ()->
# Update quests if a faction has leveled up
if SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned)
if @.factionProgressionRow #and shouldProcessQuests # TODO: shouldprocessquests? also this may fail for people who already have faction lvl 10 by the time they reach this stage
return QuestsModule.updateQuestProgressWithProgressedFactionData(txPromise,tx,userId,@.factionProgressionRow,MOMENT_NOW_UTC)
# Not performing faction based quest update
return Promise.resolve()
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
delete @.factionProgressionRow.user_id
@.factionProgressionRow.updated_at = moment.utc(@.factionProgressionRow.updated_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child('user-faction-progression').child(userId).child(factionId).child('stats'),@.factionProgressionRow)
for key,val of @.updateUserGameParams
allPromises.push FirebasePromises.set(rootRef.child('user-games').child(userId).child(gameId).child(key),val)
if @.ribbon
ribbonData = _.omit(@.ribbon,["user_id"])
ribbonData = DataAccessHelpers.restifyData(ribbonData)
allPromises.push FirebasePromises.safeTransaction(rootRef.child('user-ribbons').child(userId).child(ribbonData.ribbon_id),(data)->
data ?= {}
data.ribbon_id ?= ribbonData.ribbon_id
data.updated_at = ribbonData.created_at
data.count ?= 0
data.count += 1
return data
)
# if @.rewardRows
# for reward in @.rewardRows
# reward_id = reward.id
# delete reward.user_id
# delete reward.id
# reward.created_at = moment.utc(reward.created_at).valueOf()
# # push rewards to firebase tree
# allPromises.push(FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(reward_id),reward))
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.catch Errors.MaxFactionXPForSinglePlayerReachedError, (e)-> tx.rollback(e)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserFactionProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
# Update achievements if leveled up
if SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned) || @.factionProgressionRow.game_count == 1
Jobs.create("update-user-achievements",
name: "Update User Faction Achievements"
title: util.format("User %s :: Update Faction Achievements", userId)
userId: userId
factionProgressed: true
).removeOnComplete(true).save()
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} (#{@.factionProgressionRow["game_count"]}) faction progression recorded. Unscored: #{isUnscored?.toString().cyan}".green
return @.factionProgressionRow
.catch Errors.MaxFactionXPForSinglePlayerReachedError, (e)->
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} for faction #{factionId} not recorded. MAX LVL 10 for single player games reached."
return null
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'faction_progression')
return txPromise
###*
# Update a user's progression metrics based on the outcome of a ranked game
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw is this game a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserProgressionWithGameOutcome: (userId,opponentId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# userId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid game ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
start_of_day_int = parseInt(moment(MOMENT_NOW_UTC).startOf('day').utc().format("YYYYMMDD"))
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_progression').where('user_id',userId).first().forUpdate()
tx('user_progression_days').where({'user_id':userId,'date':start_of_day_int}).first().forUpdate()
])
.spread (userRow,progressionRow,progressionDayRow)->
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> ACQUIRED LOCK ON #{userId}".yellow
#######
#######
#######
#######
#######
#######
#######
allPromises = []
hasReachedDailyPlayRewardMaxium = false
hasReachedDailyWinRewardMaxium = false
@.hasReachedDailyWinCountBonusLimit = false
canEarnFirstWinOfTheDayReward = true
@.progressionDayRow = progressionDayRow || { user_id:userId, date:start_of_day_int }
@.progressionDayRow.game_count ?= 0
@.progressionDayRow.unscored_count ?= 0
@.progressionDayRow.game_count += 1
# controls for daily maximum of play rewards
if @.progressionDayRow.game_count - @.progressionDayRow.unscored_count > UsersModule.DAILY_REWARD_GAME_CAP
hasReachedDailyPlayRewardMaxium = true
# # controls for daily maximum of play rewards
# if counterData.win_count > UsersModule.DAILY_REWARD_WIN_CAP
# hasReachedDailyWinRewardMaxium = true
if isDraw
@.progressionDayRow.draw_count ?= 0
@.progressionDayRow.draw_count += 1
else if isWinner
# iterate win count
@.progressionDayRow.win_count ?= 0
@.progressionDayRow.win_count += 1
if @.progressionDayRow.win_count > 1
canEarnFirstWinOfTheDayReward = false
# @.hasReachedDailyWinCountBonusLimit is disabled
# if @.progressionDayRow.win_count > 14
# @.hasReachedDailyWinCountBonusLimit = true
else
# iterate loss count
@.progressionDayRow.loss_count ?= 0
@.progressionDayRow.loss_count += 1
# if it's an unscored game, iterate unscored counter
if isUnscored
@.progressionDayRow.unscored_count += 1
if progressionDayRow?
allPromises.push knex('user_progression_days').where({'user_id':userId,'date':start_of_day_int}).update(@.progressionDayRow).transacting(tx)
else
allPromises.push knex('user_progression_days').insert(@.progressionDayRow).transacting(tx)
#######
#######
#######
#######
#######
#######
#######
@.hasEarnedWinReward = false
@.hasEarnedPlayReward = false
@.hasEarnedFirstWinOfTheDayReward = false
@.progressionRow = progressionRow || { user_id:userId }
@.progressionRow.last_opponent_id = opponentId
# record total game count
@.progressionRow.game_count ?= 0
@.progressionRow.unscored_count ?= 0
@.progressionRow.last_game_id = gameId || null
@.progressionRow.updated_at = MOMENT_NOW_UTC.toDate()
# initialize last award records
@.progressionRow.last_awarded_game_count ?= 0
@.progressionRow.last_awarded_win_count ?= 0
last_daily_win_at = @.progressionRow.last_daily_win_at || 0
play_count_reward_progress = 0
win_count_reward_progress = 0
if isUnscored
@.progressionRow.unscored_count += 1
# mark all rewards as false
@.hasEarnedWinReward = false
@.hasEarnedPlayReward = false
@.hasEarnedFirstWinOfTheDayReward = false
else
@.progressionRow.game_count += 1
if not hasReachedDailyPlayRewardMaxium
play_count_reward_progress = @.progressionRow.game_count - @.progressionRow.last_awarded_game_count
if @.progressionRow.game_count > 0 and play_count_reward_progress > 0 and play_count_reward_progress % 4 == 0
@.progressionRow.last_awarded_game_count = @.progressionRow.game_count
@.hasEarnedPlayReward = true
else
@.hasEarnedPlayReward = false
else
@.progressionRow.last_awarded_game_count = @.progressionRow.game_count
@.progressionRow.play_awards_last_maxed_at = MOMENT_NOW_UTC.toDate()
@.hasEarnedPlayReward = false
if isDraw
@.progressionRow.draw_count ?= 0
@.progressionRow.draw_count += 1
else if isWinner
# set loss streak to 0
@.progressionRow.loss_streak = 0
# is this the first win of the day?
hours_since_last_win = MOMENT_NOW_UTC.diff(last_daily_win_at,'hours')
if hours_since_last_win >= UsersModule.DAILY_WIN_CYCLE_HOURS
@.hasEarnedFirstWinOfTheDayReward = true
@.progressionRow.last_daily_win_at = MOMENT_NOW_UTC.toDate()
else
@.hasEarnedFirstWinOfTheDayReward = false
# iterate win count
@.progressionRow.win_count ?= 0
@.progressionRow.win_count += 1
# iterate win streak
if gameType != GameType.Casual
@.progressionRow.win_streak ?= 0
@.progressionRow.win_streak += 1
# mark last win time
@.progressionRow.last_win_at = MOMENT_NOW_UTC.toDate()
if not hasReachedDailyWinRewardMaxium
win_count_reward_progress = @.progressionRow.win_count - @.progressionRow.last_awarded_win_count
# if we've had 3 wins since last award, the user has earned an award
if @.progressionRow.win_count - @.progressionRow.last_awarded_win_count >= CONFIG.WINS_REQUIRED_FOR_WIN_REWARD
@.hasEarnedWinReward = true
@.progressionRow.last_awarded_win_count_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.last_awarded_win_count = @.progressionRow.win_count
else
@.hasEarnedWinReward = false
else
@.progressionRow.last_awarded_win_count_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.win_awards_last_maxed_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.last_awarded_win_count = @.progressionRow.win_count
@.hasEarnedWinReward = false
else
# iterate loss count
@.progressionRow.loss_count ?= 0
@.progressionRow.loss_count += 1
# only iterate loss streak for scored games
# NOTE: control flow should never allow this to be reached for unscored, but adding this just in case someone moves code around :)
if not isUnscored
@.progressionRow.loss_streak ?= 0
@.progressionRow.loss_streak += 1
if gameType != GameType.Casual
# reset win streak
@.progressionRow.win_streak = 0
if progressionRow?
allPromises.push knex('user_progression').where({'user_id':userId}).update(@.progressionRow).transacting(tx)
else
allPromises.push knex('user_progression').insert(@.progressionRow).transacting(tx)
@.updateUserGameParams =
is_daily_win: @.hasEarnedWinReward
play_count_reward_progress: play_count_reward_progress
win_count_reward_progress: win_count_reward_progress
has_maxed_play_count_rewards: hasReachedDailyPlayRewardMaxium
has_maxed_win_count_rewards: hasReachedDailyWinRewardMaxium
allPromises.push knex('user_games').where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
return Promise.all(allPromises)
.then ()->
hasEarnedWinReward = @.hasEarnedWinReward
hasEarnedPlayReward = @.hasEarnedPlayReward
hasEarnedFirstWinOfTheDayReward = @.hasEarnedFirstWinOfTheDayReward
# let's set up
promises = []
@.rewards = []
# if the game is "unscored", assume there are NO rewards
# otherwise, the game counter rewards might fire multiple times since game_count is not updated for unscored games
if not isUnscored
if hasEarnedFirstWinOfTheDayReward
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-WIN-OF-THE-DAY reward at #{@.progressionRow["game_count"]} games!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"daily win"
gold:CONFIG.FIRST_WIN_OF_DAY_GOLD_REWARD
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if hasEarnedPlayReward
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a PLAY-COUNT reward at #{@.progressionRow["game_count"]} games!"
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"play count"
# gold:10
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if @.progressionRow["game_count"] == 3 and not isUnscored
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-3-GAMES reward!"
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"first 3 games"
# gold:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if @.progressionRow["game_count"] == 10 and not isUnscored
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-10-GAMES reward!"
# # set up reward data
# reward = {
# type:"first 10 games"
# gold_amount:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"first 10 games"
# gold:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
if hasEarnedWinReward
gold_amount = CONFIG.WIN_BASED_GOLD_REWARD
# hasReachedDailyWinCountBonusLimit is disabled
if @.hasReachedDailyWinCountBonusLimit
gold_amount = 5
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a #{gold_amount}G WIN-COUNT reward!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"win count"
gold:gold_amount
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
@.codexChapterIdsEarned = SDK.Codex.chapterIdsAwardedForGameCount(@.progressionRow.game_count)
if @.codexChapterIdsEarned && @.codexChapterIdsEarned.length != 0
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned codex chapters #{@.codexChapterIdsEarned} reward!"
for codexChapterIdEarned in @.codexChapterIdsEarned
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"codex"
reward_type:"game count"
codex_chapter:codexChapterIdEarned
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
promises.push(InventoryModule.giveUserCodexChapter(txPromise,tx,userId,codexChapterIdEarned,MOMENT_NOW_UTC))
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
return Promise.all(promises)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
delete @.progressionRow.user_id
delete @.progressionRow.last_opponent_id
if @.progressionRow.last_win_at then @.progressionRow.last_win_at = moment.utc(@.progressionRow.last_win_at).valueOf()
if @.progressionRow.last_daily_win_at then @.progressionRow.last_daily_win_at = moment.utc(@.progressionRow.last_daily_win_at).valueOf()
if @.progressionRow.last_awarded_win_count_at then @.progressionRow.last_awarded_win_count_at = moment.utc(@.progressionRow.last_awarded_win_count_at).valueOf()
if @.progressionRow.play_awards_last_maxed_at then @.progressionRow.play_awards_last_maxed_at = moment.utc(@.progressionRow.play_awards_last_maxed_at).valueOf()
if @.progressionRow.win_awards_last_maxed_at then @.progressionRow.win_awards_last_maxed_at = moment.utc(@.progressionRow.win_awards_last_maxed_at).valueOf()
if @.progressionRow.updated_at then @.progressionRow.updated_at = moment.utc().valueOf(@.progressionRow.updated_at)
allPromises.push FirebasePromises.set(rootRef.child("user-progression").child(userId).child('game-counter'),@.progressionRow)
for key,val of @.updateUserGameParams
allPromises.push FirebasePromises.set(rootRef.child('user-games').child(userId).child(gameId).child(key),val)
# for reward in @.rewards
# rewardId = reward.id
# delete reward.id
# delete reward.user_id
# if reward.created_at then moment.utc().valueOf(reward.created_at)
# allPromises.push FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(rewardId),reward)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()-> Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} G:#{@.progressionRow["game_count"]} W:#{@.progressionRow["win_count"]} L:#{@.progressionRow["loss_count"]} U:#{@.progressionRow["unscored_count"]} progression recorded. Unscored: #{isUnscored?.toString().cyan}".green
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'progression')
return txPromise
###*
# Update a user's boss progression outcome of a boss battle
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw is this game a draw?
# @param {Object} gameSessionData data for the game played
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserBossProgressionWithGameOutcome: (userId,opponentId,isWinner,gameId,gameType,isUnscored,isDraw,gameSessionData,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# userId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid game ID - #{gameId}"))
if !gameType? or gameType != SDK.GameType.BossBattle
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid game game type - #{gameType}"))
if !isWinner
return Promise.resolve(false)
# Oppenent general must be part of the boss faction
opponentPlayerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSessionData,opponentId)
bossId = opponentPlayerSetupData?.generalId
sdkBossData = SDK.GameSession.getCardCaches().getCardById(bossId)
if (not bossId?) or (not sdkBossData?) or (sdkBossData.getFactionId() != SDK.Factions.Boss)
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid boss ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
this_obj.rewards = []
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow) ->
@.userRow = userRow
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
bossEventsRef = @.fbRootRef.child("boss-events")
return FirebasePromises.once(bossEventsRef,'value')
.then (bossEventsSnapshot)->
bossEventsData = bossEventsSnapshot.val()
# data will have
# event-id :
# event_id
# boss_id
# event_start
# event_end
# valid_end (event_end + 30 minute buffer)
@.matchingEventData = null
for eventId,eventData of bossEventsData
if !eventData.boss_id? or parseInt(eventData.boss_id) != bossId
continue
if !eventData.event_start? or eventData.event_start > MOMENT_NOW_UTC.valueOf()
continue
if !eventData.valid_end? or eventData.valid_end < MOMENT_NOW_UTC.valueOf()
continue
# Reaching here means we have a matching event
@.matchingEventData = eventData
@.matchingEventId = eventData.event_id
break
if not @.matchingEventData?
Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> no matching boss event id for user #{userId} in game #{gameId}.".red
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): No matching boss event - #{gameId}"))
.then ()->
return Promise.all([
@.userRow,
tx('user_bosses_defeated').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first()
])
.spread (userRow,userBossDefeatedRow)->
if (userBossDefeatedRow?)
return Promise.resolve()
allPromises = []
# Insert defeated boss row
defeatedBossData =
user_id: userId
boss_id: bossId
game_id: gameId
boss_event_id: @.matchingEventId
defeated_at: MOMENT_NOW_UTC.toDate()
allPromises.push(tx('user_bosses_defeated').insert(defeatedBossData))
Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a BOSS BATTLE reward!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"boss battle"
spirit_orbs:SDK.CardSet.Core
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
allPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# allPromises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
allPromises.push(InventoryModule.addBoosterPackToUser(txPromise,tx,userId,rewardData.spirit_orbs,"boss battle",@.matchingEventId))
allPromises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
return Promise.all(allPromises)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
# Insert defeated boss row
defeatedBossFBData =
boss_id: bossId
boss_event_id: @.matchingEventId
defeated_at: MOMENT_NOW_UTC.valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-bosses-defeated").child(userId).child(bossId),defeatedBossFBData)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserBossProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()-> Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} boss id:#{bossId}".green
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'progression')
return txPromise
###*
# Update a user's game counters
# @public
# @param {String} userId User ID for which to update.
# @param {Number} factionId Faction ID for which to update.
# @param {Number} generalId General ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw was game a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateGameCounters: (userId,factionId,generalId,isWinner,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
MOMENT_SEASON_START_UTC = MOMENT_NOW_UTC.clone().startOf('month')
this_obj = {}
return knex.transaction (tx)->
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_game_counters').where({
'user_id': userId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_faction_counters').where({
'user_id': userId
'faction_id': factionId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_general_counters').where({
'user_id': userId
'general_id': generalId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_season_counters').where({
'user_id': userId
'season_starting_at': MOMENT_SEASON_START_UTC.toDate()
'game_type': gameType
}).first().forUpdate()
])
.spread (userRow,counterRow,factionCounterRow,generalCounterRow,seasonCounterRow)->
allPromises = []
# game type counter
counter = DataAccessHelpers.updateCounterWithGameOutcome(counterRow,isWinner,isDraw,isUnscored)
counter.user_id = userId
counter.game_type = gameType
counter.created_at ?= MOMENT_NOW_UTC.toDate()
counter.updated_at = MOMENT_NOW_UTC.toDate()
if counterRow
allPromises.push knex('user_game_counters').where({
'user_id': userId
'game_type': gameType
}).update(counter).transacting(tx)
else
allPromises.push knex('user_game_counters').insert(counter).transacting(tx)
# faction counter
factionCounter = DataAccessHelpers.updateCounterWithGameOutcome(factionCounterRow,isWinner,isDraw,isUnscored)
factionCounter.user_id = userId
factionCounter.faction_id = factionId
factionCounter.game_type = gameType
factionCounter.created_at ?= MOMENT_NOW_UTC.toDate()
factionCounter.updated_at = MOMENT_NOW_UTC.toDate()
if factionCounterRow
allPromises.push knex('user_game_faction_counters').where({
'user_id': userId
'faction_id': factionId
'game_type': gameType
}).update(factionCounter).transacting(tx)
else
allPromises.push knex('user_game_faction_counters').insert(factionCounter).transacting(tx)
# general counter
generalCounter = DataAccessHelpers.updateCounterWithGameOutcome(generalCounterRow,isWinner,isDraw,isUnscored)
generalCounter.user_id = userId
generalCounter.general_id = generalId
generalCounter.game_type = gameType
generalCounter.created_at ?= MOMENT_NOW_UTC.toDate()
generalCounter.updated_at = MOMENT_NOW_UTC.toDate()
if generalCounterRow
allPromises.push knex('user_game_general_counters').where({
'user_id': userId
'general_id': generalId
'game_type': gameType
}).update(generalCounter).transacting(tx)
else
allPromises.push knex('user_game_general_counters').insert(generalCounter).transacting(tx)
# season counter
seasonCounter = DataAccessHelpers.updateCounterWithGameOutcome(seasonCounterRow,isWinner,isDraw,isUnscored)
seasonCounter.user_id = userId
seasonCounter.game_type = gameType
seasonCounter.season_starting_at ?= MOMENT_SEASON_START_UTC.toDate()
seasonCounter.created_at ?= MOMENT_NOW_UTC.toDate()
seasonCounter.updated_at = MOMENT_NOW_UTC.toDate()
if seasonCounterRow
allPromises.push knex('user_game_season_counters').where({
'user_id': userId
'season_starting_at': MOMENT_SEASON_START_UTC.toDate()
'game_type': gameType
}).update(seasonCounter).transacting(tx)
else
allPromises.push knex('user_game_season_counters').insert(seasonCounter).transacting(tx)
@.counter = counter
@.factionCounter = factionCounter
@.generalCounter = generalCounter
@.seasonCounter = seasonCounter
return Promise.all(allPromises)
# .then ()-> return DuelystFirebase.connect().getRootRef()
# .then (rootRef)->
# allPromises = []
# firebaseCounterData = DataAccessHelpers.restifyData _.clone(@.counter)
# delete firebaseCounterData.user_id
# delete firebaseCounterData.game_type
# firebaseFactionCounterData = DataAccessHelpers.restifyData _.clone(@.factionCounter)
# delete firebaseFactionCounterData.user_id
# delete firebaseFactionCounterData.faction_id
# delete firebaseFactionCounterData.game_type
# allPromises.push FirebasePromises.update(rootRef.child('user-game-counters').child(userId).child(gameType).child('stats'),firebaseCounterData)
# allPromises.push FirebasePromises.update(rootRef.child('user-game-counters').child(userId).child(gameType).child('factions').child(factionId),firebaseFactionCounterData)
# return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateGameCounters() -> ERROR, operation timeout for u:#{userId}"
throw e
.bind this_obj
.then ()->
Logger.module("UsersModule").debug "updateGameCounters() -> updated #{gameType} game counters for #{userId.blue}"
return {
counter:@.counter
faction_counter:@.factionCounter
general_counter:@.generalCounter
season_counter:@.seasonCounter
}
###*
# Update user's stats given a game.
# @public
# @param {String} userId User ID for which to process quests.
# @param {String} gameId Game ID for which to calculate stat changes
# @param {String} gameType Game type (see SDK.GameType)
# @param {String} gameData Plain object with game data
# @return {Promise} Promise that will post STATDATA on completion.
###
@updateUserStatsWithGame: (userId,gameId,gameType,gameData,systemTime) ->
# userId must be defined
if !userId or !gameId
return Promise.reject(new Error("Can not update user-stats : invalid user ID - #{userId} - or game ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
# Begin the promise rabbit hole
return DuelystFirebase.connect().getRootRef()
.bind {}
.then (fbRootRef) ->
@fbRootRef = fbRootRef
statsRef = @fbRootRef.child("user-stats").child(userId)
return new Promise (resolve, reject) ->
statsRef.once("value", (statsSnapshot) ->
return resolve(statsSnapshot.val())
)
.then (statsData) ->
try
playerData = UtilsGameSession.getPlayerDataForId(gameData,userId)
playerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameData,userId)
isWinner = playerData.isWinner
statsRef = @fbRootRef.child("user-stats").child(userId)
if !statsData
statsData = {}
# TODO: Temp until we have queue type defined in an architecture
queueName = gameType
if !statsData[queueName]
statsData[queueName] = {}
queueStatsData = statsData[queueName]
# -- First per queue stats
# Update player's global win streak
queueStatsData.winStreak ?= 0
if gameType != GameType.Casual
if isWinner
queueStatsData.winStreak += 1
else
queueStatsData.winStreak = 0
# -- Then per faction data
factionId = playerSetupData.factionId
if !queueStatsData[factionId]
queueStatsData[factionId] = {}
factionStatsData = queueStatsData[factionId]
factionStatsData.factionId = factionId
# Update per faction win count and play count
factionStatsData.playCount = (factionStatsData.playCount or 0) + 1
if (isWinner)
factionStatsData.winCount = (factionStatsData.winCount or 0) + 1
# Update cards played counts
if !factionStatsData.cardsPlayedCounts
factionStatsData.cardsPlayedCounts = {}
cardIndices = Object.keys(gameData.cardsByIndex)
for cardIndex in cardIndices
card = gameData.cardsByIndex[cardIndex]
if card.ownerId == userId
factionStatsData.cardsPlayedCounts[card.id] = (factionStatsData.cardsPlayedCounts[card.id] or 0) + 1
# Update discarded card counts
if !factionStatsData.cardsDiscardedCounts
factionStatsData.cardsDiscardedCounts = {}
# Update total turns played (this represents turns played by opponents as well)
totalTurns = 1 # for currentTurn
if gameData.turns
totalTurns += gameData.turns.length
factionStatsData.totalTurnsPlayed = (factionStatsData.totalTurnsPlayed or 0) + totalTurns
# Update play total stats
factionStatsData.totalDamageDealt = (factionStatsData.totalDamageDealt or 0) + playerData.totalDamageDealt
factionStatsData.totalDamageDealtToGeneral = (factionStatsData.totalDamageDealtToGeneral or 0) + playerData.totalDamageDealtToGeneral
factionStatsData.totalMinionsKilled = (factionStatsData.totalMinionsKilled or 0) + playerData.totalMinionsKilled
factionStatsData.totalMinionsPlayedFromHand = (factionStatsData.totalMinionsPlayedFromHand or 0) + playerData.totalMinionsPlayedFromHand
factionStatsData.totalMinionsSpawned = (factionStatsData.totalMinionsSpawned or 0) + playerData.totalMinionsSpawned
factionStatsData.totalSpellsCast = (factionStatsData.totalSpellsCast or 0) + playerData.totalSpellsCast
factionStatsData.totalSpellsPlayedFromHand = (factionStatsData.totalSpellsPlayedFromHand or 0) + playerData.totalSpellsPlayedFromHand
catch e
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> caught ERROR processing stats data for user #{userId}: #{e.message}".red
throw new Error("ERROR PROCESSING STATS DATA")
# Perform firebase transaction to update stats
return new Promise (resolve, reject) ->
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> UPDATING stats for user #{userId}"
# function to update quest list
onUpdateUserStatsTransaction = (userStatsTransactionData)->
# Don't care what the previous stats were, replace them with the updated version
userStatsTransactionData = statsData
userStatsTransactionData.updated_at = MOMENT_NOW_UTC.valueOf()
return userStatsTransactionData
# function to call when the quest update is complete
onUpdateUserStatsTransactionComplete = (error,committed,snapshot) ->
if error
return reject(error)
else if committed
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> updated user-stats committed for #{userId.blue}"
return resolve(snapshot.val())
else
return reject(new Errors.FirebaseTransactionDidNotCommitError("User Stats for #{userId.blue} did NOT COMMIT"))
# update users stats
statsRef.transaction(onUpdateUserStatsTransaction,onUpdateUserStatsTransactionComplete)
###*
# Completes a challenge for a user and unlocks any rewards !if! it's not already completed
# @public
# @param {String} userId User ID.
# @param {String} challenge_type type of challenge completed
# @param {Boolean} shouldProcessQuests should we attempt to process quests as a result of this challenge completion (since beginner quests include a challenge quest)
# @return {Promise} Promise that will resolve and give rewards if challenge hasn't been completed before, will resolve false and not give rewards if it has
###
@completeChallengeWithType: (userId,challengeType,shouldProcessQuests) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "completeChallengeWithType() -> user #{userId.blue} completed challenge type #{challengeType}."
knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).first()
.bind this_obj
.then (challengeRow)->
if challengeRow and challengeRow.completed_at
Logger.module("UsersModule").debug "completeChallengeWithType() -> user #{userId.blue} has already completed challenge type #{challengeType}."
return Promise.resolve(false)
else
txPromise = knex.transaction (tx)->
# lock user record while updating data
knex("users").where({'id':userId}).first('id').forUpdate().transacting(tx)
.bind this_obj
.then ()->
# give the user their rewards
goldReward = SDK.ChallengeFactory.getGoldRewardedForChallengeType(challengeType)
cardRewards = SDK.ChallengeFactory.getCardIdsRewardedForChallengeType(challengeType)
spiritReward = SDK.ChallengeFactory.getSpiritRewardedForChallengeType(challengeType)
boosterPackRewards = SDK.ChallengeFactory.getBoosterPacksRewardedForChallengeType(challengeType)
factionUnlockedReward = SDK.ChallengeFactory.getFactionUnlockedRewardedForChallengeType(challengeType)
@.rewards = []
@.challengeRow =
user_id:userId
challenge_id:challengeType
completed_at:MOMENT_NOW_UTC.toDate()
last_attempted_at: challengeRow?.last_attempted_at || MOMENT_NOW_UTC.toDate()
reward_ids:[]
is_unread:true
rewardPromises = []
if goldReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
gold:goldReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserGold(txPromise,tx,userId,goldReward,'challenge',challengeType))
if cardRewards
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
cards:cardRewards
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserCards(txPromise,tx,userId,cardRewards,'challenge'))
if spiritReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
spirit:spiritReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserSpirit(txPromise,tx,userId,spiritReward,'challenge'))
if boosterPackRewards
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
spirit_orbs:boosterPackRewards.length
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
_.each boosterPackRewards, (boosterPackData) ->
# Bound to array of reward promises
rewardPromises.push(InventoryModule.addBoosterPackToUser(txPromise,tx,userId,1,"soft",boosterPackData))
if factionUnlockedReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
unlocked_faction_id:factionUnlockedReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
@.challengeRow.reward_ids = _.map(@.rewards, (r)-> return r.id)
if challengeRow
rewardPromises.push knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(@.challengeRow).transacting(tx)
else
rewardPromises.push knex("user_challenges").insert(@.challengeRow).transacting(tx)
Promise.all(rewardPromises)
.then ()->
if @.challengeRow and shouldProcessQuests
return QuestsModule.updateQuestProgressWithCompletedChallenge(txPromise,tx,userId,challengeType,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then (questProgressResponse)->
if @.challengeRow and questProgressResponse?.rewards?.length > 0
Logger.module("UsersModule").debug "completeChallengeWithType() -> user #{userId.blue} completed challenge quest rewards count: #{ questProgressResponse?.rewards.length}"
for reward in questProgressResponse.rewards
@.rewards.push(reward)
@.challengeRow.reward_ids.push(reward.id)
return knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(
reward_ids:@.challengeRow.reward_ids
).transacting(tx)
.then ()->
return Promise.all([
DuelystFirebase.connect().getRootRef(),
@.challengeRow,
@.rewards
])
.spread (rootRef,challengeRow,rewards)->
allPromises = []
if challengeRow?
delete challengeRow.user_id
# delete challengeRow.challenge_id
if challengeRow.last_attempted_at then challengeRow.last_attempted_at = moment.utc(challengeRow.last_attempted_at).valueOf()
if challengeRow.completed_at then challengeRow.completed_at = moment.utc(challengeRow.completed_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-challenge-progression").child(userId).child(challengeType),challengeRow)
@.challengeRow = challengeRow
# if rewards?
# for reward in rewards
# reward_id = reward.id
# delete reward.id
# delete reward.user_id
# reward.created_at = moment.utc(reward.created_at).valueOf()
# allPromises.push FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(reward_id),reward)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
return txPromise
.then ()->
Logger.module("UsersModule").timeEnd "completeChallengeWithType() -> user #{userId.blue} completed challenge type #{challengeType}."
responseData = null
if @.challengeRow
responseData = { challenge: @.challengeRow }
if @.rewards
responseData.rewards = @.rewards
return responseData
###*
# Marks a challenge as attempted.
# @public
# @param {String} userId User ID.
# @param {String} challenge_type type of challenge
# @return {Promise} Promise that will resolve on completion
###
@markChallengeAsAttempted: (userId,challengeType) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "markChallengeAsAttempted() -> user #{userId.blue} attempted challenge type #{challengeType}."
txPromise = knex.transaction (tx)->
# lock user and challenge row
Promise.all([
knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).first().forUpdate().transacting(tx)
knex("users").where({'id':userId}).first('id').forUpdate().transacting(tx)
])
.bind this_obj
.spread (challengeRow)->
@.challengeRow = challengeRow
if @.challengeRow?
@.challengeRow.last_attempted_at = MOMENT_NOW_UTC.toDate()
return knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(@.challengeRow).transacting(tx)
else
@.challengeRow =
user_id:userId
challenge_id:challengeType
last_attempted_at:MOMENT_NOW_UTC.toDate()
return knex("user_challenges").insert(@.challengeRow).transacting(tx)
.then ()-> DuelystFirebase.connect().getRootRef()
.then (rootRef)->
allPromises = []
if @.challengeRow?
delete @.challengeRow.user_id
# delete @.challengeRow.challenge_id
if @.challengeRow.last_attempted_at then @.challengeRow.last_attempted_at = moment.utc(@.challengeRow.last_attempted_at).valueOf()
if @.challengeRow.completed_at then @.challengeRow.completed_at = moment.utc(@.challengeRow.completed_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-challenge-progression").child(userId).child(challengeType),@.challengeRow)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
responseData = { challenge: @.challengeRow }
return responseData
return txPromise
###*
# Iterate core new player progression up by one point if all requirements met, or generate missing quests if any required quests are missing from current/complete quest list for this user.
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@iterateNewPlayerCoreProgression: (userId) ->
knex("user_new_player_progression").where('user_id',userId).andWhere('module_name',NewPlayerProgressionModuleLookup.Core).first()
.bind {}
.then (moduleProgression)->
stage = NewPlayerProgressionStageEnum[moduleProgression?.stage] || NewPlayerProgressionStageEnum.Tutorial
# if we're at the final stage, just return
if stage.value >= NewPlayerProgressionHelper.FinalStage.value
return Promise.resolve()
Promise.all([
knex("user_quests").where('user_id',userId).select()
knex("user_quests_complete").where('user_id',userId).select()
])
.bind @
.spread (quests,questsComplete)->
beginnerQuests = NewPlayerProgressionHelper.questsForStage(stage)
# exclude non-required beginner quests for this tage
beginnerQuests = _.filter beginnerQuests, (q)-> return q.isRequired
# if we have active quests, check that none are beginner for current stage
if quests?.length > 0
# let's see if any beginner quests for this stage are still in progress
beginnerQuestInProgress = _.find(quests,(q)->
return _.find(beginnerQuests,(bq)-> bq.id == q.quest_type_id)
)
# if any beginner quests for this stage are still in progress, DO NOTHING
if beginnerQuestInProgress
return Promise.resolve()
# let's see if all beginner quests for this stage are completed
beginnerQuestsComplete = _.filter(questsComplete,(q)->
return _.find(beginnerQuests,(bq)-> bq.id == q.quest_type_id)
)
# if any beginner quests for this stage have NOT been completed, we have a problem... looks like we need to generate these quests
if beginnerQuestsComplete?.length < beginnerQuests.length
# throw new Error("Invalid state: user never received all required stage quests")
Logger.module('SDK').warn "iterateNewPlayerCoreProgression() -> Invalid state: user #{userId.blue} never received all required stage #{stage.key} quests"
return QuestsModule.generateBeginnerQuests(userId)
.bind {}
.then (questData)->
if questData
@.questData = questData
.catch Errors.NoNeedForNewBeginnerQuestsError, (e)->
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> no need for new quests at #{nextStage.key} for #{userId.blue}"
.then ()->
@.progressionData = moduleProgression
return @
# if we're here, it means all required beginner quests have been completed up to here...
# so let's push the core stage forward
# calculate the next linear stage point for core progression
nextStage = null
for s in NewPlayerProgressionStageEnum.enums
if s.value > stage.value
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> from stage #{stage.key} to next stage #{s.key} for #{userId.blue}"
nextStage = s
break
# update current stage and generate any new beginner quests
return UsersModule.setNewPlayerFeatureProgression(userId,NewPlayerProgressionModuleLookup.Core,nextStage.key)
.bind {}
.then (progressionData) ->
@.progressionData = progressionData
return QuestsModule.generateBeginnerQuests(userId)
.then (questData)->
if questData
@.questData = questData
.catch Errors.NoNeedForNewBeginnerQuestsError, (e)->
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> no need for new quests at #{nextStage.key} for #{userId.blue}"
.then ()->
return @
.then (responseData)->
return responseData
###*
# Sets user feature progression for a module
# @public
# @param {String} userId User ID.
# @param {String} moduleName Arbitrary name of a module
# @param {String} stage Arbitrary key for a progression item
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@setNewPlayerFeatureProgression: (userId,moduleName,stage) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setNewPlayerFeatureProgression() -> user #{userId.blue} marking module #{moduleName} as #{stage}."
if moduleName == NewPlayerProgressionModuleLookup.Core and not NewPlayerProgressionStageEnum[stage]?
return Promise.reject(new Errors.BadRequestError("Invalid core new player stage"))
txPromise = knex.transaction (tx)->
tx("user_new_player_progression").where({'user_id':userId,'module_name':moduleName}).first().forUpdate()
.bind this_obj
.then (progressionRow)->
# core stage has some special rules
if moduleName == NewPlayerProgressionModuleLookup.Core
currentStage = progressionRow?.stage || NewPlayerProgressionStageEnum.Tutorial
if NewPlayerProgressionStageEnum[stage].value < currentStage.value
throw new Errors.BadRequestError("Can not roll back to a previous core new player stage")
@.progressionRow = progressionRow
queryPromise = null
if progressionRow and progressionRow.stage == stage
Logger.module("UsersModule").error "setNewPlayerFeatureProgression() -> ERROR: requested same stage: #{stage}."
throw new Errors.BadRequestError("New player progression stage already at the requested stage")
else if progressionRow
# TODO: this never gets called, here 2 gets called twice for tutorial -> tutorialdone
@.progressionRow.stage = stage
@.progressionRow.updated_at = MOMENT_NOW_UTC.toDate()
queryPromise = tx("user_new_player_progression").where({'user_id':userId,'module_name':moduleName}).update({
stage: @.progressionRow.stage,
updated_at: @.progressionRow.updated_at
})
else
@.progressionRow =
user_id:userId
module_name:moduleName
stage:stage
queryPromise = tx("user_new_player_progression").insert(@.progressionRow)
return queryPromise
.then (updateCount)->
if updateCount
SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setNewPlayerFeatureProgression() -> user #{userId.blue} marking module #{moduleName} as #{stage}."
return @.progressionRow
return txPromise
###*
# Set a new portrait for a user
# @public
# @param {String} userId User ID.
# @param {String} portraitId Portrait ID
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@setPortraitId: (userId,portraitId) ->
# userId must be defined
if !userId?
return Promise.reject(new Errors.NotFoundError("Can not setPortraitId(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setPortraitId() -> user #{userId.blue}."
txPromise = knex.transaction (tx)->
InventoryModule.isAllowedToUseCosmetic(txPromise, tx, userId, portraitId)
.bind this_obj
.then ()->
return knex("users").where({'id':userId}).update(
portrait_id:portraitId
)
.then (updateCount)->
if updateCount == 0
throw new Errors.NotFoundError("User with id #{userId} not found")
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.set(rootRef.child('users').child(userId).child('presence').child('portrait_id'),portraitId)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setPortraitId() -> user #{userId.blue}."
return portraitId
###*
# Set a the preferred Battle Map for a user
# @public
# @param {String} userId User ID.
# @param {String} battleMapId Battle Map ID
# @return {Promise} Promise that will resolve when complete
###
@setBattleMapId: (userId,battleMapId) ->
# userId must be defined
if !userId?
return Promise.reject(new Errors.NotFoundError("Can not setPortraitId(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setBattleMapId() -> user #{userId.blue}."
txPromise = knex.transaction (tx)->
checkForInventoryPromise = if battleMapId != null then InventoryModule.isAllowedToUseCosmetic(txPromise, tx, userId, battleMapId) else Promise.resolve(true)
checkForInventoryPromise
.bind this_obj
.then ()->
return tx("users").where({'id':userId}).update(
battle_map_id:battleMapId
)
.then (updateCount)->
if updateCount == 0
throw new Errors.NotFoundError("User with id #{userId} not found")
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.set(rootRef.child('users').child(userId).child('battle_map_id'),battleMapId)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setBattleMapId() -> user #{userId.blue}."
return battleMapId
###*
# Add a small in-game notification for a user
# @public
# @param {String} userId User ID.
# @param {String} message What message to show
# @param {String} type Message type
# @return {Promise} Promise that will resolve when complete
###
@inGameNotify: (userId,message,type=null) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
return Promise.resolve()
.bind {}
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.push(rootRef.child("user-notifications").child(userId),{message:message,created_at:moment().utc().valueOf(),type:type})
@___hardWipeUserData: (userId)->
Logger.module("UsersModule").time "___hardWipeUserData() -> WARNING: hard wiping #{userId.blue}".red
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef)->
return Promise.all([
FirebasePromises.remove(fbRootRef.child('user-aggregates').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-arena-run').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-challenge-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-decks').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-faction-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-games').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-games').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-game-job-status').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-inventory').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-logs').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-matchmaking-errors').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-news').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-quests').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-ranking').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-rewards').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-stats').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-transactions').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-achievements').child(userId)),
knex("user_cards").where('user_id',userId).delete(),
knex("user_card_collection").where('user_id',userId).delete(),
knex("user_card_log").where('user_id',userId).delete(),
knex("user_challenges").where('user_id',userId).delete(),
knex("user_charges").where('user_id',userId).delete(),
knex("user_currency_log").where('user_id',userId).delete(),
knex("user_decks").where('user_id',userId).delete(),
knex("user_faction_progression").where('user_id',userId).delete(),
knex("user_faction_progression_events").where('user_id',userId).delete(),
knex("user_games").where('user_id',userId).delete(),
knex("user_gauntlet_run").where('user_id',userId).delete(),
knex("user_gauntlet_run_complete").where('user_id',userId).delete(),
knex("user_gauntlet_tickets").where('user_id',userId).delete(),
knex("user_gauntlet_tickets_used").where('user_id',userId).delete(),
knex("user_progression").where('user_id',userId).delete(),
knex("user_progression_days").where('user_id',userId).delete(),
knex("user_quests").where('user_id',userId).delete(),
knex("user_quests_complete").where('user_id',userId).delete(),
knex("user_rank_events").where('user_id',userId).delete(),
knex("user_rank_history").where('user_id',userId).delete(),
knex("user_rewards").where('user_id',userId).delete(),
knex("user_spirit_orbs").where('user_id',userId).delete(),
knex("user_spirit_orbs_opened").where('user_id',userId).delete(),
knex("user_codex_inventory").where('user_id',userId).delete(),
knex("user_new_player_progression").where('user_id',userId).delete(),
knex("user_achievements").where('user_id',userId).delete(),
knex("users").where('id',userId).update({
ltv:0,
rank:30,
rank_created_at:null,
rank_starting_at:null,
rank_stars:0,
rank_stars_required:1,
rank_updated_at:null,
rank_win_streak:0,
rank_top_rank:null,
rank_is_unread:false,
top_rank:null,
top_rank_starting_at:null,
top_rank_updated_at:null,
wallet_gold:0,
wallet_spirit:0,
wallet_cores:0,
wallet_updated_at:null,
total_gold_earned:0,
total_spirit_earned:0,
daily_quests_generated_at:null,
daily_quests_updated_at:null
})
])
.then ()->
Logger.module("UsersModule").timeEnd "___hardWipeUserData() -> WARNING: hard wiping #{userId.blue}".red
###*
# Sets user feature progression for a module
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@___snapshotUserData: (userId)->
Logger.module("UsersModule").time "___snapshotUserData() -> retrieving data for user ID #{userId.blue}".green
# List of the columns we want to grab from the users table, is everything except password
userTableColumns = ["id","created_at","updated_at","last_session_at","session_count","username_updated_at",
"email_verified_at","password_updated_at","invite_code","ltv","purchase_count","last_purchase_at","rank",
"rank_created_at","rank_starting_at","rank_stars","rank_stars_required","rank_delta","rank_top_rank",
"rank_updated_at","rank_win_streak","rank_is_unread","top_rank","top_rank_starting_at","top_rank_updated_at",
"daily_quests_generated_at","daily_quests_updated_at","achievements_last_read_at","wallet_gold",
"wallet_spirit","wallet_cores","wallet_updated_at","total_gold_earned","total_spirit_earned","buddy_count",
"tx_count","synced_firebase_at","stripe_customer_id","card_last_four_digits","card_updated_at",
"top_gauntlet_win_count","portrait_id","total_gold_tips_given","referral_code","is_suspended","suspended_at",
"suspended_memo","top_rank_ladder_position","top_rank_rating","is_bot"];
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef)->
return Promise.all([
FirebasePromises.once(fbRootRef.child('user-aggregates').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-arena-run').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-challenge-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-decks').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-faction-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-games').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-game-job-status').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-inventory').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-logs').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-matchmaking-errors').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-news').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-quests').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-ranking').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-rewards').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-stats').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-transactions').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-achievements').child(userId),"value"),
knex("user_cards").where('user_id',userId).select(),
knex("user_card_collection").where('user_id',userId).select(),
knex("user_card_log").where('user_id',userId).select(),
knex("user_challenges").where('user_id',userId).select(),
knex("user_charges").where('user_id',userId).select(),
knex("user_currency_log").where('user_id',userId).select(),
knex("user_decks").where('user_id',userId).select(),
knex("user_faction_progression").where('user_id',userId).select(),
knex("user_faction_progression_events").where('user_id',userId).select(),
knex("user_games").where('user_id',userId).select(),
knex("user_gauntlet_run").where('user_id',userId).select(),
knex("user_gauntlet_run_complete").where('user_id',userId).select(),
knex("user_gauntlet_tickets").where('user_id',userId).select(),
knex("user_gauntlet_tickets_used").where('user_id',userId).select(),
knex("user_progression").where('user_id',userId).select(),
knex("user_progression_days").where('user_id',userId).select(),
knex("user_quests").where('user_id',userId).select(),
knex("user_quests_complete").where('user_id',userId).select(),
knex("user_rank_events").where('user_id',userId).select(),
knex("user_rank_history").where('user_id',userId).select(),
knex("user_rewards").where('user_id',userId).select(),
knex("user_spirit_orbs").where('user_id',userId).select(),
knex("user_spirit_orbs_opened").where('user_id',userId).select(),
knex("user_codex_inventory").where('user_id',userId).select(),
knex("user_new_player_progression").where('user_id',userId).select(),
knex("user_achievements").where('user_id',userId).select(),
knex("user_cosmetic_chests").where('user_id',userId).select(),
knex("user_cosmetic_chests_opened").where('user_id',userId).select(),
knex("user_cosmetic_chest_keys").where('user_id',userId).select(),
knex("user_cosmetic_chest_keys_used").where('user_id',userId).select(),
knex("users").where('id',userId).first(userTableColumns)
])
.spread (fbUserAggregates,fbUserArenaRun,fbUserChallengeProgression,fbUserDecks,fbUserFactionProgression,fbUserGames,fbUserGameJobStatus,fbUserInventory,fbUserLogs,
fbUserMatchmakingErrors,fbUserNews,fbUserProgression,fbUserQuests,fbUserRanking,fbUserRewards,fbUserStats,fbUserTransactions,fbUserAchievements,
sqlUserCards,sqlUserCardCollection,sqlUserCardLog,sqlUserChallenges,sqlUserCharges,sqlUserCurrencyLog,sqlUserDecks,sqlUserFactionProgression,sqlUserFactionProgressionEvents,
sqlUserGames,sqlUserGauntletRun,sqlUserGauntletRunComplete,sqlUserGauntletTickets,sqlUserGauntletTicketsUsed,sqlUserProgression,
sqlUserProgressionDays,sqlUserQuests,sqlUserQuestsComplete,sqlUserRankEvents,sqlUserRankHistory,sqlUserRewards,sqlUserSpiritOrbs,sqlUserSpiritOrbsOpened,
sqlUserCodexInventory,sqlUserNewPlayerProgression,sqlUserAchievements,sqlUserChestRows,sqlUserChestOpenedRows,sqlUserChestKeyRows,sqlUserChestKeyUsedRows,sqlUserRow)->
userSnapshot = {
firebase: {}
sql: {}
}
userSnapshot.firebase.fbUserAggregates = fbUserAggregates?.val()
userSnapshot.firebase.fbUserArenaRun = fbUserArenaRun?.val()
userSnapshot.firebase.fbUserChallengeProgression = fbUserChallengeProgression?.val()
userSnapshot.firebase.fbUserDecks = fbUserDecks?.val()
userSnapshot.firebase.fbUserFactionProgression = fbUserFactionProgression?.val()
userSnapshot.firebase.fbUserGames = fbUserGames?.val()
userSnapshot.firebase.fbUserGameJobStatus = fbUserGameJobStatus?.val()
userSnapshot.firebase.fbUserInventory = fbUserInventory?.val()
userSnapshot.firebase.fbUserLogs = fbUserLogs?.val()
userSnapshot.firebase.fbUserMatchmakingErrors = fbUserMatchmakingErrors?.val()
userSnapshot.firebase.fbUserNews = fbUserNews?.val()
userSnapshot.firebase.fbUserProgression = fbUserProgression?.val()
userSnapshot.firebase.fbUserQuests = fbUserQuests?.val()
userSnapshot.firebase.fbUserRanking = fbUserRanking?.val()
userSnapshot.firebase.fbUserRewards = fbUserRewards?.val()
userSnapshot.firebase.fbUserStats = fbUserStats?.val()
userSnapshot.firebase.fbUserTransactions = fbUserTransactions?.val()
userSnapshot.firebase.fbUserAchievements = fbUserAchievements?.val()
userSnapshot.sql.sqlUserCards = sqlUserCards
userSnapshot.sql.sqlUserCardCollection = sqlUserCardCollection
userSnapshot.sql.sqlUserCardLog = sqlUserCardLog
userSnapshot.sql.sqlUserChallenges = sqlUserChallenges
userSnapshot.sql.sqlUserCharges = sqlUserCharges
userSnapshot.sql.sqlUserCurrencyLog = sqlUserCurrencyLog
userSnapshot.sql.sqlUserFactionProgression = sqlUserFactionProgression
userSnapshot.sql.sqlUserFactionProgressionEvents = sqlUserFactionProgressionEvents
userSnapshot.sql.sqlUserGames = sqlUserGames
userSnapshot.sql.sqlUserGauntletRun = sqlUserGauntletRun
userSnapshot.sql.sqlUserGauntletRunComplete = sqlUserGauntletRunComplete
userSnapshot.sql.sqlUserGauntletTickets = sqlUserGauntletTickets
userSnapshot.sql.sqlUserGauntletTicketsUsed = sqlUserGauntletTicketsUsed
userSnapshot.sql.sqlUserProgression = sqlUserProgression
userSnapshot.sql.sqlUserProgressionDays = sqlUserProgressionDays
userSnapshot.sql.sqlUserQuests = sqlUserQuests
userSnapshot.sql.sqlUserQuestsComplete = sqlUserQuestsComplete
userSnapshot.sql.sqlUserRankEvents = sqlUserRankEvents
userSnapshot.sql.sqlUserRankHistory = sqlUserRankHistory
userSnapshot.sql.sqlUserRewards = sqlUserRewards
userSnapshot.sql.sqlUserSpiritOrbs = sqlUserSpiritOrbs
userSnapshot.sql.sqlUserSpiritOrbsOpened = sqlUserSpiritOrbsOpened
userSnapshot.sql.sqlUserCodexInventory = sqlUserCodexInventory
userSnapshot.sql.sqlUserNewPlayerProgression = sqlUserNewPlayerProgression
userSnapshot.sql.sqlUserAchievements = sqlUserAchievements
userSnapshot.sql.sqlUserChestRows = sqlUserChestRows
userSnapshot.sql.sqlUserChestOpenedRows = sqlUserChestOpenedRows
userSnapshot.sql.sqlUserChestKeyRows = sqlUserChestKeyRows
userSnapshot.sql.sqlUserChestKeyUsedRows = sqlUserChestKeyUsedRows
userSnapshot.sql.sqlUserRow = sqlUserRow
Logger.module("UsersModule").timeEnd "___snapshotUserData() -> retrieving data for user ID #{userId.blue}".green
return userSnapshot
###*
# Tip your opponent for a specific game
# @public
# @param {String} userId User ID.
# @param {String} gameId Game ID to tip for
# @return {Promise} Promise that will resolve when complete
###
@tipAnotherPlayerForGame: (userId,gameId,goldAmount=5)->
MOMENT_NOW_UTC = moment().utc()
Promise.all([
knex("users").where('id',userId).first('username','wallet_gold')
knex("user_games").where({user_id:userId,game_id:gameId}).first()
]).spread (userRow,gameRow)->
# we need a game row
if not gameRow?
throw new Errors.NotFoundError("Player game not found")
# game must be less than a day old
timeSinceCreated = moment.duration(MOMENT_NOW_UTC.diff(moment.utc(gameRow.created_at)))
if timeSinceCreated.asDays() > 1.0
throw new Errors.BadRequestError("Game is too old")
# only the winner can tip
if not gameRow.is_winner
throw new Errors.BadRequestError("Only the winner can tip")
# we don't allow multiple tips
if gameRow.gold_tip_amount?
throw new Errors.AlreadyExistsError("Tip already given")
# we don't allow multiple tips
if userRow?.wallet_gold < goldAmount
throw new Errors.InsufficientFundsError("Not enough GOLD to tip")
# don't allow tips in friendly or sp games
if gameRow.game_type == "friendly" || gameRow.game_type == "single_player"
throw new Errors.BadRequestError("Can not tip in friendly or single player games")
# grab the opponent id so we know who to tip
playerId = gameRow.opponent_id
txPromise = knex.transaction (tx)->
Promise.all([
# debit user's gold
InventoryModule.debitGoldFromUser(txPromise,tx,userId,-goldAmount,"gold tip to #{gameId}:#{playerId}")
# give opponent gold
InventoryModule.giveUserGold(txPromise,tx,playerId,goldAmount,"gold tip from #{gameId}:#{userId}")
# update user game record
knex("user_games").where({user_id:userId,game_id:gameId}).update('gold_tip_amount',goldAmount).transacting(tx)
# update master game record
knex("games").where({id:gameId}).increment('gold_tip_amount',goldAmount).transacting(tx)
# update master game record
knex("users").where({id:userId}).increment('total_gold_tips_given',goldAmount).transacting(tx)
]).then ()->
return Promise.all([
SyncModule._bumpUserTransactionCounter(tx,userId)
SyncModule._bumpUserTransactionCounter(tx,playerId)
])
.then ()-> return UsersModule.inGameNotify(playerId,"#{userRow.username} tipped you #{goldAmount} GOLD","gold tip")
.then tx.commit
.catch tx.rollback
return txPromise
###*
# Suspend a user account
# @public
# @param {String} userId User ID.
# @param {String} reasonMemo Why is this user suspended?
# @return {Promise} Promise that will resolve when complete
###
@suspendUser: (userId,reasonMemo)->
return knex("users").where('id',userId).update({
is_suspended: true
suspended_at: moment().utc().toDate()
suspended_memo: reasonMemo
})
###*
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@isEligibleForTwitchDrop: (userId, itemId = null)->
return Promise.resolve(true)
###*
# Export a user account data as is (for user requested account export)
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@exportUser: (userId)->
return UsersModule.___snapshotUserData(userId)
.then (userData) ->
# we may want to filter out selective data at this point before exporting
return userData
.catch (e) ->
Logger.module("UsersModule").error "exportUser() -> #{e.message}".red
return null
###*
# Anonymize a user (prevents future logins and removes PID)
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@anonymizeUser: (userId)->
randomString = crypto.randomBytes(Math.ceil(32)).toString('hex').slice(0,64)
timestamp = moment().utc().valueOf()
randomEmail = "#{timestamp}-#{randomString}@anon.com"
randomUser = "#{timestamp}-#{randomString}-anon"
return UsersModule.userDataForId(userId)
.then (userRow) ->
if !userRow
throw new Errors.NotFoundError()
return Promise.all([
UsersModule.disassociateSteamId(userId),
UsersModule.changeEmail(userId, randomEmail),
UsersModule.changeUsername(userId, randomUser, true)
])
.catch (e) ->
# catch the error if any of the functions above fail and continue with suspending the user
Logger.module("UsersModule").error "anonymizeUser() partial failure -> #{e.message}".red
.then () ->
return UsersModule.suspendUser(userId, "User requested account deletion.")
module.exports = UsersModule
| 86865 | Promise = require 'bluebird'
util = require 'util'
crypto = require 'crypto'
FirebasePromises = require '../firebase_promises'
DuelystFirebase = require '../duelyst_firebase_module'
fbUtil = require '../../../app/common/utils/utils_firebase.js'
Logger = require '../../../app/common/logger.coffee'
colors = require 'colors'
validator = require 'validator'
uuid = require 'node-uuid'
moment = require 'moment'
_ = require 'underscore'
SyncModule = require './sync'
MigrationsModule = require './migrations'
InventoryModule = require './inventory'
QuestsModule = require './quests'
GamesModule = require './games'
RiftModule = require './rift'
RiftModule = require './gauntlet'
CosmeticChestsModule = require './cosmetic_chests'
CONFIG = require '../../../app/common/config.js'
Errors = require '../custom_errors'
mail = require '../../mailer'
knex = require("../data_access/knex")
config = require '../../../config/config.js'
generatePushId = require '../../../app/common/generate_push_id'
DataAccessHelpers = require('./helpers')
hashHelpers = require '../hash_helpers.coffee'
Promise.promisifyAll(mail)
AnalyticsUtil = require '../../../app/common/analyticsUtil.coffee'
{version} = require '../../../version.json'
# redis
{Redis, Jobs, GameManager} = require '../../redis/'
# SDK imports
SDK = require '../../../app/sdk'
Cards = require '../../../app/sdk/cards/cardsLookupComplete'
CardSetFactory = require '../../../app/sdk/cards/cardSetFactory'
RankFactory = require '../../../app/sdk/rank/rankFactory'
Entity = require '../../../app/sdk/entities/entity'
QuestFactory = require '../../../app/sdk/quests/questFactory'
QuestType = require '../../../app/sdk/quests/questTypeLookup'
GameType = require '../../../app/sdk/gameType'
GameFormat = require '../../../app/sdk/gameFormat'
UtilsGameSession = require '../../../app/common/utils/utils_game_session.coffee'
NewPlayerProgressionHelper = require '../../../app/sdk/progression/newPlayerProgressionHelper'
NewPlayerProgressionStageEnum = require '../../../app/sdk/progression/newPlayerProgressionStageEnum'
NewPlayerProgressionModuleLookup = require '../../../app/sdk/progression/newPlayerProgressionModuleLookup'
{Redis, Jobs} = require '../../redis/'
class UsersModule
###*
# MAX number of daily games to count for play rewards.
# @public
###
@DAILY_REWARD_GAME_CAP: 200
###*
# Hours until FWOTD is available again.
# @public
###
@DAILY_WIN_CYCLE_HOURS: 22
###*
# Retrieve an active and valid global referral code.
# @public
# @param {String} code Referral Code
# @return {Promise} Promise that will return true or throw InvalidReferralCodeError exception .
###
@getValidReferralCode: (code) ->
# validate referral code and force it to lower case
code = code?.toLowerCase().trim()
if not validator.isLength(code,4)
return Promise.reject(new Errors.InvalidReferralCodeError("invalid referral code"))
MOMENT_NOW_UTC = moment().utc()
# we check if the referral code is a UUID so that anyone accidentally using invite codes doesn't error out
if validator.isUUID(code)
return Promise.resolve({})
return knex("referral_codes").where('code',code).first()
.then (referralCodeRow)->
if referralCodeRow? and
referralCodeRow?.is_active and
(!referralCodeRow?.signup_limit? or referralCodeRow?.signup_count < referralCodeRow?.signup_limit) and
(!referralCodeRow?.expires_at? or moment.utc(referralCodeRow?.expires_at).isAfter(MOMENT_NOW_UTC))
return referralCodeRow
else
throw new Errors.InvalidReferralCodeError("referral code not found")
###*
# Check if an invite code is valid.
# @public
# @param {String} inviteCode Invite Code
# @return {Promise} Promise that will return true or throw InvalidInviteCodeError exception .
###
@isValidInviteCode: (inviteCode,cb) ->
inviteCode ?= null
return knex("invite_codes").where('code',inviteCode).first()
.then (codeRow)->
if !config.get("inviteCodesActive") || codeRow? || inviteCode is "kumite14" || inviteCode is "keysign789"
return true
else
throw new Errors.InvalidInviteCodeError("Invalid Invite Code")
###*
# Create a user record for the specified parameters.
# @public
# @param {String} email User's email (no longer strictly required)
# @param {String} username User's username
# @param {String} password <PASSWORD>
# @param {String} inviteCode Invite code used
# @return {Promise} Promise that will return the userId on completion.
###
@createNewUser: (email = null,username,password,inviteCode = '<PASSWORD>',referralCode,campaignData,registrationSource = null)->
# validate referral code and force it to lower case
referralCode = referralCode?.toLowerCase().trim()
if referralCode? and not validator.isLength(referralCode,3)
return Promise.reject(new Errors.InvalidReferralCodeError("invalid referral code"))
if email then email = email.toLowerCase()
userId = generatePushId()
username = username.toLowerCase()
inviteCode ?= null
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
return knex("invite_codes").where('code',inviteCode).first()
.bind this_obj
.then (inviteCodeRow)->
if config.get("inviteCodesActive") and !inviteCodeRow and inviteCode != "kumite14" and inviteCode != "keysign789"
throw new Errors.InvalidInviteCodeError("Invite code not found")
referralCodePromise = Promise.resolve(null)
# we check if the referral code is a UUID so that anyone accidentally using invite codes doesn't error out
if referralCode? and not validator.isUUID(referralCode)
referralCodePromise = UsersModule.getValidReferralCode(referralCode)
return Promise.all([
UsersModule.userIdForEmail(email),
UsersModule.userIdForUsername(username),
referralCodePromise
])
.spread (idForEmail,idForUsername,referralCodeRow)->
if idForEmail
throw new Errors.AlreadyExistsError("Email already registered")
if idForUsername
throw new Errors.AlreadyExistsError("Username not available")
@.referralCodeRow = referralCodeRow
return hashHelpers.generateHash(password)
.then (passwordHash)->
return knex.transaction (tx) =>
userRecord =
id:userId
email:email # email maybe equals null here
username:username
password:<PASSWORD>
created_at:MOMENT_NOW_UTC.toDate()
if registrationSource
userRecord.registration_source = registrationSource
if config.get("inviteCodesActive")
userRecord.invite_code = inviteCode
# Add campaign data to userRecord
if campaignData?
userRecord.campaign_source ?= campaignData.campaign_source
userRecord.campaign_medium ?= campaignData.campaign_medium
userRecord.campaign_term ?= campaignData.campaign_term
userRecord.campaign_content ?= campaignData.campaign_content
userRecord.campaign_name ?= campaignData.campaign_name
userRecord.referrer ?= campaignData.referrer
updateReferralCodePromise = Promise.resolve()
if @.referralCodeRow?
Logger.module("USERS").debug "createNewUser() -> using referral code #{referralCode.yellow} for user #{userId.blue} ", @.referralCodeRow.params
userRecord.referral_code = referralCode
updateReferralCodePromise = knex("referral_codes").where('code',referralCode).increment('signup_count',1).transacting(tx)
if @.referralCodeRow.params?.gold
userRecord.wallet_gold ?= 0
userRecord.wallet_gold += @.referralCodeRow.params?.gold
if @.referralCodeRow.params?.spirit
userRecord.wallet_spirit ?= 0
userRecord.wallet_spirit += @.referralCodeRow.params?.spirit
Promise.all([
# user record
knex('users').insert(userRecord).transacting(tx),
# update referal code table
updateReferralCodePromise
])
.bind this_obj
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
# collect all the firebase update promises here
allPromises = []
userData = {
id: userId
username: username
created_at: MOMENT_NOW_UTC.valueOf()
presence: {
rank: 30
username: username
status: "offline"
}
tx_counter: {
count:0
}
# all new users have accepted EULA before signing up
hasAcceptedEula: false
hasAcceptedSteamEula: false
}
starting_gold = @.referralCodeRow?.params?.gold || 0
starting_spirit = @.referralCodeRow?.params?.spirit || 0
allPromises.push(FirebasePromises.set(rootRef.child('users').child(userId),userData))
allPromises.push(FirebasePromises.set(rootRef.child('username-index').child(username),userId))
allPromises.push(FirebasePromises.set(rootRef.child('user-inventory').child(userId).child('wallet'),{
gold_amount:starting_gold
spirit_amount:starting_spirit
}))
return Promise.all(allPromises)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
if config.get("inviteCodesActive")
return knex("invite_codes").where('code',inviteCode).delete()
.then ()->
# if email then mail.sendSignupAsync(username, email, verifyToken)
# NOTE: don't send registration notifications at large volume, and also since they contain PID
# mail.sendNotificationAsync("New Registration", "#{email} has registered with #{username}.")
return Promise.resolve(userId)
###*
# Delete a newly created user record in the event of partial registration.
# @public
# @param {String} userId User's ID
# @return {Promise} Promise that will return the userId on completion.
###
@deleteNewUser: (userId) ->
username = null
return @userDataForId(userId)
.then (userRow) ->
if !userRow
throw new Errors.NotFoundError()
username = userRow.username
return knex("users").where('id',userId).delete()
.then () -> return DuelystFirebase.connect().getRootRef()
.then (rootRef) ->
promises = [
FirebasePromises.remove(rootRef.child('users').child(userId)),
FirebasePromises.remove(rootRef.child('user-inventory').child(userId))
]
if username
promises.push(FirebasePromises.remove(rootRef.child('username-index').child(username)))
return Promise.all(promises)
###*
# Change a user's username.
# It will skip gold check if the username has never been set (currently null)
# @public
# @param {String} userId User ID
# @param {String} username New username
# @param {Moment} systemTime Pass in the current system time to override clock. Used mostly for testing.
# @return {Promise} Promise that will return on completion.
###
@changeUsername: (userId,newUsername,forceItForNoGold=false,systemTime)->
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
return UsersModule.userIdForUsername(newUsername)
.bind {}
.then (existingUserId)->
if existingUserId
throw new Errors.AlreadyExistsError("Username already exists")
else
return knex.transaction (tx)->
knex("users").where('id',userId).first('username','username_updated_at','wallet_gold').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
# we should have a user
if !userRow
throw new Errors.NotFoundError()
# let's figure out if we're allowed to change the username and how much it should cost
# if username was null, price stays 0
price = 0
if not forceItForNoGold and userRow.username_updated_at and userRow.username
price = 100
timeSinceLastChange = moment.duration(MOMENT_NOW_UTC.diff(moment.utc(userRow.username_updated_at)))
if timeSinceLastChange.asMonths() < 1.0
throw new Errors.InvalidRequestError("Username can't be changed twice in one month")
@.price = price
@.oldUsername = userRow.username
if price > 0 and userRow.wallet_gold < price
throw new Errors.InsufficientFundsError("Insufficient gold to update username")
allUpdates = []
# if username was null, we skip setting the updated_at flag since it is being set for first time
if !@.oldUsername
userUpdateParams =
username:newUsername
else
userUpdateParams =
username:newUsername
username_updated_at:MOMENT_NOW_UTC.toDate()
if price > 0
userUpdateParams.wallet_gold = userRow.wallet_gold-price
userUpdateParams.wallet_updated_at = MOMENT_NOW_UTC.toDate()
userCurrencyLogItem =
id: generatePushId()
user_id: userId
gold: -price
memo: "username change"
created_at: MOMENT_NOW_UTC.toDate()
allUpdates.push knex("user_currency_log").insert(userCurrencyLogItem).transacting(tx)
allUpdates.push knex("users").where('id',userId).update(userUpdateParams).transacting(tx)
return Promise.all(allUpdates)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
updateWalletData = (walletData)=>
walletData ?= {}
walletData.gold_amount ?= 0
walletData.gold_amount -= @.price
walletData.updated_at = MOMENT_NOW_UTC.valueOf()
return walletData
allPromises = [
FirebasePromises.set(rootRef.child('username-index').child(newUsername),userId)
FirebasePromises.set(rootRef.child('users').child(userId).child('presence').child('username'),newUsername)
]
# if username was null, we skip setting the updated_at flag since it is being set for first time
# and there is no old index to remove
if !@.oldUsername
allPromises.push(FirebasePromises.update(rootRef.child('users').child(userId),{username: newUsername}))
else
allPromises.push(FirebasePromises.remove(rootRef.child('username-index').child(@.oldUsername)))
allPromises.push(FirebasePromises.update(rootRef.child('users').child(userId),{username: newUsername, username_updated_at:MOMENT_NOW_UTC.valueOf()}))
if @.price > 0
allPromises.push FirebasePromises.safeTransaction(rootRef.child("user-inventory").child(userId).child("wallet"),updateWalletData)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
###*
# Change a user's email address.
# @public
# @param {String} userId User ID
# @param {String} newEmail New email
# @param {Moment} systemTime Pass in the current system time to override clock. Used mostly for testing.
# @return {Promise} Promise that will return on completion.
###
@changeEmail: (userId,newEmail,systemTime)->
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
return UsersModule.userIdForEmail(newEmail)
.bind {}
.then (existingUserId)->
if existingUserId
throw new Errors.AlreadyExistsError("Email already exists")
else
return knex.transaction (tx)->
knex("users").where('id',userId).first('email').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
# we should have a user
if !userRow
throw new Errors.NotFoundError()
@.oldEmail = userRow.email
userUpdateParams =
email:newEmail
return knex("users").where('id',userId).update(userUpdateParams).transacting(tx)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
###*
# Mark a user record as having verified email.
# @public
# @param {String} token Verification Token
# @return {Promise} Promise that will return on completion.
###
@verifyEmailUsingToken: (token)->
MOMENT_NOW_UTC = moment().utc()
return knex("email_verify_tokens").first().where('verify_token',token)
.bind {}
.then (tokenRow)->
@.tokenRow = tokenRow
unless tokenRow?.created_at
throw new Errors.NotFoundError()
duration = moment.duration(moment().utc().valueOf() - moment.utc(tokenRow?.created_at).valueOf())
if duration.asDays() < 1
return Promise.all([
knex('users').where('id',tokenRow.user_id).update({ email_verified_at: MOMENT_NOW_UTC.toDate() }) # mark user as verified
knex('email_verify_tokens').where('user_id',tokenRow.user_id).delete() # delete all user's verify tokens
])
else
throw new Errors.NotFoundError()
###*
# Change a user's password.
# @public
# @param {String} userId User ID
# @param {String} oldPassword <PASSWORD>
# @param {String} newPassword <PASSWORD>
# @return {Promise} Promise that will return on completion.
###
@changePassword: (userId,oldPassword,newPassword)->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx)->
knex("users").where('id',userId).first('password').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
return hashHelpers.comparePassword(oldPassword, userRow.password)
.then (match) ->
if (!match)
throw new Errors.BadPasswordError()
else
return hashHelpers.generateHash(newPassword)
.then (hash) ->
knex("users").where('id',userId).update({
password:<PASSWORD>
password_updated_at:MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Google Play ID to a User
# @public
# @param {String} userId User ID
# @param {String} googlePlayId User's Google Play ID
# @return {Promise} Promise that will return on completion
###
@associateGooglePlayId: (userId, googlePlayId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
google_play_id: googlePlayId
google_play_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Google Play ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateGooglePlayId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
google_play_id: null
google_play_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Gamecenter ID to a user
# @public
# @param {String} userId User ID
# @param {String} gamecenterId User's Gamecenter Id
# @return {Promise} Promise that will return on completion
###
@associateGameCenterId: (userId, gameCenterId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
gamecenter_id: gameCenterId
gamecenter_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Gamecenter ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateGameCenterId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
gamecenter_id: null
gamecenter_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Steam ID to a User
# @public
# @param {String} userId User ID
# @param {String} steamId User's Steam ID as returned from steam.coffee authenticateUserTicket
# @return {Promise} Promise that will return on completion.
###
@associateSteamId: (userId, steamId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
steam_id: steamId
steam_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Steam ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateSteamId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
steam_id: null
steam_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Get user data for id.
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return the user data on completion.
###
@userDataForId: (userId)->
return knex("users").first().where('id',userId)
###*
# Get user data for email.
# @public
# @param {String} email User Email
# @return {Promise} Promise that will return the user data on completion.
###
@userDataForEmail: (email)->
return knex("users").first().where('email',email)
###*
# Intended to be called on login/reload to bump session counter and check transaction counter to update user caches / initiate any hot copies.
# @public
# @param {String} userId User ID
# @param {Object} userData User data if previously loaded
# @return {Promise} Promise that will return synced when done
###
@bumpSessionCountAndSyncDataIfNeeded: (userId,userData=null,systemTime=null)->
MOMENT_NOW_UTC = systemTime || moment().utc()
startPromise = null
if userData
startPromise = Promise.resolve(userData)
else
startPromise = knex("users").where('id',userId).first('id','created_at','session_count','last_session_at','last_session_version')
return startPromise
.then (userData)->
@.userData = userData
if not @.userData?
throw new Errors.NotFoundError("User not found")
# Check if user needs to have emotes migrated to cosmetics inventory
return MigrationsModule.checkIfUserNeedsMigrateEmotes20160708(@.userData)
.then (userNeedsMigrateEmotes) ->
if userNeedsMigrateEmotes
return MigrationsModule.userMigrateEmotes20160708(userId,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then () ->
return MigrationsModule.checkIfUserNeedsPrismaticBackfillReward(@.userData)
.then (userNeedsPrismaticBackfill) ->
if userNeedsPrismaticBackfill
return MigrationsModule.userBackfillPrismaticRewards(userId,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then ()-> # migrate user charge counts for purchase limits
return MigrationsModule.checkIfUserNeedsChargeCountsMigration(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userCreateChargeCountsMigration(userId)
else
return Promise.resolve()
.then ()->
return MigrationsModule.checkIfUserNeedsIncompleteGauntletRefund(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userIncompleteGauntletRefund(userId)
else
return Promise.resolve()
.then ()->
return MigrationsModule.checkIfUserNeedsUnlockableOrbsRefund(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userUnlockableOrbsRefund(userId)
else
return Promise.resolve()
.then () ->
lastSessionTime = moment.utc(@.userData.last_session_at).valueOf() || 0
duration = moment.duration(MOMENT_NOW_UTC.valueOf() - lastSessionTime)
if moment.utc(@.userData.created_at).isBefore(moment.utc("2016-06-18")) and moment.utc(@.userData.last_session_at).isBefore(moment.utc("2016-06-18"))
Logger.module("UsersModule").debug "bumpSessionCountAndSyncDataIfNeeded() -> starting inventory achievements for user - #{userId.blue}."
# Kick off job to update achievements
Jobs.create("update-user-achievements",
name: "Update User Inventory Achievements"
title: util.format("User %s :: Update Inventory Achievements", userId)
userId: userId
inventoryChanged: true
).removeOnComplete(true).save()
if duration.asHours() > 2
return knex("users").where('id',userId).update(
session_count: @.userData.session_count+1
last_session_at: MOMENT_NOW_UTC.toDate()
)
else
return Promise.resolve()
.then ()->
# Update a user's last seen session if needed
if not @.userData.last_session_version? or @.userData.last_session_version != version
return knex("users").where('id',userId).update(
last_session_version: version
)
else
return Promise.resolve()
.then ()->
return SyncModule.syncUserDataIfTrasactionCountMismatched(userId,@.userData)
.then (synced)->
# # Job: Sync user buddy data
# Jobs.create("data-sync-user-buddy-list",
# name: "Sync User Buddy Data"
# title: util.format("User %s :: Sync Buddies", userId)
# userId: userId
# ).removeOnComplete(true).save()
return synced
###*
# Intended to be called on login/reload to fire off a job which tracks cohort data for given user
# @public
# @param {String} userId User ID
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise.resolve() for now since all handling is done in job
###
@createDaysSeenOnJob: (userId,systemTime) ->
MOMENT_NOW_UTC = systemTime || moment().utc()
Jobs.create("update-user-seen-on",
name: "Update User Seen On"
title: util.format("User %s :: Update Seen On", userId)
userId: userId
userSeenOn: MOMENT_NOW_UTC.valueOf()
).removeOnComplete(true).save()
return Promise.resolve()
###*
# Intended to be called on login/reload to fire off a job which tracks cohort data for given user
# @public
# @param {String} userId User ID
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise.resolve() for now since all handling is done in job
###
@createSteamFriendsSyncJob: (userId, friendSteamIds) ->
Jobs.create("data-sync-steam-friends",
name: "Sync Steam Friends"
title: util.format("User %s :: Sync Steam Friends", userId)
userId: userId
friendsSteamIds: friendSteamIds
).removeOnComplete(true).save()
return Promise.resolve()
###*
# Updates the users row if they have newly logged in on a set day
# @public
# @param {String} userId User ID
# @param {Moment} userSeenOn Moment representing the time the user was seen (at point of log in)
# @return {Promise} Promise that completes when user's days seen is updated (if needed)
###
@updateDaysSeen: (userId,userSeenOn) ->
return knex.first('created_at','seen_on_days').from('users').where('id',userId)
.then (userRow) ->
recordedDayIndex = AnalyticsUtil.recordedDayIndexForRegistrationAndSeenOn(moment.utc(userRow.created_at),userSeenOn)
if not recordedDayIndex?
return Promise.resolve()
else
userSeenOnDays = userRow.seen_on_days || []
needsUpdate = false
if not _.contains(userSeenOnDays,recordedDayIndex)
needsUpdate = true
userSeenOnDays.push(recordedDayIndex)
# perform update if needed
if needsUpdate
return knex('users').where({'id':userId}).update({seen_on_days:userSeenOnDays})
else
return Promise.resolve()
###*
# Get the user ID for the specified email.
# @public
# @param {String} email User's email
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForEmail: (email, callback) ->
if !email then return Promise.resolve(null).nodeify(callback)
return knex.first('id').from('users').where('email',email)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified username.
# @public
# @param {String} username User's username (CaSE in-sensitive)
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForUsername: (username, callback) ->
# usernames are ALWAYS lowercase, so when searching downcase by default
username = username?.toLowerCase()
return knex.first('id').from('users').where('username',username)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Steam ID.
# Reference steam.coffee's authenticateUserTicket
# @public
# @param {String} steamId User's Steam ID as returned from steam.coffee authenticateUserTicket
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForSteamId: (steamId, callback) ->
return knex.first('id').from('users').where('steam_id',steamId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Google Play ID.
# @public
# @param {String} googlePlayId User's Google Play ID
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForGooglePlayId: (googlePlayId, callback) ->
return knex.first('id').from('users').where('google_play_id',googlePlayId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Gamecenter ID.
# @public
# @param {String} gameCenterId User's Gamecenter ID
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForGameCenterId: (gameCenterId, callback) ->
return knex.first('id').from('users').where('gamecenter_id',gameCenterId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Validate that a deck is valid and that the user is allowed to play it.
# @public
# @param {String} userId User ID.
# @param {Array} deck Array of card objects with at least card IDs.
# @param {String} gameType game type (see SDK.GameType)
# @param {Boolean} [forceValidation=false] Force validation regardless of ENV. Useful for unit tests.
# @return {Promise} Promise that will resolve if the deck is valid and throw an "InvalidDeckError" otherwise
###
@isAllowedToUseDeck: (userId,deck,gameType, ticketId, forceValidation) ->
# userId must be defined
if !userId || !deck
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid user ID or deck parameter - #{userId.blue}.".red
return Promise.reject(new Errors.InvalidDeckError("invalid user ID or deck - #{userId}"))
# on DEV + STAGING environments, always allow any deck
if !forceValidation and config.get('allCardsAvailable')
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> valid deck because this environment allows all cards ALL_CARDS_AVAILABLE = #{config.get('allCardsAvailable')} - #{userId.blue}.".green
return Promise.resolve(true)
# check for valid general
deckFactionId = null
generalId = deck[0]?.id
if generalId?
generalCard = SDK.GameSession.getCardCaches().getCardById(generalId)
if not generalCard?.isGeneral
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> first card in the deck must be a general - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("First card in the deck must be a general"))
else
deckFactionId = generalCard.factionId
if gameType == GameType.Gauntlet
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> Allowing ANY arena deck for now - #{userId.blue}.".green
return Promise.resolve(true)
else if ticketId? && gameType == GameType.Friendly
# # Validate a friendly rift deck
# return RiftModule.getRiftRunDeck(userId,ticketId)
# .then (riftDeck) ->
# sortedDeckIds = _.sortBy(_.map(deck,(cardObject) -> return cardObject.id),(id) -> return id)
# sortedRiftDeckIds = _.sortBy(riftDeck,(id)-> return id)
# if (sortedDeckIds.length != sortedRiftDeckIds.length)
# return Promise.reject(new Errors.InvalidDeckError("Friendly rift deck has incorrect card count: " + sortedDeckIds.length))
#
# for i in [0...sortedDeckIds.length]
# if sortedDeckIds[i] != sortedRiftDeckIds[i]
# return Promise.reject(new Errors.InvalidDeckError("Friendly rift deck has incorrect cards"))
#
# return Promise.resolve(true)
# Validate a friendly gauntlet deck
decksExpireMoment = moment.utc().subtract(CONFIG.DAYS_BEFORE_GAUNTLET_DECK_EXPIRES,"days")
currentDeckPromise = knex("user_gauntlet_run").first("deck").where("user_id",userId).andWhere("ticket_id",ticketId)
oldDeckPromise = knex("user_gauntlet_run_complete").first("deck","ended_at").where("user_id",userId).andWhere("id",ticketId).andWhere("ended_at",">",decksExpireMoment.toDate())
return Promise.all([currentDeckPromise,oldDeckPromise])
.spread (currentRunRow,completedRunRow) ->
matchingRunRow = null
if (currentRunRow?)
matchingRunRow = currentRunRow
else if (completedRunRow?)
matchingRunRow = completedRunRow
else
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has no matching recent run, ticket_id: " + ticketId))
gauntletDeck = matchingRunRow.deck
sortedDeckIds = _.sortBy(_.map(deck,(cardObject) -> return cardObject.id),(id) -> return id)
sortedGauntletDeckIds = _.sortBy(gauntletDeck,(id)-> return id)
if (sortedDeckIds.length != sortedGauntletDeckIds.length)
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has incorrect card count: " + sortedDeckIds.length))
for i in [0...sortedDeckIds.length]
if sortedDeckIds[i] != sortedGauntletDeckIds[i]
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has incorrect cards"))
return Promise.resolve(true)
else if gameType # allow all other game modes
cardsToValidateAgainstInventory = []
cardSkinsToValidateAgainstInventory = []
basicsOnly = true
for card in deck
cardId = card.id
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if sdkCard.rarityId != SDK.Rarity.Fixed
basicsOnly = false
if sdkCard.factionId != deckFactionId && sdkCard.factionId != SDK.Factions.Neutral
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> found a card with faction #{sdkCard.factionId} that doesn't belong in a #{deckFactionId} faction deck - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Deck has cards from more than one faction"))
if (sdkCard.rarityId != SDK.Rarity.Fixed and sdkCard.rarityId != SDK.Rarity.TokenUnit) || sdkCard.getIsUnlockable()
cardSkinId = SDK.Cards.getCardSkinIdForCardId(cardId)
if cardSkinId?
# add skin to validate against inventory
if !_.contains(cardSkinsToValidateAgainstInventory, cardSkinId)
cardSkinsToValidateAgainstInventory.push(cardSkinId)
# add unskinned card to validate against inventory if needed
unskinnedCardId = SDK.Cards.getNonSkinnedCardId(cardId)
unskinnedSDKCard = SDK.GameSession.getCardCaches().getIsSkinned(false).getCardById(unskinnedCardId)
if unskinnedSDKCard.getRarityId() != SDK.Rarity.Fixed and unskinnedSDKCard.getRarityId() != SDK.Rarity.TokenUnit
cardsToValidateAgainstInventory.push(unskinnedCardId)
else
# add card to validate against inventory
cardsToValidateAgainstInventory.push(card.id)
# starter decks must contain all cards in level 0 faction starter deck
# normal decks must match exact deck size
maxDeckSize = if CONFIG.DECK_SIZE_INCLUDES_GENERAL then CONFIG.MAX_DECK_SIZE else CONFIG.MAX_DECK_SIZE + 1
if basicsOnly
if deck.length < CONFIG.MIN_BASICS_DECK_SIZE
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid starter deck (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Starter decks must have at least #{CONFIG.MIN_BASICS_DECK_SIZE} cards!"))
else if deck.length > maxDeckSize
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid starter deck (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Starter decks must not have more than #{maxDeckSize} cards!"))
else if deck.length != maxDeckSize
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid deck length (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Deck must have #{maxDeckSize} cards"))
# ensure that player has no more than 3 of a base card (normal + prismatic) in deck
cardCountsById = _.countBy(deck, (cardData) ->
return Cards.getBaseCardId(cardData.id)
)
for k,v of cardCountsById
if v > 3
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 3 of a card"))
# Ensure that player doesn't have any cards that are in development, hidden in collection, and only one general
gameSessionCards = _.map(deck, (cardData) ->
cardId = cardData.id
return SDK.GameSession.getCardCaches().getCardById(cardId)
)
generalCount = 0
for gameSessionCard in gameSessionCards
if gameSessionCard instanceof Entity and gameSessionCard.getIsGeneral()
generalCount += 1
if not gameSessionCard.getIsAvailable(null, forceValidation)
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are not yet available - player #{userId.blue}.".red
return Promise.reject(new Errors.NotFoundError("Deck has cards that are not yet available"))
if gameSessionCard.getIsHiddenInCollection()
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are in hidden to collection - player #{userId.blue}.".red
return Promise.reject(new Errors.InvalidDeckError("Deck has cards that are in hidden to collection"))
if (gameSessionCard.getIsLegacy() || CardSetFactory.cardSetForIdentifier(gameSessionCard.getCardSetId()).isLegacy?) and GameType.getGameFormatForGameType(gameType) == GameFormat.Standard
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are in LEGACY format but game mode is STANDARD format"
return Promise.reject(new Errors.InvalidDeckError("Game Mode is STANDARD but deck contains LEGACY card"))
if generalCount != 1
return Promise.reject(new Errors.InvalidDeckError("Deck has " + generalCount + " generals"))
# ensure that player has no more than 1 of a mythron card (normal + prismatic) in deck
mythronCardCountsById = _.countBy(gameSessionCards, (card) ->
if card.getRarityId() == SDK.Rarity.Mythron
return Cards.getBaseCardId(card.getId())
else
return -1
)
for k,v of mythronCardCountsById
if k != '-1' and v > 1
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 1 of a mythron card"))
# ensure that player has no more than 1 trial card total
trialCardCount = _.countBy(gameSessionCards, (card) ->
baseCardId = Cards.getBaseCardId(card.getId())
if baseCardId in [Cards.Faction1.RightfulHeir, Cards.Faction2.DarkHeart, Cards.Faction3.KeeperOfAges, Cards.Faction4.DemonOfEternity, Cards.Faction5.Dinomancer, Cards.Faction6.VanarQuest, Cards.Neutral.Singleton]
return 'trialCard'
else
return -1
)
for k,v of trialCardCount
if k != '-1' and v > 1
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 1 total trial card"))
# setup method to validate cards against user inventory
validateCards = () ->
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> doesUserHaveCards -> #{cardsToValidateAgainstInventory.length} cards to validate - #{userId.blue}.".green
# if we're playing basic cards only, mark deck as valid, and only check against inventory otherwise
if cardsToValidateAgainstInventory.length == 0
return Promise.resolve(true)
else
return InventoryModule.isAllowedToUseCards(Promise.resolve(), knex, userId, cardsToValidateAgainstInventory)
# setup method to validate skins against user inventory
validateSkins = () ->
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> doesUserHaveSkins -> #{cardSkinsToValidateAgainstInventory.length} skins to validate - #{userId.blue}.".green
if cardSkinsToValidateAgainstInventory.length == 0
return Promise.resolve(true)
else
return InventoryModule.isAllowedToUseCosmetics(Promise.resolve(), knex, userId, cardSkinsToValidateAgainstInventory, SDK.CosmeticsTypeLookup.CardSkin)
return Promise.all([
validateCards(),
validateSkins()
])
else
return Promise.reject(new Error("Unknown game type: #{gameType}"))
###*
# Creates a blank faction progression (0 XP) record for a user. This is used to mark a faction as "unlocked".
# @public
# @param {String} userId User ID for which to update.
# @param {String} factionId Faction ID for which to update.
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@createFactionProgressionRecord: (userId,factionId,gameId,gameType,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not createFactionProgressionRecord(): invalid user ID - #{userId}"))
# factionId must be defined
if !factionId
return Promise.reject(new Error("Can not createFactionProgressionRecord(): invalid faction ID - #{factionId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx('users').where('id',userId).first('id').forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).first().forUpdate()
])
.spread (userRow,factionProgressionRow)->
if factionProgressionRow
throw new Errors.AlreadyExistsError()
# faction progression row
factionProgressionRow ?= { user_id:userId, faction_id:factionId }
@.factionProgressionRow = factionProgressionRow
factionProgressionRow.xp ?= 0
factionProgressionRow.game_count ?= 0
factionProgressionRow.unscored_count ?= 0
factionProgressionRow.loss_count ?= 0
factionProgressionRow.win_count ?= 0
factionProgressionRow.draw_count ?= 0
factionProgressionRow.single_player_win_count ?= 0
factionProgressionRow.friendly_win_count ?= 0
factionProgressionRow.xp_earned ?= 0
factionProgressionRow.updated_at = MOMENT_NOW_UTC.toDate()
factionProgressionRow.last_game_id = gameId
factionProgressionRow.level = SDK.FactionProgression.levelForXP(factionProgressionRow.xp)
# reward row
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"faction unlock"
game_id:gameId
unlocked_faction_id:factionId
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
return Promise.all([
tx('user_faction_progression').insert(factionProgressionRow)
tx("user_rewards").insert(rewardData)
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
])
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
delete @.factionProgressionRow.user_id
@.factionProgressionRow.updated_at = moment.utc(@.factionProgressionRow.updated_at).valueOf()
return FirebasePromises.set(rootRef.child('user-faction-progression').child(userId).child(factionId).child('stats'),@.factionProgressionRow)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "createFactionProgressionRecord() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
return txPromise
###*
# Update a user's per-faction progression metrics based on the outcome of a ranked game
# @public
# @param {String} userId User ID for which to update.
# @param {String} factionId Faction ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserFactionProgressionWithGameOutcome: (userId,factionId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserFactionProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# factionId must be defined
if !factionId
return Promise.reject(new Error("Can not updateUserFactionProgressionWithGameOutcome(): invalid faction ID - #{factionId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").first('id','is_bot').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).first().forUpdate()
])
.spread (userRow,factionProgressionRow)->
# Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> ACQUIRED LOCK ON #{userId}".yellow
@userRow = userRow
allPromises = []
needsInsert = _.isUndefined(factionProgressionRow)
factionProgressionRow ?= {user_id:userId,faction_id:factionId}
@.factionProgressionRow = factionProgressionRow
factionProgressionRow.xp ?= 0
factionProgressionRow.game_count ?= 0
factionProgressionRow.unscored_count ?= 0
factionProgressionRow.loss_count ?= 0
factionProgressionRow.win_count ?= 0
factionProgressionRow.draw_count ?= 0
factionProgressionRow.single_player_win_count ?= 0
factionProgressionRow.friendly_win_count ?= 0
factionProgressionRow.level ?= 0
# faction xp progression for single player and friendly games is capped at 10
# levels are indexed from 0 so we check 9 here instead of 10
if (gameType == GameType.SinglePlayer or gameType == GameType.BossBattle or gameType == GameType.Friendly) and factionProgressionRow.level >= 9
throw new Errors.MaxFactionXPForSinglePlayerReachedError()
# grab the default xp earned for a win/loss
# xp_earned = if isWinner then SDK.FactionProgression.winXP else SDK.FactionProgression.lossXP
xp_earned = SDK.FactionProgression.xpEarnedForGameOutcome(isWinner, factionProgressionRow.level)
# if this game should not earn XP for some reason (early concede for example)
if isUnscored then xp_earned = 0
xp = factionProgressionRow.xp
game_count = factionProgressionRow.game_count
win_count = factionProgressionRow.win_count
xp_cap = SDK.FactionProgression.totalXPForLevel(SDK.FactionProgression.maxLevel)
# do not commit transaction if we're at the max level
if (SDK.FactionProgression.levelForXP(xp) >= SDK.FactionProgression.maxLevel)
xp_earned = 0
# make sure user can't earn XP over cap
else if (xp_cap - xp < xp_earned)
xp_earned = xp_cap - xp
factionProgressionRow.xp_earned = xp_earned
factionProgressionRow.updated_at = MOMENT_NOW_UTC.toDate()
factionProgressionRow.last_game_id = gameId
if isUnscored
unscored_count = factionProgressionRow.unscored_count
factionProgressionRow.unscored_count += 1
else
factionProgressionRow.xp = xp + xp_earned
factionProgressionRow.level = SDK.FactionProgression.levelForXP(factionProgressionRow.xp)
factionProgressionRow.game_count += 1
if isDraw
factionProgressionRow.draw_count += 1
else if isWinner
factionProgressionRow.win_count += 1
if gameType == GameType.SinglePlayer or gameType == GameType.BossBattle
factionProgressionRow.single_player_win_count += 1
if gameType == GameType.Friendly
factionProgressionRow.friendly_win_count += 1
else
factionProgressionRow.loss_count += 1
# Logger.module("UsersModule").debug factionProgressionRow
if needsInsert
allPromises.push knex('user_faction_progression').insert(factionProgressionRow).transacting(tx)
else
allPromises.push knex('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).update(factionProgressionRow).transacting(tx)
if !isUnscored and not @.factionProgressionRow.xp_earned > 0
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> F#{factionId} MAX level reached"
# update the user game params
@.updateUserGameParams =
faction_xp: @.factionProgressionRow.xp
faction_xp_earned: 0
allPromises.push knex("user_games").where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
else
level = SDK.FactionProgression.levelForXP(@.factionProgressionRow.xp)
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> At F#{factionId} L:#{level} [#{@.factionProgressionRow.xp}] earned #{@.factionProgressionRow.xp_earned} for G:#{gameId}"
progressData = {
user_id:userId
faction_id:factionId
xp_earned:@.factionProgressionRow.xp_earned
is_winner:isWinner || false
is_draw:isDraw || false
game_id:gameId
created_at:MOMENT_NOW_UTC.toDate()
is_scored:!isUnscored
}
@.updateUserGameParams =
faction_xp: @.factionProgressionRow.xp - @.factionProgressionRow.xp_earned
faction_xp_earned: @.factionProgressionRow.xp_earned
allPromises.push knex("user_faction_progression_events").insert(progressData).transacting(tx)
allPromises.push knex("user_games").where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
return Promise.all(allPromises)
.then ()->
allPromises = []
if (!isUnscored and @.factionProgressionRow) and SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned)
# Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> LEVELED up"
factionName = SDK.FactionFactory.factionForIdentifier(factionId).devName
level = SDK.FactionProgression.levelForXP(@.factionProgressionRow.xp)
rewardData = SDK.FactionProgression.rewardDataForLevel(factionId,level)
@.rewardRows = []
if rewardData?
rewardRowData =
id: generatePushId()
user_id: userId
reward_category: 'faction xp'
reward_type: "#{factionName} L#{level}"
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread:true
@.rewardRows.push(rewardRowData)
rewardData.created_at = MOMENT_NOW_UTC.valueOf()
rewardData.level = level
# update inventory
earnRewardInventoryPromise = null
if rewardData.gold?
rewardRowData.gold = rewardData.gold
# update wallet
earnRewardInventoryPromise = InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,"#{factionName} L#{level}",gameId)
else if rewardData.spirit?
rewardRowData.spirit = rewardData.spirit
# update wallet
earnRewardInventoryPromise = InventoryModule.giveUserSpirit(txPromise,tx,userId,rewardData.spirit,"#{factionName} L#{level}",gameId)
else if rewardData.cards?
cardIds = []
_.each(rewardData.cards,(c)->
_.times c.count, ()->
cardIds.push(c.id)
)
rewardRowData.cards = cardIds
# give cards
earnRewardInventoryPromise = InventoryModule.giveUserCards(txPromise,tx,userId,cardIds,'faction xp',gameId,"#{factionName} L#{level}")
else if rewardData.booster_packs?
rewardRowData.spirit_orbs = rewardData.booster_packs
# TODO: what about more than 1 booster pack?
earnRewardInventoryPromise = InventoryModule.addBoosterPackToUser(txPromise,tx,userId,1,"faction xp","#{factionName} L#{level}",{factionId:factionId,level:level,gameId:gameId})
else if rewardData.emotes?
rewardRowData.cosmetics = []
# update emotes inventory
emotes_promises = []
for emote_id in rewardData.emotes
rewardRowData.cosmetics.push(emote_id)
allPromises.push InventoryModule.giveUserCosmeticId(txPromise, tx, userId, emote_id, "faction xp reward", rewardRowData.id,null, MOMENT_NOW_UTC)
earnRewardInventoryPromise = Promise.all(emotes_promises)
# resolve master promise whan reward is saved and inventory updated
allPromises = allPromises.concat [
knex("user_rewards").insert(rewardRowData).transacting(tx),
earnRewardInventoryPromise,
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardRowData.id)
]
# let's see if we need to add any faction ribbons for this user
winCountForRibbons = @.factionProgressionRow.win_count - (@.factionProgressionRow.single_player_win_count + @.factionProgressionRow.friendly_win_count)
if isWinner and winCountForRibbons > 0 and winCountForRibbons % 100 == 0 and not @.userRow.is_bot
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} earned WIN RIBBON for faction #{factionId}"
ribbonId = "f#{factionId}_champion"
rewardRowData =
id: generatePushId()
user_id: userId
reward_category: 'ribbon'
reward_type: "#{factionName} wins"
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
ribbons:[ribbonId]
is_unread:true
# looks like the user earned a faction ribbon!
ribbon =
user_id:userId
ribbon_id:ribbonId
game_id:gameId
created_at:MOMENT_NOW_UTC.toDate()
@.ribbon = ribbon
allPromises = allPromises.concat [
knex("user_ribbons").insert(ribbon).transacting(tx)
knex("user_rewards").insert(rewardRowData).transacting(tx),
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardRowData.id)
]
return Promise.all(allPromises)
.then ()->
# Update quests if a faction has leveled up
if SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned)
if @.factionProgressionRow #and shouldProcessQuests # TODO: shouldprocessquests? also this may fail for people who already have faction lvl 10 by the time they reach this stage
return QuestsModule.updateQuestProgressWithProgressedFactionData(txPromise,tx,userId,@.factionProgressionRow,MOMENT_NOW_UTC)
# Not performing faction based quest update
return Promise.resolve()
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
delete @.factionProgressionRow.user_id
@.factionProgressionRow.updated_at = moment.utc(@.factionProgressionRow.updated_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child('user-faction-progression').child(userId).child(factionId).child('stats'),@.factionProgressionRow)
for key,val of @.updateUserGameParams
allPromises.push FirebasePromises.set(rootRef.child('user-games').child(userId).child(gameId).child(key),val)
if @.ribbon
ribbonData = _.omit(@.ribbon,["user_id"])
ribbonData = DataAccessHelpers.restifyData(ribbonData)
allPromises.push FirebasePromises.safeTransaction(rootRef.child('user-ribbons').child(userId).child(ribbonData.ribbon_id),(data)->
data ?= {}
data.ribbon_id ?= ribbonData.ribbon_id
data.updated_at = ribbonData.created_at
data.count ?= 0
data.count += 1
return data
)
# if @.rewardRows
# for reward in @.rewardRows
# reward_id = reward.id
# delete reward.user_id
# delete reward.id
# reward.created_at = moment.utc(reward.created_at).valueOf()
# # push rewards to firebase tree
# allPromises.push(FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(reward_id),reward))
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.catch Errors.MaxFactionXPForSinglePlayerReachedError, (e)-> tx.rollback(e)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserFactionProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
# Update achievements if leveled up
if SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned) || @.factionProgressionRow.game_count == 1
Jobs.create("update-user-achievements",
name: "Update User Faction Achievements"
title: util.format("User %s :: Update Faction Achievements", userId)
userId: userId
factionProgressed: true
).removeOnComplete(true).save()
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} (#{@.factionProgressionRow["game_count"]}) faction progression recorded. Unscored: #{isUnscored?.toString().cyan}".green
return @.factionProgressionRow
.catch Errors.MaxFactionXPForSinglePlayerReachedError, (e)->
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} for faction #{factionId} not recorded. MAX LVL 10 for single player games reached."
return null
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'faction_progression')
return txPromise
###*
# Update a user's progression metrics based on the outcome of a ranked game
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw is this game a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserProgressionWithGameOutcome: (userId,opponentId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# userId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid game ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
start_of_day_int = parseInt(moment(MOMENT_NOW_UTC).startOf('day').utc().format("YYYYMMDD"))
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_progression').where('user_id',userId).first().forUpdate()
tx('user_progression_days').where({'user_id':userId,'date':start_of_day_int}).first().forUpdate()
])
.spread (userRow,progressionRow,progressionDayRow)->
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> ACQUIRED LOCK ON #{userId}".yellow
#######
#######
#######
#######
#######
#######
#######
allPromises = []
hasReachedDailyPlayRewardMaxium = false
hasReachedDailyWinRewardMaxium = false
@.hasReachedDailyWinCountBonusLimit = false
canEarnFirstWinOfTheDayReward = true
@.progressionDayRow = progressionDayRow || { user_id:userId, date:start_of_day_int }
@.progressionDayRow.game_count ?= 0
@.progressionDayRow.unscored_count ?= 0
@.progressionDayRow.game_count += 1
# controls for daily maximum of play rewards
if @.progressionDayRow.game_count - @.progressionDayRow.unscored_count > UsersModule.DAILY_REWARD_GAME_CAP
hasReachedDailyPlayRewardMaxium = true
# # controls for daily maximum of play rewards
# if counterData.win_count > UsersModule.DAILY_REWARD_WIN_CAP
# hasReachedDailyWinRewardMaxium = true
if isDraw
@.progressionDayRow.draw_count ?= 0
@.progressionDayRow.draw_count += 1
else if isWinner
# iterate win count
@.progressionDayRow.win_count ?= 0
@.progressionDayRow.win_count += 1
if @.progressionDayRow.win_count > 1
canEarnFirstWinOfTheDayReward = false
# @.hasReachedDailyWinCountBonusLimit is disabled
# if @.progressionDayRow.win_count > 14
# @.hasReachedDailyWinCountBonusLimit = true
else
# iterate loss count
@.progressionDayRow.loss_count ?= 0
@.progressionDayRow.loss_count += 1
# if it's an unscored game, iterate unscored counter
if isUnscored
@.progressionDayRow.unscored_count += 1
if progressionDayRow?
allPromises.push knex('user_progression_days').where({'user_id':userId,'date':start_of_day_int}).update(@.progressionDayRow).transacting(tx)
else
allPromises.push knex('user_progression_days').insert(@.progressionDayRow).transacting(tx)
#######
#######
#######
#######
#######
#######
#######
@.hasEarnedWinReward = false
@.hasEarnedPlayReward = false
@.hasEarnedFirstWinOfTheDayReward = false
@.progressionRow = progressionRow || { user_id:userId }
@.progressionRow.last_opponent_id = opponentId
# record total game count
@.progressionRow.game_count ?= 0
@.progressionRow.unscored_count ?= 0
@.progressionRow.last_game_id = gameId || null
@.progressionRow.updated_at = MOMENT_NOW_UTC.toDate()
# initialize last award records
@.progressionRow.last_awarded_game_count ?= 0
@.progressionRow.last_awarded_win_count ?= 0
last_daily_win_at = @.progressionRow.last_daily_win_at || 0
play_count_reward_progress = 0
win_count_reward_progress = 0
if isUnscored
@.progressionRow.unscored_count += 1
# mark all rewards as false
@.hasEarnedWinReward = false
@.hasEarnedPlayReward = false
@.hasEarnedFirstWinOfTheDayReward = false
else
@.progressionRow.game_count += 1
if not hasReachedDailyPlayRewardMaxium
play_count_reward_progress = @.progressionRow.game_count - @.progressionRow.last_awarded_game_count
if @.progressionRow.game_count > 0 and play_count_reward_progress > 0 and play_count_reward_progress % 4 == 0
@.progressionRow.last_awarded_game_count = @.progressionRow.game_count
@.hasEarnedPlayReward = true
else
@.hasEarnedPlayReward = false
else
@.progressionRow.last_awarded_game_count = @.progressionRow.game_count
@.progressionRow.play_awards_last_maxed_at = MOMENT_NOW_UTC.toDate()
@.hasEarnedPlayReward = false
if isDraw
@.progressionRow.draw_count ?= 0
@.progressionRow.draw_count += 1
else if isWinner
# set loss streak to 0
@.progressionRow.loss_streak = 0
# is this the first win of the day?
hours_since_last_win = MOMENT_NOW_UTC.diff(last_daily_win_at,'hours')
if hours_since_last_win >= UsersModule.DAILY_WIN_CYCLE_HOURS
@.hasEarnedFirstWinOfTheDayReward = true
@.progressionRow.last_daily_win_at = MOMENT_NOW_UTC.toDate()
else
@.hasEarnedFirstWinOfTheDayReward = false
# iterate win count
@.progressionRow.win_count ?= 0
@.progressionRow.win_count += 1
# iterate win streak
if gameType != GameType.Casual
@.progressionRow.win_streak ?= 0
@.progressionRow.win_streak += 1
# mark last win time
@.progressionRow.last_win_at = MOMENT_NOW_UTC.toDate()
if not hasReachedDailyWinRewardMaxium
win_count_reward_progress = @.progressionRow.win_count - @.progressionRow.last_awarded_win_count
# if we've had 3 wins since last award, the user has earned an award
if @.progressionRow.win_count - @.progressionRow.last_awarded_win_count >= CONFIG.WINS_REQUIRED_FOR_WIN_REWARD
@.hasEarnedWinReward = true
@.progressionRow.last_awarded_win_count_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.last_awarded_win_count = @.progressionRow.win_count
else
@.hasEarnedWinReward = false
else
@.progressionRow.last_awarded_win_count_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.win_awards_last_maxed_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.last_awarded_win_count = @.progressionRow.win_count
@.hasEarnedWinReward = false
else
# iterate loss count
@.progressionRow.loss_count ?= 0
@.progressionRow.loss_count += 1
# only iterate loss streak for scored games
# NOTE: control flow should never allow this to be reached for unscored, but adding this just in case someone moves code around :)
if not isUnscored
@.progressionRow.loss_streak ?= 0
@.progressionRow.loss_streak += 1
if gameType != GameType.Casual
# reset win streak
@.progressionRow.win_streak = 0
if progressionRow?
allPromises.push knex('user_progression').where({'user_id':userId}).update(@.progressionRow).transacting(tx)
else
allPromises.push knex('user_progression').insert(@.progressionRow).transacting(tx)
@.updateUserGameParams =
is_daily_win: @.hasEarnedWinReward
play_count_reward_progress: play_count_reward_progress
win_count_reward_progress: win_count_reward_progress
has_maxed_play_count_rewards: hasReachedDailyPlayRewardMaxium
has_maxed_win_count_rewards: hasReachedDailyWinRewardMaxium
allPromises.push knex('user_games').where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
return Promise.all(allPromises)
.then ()->
hasEarnedWinReward = @.hasEarnedWinReward
hasEarnedPlayReward = @.hasEarnedPlayReward
hasEarnedFirstWinOfTheDayReward = @.hasEarnedFirstWinOfTheDayReward
# let's set up
promises = []
@.rewards = []
# if the game is "unscored", assume there are NO rewards
# otherwise, the game counter rewards might fire multiple times since game_count is not updated for unscored games
if not isUnscored
if hasEarnedFirstWinOfTheDayReward
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-WIN-OF-THE-DAY reward at #{@.progressionRow["game_count"]} games!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"daily win"
gold:CONFIG.FIRST_WIN_OF_DAY_GOLD_REWARD
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if hasEarnedPlayReward
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a PLAY-COUNT reward at #{@.progressionRow["game_count"]} games!"
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"play count"
# gold:10
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if @.progressionRow["game_count"] == 3 and not isUnscored
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-3-GAMES reward!"
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"first 3 games"
# gold:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if @.progressionRow["game_count"] == 10 and not isUnscored
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-10-GAMES reward!"
# # set up reward data
# reward = {
# type:"first 10 games"
# gold_amount:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"first 10 games"
# gold:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
if hasEarnedWinReward
gold_amount = CONFIG.WIN_BASED_GOLD_REWARD
# hasReachedDailyWinCountBonusLimit is disabled
if @.hasReachedDailyWinCountBonusLimit
gold_amount = 5
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a #{gold_amount}G WIN-COUNT reward!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"win count"
gold:gold_amount
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
@.codexChapterIdsEarned = SDK.Codex.chapterIdsAwardedForGameCount(@.progressionRow.game_count)
if @.codexChapterIdsEarned && @.codexChapterIdsEarned.length != 0
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned codex chapters #{@.codexChapterIdsEarned} reward!"
for codexChapterIdEarned in @.codexChapterIdsEarned
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"codex"
reward_type:"game count"
codex_chapter:codexChapterIdEarned
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
promises.push(InventoryModule.giveUserCodexChapter(txPromise,tx,userId,codexChapterIdEarned,MOMENT_NOW_UTC))
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
return Promise.all(promises)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
delete @.progressionRow.user_id
delete @.progressionRow.last_opponent_id
if @.progressionRow.last_win_at then @.progressionRow.last_win_at = moment.utc(@.progressionRow.last_win_at).valueOf()
if @.progressionRow.last_daily_win_at then @.progressionRow.last_daily_win_at = moment.utc(@.progressionRow.last_daily_win_at).valueOf()
if @.progressionRow.last_awarded_win_count_at then @.progressionRow.last_awarded_win_count_at = moment.utc(@.progressionRow.last_awarded_win_count_at).valueOf()
if @.progressionRow.play_awards_last_maxed_at then @.progressionRow.play_awards_last_maxed_at = moment.utc(@.progressionRow.play_awards_last_maxed_at).valueOf()
if @.progressionRow.win_awards_last_maxed_at then @.progressionRow.win_awards_last_maxed_at = moment.utc(@.progressionRow.win_awards_last_maxed_at).valueOf()
if @.progressionRow.updated_at then @.progressionRow.updated_at = moment.utc().valueOf(@.progressionRow.updated_at)
allPromises.push FirebasePromises.set(rootRef.child("user-progression").child(userId).child('game-counter'),@.progressionRow)
for key,val of @.updateUserGameParams
allPromises.push FirebasePromises.set(rootRef.child('user-games').child(userId).child(gameId).child(key),val)
# for reward in @.rewards
# rewardId = reward.id
# delete reward.id
# delete reward.user_id
# if reward.created_at then moment.utc().valueOf(reward.created_at)
# allPromises.push FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(rewardId),reward)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()-> Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} G:#{@.progressionRow["game_count"]} W:#{@.progressionRow["win_count"]} L:#{@.progressionRow["loss_count"]} U:#{@.progressionRow["unscored_count"]} progression recorded. Unscored: #{isUnscored?.toString().cyan}".green
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'progression')
return txPromise
###*
# Update a user's boss progression outcome of a boss battle
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw is this game a draw?
# @param {Object} gameSessionData data for the game played
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserBossProgressionWithGameOutcome: (userId,opponentId,isWinner,gameId,gameType,isUnscored,isDraw,gameSessionData,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# userId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid game ID - #{gameId}"))
if !gameType? or gameType != SDK.GameType.BossBattle
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid game game type - #{gameType}"))
if !isWinner
return Promise.resolve(false)
# Oppenent general must be part of the boss faction
opponentPlayerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSessionData,opponentId)
bossId = opponentPlayerSetupData?.generalId
sdkBossData = SDK.GameSession.getCardCaches().getCardById(bossId)
if (not bossId?) or (not sdkBossData?) or (sdkBossData.getFactionId() != SDK.Factions.Boss)
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid boss ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
this_obj.rewards = []
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow) ->
@.userRow = userRow
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
bossEventsRef = @.fbRootRef.child("boss-events")
return FirebasePromises.once(bossEventsRef,'value')
.then (bossEventsSnapshot)->
bossEventsData = bossEventsSnapshot.val()
# data will have
# event-id :
# event_id
# boss_id
# event_start
# event_end
# valid_end (event_end + 30 minute buffer)
@.matchingEventData = null
for eventId,eventData of bossEventsData
if !eventData.boss_id? or parseInt(eventData.boss_id) != bossId
continue
if !eventData.event_start? or eventData.event_start > MOMENT_NOW_UTC.valueOf()
continue
if !eventData.valid_end? or eventData.valid_end < MOMENT_NOW_UTC.valueOf()
continue
# Reaching here means we have a matching event
@.matchingEventData = eventData
@.matchingEventId = eventData.event_id
break
if not @.matchingEventData?
Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> no matching boss event id for user #{userId} in game #{gameId}.".red
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): No matching boss event - #{gameId}"))
.then ()->
return Promise.all([
@.userRow,
tx('user_bosses_defeated').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first()
])
.spread (userRow,userBossDefeatedRow)->
if (userBossDefeatedRow?)
return Promise.resolve()
allPromises = []
# Insert defeated boss row
defeatedBossData =
user_id: userId
boss_id: bossId
game_id: gameId
boss_event_id: @.matchingEventId
defeated_at: MOMENT_NOW_UTC.toDate()
allPromises.push(tx('user_bosses_defeated').insert(defeatedBossData))
Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a BOSS BATTLE reward!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"boss battle"
spirit_orbs:SDK.CardSet.Core
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
allPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# allPromises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
allPromises.push(InventoryModule.addBoosterPackToUser(txPromise,tx,userId,rewardData.spirit_orbs,"boss battle",@.matchingEventId))
allPromises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
return Promise.all(allPromises)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
# Insert defeated boss row
defeatedBossFBData =
boss_id: bossId
boss_event_id: @.matchingEventId
defeated_at: MOMENT_NOW_UTC.valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-bosses-defeated").child(userId).child(bossId),defeatedBossFBData)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserBossProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()-> Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} boss id:#{bossId}".green
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'progression')
return txPromise
###*
# Update a user's game counters
# @public
# @param {String} userId User ID for which to update.
# @param {Number} factionId Faction ID for which to update.
# @param {Number} generalId General ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw was game a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateGameCounters: (userId,factionId,generalId,isWinner,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
MOMENT_SEASON_START_UTC = MOMENT_NOW_UTC.clone().startOf('month')
this_obj = {}
return knex.transaction (tx)->
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_game_counters').where({
'user_id': userId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_faction_counters').where({
'user_id': userId
'faction_id': factionId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_general_counters').where({
'user_id': userId
'general_id': generalId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_season_counters').where({
'user_id': userId
'season_starting_at': MOMENT_SEASON_START_UTC.toDate()
'game_type': gameType
}).first().forUpdate()
])
.spread (userRow,counterRow,factionCounterRow,generalCounterRow,seasonCounterRow)->
allPromises = []
# game type counter
counter = DataAccessHelpers.updateCounterWithGameOutcome(counterRow,isWinner,isDraw,isUnscored)
counter.user_id = userId
counter.game_type = gameType
counter.created_at ?= MOMENT_NOW_UTC.toDate()
counter.updated_at = MOMENT_NOW_UTC.toDate()
if counterRow
allPromises.push knex('user_game_counters').where({
'user_id': userId
'game_type': gameType
}).update(counter).transacting(tx)
else
allPromises.push knex('user_game_counters').insert(counter).transacting(tx)
# faction counter
factionCounter = DataAccessHelpers.updateCounterWithGameOutcome(factionCounterRow,isWinner,isDraw,isUnscored)
factionCounter.user_id = userId
factionCounter.faction_id = factionId
factionCounter.game_type = gameType
factionCounter.created_at ?= MOMENT_NOW_UTC.toDate()
factionCounter.updated_at = MOMENT_NOW_UTC.toDate()
if factionCounterRow
allPromises.push knex('user_game_faction_counters').where({
'user_id': userId
'faction_id': factionId
'game_type': gameType
}).update(factionCounter).transacting(tx)
else
allPromises.push knex('user_game_faction_counters').insert(factionCounter).transacting(tx)
# general counter
generalCounter = DataAccessHelpers.updateCounterWithGameOutcome(generalCounterRow,isWinner,isDraw,isUnscored)
generalCounter.user_id = userId
generalCounter.general_id = generalId
generalCounter.game_type = gameType
generalCounter.created_at ?= MOMENT_NOW_UTC.toDate()
generalCounter.updated_at = MOMENT_NOW_UTC.toDate()
if generalCounterRow
allPromises.push knex('user_game_general_counters').where({
'user_id': userId
'general_id': generalId
'game_type': gameType
}).update(generalCounter).transacting(tx)
else
allPromises.push knex('user_game_general_counters').insert(generalCounter).transacting(tx)
# season counter
seasonCounter = DataAccessHelpers.updateCounterWithGameOutcome(seasonCounterRow,isWinner,isDraw,isUnscored)
seasonCounter.user_id = userId
seasonCounter.game_type = gameType
seasonCounter.season_starting_at ?= MOMENT_SEASON_START_UTC.toDate()
seasonCounter.created_at ?= MOMENT_NOW_UTC.toDate()
seasonCounter.updated_at = MOMENT_NOW_UTC.toDate()
if seasonCounterRow
allPromises.push knex('user_game_season_counters').where({
'user_id': userId
'season_starting_at': MOMENT_SEASON_START_UTC.toDate()
'game_type': gameType
}).update(seasonCounter).transacting(tx)
else
allPromises.push knex('user_game_season_counters').insert(seasonCounter).transacting(tx)
@.counter = counter
@.factionCounter = factionCounter
@.generalCounter = generalCounter
@.seasonCounter = seasonCounter
return Promise.all(allPromises)
# .then ()-> return DuelystFirebase.connect().getRootRef()
# .then (rootRef)->
# allPromises = []
# firebaseCounterData = DataAccessHelpers.restifyData _.clone(@.counter)
# delete firebaseCounterData.user_id
# delete firebaseCounterData.game_type
# firebaseFactionCounterData = DataAccessHelpers.restifyData _.clone(@.factionCounter)
# delete firebaseFactionCounterData.user_id
# delete firebaseFactionCounterData.faction_id
# delete firebaseFactionCounterData.game_type
# allPromises.push FirebasePromises.update(rootRef.child('user-game-counters').child(userId).child(gameType).child('stats'),firebaseCounterData)
# allPromises.push FirebasePromises.update(rootRef.child('user-game-counters').child(userId).child(gameType).child('factions').child(factionId),firebaseFactionCounterData)
# return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateGameCounters() -> ERROR, operation timeout for u:#{userId}"
throw e
.bind this_obj
.then ()->
Logger.module("UsersModule").debug "updateGameCounters() -> updated #{gameType} game counters for #{userId.blue}"
return {
counter:@.counter
faction_counter:@.factionCounter
general_counter:@.generalCounter
season_counter:@.seasonCounter
}
###*
# Update user's stats given a game.
# @public
# @param {String} userId User ID for which to process quests.
# @param {String} gameId Game ID for which to calculate stat changes
# @param {String} gameType Game type (see SDK.GameType)
# @param {String} gameData Plain object with game data
# @return {Promise} Promise that will post STATDATA on completion.
###
@updateUserStatsWithGame: (userId,gameId,gameType,gameData,systemTime) ->
# userId must be defined
if !userId or !gameId
return Promise.reject(new Error("Can not update user-stats : invalid user ID - #{userId} - or game ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
# Begin the promise rabbit hole
return DuelystFirebase.connect().getRootRef()
.bind {}
.then (fbRootRef) ->
@fbRootRef = fbRootRef
statsRef = @fbRootRef.child("user-stats").child(userId)
return new Promise (resolve, reject) ->
statsRef.once("value", (statsSnapshot) ->
return resolve(statsSnapshot.val())
)
.then (statsData) ->
try
playerData = UtilsGameSession.getPlayerDataForId(gameData,userId)
playerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameData,userId)
isWinner = playerData.isWinner
statsRef = @fbRootRef.child("user-stats").child(userId)
if !statsData
statsData = {}
# TODO: Temp until we have queue type defined in an architecture
queueName = gameType
if !statsData[queueName]
statsData[queueName] = {}
queueStatsData = statsData[queueName]
# -- First per queue stats
# Update player's global win streak
queueStatsData.winStreak ?= 0
if gameType != GameType.Casual
if isWinner
queueStatsData.winStreak += 1
else
queueStatsData.winStreak = 0
# -- Then per faction data
factionId = playerSetupData.factionId
if !queueStatsData[factionId]
queueStatsData[factionId] = {}
factionStatsData = queueStatsData[factionId]
factionStatsData.factionId = factionId
# Update per faction win count and play count
factionStatsData.playCount = (factionStatsData.playCount or 0) + 1
if (isWinner)
factionStatsData.winCount = (factionStatsData.winCount or 0) + 1
# Update cards played counts
if !factionStatsData.cardsPlayedCounts
factionStatsData.cardsPlayedCounts = {}
cardIndices = Object.keys(gameData.cardsByIndex)
for cardIndex in cardIndices
card = gameData.cardsByIndex[cardIndex]
if card.ownerId == userId
factionStatsData.cardsPlayedCounts[card.id] = (factionStatsData.cardsPlayedCounts[card.id] or 0) + 1
# Update discarded card counts
if !factionStatsData.cardsDiscardedCounts
factionStatsData.cardsDiscardedCounts = {}
# Update total turns played (this represents turns played by opponents as well)
totalTurns = 1 # for currentTurn
if gameData.turns
totalTurns += gameData.turns.length
factionStatsData.totalTurnsPlayed = (factionStatsData.totalTurnsPlayed or 0) + totalTurns
# Update play total stats
factionStatsData.totalDamageDealt = (factionStatsData.totalDamageDealt or 0) + playerData.totalDamageDealt
factionStatsData.totalDamageDealtToGeneral = (factionStatsData.totalDamageDealtToGeneral or 0) + playerData.totalDamageDealtToGeneral
factionStatsData.totalMinionsKilled = (factionStatsData.totalMinionsKilled or 0) + playerData.totalMinionsKilled
factionStatsData.totalMinionsPlayedFromHand = (factionStatsData.totalMinionsPlayedFromHand or 0) + playerData.totalMinionsPlayedFromHand
factionStatsData.totalMinionsSpawned = (factionStatsData.totalMinionsSpawned or 0) + playerData.totalMinionsSpawned
factionStatsData.totalSpellsCast = (factionStatsData.totalSpellsCast or 0) + playerData.totalSpellsCast
factionStatsData.totalSpellsPlayedFromHand = (factionStatsData.totalSpellsPlayedFromHand or 0) + playerData.totalSpellsPlayedFromHand
catch e
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> caught ERROR processing stats data for user #{userId}: #{e.message}".red
throw new Error("ERROR PROCESSING STATS DATA")
# Perform firebase transaction to update stats
return new Promise (resolve, reject) ->
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> UPDATING stats for user #{userId}"
# function to update quest list
onUpdateUserStatsTransaction = (userStatsTransactionData)->
# Don't care what the previous stats were, replace them with the updated version
userStatsTransactionData = statsData
userStatsTransactionData.updated_at = MOMENT_NOW_UTC.valueOf()
return userStatsTransactionData
# function to call when the quest update is complete
onUpdateUserStatsTransactionComplete = (error,committed,snapshot) ->
if error
return reject(error)
else if committed
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> updated user-stats committed for #{userId.blue}"
return resolve(snapshot.val())
else
return reject(new Errors.FirebaseTransactionDidNotCommitError("User Stats for #{userId.blue} did NOT COMMIT"))
# update users stats
statsRef.transaction(onUpdateUserStatsTransaction,onUpdateUserStatsTransactionComplete)
###*
# Completes a challenge for a user and unlocks any rewards !if! it's not already completed
# @public
# @param {String} userId User ID.
# @param {String} challenge_type type of challenge completed
# @param {Boolean} shouldProcessQuests should we attempt to process quests as a result of this challenge completion (since beginner quests include a challenge quest)
# @return {Promise} Promise that will resolve and give rewards if challenge hasn't been completed before, will resolve false and not give rewards if it has
###
@completeChallengeWithType: (userId,challengeType,shouldProcessQuests) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "completeChallengeWithType() -> user #{userId.blue} completed challenge type #{challengeType}."
knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).first()
.bind this_obj
.then (challengeRow)->
if challengeRow and challengeRow.completed_at
Logger.module("UsersModule").debug "completeChallengeWithType() -> user #{userId.blue} has already completed challenge type #{challengeType}."
return Promise.resolve(false)
else
txPromise = knex.transaction (tx)->
# lock user record while updating data
knex("users").where({'id':userId}).first('id').forUpdate().transacting(tx)
.bind this_obj
.then ()->
# give the user their rewards
goldReward = SDK.ChallengeFactory.getGoldRewardedForChallengeType(challengeType)
cardRewards = SDK.ChallengeFactory.getCardIdsRewardedForChallengeType(challengeType)
spiritReward = SDK.ChallengeFactory.getSpiritRewardedForChallengeType(challengeType)
boosterPackRewards = SDK.ChallengeFactory.getBoosterPacksRewardedForChallengeType(challengeType)
factionUnlockedReward = SDK.ChallengeFactory.getFactionUnlockedRewardedForChallengeType(challengeType)
@.rewards = []
@.challengeRow =
user_id:userId
challenge_id:challengeType
completed_at:MOMENT_NOW_UTC.toDate()
last_attempted_at: challengeRow?.last_attempted_at || MOMENT_NOW_UTC.toDate()
reward_ids:[]
is_unread:true
rewardPromises = []
if goldReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
gold:goldReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserGold(txPromise,tx,userId,goldReward,'challenge',challengeType))
if cardRewards
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
cards:cardRewards
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserCards(txPromise,tx,userId,cardRewards,'challenge'))
if spiritReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
spirit:spiritReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserSpirit(txPromise,tx,userId,spiritReward,'challenge'))
if boosterPackRewards
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
spirit_orbs:boosterPackRewards.length
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
_.each boosterPackRewards, (boosterPackData) ->
# Bound to array of reward promises
rewardPromises.push(InventoryModule.addBoosterPackToUser(txPromise,tx,userId,1,"soft",boosterPackData))
if factionUnlockedReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
unlocked_faction_id:factionUnlockedReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
@.challengeRow.reward_ids = _.map(@.rewards, (r)-> return r.id)
if challengeRow
rewardPromises.push knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(@.challengeRow).transacting(tx)
else
rewardPromises.push knex("user_challenges").insert(@.challengeRow).transacting(tx)
Promise.all(rewardPromises)
.then ()->
if @.challengeRow and shouldProcessQuests
return QuestsModule.updateQuestProgressWithCompletedChallenge(txPromise,tx,userId,challengeType,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then (questProgressResponse)->
if @.challengeRow and questProgressResponse?.rewards?.length > 0
Logger.module("UsersModule").debug "completeChallengeWithType() -> user #{userId.blue} completed challenge quest rewards count: #{ questProgressResponse?.rewards.length}"
for reward in questProgressResponse.rewards
@.rewards.push(reward)
@.challengeRow.reward_ids.push(reward.id)
return knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(
reward_ids:@.challengeRow.reward_ids
).transacting(tx)
.then ()->
return Promise.all([
DuelystFirebase.connect().getRootRef(),
@.challengeRow,
@.rewards
])
.spread (rootRef,challengeRow,rewards)->
allPromises = []
if challengeRow?
delete challengeRow.user_id
# delete challengeRow.challenge_id
if challengeRow.last_attempted_at then challengeRow.last_attempted_at = moment.utc(challengeRow.last_attempted_at).valueOf()
if challengeRow.completed_at then challengeRow.completed_at = moment.utc(challengeRow.completed_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-challenge-progression").child(userId).child(challengeType),challengeRow)
@.challengeRow = challengeRow
# if rewards?
# for reward in rewards
# reward_id = reward.id
# delete reward.id
# delete reward.user_id
# reward.created_at = moment.utc(reward.created_at).valueOf()
# allPromises.push FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(reward_id),reward)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
return txPromise
.then ()->
Logger.module("UsersModule").timeEnd "completeChallengeWithType() -> user #{userId.blue} completed challenge type #{challengeType}."
responseData = null
if @.challengeRow
responseData = { challenge: @.challengeRow }
if @.rewards
responseData.rewards = @.rewards
return responseData
###*
# Marks a challenge as attempted.
# @public
# @param {String} userId User ID.
# @param {String} challenge_type type of challenge
# @return {Promise} Promise that will resolve on completion
###
@markChallengeAsAttempted: (userId,challengeType) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "markChallengeAsAttempted() -> user #{userId.blue} attempted challenge type #{challengeType}."
txPromise = knex.transaction (tx)->
# lock user and challenge row
Promise.all([
knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).first().forUpdate().transacting(tx)
knex("users").where({'id':userId}).first('id').forUpdate().transacting(tx)
])
.bind this_obj
.spread (challengeRow)->
@.challengeRow = challengeRow
if @.challengeRow?
@.challengeRow.last_attempted_at = MOMENT_NOW_UTC.toDate()
return knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(@.challengeRow).transacting(tx)
else
@.challengeRow =
user_id:userId
challenge_id:challengeType
last_attempted_at:MOMENT_NOW_UTC.toDate()
return knex("user_challenges").insert(@.challengeRow).transacting(tx)
.then ()-> DuelystFirebase.connect().getRootRef()
.then (rootRef)->
allPromises = []
if @.challengeRow?
delete @.challengeRow.user_id
# delete @.challengeRow.challenge_id
if @.challengeRow.last_attempted_at then @.challengeRow.last_attempted_at = moment.utc(@.challengeRow.last_attempted_at).valueOf()
if @.challengeRow.completed_at then @.challengeRow.completed_at = moment.utc(@.challengeRow.completed_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-challenge-progression").child(userId).child(challengeType),@.challengeRow)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
responseData = { challenge: @.challengeRow }
return responseData
return txPromise
###*
# Iterate core new player progression up by one point if all requirements met, or generate missing quests if any required quests are missing from current/complete quest list for this user.
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@iterateNewPlayerCoreProgression: (userId) ->
knex("user_new_player_progression").where('user_id',userId).andWhere('module_name',NewPlayerProgressionModuleLookup.Core).first()
.bind {}
.then (moduleProgression)->
stage = NewPlayerProgressionStageEnum[moduleProgression?.stage] || NewPlayerProgressionStageEnum.Tutorial
# if we're at the final stage, just return
if stage.value >= NewPlayerProgressionHelper.FinalStage.value
return Promise.resolve()
Promise.all([
knex("user_quests").where('user_id',userId).select()
knex("user_quests_complete").where('user_id',userId).select()
])
.bind @
.spread (quests,questsComplete)->
beginnerQuests = NewPlayerProgressionHelper.questsForStage(stage)
# exclude non-required beginner quests for this tage
beginnerQuests = _.filter beginnerQuests, (q)-> return q.isRequired
# if we have active quests, check that none are beginner for current stage
if quests?.length > 0
# let's see if any beginner quests for this stage are still in progress
beginnerQuestInProgress = _.find(quests,(q)->
return _.find(beginnerQuests,(bq)-> bq.id == q.quest_type_id)
)
# if any beginner quests for this stage are still in progress, DO NOTHING
if beginnerQuestInProgress
return Promise.resolve()
# let's see if all beginner quests for this stage are completed
beginnerQuestsComplete = _.filter(questsComplete,(q)->
return _.find(beginnerQuests,(bq)-> bq.id == q.quest_type_id)
)
# if any beginner quests for this stage have NOT been completed, we have a problem... looks like we need to generate these quests
if beginnerQuestsComplete?.length < beginnerQuests.length
# throw new Error("Invalid state: user never received all required stage quests")
Logger.module('SDK').warn "iterateNewPlayerCoreProgression() -> Invalid state: user #{userId.blue} never received all required stage #{stage.key} quests"
return QuestsModule.generateBeginnerQuests(userId)
.bind {}
.then (questData)->
if questData
@.questData = questData
.catch Errors.NoNeedForNewBeginnerQuestsError, (e)->
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> no need for new quests at #{nextStage.key} for #{userId.blue}"
.then ()->
@.progressionData = moduleProgression
return @
# if we're here, it means all required beginner quests have been completed up to here...
# so let's push the core stage forward
# calculate the next linear stage point for core progression
nextStage = null
for s in NewPlayerProgressionStageEnum.enums
if s.value > stage.value
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> from stage #{stage.key} to next stage #{s.key} for #{userId.blue}"
nextStage = s
break
# update current stage and generate any new beginner quests
return UsersModule.setNewPlayerFeatureProgression(userId,NewPlayerProgressionModuleLookup.Core,nextStage.key)
.bind {}
.then (progressionData) ->
@.progressionData = progressionData
return QuestsModule.generateBeginnerQuests(userId)
.then (questData)->
if questData
@.questData = questData
.catch Errors.NoNeedForNewBeginnerQuestsError, (e)->
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> no need for new quests at #{nextStage.key} for #{userId.blue}"
.then ()->
return @
.then (responseData)->
return responseData
###*
# Sets user feature progression for a module
# @public
# @param {String} userId User ID.
# @param {String} moduleName Arbitrary name of a module
# @param {String} stage Arbitrary key for a progression item
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@setNewPlayerFeatureProgression: (userId,moduleName,stage) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setNewPlayerFeatureProgression() -> user #{userId.blue} marking module #{moduleName} as #{stage}."
if moduleName == NewPlayerProgressionModuleLookup.Core and not NewPlayerProgressionStageEnum[stage]?
return Promise.reject(new Errors.BadRequestError("Invalid core new player stage"))
txPromise = knex.transaction (tx)->
tx("user_new_player_progression").where({'user_id':userId,'module_name':moduleName}).first().forUpdate()
.bind this_obj
.then (progressionRow)->
# core stage has some special rules
if moduleName == NewPlayerProgressionModuleLookup.Core
currentStage = progressionRow?.stage || NewPlayerProgressionStageEnum.Tutorial
if NewPlayerProgressionStageEnum[stage].value < currentStage.value
throw new Errors.BadRequestError("Can not roll back to a previous core new player stage")
@.progressionRow = progressionRow
queryPromise = null
if progressionRow and progressionRow.stage == stage
Logger.module("UsersModule").error "setNewPlayerFeatureProgression() -> ERROR: requested same stage: #{stage}."
throw new Errors.BadRequestError("New player progression stage already at the requested stage")
else if progressionRow
# TODO: this never gets called, here 2 gets called twice for tutorial -> tutorialdone
@.progressionRow.stage = stage
@.progressionRow.updated_at = MOMENT_NOW_UTC.toDate()
queryPromise = tx("user_new_player_progression").where({'user_id':userId,'module_name':moduleName}).update({
stage: @.progressionRow.stage,
updated_at: @.progressionRow.updated_at
})
else
@.progressionRow =
user_id:userId
module_name:moduleName
stage:stage
queryPromise = tx("user_new_player_progression").insert(@.progressionRow)
return queryPromise
.then (updateCount)->
if updateCount
SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setNewPlayerFeatureProgression() -> user #{userId.blue} marking module #{moduleName} as #{stage}."
return @.progressionRow
return txPromise
###*
# Set a new portrait for a user
# @public
# @param {String} userId User ID.
# @param {String} portraitId Portrait ID
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@setPortraitId: (userId,portraitId) ->
# userId must be defined
if !userId?
return Promise.reject(new Errors.NotFoundError("Can not setPortraitId(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setPortraitId() -> user #{userId.blue}."
txPromise = knex.transaction (tx)->
InventoryModule.isAllowedToUseCosmetic(txPromise, tx, userId, portraitId)
.bind this_obj
.then ()->
return knex("users").where({'id':userId}).update(
portrait_id:portraitId
)
.then (updateCount)->
if updateCount == 0
throw new Errors.NotFoundError("User with id #{userId} not found")
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.set(rootRef.child('users').child(userId).child('presence').child('portrait_id'),portraitId)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setPortraitId() -> user #{userId.blue}."
return portraitId
###*
# Set a the preferred Battle Map for a user
# @public
# @param {String} userId User ID.
# @param {String} battleMapId Battle Map ID
# @return {Promise} Promise that will resolve when complete
###
@setBattleMapId: (userId,battleMapId) ->
# userId must be defined
if !userId?
return Promise.reject(new Errors.NotFoundError("Can not setPortraitId(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setBattleMapId() -> user #{userId.blue}."
txPromise = knex.transaction (tx)->
checkForInventoryPromise = if battleMapId != null then InventoryModule.isAllowedToUseCosmetic(txPromise, tx, userId, battleMapId) else Promise.resolve(true)
checkForInventoryPromise
.bind this_obj
.then ()->
return tx("users").where({'id':userId}).update(
battle_map_id:battleMapId
)
.then (updateCount)->
if updateCount == 0
throw new Errors.NotFoundError("User with id #{userId} not found")
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.set(rootRef.child('users').child(userId).child('battle_map_id'),battleMapId)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setBattleMapId() -> user #{userId.blue}."
return battleMapId
###*
# Add a small in-game notification for a user
# @public
# @param {String} userId User ID.
# @param {String} message What message to show
# @param {String} type Message type
# @return {Promise} Promise that will resolve when complete
###
@inGameNotify: (userId,message,type=null) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
return Promise.resolve()
.bind {}
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.push(rootRef.child("user-notifications").child(userId),{message:message,created_at:moment().utc().valueOf(),type:type})
@___hardWipeUserData: (userId)->
Logger.module("UsersModule").time "___hardWipeUserData() -> WARNING: hard wiping #{userId.blue}".red
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef)->
return Promise.all([
FirebasePromises.remove(fbRootRef.child('user-aggregates').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-arena-run').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-challenge-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-decks').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-faction-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-games').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-games').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-game-job-status').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-inventory').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-logs').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-matchmaking-errors').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-news').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-quests').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-ranking').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-rewards').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-stats').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-transactions').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-achievements').child(userId)),
knex("user_cards").where('user_id',userId).delete(),
knex("user_card_collection").where('user_id',userId).delete(),
knex("user_card_log").where('user_id',userId).delete(),
knex("user_challenges").where('user_id',userId).delete(),
knex("user_charges").where('user_id',userId).delete(),
knex("user_currency_log").where('user_id',userId).delete(),
knex("user_decks").where('user_id',userId).delete(),
knex("user_faction_progression").where('user_id',userId).delete(),
knex("user_faction_progression_events").where('user_id',userId).delete(),
knex("user_games").where('user_id',userId).delete(),
knex("user_gauntlet_run").where('user_id',userId).delete(),
knex("user_gauntlet_run_complete").where('user_id',userId).delete(),
knex("user_gauntlet_tickets").where('user_id',userId).delete(),
knex("user_gauntlet_tickets_used").where('user_id',userId).delete(),
knex("user_progression").where('user_id',userId).delete(),
knex("user_progression_days").where('user_id',userId).delete(),
knex("user_quests").where('user_id',userId).delete(),
knex("user_quests_complete").where('user_id',userId).delete(),
knex("user_rank_events").where('user_id',userId).delete(),
knex("user_rank_history").where('user_id',userId).delete(),
knex("user_rewards").where('user_id',userId).delete(),
knex("user_spirit_orbs").where('user_id',userId).delete(),
knex("user_spirit_orbs_opened").where('user_id',userId).delete(),
knex("user_codex_inventory").where('user_id',userId).delete(),
knex("user_new_player_progression").where('user_id',userId).delete(),
knex("user_achievements").where('user_id',userId).delete(),
knex("users").where('id',userId).update({
ltv:0,
rank:30,
rank_created_at:null,
rank_starting_at:null,
rank_stars:0,
rank_stars_required:1,
rank_updated_at:null,
rank_win_streak:0,
rank_top_rank:null,
rank_is_unread:false,
top_rank:null,
top_rank_starting_at:null,
top_rank_updated_at:null,
wallet_gold:0,
wallet_spirit:0,
wallet_cores:0,
wallet_updated_at:null,
total_gold_earned:0,
total_spirit_earned:0,
daily_quests_generated_at:null,
daily_quests_updated_at:null
})
])
.then ()->
Logger.module("UsersModule").timeEnd "___hardWipeUserData() -> WARNING: hard wiping #{userId.blue}".red
###*
# Sets user feature progression for a module
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@___snapshotUserData: (userId)->
Logger.module("UsersModule").time "___snapshotUserData() -> retrieving data for user ID #{userId.blue}".green
# List of the columns we want to grab from the users table, is everything except password
userTableColumns = ["id","created_at","updated_at","last_session_at","session_count","username_updated_at",
"email_verified_at","password_updated_at","invite_code","ltv","purchase_count","last_purchase_at","rank",
"rank_created_at","rank_starting_at","rank_stars","rank_stars_required","rank_delta","rank_top_rank",
"rank_updated_at","rank_win_streak","rank_is_unread","top_rank","top_rank_starting_at","top_rank_updated_at",
"daily_quests_generated_at","daily_quests_updated_at","achievements_last_read_at","wallet_gold",
"wallet_spirit","wallet_cores","wallet_updated_at","total_gold_earned","total_spirit_earned","buddy_count",
"tx_count","synced_firebase_at","stripe_customer_id","card_last_four_digits","card_updated_at",
"top_gauntlet_win_count","portrait_id","total_gold_tips_given","referral_code","is_suspended","suspended_at",
"suspended_memo","top_rank_ladder_position","top_rank_rating","is_bot"];
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef)->
return Promise.all([
FirebasePromises.once(fbRootRef.child('user-aggregates').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-arena-run').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-challenge-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-decks').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-faction-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-games').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-game-job-status').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-inventory').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-logs').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-matchmaking-errors').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-news').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-quests').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-ranking').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-rewards').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-stats').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-transactions').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-achievements').child(userId),"value"),
knex("user_cards").where('user_id',userId).select(),
knex("user_card_collection").where('user_id',userId).select(),
knex("user_card_log").where('user_id',userId).select(),
knex("user_challenges").where('user_id',userId).select(),
knex("user_charges").where('user_id',userId).select(),
knex("user_currency_log").where('user_id',userId).select(),
knex("user_decks").where('user_id',userId).select(),
knex("user_faction_progression").where('user_id',userId).select(),
knex("user_faction_progression_events").where('user_id',userId).select(),
knex("user_games").where('user_id',userId).select(),
knex("user_gauntlet_run").where('user_id',userId).select(),
knex("user_gauntlet_run_complete").where('user_id',userId).select(),
knex("user_gauntlet_tickets").where('user_id',userId).select(),
knex("user_gauntlet_tickets_used").where('user_id',userId).select(),
knex("user_progression").where('user_id',userId).select(),
knex("user_progression_days").where('user_id',userId).select(),
knex("user_quests").where('user_id',userId).select(),
knex("user_quests_complete").where('user_id',userId).select(),
knex("user_rank_events").where('user_id',userId).select(),
knex("user_rank_history").where('user_id',userId).select(),
knex("user_rewards").where('user_id',userId).select(),
knex("user_spirit_orbs").where('user_id',userId).select(),
knex("user_spirit_orbs_opened").where('user_id',userId).select(),
knex("user_codex_inventory").where('user_id',userId).select(),
knex("user_new_player_progression").where('user_id',userId).select(),
knex("user_achievements").where('user_id',userId).select(),
knex("user_cosmetic_chests").where('user_id',userId).select(),
knex("user_cosmetic_chests_opened").where('user_id',userId).select(),
knex("user_cosmetic_chest_keys").where('user_id',userId).select(),
knex("user_cosmetic_chest_keys_used").where('user_id',userId).select(),
knex("users").where('id',userId).first(userTableColumns)
])
.spread (fbUserAggregates,fbUserArenaRun,fbUserChallengeProgression,fbUserDecks,fbUserFactionProgression,fbUserGames,fbUserGameJobStatus,fbUserInventory,fbUserLogs,
fbUserMatchmakingErrors,fbUserNews,fbUserProgression,fbUserQuests,fbUserRanking,fbUserRewards,fbUserStats,fbUserTransactions,fbUserAchievements,
sqlUserCards,sqlUserCardCollection,sqlUserCardLog,sqlUserChallenges,sqlUserCharges,sqlUserCurrencyLog,sqlUserDecks,sqlUserFactionProgression,sqlUserFactionProgressionEvents,
sqlUserGames,sqlUserGauntletRun,sqlUserGauntletRunComplete,sqlUserGauntletTickets,sqlUserGauntletTicketsUsed,sqlUserProgression,
sqlUserProgressionDays,sqlUserQuests,sqlUserQuestsComplete,sqlUserRankEvents,sqlUserRankHistory,sqlUserRewards,sqlUserSpiritOrbs,sqlUserSpiritOrbsOpened,
sqlUserCodexInventory,sqlUserNewPlayerProgression,sqlUserAchievements,sqlUserChestRows,sqlUserChestOpenedRows,sqlUserChestKeyRows,sqlUserChestKeyUsedRows,sqlUserRow)->
userSnapshot = {
firebase: {}
sql: {}
}
userSnapshot.firebase.fbUserAggregates = fbUserAggregates?.val()
userSnapshot.firebase.fbUserArenaRun = fbUserArenaRun?.val()
userSnapshot.firebase.fbUserChallengeProgression = fbUserChallengeProgression?.val()
userSnapshot.firebase.fbUserDecks = fbUserDecks?.val()
userSnapshot.firebase.fbUserFactionProgression = fbUserFactionProgression?.val()
userSnapshot.firebase.fbUserGames = fbUserGames?.val()
userSnapshot.firebase.fbUserGameJobStatus = fbUserGameJobStatus?.val()
userSnapshot.firebase.fbUserInventory = fbUserInventory?.val()
userSnapshot.firebase.fbUserLogs = fbUserLogs?.val()
userSnapshot.firebase.fbUserMatchmakingErrors = fbUserMatchmakingErrors?.val()
userSnapshot.firebase.fbUserNews = fbUserNews?.val()
userSnapshot.firebase.fbUserProgression = fbUserProgression?.val()
userSnapshot.firebase.fbUserQuests = fbUserQuests?.val()
userSnapshot.firebase.fbUserRanking = fbUserRanking?.val()
userSnapshot.firebase.fbUserRewards = fbUserRewards?.val()
userSnapshot.firebase.fbUserStats = fbUserStats?.val()
userSnapshot.firebase.fbUserTransactions = fbUserTransactions?.val()
userSnapshot.firebase.fbUserAchievements = fbUserAchievements?.val()
userSnapshot.sql.sqlUserCards = sqlUserCards
userSnapshot.sql.sqlUserCardCollection = sqlUserCardCollection
userSnapshot.sql.sqlUserCardLog = sqlUserCardLog
userSnapshot.sql.sqlUserChallenges = sqlUserChallenges
userSnapshot.sql.sqlUserCharges = sqlUserCharges
userSnapshot.sql.sqlUserCurrencyLog = sqlUserCurrencyLog
userSnapshot.sql.sqlUserFactionProgression = sqlUserFactionProgression
userSnapshot.sql.sqlUserFactionProgressionEvents = sqlUserFactionProgressionEvents
userSnapshot.sql.sqlUserGames = sqlUserGames
userSnapshot.sql.sqlUserGauntletRun = sqlUserGauntletRun
userSnapshot.sql.sqlUserGauntletRunComplete = sqlUserGauntletRunComplete
userSnapshot.sql.sqlUserGauntletTickets = sqlUserGauntletTickets
userSnapshot.sql.sqlUserGauntletTicketsUsed = sqlUserGauntletTicketsUsed
userSnapshot.sql.sqlUserProgression = sqlUserProgression
userSnapshot.sql.sqlUserProgressionDays = sqlUserProgressionDays
userSnapshot.sql.sqlUserQuests = sqlUserQuests
userSnapshot.sql.sqlUserQuestsComplete = sqlUserQuestsComplete
userSnapshot.sql.sqlUserRankEvents = sqlUserRankEvents
userSnapshot.sql.sqlUserRankHistory = sqlUserRankHistory
userSnapshot.sql.sqlUserRewards = sqlUserRewards
userSnapshot.sql.sqlUserSpiritOrbs = sqlUserSpiritOrbs
userSnapshot.sql.sqlUserSpiritOrbsOpened = sqlUserSpiritOrbsOpened
userSnapshot.sql.sqlUserCodexInventory = sqlUserCodexInventory
userSnapshot.sql.sqlUserNewPlayerProgression = sqlUserNewPlayerProgression
userSnapshot.sql.sqlUserAchievements = sqlUserAchievements
userSnapshot.sql.sqlUserChestRows = sqlUserChestRows
userSnapshot.sql.sqlUserChestOpenedRows = sqlUserChestOpenedRows
userSnapshot.sql.sqlUserChestKeyRows = sqlUserChestKeyRows
userSnapshot.sql.sqlUserChestKeyUsedRows = sqlUserChestKeyUsedRows
userSnapshot.sql.sqlUserRow = sqlUserRow
Logger.module("UsersModule").timeEnd "___snapshotUserData() -> retrieving data for user ID #{userId.blue}".green
return userSnapshot
###*
# Tip your opponent for a specific game
# @public
# @param {String} userId User ID.
# @param {String} gameId Game ID to tip for
# @return {Promise} Promise that will resolve when complete
###
@tipAnotherPlayerForGame: (userId,gameId,goldAmount=5)->
MOMENT_NOW_UTC = moment().utc()
Promise.all([
knex("users").where('id',userId).first('username','wallet_gold')
knex("user_games").where({user_id:userId,game_id:gameId}).first()
]).spread (userRow,gameRow)->
# we need a game row
if not gameRow?
throw new Errors.NotFoundError("Player game not found")
# game must be less than a day old
timeSinceCreated = moment.duration(MOMENT_NOW_UTC.diff(moment.utc(gameRow.created_at)))
if timeSinceCreated.asDays() > 1.0
throw new Errors.BadRequestError("Game is too old")
# only the winner can tip
if not gameRow.is_winner
throw new Errors.BadRequestError("Only the winner can tip")
# we don't allow multiple tips
if gameRow.gold_tip_amount?
throw new Errors.AlreadyExistsError("Tip already given")
# we don't allow multiple tips
if userRow?.wallet_gold < goldAmount
throw new Errors.InsufficientFundsError("Not enough GOLD to tip")
# don't allow tips in friendly or sp games
if gameRow.game_type == "friendly" || gameRow.game_type == "single_player"
throw new Errors.BadRequestError("Can not tip in friendly or single player games")
# grab the opponent id so we know who to tip
playerId = gameRow.opponent_id
txPromise = knex.transaction (tx)->
Promise.all([
# debit user's gold
InventoryModule.debitGoldFromUser(txPromise,tx,userId,-goldAmount,"gold tip to #{gameId}:#{playerId}")
# give opponent gold
InventoryModule.giveUserGold(txPromise,tx,playerId,goldAmount,"gold tip from #{gameId}:#{userId}")
# update user game record
knex("user_games").where({user_id:userId,game_id:gameId}).update('gold_tip_amount',goldAmount).transacting(tx)
# update master game record
knex("games").where({id:gameId}).increment('gold_tip_amount',goldAmount).transacting(tx)
# update master game record
knex("users").where({id:userId}).increment('total_gold_tips_given',goldAmount).transacting(tx)
]).then ()->
return Promise.all([
SyncModule._bumpUserTransactionCounter(tx,userId)
SyncModule._bumpUserTransactionCounter(tx,playerId)
])
.then ()-> return UsersModule.inGameNotify(playerId,"#{userRow.username} tipped you #{goldAmount} GOLD","gold tip")
.then tx.commit
.catch tx.rollback
return txPromise
###*
# Suspend a user account
# @public
# @param {String} userId User ID.
# @param {String} reasonMemo Why is this user suspended?
# @return {Promise} Promise that will resolve when complete
###
@suspendUser: (userId,reasonMemo)->
return knex("users").where('id',userId).update({
is_suspended: true
suspended_at: moment().utc().toDate()
suspended_memo: reasonMemo
})
###*
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@isEligibleForTwitchDrop: (userId, itemId = null)->
return Promise.resolve(true)
###*
# Export a user account data as is (for user requested account export)
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@exportUser: (userId)->
return UsersModule.___snapshotUserData(userId)
.then (userData) ->
# we may want to filter out selective data at this point before exporting
return userData
.catch (e) ->
Logger.module("UsersModule").error "exportUser() -> #{e.message}".red
return null
###*
# Anonymize a user (prevents future logins and removes PID)
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@anonymizeUser: (userId)->
randomString = crypto.randomBytes(Math.ceil(32)).toString('hex').slice(0,64)
timestamp = moment().utc().valueOf()
randomEmail = <EMAIL>"
randomUser = "#{timestamp}-#{randomString}-anon"
return UsersModule.userDataForId(userId)
.then (userRow) ->
if !userRow
throw new Errors.NotFoundError()
return Promise.all([
UsersModule.disassociateSteamId(userId),
UsersModule.changeEmail(userId, randomEmail),
UsersModule.changeUsername(userId, randomUser, true)
])
.catch (e) ->
# catch the error if any of the functions above fail and continue with suspending the user
Logger.module("UsersModule").error "anonymizeUser() partial failure -> #{e.message}".red
.then () ->
return UsersModule.suspendUser(userId, "User requested account deletion.")
module.exports = UsersModule
| true | Promise = require 'bluebird'
util = require 'util'
crypto = require 'crypto'
FirebasePromises = require '../firebase_promises'
DuelystFirebase = require '../duelyst_firebase_module'
fbUtil = require '../../../app/common/utils/utils_firebase.js'
Logger = require '../../../app/common/logger.coffee'
colors = require 'colors'
validator = require 'validator'
uuid = require 'node-uuid'
moment = require 'moment'
_ = require 'underscore'
SyncModule = require './sync'
MigrationsModule = require './migrations'
InventoryModule = require './inventory'
QuestsModule = require './quests'
GamesModule = require './games'
RiftModule = require './rift'
RiftModule = require './gauntlet'
CosmeticChestsModule = require './cosmetic_chests'
CONFIG = require '../../../app/common/config.js'
Errors = require '../custom_errors'
mail = require '../../mailer'
knex = require("../data_access/knex")
config = require '../../../config/config.js'
generatePushId = require '../../../app/common/generate_push_id'
DataAccessHelpers = require('./helpers')
hashHelpers = require '../hash_helpers.coffee'
Promise.promisifyAll(mail)
AnalyticsUtil = require '../../../app/common/analyticsUtil.coffee'
{version} = require '../../../version.json'
# redis
{Redis, Jobs, GameManager} = require '../../redis/'
# SDK imports
SDK = require '../../../app/sdk'
Cards = require '../../../app/sdk/cards/cardsLookupComplete'
CardSetFactory = require '../../../app/sdk/cards/cardSetFactory'
RankFactory = require '../../../app/sdk/rank/rankFactory'
Entity = require '../../../app/sdk/entities/entity'
QuestFactory = require '../../../app/sdk/quests/questFactory'
QuestType = require '../../../app/sdk/quests/questTypeLookup'
GameType = require '../../../app/sdk/gameType'
GameFormat = require '../../../app/sdk/gameFormat'
UtilsGameSession = require '../../../app/common/utils/utils_game_session.coffee'
NewPlayerProgressionHelper = require '../../../app/sdk/progression/newPlayerProgressionHelper'
NewPlayerProgressionStageEnum = require '../../../app/sdk/progression/newPlayerProgressionStageEnum'
NewPlayerProgressionModuleLookup = require '../../../app/sdk/progression/newPlayerProgressionModuleLookup'
{Redis, Jobs} = require '../../redis/'
class UsersModule
###*
# MAX number of daily games to count for play rewards.
# @public
###
@DAILY_REWARD_GAME_CAP: 200
###*
# Hours until FWOTD is available again.
# @public
###
@DAILY_WIN_CYCLE_HOURS: 22
###*
# Retrieve an active and valid global referral code.
# @public
# @param {String} code Referral Code
# @return {Promise} Promise that will return true or throw InvalidReferralCodeError exception .
###
@getValidReferralCode: (code) ->
# validate referral code and force it to lower case
code = code?.toLowerCase().trim()
if not validator.isLength(code,4)
return Promise.reject(new Errors.InvalidReferralCodeError("invalid referral code"))
MOMENT_NOW_UTC = moment().utc()
# we check if the referral code is a UUID so that anyone accidentally using invite codes doesn't error out
if validator.isUUID(code)
return Promise.resolve({})
return knex("referral_codes").where('code',code).first()
.then (referralCodeRow)->
if referralCodeRow? and
referralCodeRow?.is_active and
(!referralCodeRow?.signup_limit? or referralCodeRow?.signup_count < referralCodeRow?.signup_limit) and
(!referralCodeRow?.expires_at? or moment.utc(referralCodeRow?.expires_at).isAfter(MOMENT_NOW_UTC))
return referralCodeRow
else
throw new Errors.InvalidReferralCodeError("referral code not found")
###*
# Check if an invite code is valid.
# @public
# @param {String} inviteCode Invite Code
# @return {Promise} Promise that will return true or throw InvalidInviteCodeError exception .
###
@isValidInviteCode: (inviteCode,cb) ->
inviteCode ?= null
return knex("invite_codes").where('code',inviteCode).first()
.then (codeRow)->
if !config.get("inviteCodesActive") || codeRow? || inviteCode is "kumite14" || inviteCode is "keysign789"
return true
else
throw new Errors.InvalidInviteCodeError("Invalid Invite Code")
###*
# Create a user record for the specified parameters.
# @public
# @param {String} email User's email (no longer strictly required)
# @param {String} username User's username
# @param {String} password PI:PASSWORD:<PASSWORD>END_PI
# @param {String} inviteCode Invite code used
# @return {Promise} Promise that will return the userId on completion.
###
@createNewUser: (email = null,username,password,inviteCode = 'PI:PASSWORD:<PASSWORD>END_PI',referralCode,campaignData,registrationSource = null)->
# validate referral code and force it to lower case
referralCode = referralCode?.toLowerCase().trim()
if referralCode? and not validator.isLength(referralCode,3)
return Promise.reject(new Errors.InvalidReferralCodeError("invalid referral code"))
if email then email = email.toLowerCase()
userId = generatePushId()
username = username.toLowerCase()
inviteCode ?= null
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
return knex("invite_codes").where('code',inviteCode).first()
.bind this_obj
.then (inviteCodeRow)->
if config.get("inviteCodesActive") and !inviteCodeRow and inviteCode != "kumite14" and inviteCode != "keysign789"
throw new Errors.InvalidInviteCodeError("Invite code not found")
referralCodePromise = Promise.resolve(null)
# we check if the referral code is a UUID so that anyone accidentally using invite codes doesn't error out
if referralCode? and not validator.isUUID(referralCode)
referralCodePromise = UsersModule.getValidReferralCode(referralCode)
return Promise.all([
UsersModule.userIdForEmail(email),
UsersModule.userIdForUsername(username),
referralCodePromise
])
.spread (idForEmail,idForUsername,referralCodeRow)->
if idForEmail
throw new Errors.AlreadyExistsError("Email already registered")
if idForUsername
throw new Errors.AlreadyExistsError("Username not available")
@.referralCodeRow = referralCodeRow
return hashHelpers.generateHash(password)
.then (passwordHash)->
return knex.transaction (tx) =>
userRecord =
id:userId
email:email # email maybe equals null here
username:username
password:PI:PASSWORD:<PASSWORD>END_PI
created_at:MOMENT_NOW_UTC.toDate()
if registrationSource
userRecord.registration_source = registrationSource
if config.get("inviteCodesActive")
userRecord.invite_code = inviteCode
# Add campaign data to userRecord
if campaignData?
userRecord.campaign_source ?= campaignData.campaign_source
userRecord.campaign_medium ?= campaignData.campaign_medium
userRecord.campaign_term ?= campaignData.campaign_term
userRecord.campaign_content ?= campaignData.campaign_content
userRecord.campaign_name ?= campaignData.campaign_name
userRecord.referrer ?= campaignData.referrer
updateReferralCodePromise = Promise.resolve()
if @.referralCodeRow?
Logger.module("USERS").debug "createNewUser() -> using referral code #{referralCode.yellow} for user #{userId.blue} ", @.referralCodeRow.params
userRecord.referral_code = referralCode
updateReferralCodePromise = knex("referral_codes").where('code',referralCode).increment('signup_count',1).transacting(tx)
if @.referralCodeRow.params?.gold
userRecord.wallet_gold ?= 0
userRecord.wallet_gold += @.referralCodeRow.params?.gold
if @.referralCodeRow.params?.spirit
userRecord.wallet_spirit ?= 0
userRecord.wallet_spirit += @.referralCodeRow.params?.spirit
Promise.all([
# user record
knex('users').insert(userRecord).transacting(tx),
# update referal code table
updateReferralCodePromise
])
.bind this_obj
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
# collect all the firebase update promises here
allPromises = []
userData = {
id: userId
username: username
created_at: MOMENT_NOW_UTC.valueOf()
presence: {
rank: 30
username: username
status: "offline"
}
tx_counter: {
count:0
}
# all new users have accepted EULA before signing up
hasAcceptedEula: false
hasAcceptedSteamEula: false
}
starting_gold = @.referralCodeRow?.params?.gold || 0
starting_spirit = @.referralCodeRow?.params?.spirit || 0
allPromises.push(FirebasePromises.set(rootRef.child('users').child(userId),userData))
allPromises.push(FirebasePromises.set(rootRef.child('username-index').child(username),userId))
allPromises.push(FirebasePromises.set(rootRef.child('user-inventory').child(userId).child('wallet'),{
gold_amount:starting_gold
spirit_amount:starting_spirit
}))
return Promise.all(allPromises)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
if config.get("inviteCodesActive")
return knex("invite_codes").where('code',inviteCode).delete()
.then ()->
# if email then mail.sendSignupAsync(username, email, verifyToken)
# NOTE: don't send registration notifications at large volume, and also since they contain PID
# mail.sendNotificationAsync("New Registration", "#{email} has registered with #{username}.")
return Promise.resolve(userId)
###*
# Delete a newly created user record in the event of partial registration.
# @public
# @param {String} userId User's ID
# @return {Promise} Promise that will return the userId on completion.
###
@deleteNewUser: (userId) ->
username = null
return @userDataForId(userId)
.then (userRow) ->
if !userRow
throw new Errors.NotFoundError()
username = userRow.username
return knex("users").where('id',userId).delete()
.then () -> return DuelystFirebase.connect().getRootRef()
.then (rootRef) ->
promises = [
FirebasePromises.remove(rootRef.child('users').child(userId)),
FirebasePromises.remove(rootRef.child('user-inventory').child(userId))
]
if username
promises.push(FirebasePromises.remove(rootRef.child('username-index').child(username)))
return Promise.all(promises)
###*
# Change a user's username.
# It will skip gold check if the username has never been set (currently null)
# @public
# @param {String} userId User ID
# @param {String} username New username
# @param {Moment} systemTime Pass in the current system time to override clock. Used mostly for testing.
# @return {Promise} Promise that will return on completion.
###
@changeUsername: (userId,newUsername,forceItForNoGold=false,systemTime)->
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
return UsersModule.userIdForUsername(newUsername)
.bind {}
.then (existingUserId)->
if existingUserId
throw new Errors.AlreadyExistsError("Username already exists")
else
return knex.transaction (tx)->
knex("users").where('id',userId).first('username','username_updated_at','wallet_gold').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
# we should have a user
if !userRow
throw new Errors.NotFoundError()
# let's figure out if we're allowed to change the username and how much it should cost
# if username was null, price stays 0
price = 0
if not forceItForNoGold and userRow.username_updated_at and userRow.username
price = 100
timeSinceLastChange = moment.duration(MOMENT_NOW_UTC.diff(moment.utc(userRow.username_updated_at)))
if timeSinceLastChange.asMonths() < 1.0
throw new Errors.InvalidRequestError("Username can't be changed twice in one month")
@.price = price
@.oldUsername = userRow.username
if price > 0 and userRow.wallet_gold < price
throw new Errors.InsufficientFundsError("Insufficient gold to update username")
allUpdates = []
# if username was null, we skip setting the updated_at flag since it is being set for first time
if !@.oldUsername
userUpdateParams =
username:newUsername
else
userUpdateParams =
username:newUsername
username_updated_at:MOMENT_NOW_UTC.toDate()
if price > 0
userUpdateParams.wallet_gold = userRow.wallet_gold-price
userUpdateParams.wallet_updated_at = MOMENT_NOW_UTC.toDate()
userCurrencyLogItem =
id: generatePushId()
user_id: userId
gold: -price
memo: "username change"
created_at: MOMENT_NOW_UTC.toDate()
allUpdates.push knex("user_currency_log").insert(userCurrencyLogItem).transacting(tx)
allUpdates.push knex("users").where('id',userId).update(userUpdateParams).transacting(tx)
return Promise.all(allUpdates)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
updateWalletData = (walletData)=>
walletData ?= {}
walletData.gold_amount ?= 0
walletData.gold_amount -= @.price
walletData.updated_at = MOMENT_NOW_UTC.valueOf()
return walletData
allPromises = [
FirebasePromises.set(rootRef.child('username-index').child(newUsername),userId)
FirebasePromises.set(rootRef.child('users').child(userId).child('presence').child('username'),newUsername)
]
# if username was null, we skip setting the updated_at flag since it is being set for first time
# and there is no old index to remove
if !@.oldUsername
allPromises.push(FirebasePromises.update(rootRef.child('users').child(userId),{username: newUsername}))
else
allPromises.push(FirebasePromises.remove(rootRef.child('username-index').child(@.oldUsername)))
allPromises.push(FirebasePromises.update(rootRef.child('users').child(userId),{username: newUsername, username_updated_at:MOMENT_NOW_UTC.valueOf()}))
if @.price > 0
allPromises.push FirebasePromises.safeTransaction(rootRef.child("user-inventory").child(userId).child("wallet"),updateWalletData)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
###*
# Change a user's email address.
# @public
# @param {String} userId User ID
# @param {String} newEmail New email
# @param {Moment} systemTime Pass in the current system time to override clock. Used mostly for testing.
# @return {Promise} Promise that will return on completion.
###
@changeEmail: (userId,newEmail,systemTime)->
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
return UsersModule.userIdForEmail(newEmail)
.bind {}
.then (existingUserId)->
if existingUserId
throw new Errors.AlreadyExistsError("Email already exists")
else
return knex.transaction (tx)->
knex("users").where('id',userId).first('email').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
# we should have a user
if !userRow
throw new Errors.NotFoundError()
@.oldEmail = userRow.email
userUpdateParams =
email:newEmail
return knex("users").where('id',userId).update(userUpdateParams).transacting(tx)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
###*
# Mark a user record as having verified email.
# @public
# @param {String} token Verification Token
# @return {Promise} Promise that will return on completion.
###
@verifyEmailUsingToken: (token)->
MOMENT_NOW_UTC = moment().utc()
return knex("email_verify_tokens").first().where('verify_token',token)
.bind {}
.then (tokenRow)->
@.tokenRow = tokenRow
unless tokenRow?.created_at
throw new Errors.NotFoundError()
duration = moment.duration(moment().utc().valueOf() - moment.utc(tokenRow?.created_at).valueOf())
if duration.asDays() < 1
return Promise.all([
knex('users').where('id',tokenRow.user_id).update({ email_verified_at: MOMENT_NOW_UTC.toDate() }) # mark user as verified
knex('email_verify_tokens').where('user_id',tokenRow.user_id).delete() # delete all user's verify tokens
])
else
throw new Errors.NotFoundError()
###*
# Change a user's password.
# @public
# @param {String} userId User ID
# @param {String} oldPassword PI:PASSWORD:<PASSWORD>END_PI
# @param {String} newPassword PI:PASSWORD:<PASSWORD>END_PI
# @return {Promise} Promise that will return on completion.
###
@changePassword: (userId,oldPassword,newPassword)->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx)->
knex("users").where('id',userId).first('password').forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
return hashHelpers.comparePassword(oldPassword, userRow.password)
.then (match) ->
if (!match)
throw new Errors.BadPasswordError()
else
return hashHelpers.generateHash(newPassword)
.then (hash) ->
knex("users").where('id',userId).update({
password:PI:PASSWORD:<PASSWORD>END_PI
password_updated_at:MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Google Play ID to a User
# @public
# @param {String} userId User ID
# @param {String} googlePlayId User's Google Play ID
# @return {Promise} Promise that will return on completion
###
@associateGooglePlayId: (userId, googlePlayId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
google_play_id: googlePlayId
google_play_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Google Play ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateGooglePlayId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
google_play_id: null
google_play_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Gamecenter ID to a user
# @public
# @param {String} userId User ID
# @param {String} gamecenterId User's Gamecenter Id
# @return {Promise} Promise that will return on completion
###
@associateGameCenterId: (userId, gameCenterId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
gamecenter_id: gameCenterId
gamecenter_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Gamecenter ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateGameCenterId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
gamecenter_id: null
gamecenter_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Associate a Steam ID to a User
# @public
# @param {String} userId User ID
# @param {String} steamId User's Steam ID as returned from steam.coffee authenticateUserTicket
# @return {Promise} Promise that will return on completion.
###
@associateSteamId: (userId, steamId) ->
MOMENT_NOW_UTC = moment().utc()
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
steam_id: steamId
steam_associated_at: MOMENT_NOW_UTC.toDate()
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Disassociate a Steam ID to a User
# Currently only used for testing
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return on completion.
###
@disassociateSteamId: (userId) ->
return knex.transaction (tx) ->
knex("users").where('id',userId).first().forUpdate().transacting(tx)
.bind {}
.then (userRow)->
if !userRow
throw new Errors.NotFoundError()
else
knex("users").where('id',userId).update({
steam_id: null
steam_associated_at: null
}).transacting(tx)
.then tx.commit
.catch tx.rollback
return
###*
# Get user data for id.
# @public
# @param {String} userId User ID
# @return {Promise} Promise that will return the user data on completion.
###
@userDataForId: (userId)->
return knex("users").first().where('id',userId)
###*
# Get user data for email.
# @public
# @param {String} email User Email
# @return {Promise} Promise that will return the user data on completion.
###
@userDataForEmail: (email)->
return knex("users").first().where('email',email)
###*
# Intended to be called on login/reload to bump session counter and check transaction counter to update user caches / initiate any hot copies.
# @public
# @param {String} userId User ID
# @param {Object} userData User data if previously loaded
# @return {Promise} Promise that will return synced when done
###
@bumpSessionCountAndSyncDataIfNeeded: (userId,userData=null,systemTime=null)->
MOMENT_NOW_UTC = systemTime || moment().utc()
startPromise = null
if userData
startPromise = Promise.resolve(userData)
else
startPromise = knex("users").where('id',userId).first('id','created_at','session_count','last_session_at','last_session_version')
return startPromise
.then (userData)->
@.userData = userData
if not @.userData?
throw new Errors.NotFoundError("User not found")
# Check if user needs to have emotes migrated to cosmetics inventory
return MigrationsModule.checkIfUserNeedsMigrateEmotes20160708(@.userData)
.then (userNeedsMigrateEmotes) ->
if userNeedsMigrateEmotes
return MigrationsModule.userMigrateEmotes20160708(userId,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then () ->
return MigrationsModule.checkIfUserNeedsPrismaticBackfillReward(@.userData)
.then (userNeedsPrismaticBackfill) ->
if userNeedsPrismaticBackfill
return MigrationsModule.userBackfillPrismaticRewards(userId,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then ()-> # migrate user charge counts for purchase limits
return MigrationsModule.checkIfUserNeedsChargeCountsMigration(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userCreateChargeCountsMigration(userId)
else
return Promise.resolve()
.then ()->
return MigrationsModule.checkIfUserNeedsIncompleteGauntletRefund(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userIncompleteGauntletRefund(userId)
else
return Promise.resolve()
.then ()->
return MigrationsModule.checkIfUserNeedsUnlockableOrbsRefund(@.userData).then (needsMigration)->
if needsMigration
return MigrationsModule.userUnlockableOrbsRefund(userId)
else
return Promise.resolve()
.then () ->
lastSessionTime = moment.utc(@.userData.last_session_at).valueOf() || 0
duration = moment.duration(MOMENT_NOW_UTC.valueOf() - lastSessionTime)
if moment.utc(@.userData.created_at).isBefore(moment.utc("2016-06-18")) and moment.utc(@.userData.last_session_at).isBefore(moment.utc("2016-06-18"))
Logger.module("UsersModule").debug "bumpSessionCountAndSyncDataIfNeeded() -> starting inventory achievements for user - #{userId.blue}."
# Kick off job to update achievements
Jobs.create("update-user-achievements",
name: "Update User Inventory Achievements"
title: util.format("User %s :: Update Inventory Achievements", userId)
userId: userId
inventoryChanged: true
).removeOnComplete(true).save()
if duration.asHours() > 2
return knex("users").where('id',userId).update(
session_count: @.userData.session_count+1
last_session_at: MOMENT_NOW_UTC.toDate()
)
else
return Promise.resolve()
.then ()->
# Update a user's last seen session if needed
if not @.userData.last_session_version? or @.userData.last_session_version != version
return knex("users").where('id',userId).update(
last_session_version: version
)
else
return Promise.resolve()
.then ()->
return SyncModule.syncUserDataIfTrasactionCountMismatched(userId,@.userData)
.then (synced)->
# # Job: Sync user buddy data
# Jobs.create("data-sync-user-buddy-list",
# name: "Sync User Buddy Data"
# title: util.format("User %s :: Sync Buddies", userId)
# userId: userId
# ).removeOnComplete(true).save()
return synced
###*
# Intended to be called on login/reload to fire off a job which tracks cohort data for given user
# @public
# @param {String} userId User ID
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise.resolve() for now since all handling is done in job
###
@createDaysSeenOnJob: (userId,systemTime) ->
MOMENT_NOW_UTC = systemTime || moment().utc()
Jobs.create("update-user-seen-on",
name: "Update User Seen On"
title: util.format("User %s :: Update Seen On", userId)
userId: userId
userSeenOn: MOMENT_NOW_UTC.valueOf()
).removeOnComplete(true).save()
return Promise.resolve()
###*
# Intended to be called on login/reload to fire off a job which tracks cohort data for given user
# @public
# @param {String} userId User ID
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise.resolve() for now since all handling is done in job
###
@createSteamFriendsSyncJob: (userId, friendSteamIds) ->
Jobs.create("data-sync-steam-friends",
name: "Sync Steam Friends"
title: util.format("User %s :: Sync Steam Friends", userId)
userId: userId
friendsSteamIds: friendSteamIds
).removeOnComplete(true).save()
return Promise.resolve()
###*
# Updates the users row if they have newly logged in on a set day
# @public
# @param {String} userId User ID
# @param {Moment} userSeenOn Moment representing the time the user was seen (at point of log in)
# @return {Promise} Promise that completes when user's days seen is updated (if needed)
###
@updateDaysSeen: (userId,userSeenOn) ->
return knex.first('created_at','seen_on_days').from('users').where('id',userId)
.then (userRow) ->
recordedDayIndex = AnalyticsUtil.recordedDayIndexForRegistrationAndSeenOn(moment.utc(userRow.created_at),userSeenOn)
if not recordedDayIndex?
return Promise.resolve()
else
userSeenOnDays = userRow.seen_on_days || []
needsUpdate = false
if not _.contains(userSeenOnDays,recordedDayIndex)
needsUpdate = true
userSeenOnDays.push(recordedDayIndex)
# perform update if needed
if needsUpdate
return knex('users').where({'id':userId}).update({seen_on_days:userSeenOnDays})
else
return Promise.resolve()
###*
# Get the user ID for the specified email.
# @public
# @param {String} email User's email
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForEmail: (email, callback) ->
if !email then return Promise.resolve(null).nodeify(callback)
return knex.first('id').from('users').where('email',email)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified username.
# @public
# @param {String} username User's username (CaSE in-sensitive)
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForUsername: (username, callback) ->
# usernames are ALWAYS lowercase, so when searching downcase by default
username = username?.toLowerCase()
return knex.first('id').from('users').where('username',username)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Steam ID.
# Reference steam.coffee's authenticateUserTicket
# @public
# @param {String} steamId User's Steam ID as returned from steam.coffee authenticateUserTicket
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForSteamId: (steamId, callback) ->
return knex.first('id').from('users').where('steam_id',steamId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Google Play ID.
# @public
# @param {String} googlePlayId User's Google Play ID
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForGooglePlayId: (googlePlayId, callback) ->
return knex.first('id').from('users').where('google_play_id',googlePlayId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Get the user ID for the specified Gamecenter ID.
# @public
# @param {String} gameCenterId User's Gamecenter ID
# @return {Promise} Promise that will return the userId data on completion.
###
@userIdForGameCenterId: (gameCenterId, callback) ->
return knex.first('id').from('users').where('gamecenter_id',gameCenterId)
.then (userRow) ->
return new Promise( (resolve, reject) ->
if userRow
return resolve(userRow.id)
else
return resolve(null)
).nodeify(callback)
###*
# Validate that a deck is valid and that the user is allowed to play it.
# @public
# @param {String} userId User ID.
# @param {Array} deck Array of card objects with at least card IDs.
# @param {String} gameType game type (see SDK.GameType)
# @param {Boolean} [forceValidation=false] Force validation regardless of ENV. Useful for unit tests.
# @return {Promise} Promise that will resolve if the deck is valid and throw an "InvalidDeckError" otherwise
###
@isAllowedToUseDeck: (userId,deck,gameType, ticketId, forceValidation) ->
# userId must be defined
if !userId || !deck
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid user ID or deck parameter - #{userId.blue}.".red
return Promise.reject(new Errors.InvalidDeckError("invalid user ID or deck - #{userId}"))
# on DEV + STAGING environments, always allow any deck
if !forceValidation and config.get('allCardsAvailable')
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> valid deck because this environment allows all cards ALL_CARDS_AVAILABLE = #{config.get('allCardsAvailable')} - #{userId.blue}.".green
return Promise.resolve(true)
# check for valid general
deckFactionId = null
generalId = deck[0]?.id
if generalId?
generalCard = SDK.GameSession.getCardCaches().getCardById(generalId)
if not generalCard?.isGeneral
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> first card in the deck must be a general - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("First card in the deck must be a general"))
else
deckFactionId = generalCard.factionId
if gameType == GameType.Gauntlet
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> Allowing ANY arena deck for now - #{userId.blue}.".green
return Promise.resolve(true)
else if ticketId? && gameType == GameType.Friendly
# # Validate a friendly rift deck
# return RiftModule.getRiftRunDeck(userId,ticketId)
# .then (riftDeck) ->
# sortedDeckIds = _.sortBy(_.map(deck,(cardObject) -> return cardObject.id),(id) -> return id)
# sortedRiftDeckIds = _.sortBy(riftDeck,(id)-> return id)
# if (sortedDeckIds.length != sortedRiftDeckIds.length)
# return Promise.reject(new Errors.InvalidDeckError("Friendly rift deck has incorrect card count: " + sortedDeckIds.length))
#
# for i in [0...sortedDeckIds.length]
# if sortedDeckIds[i] != sortedRiftDeckIds[i]
# return Promise.reject(new Errors.InvalidDeckError("Friendly rift deck has incorrect cards"))
#
# return Promise.resolve(true)
# Validate a friendly gauntlet deck
decksExpireMoment = moment.utc().subtract(CONFIG.DAYS_BEFORE_GAUNTLET_DECK_EXPIRES,"days")
currentDeckPromise = knex("user_gauntlet_run").first("deck").where("user_id",userId).andWhere("ticket_id",ticketId)
oldDeckPromise = knex("user_gauntlet_run_complete").first("deck","ended_at").where("user_id",userId).andWhere("id",ticketId).andWhere("ended_at",">",decksExpireMoment.toDate())
return Promise.all([currentDeckPromise,oldDeckPromise])
.spread (currentRunRow,completedRunRow) ->
matchingRunRow = null
if (currentRunRow?)
matchingRunRow = currentRunRow
else if (completedRunRow?)
matchingRunRow = completedRunRow
else
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has no matching recent run, ticket_id: " + ticketId))
gauntletDeck = matchingRunRow.deck
sortedDeckIds = _.sortBy(_.map(deck,(cardObject) -> return cardObject.id),(id) -> return id)
sortedGauntletDeckIds = _.sortBy(gauntletDeck,(id)-> return id)
if (sortedDeckIds.length != sortedGauntletDeckIds.length)
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has incorrect card count: " + sortedDeckIds.length))
for i in [0...sortedDeckIds.length]
if sortedDeckIds[i] != sortedGauntletDeckIds[i]
return Promise.reject(new Errors.InvalidDeckError("Friendly gauntlet deck has incorrect cards"))
return Promise.resolve(true)
else if gameType # allow all other game modes
cardsToValidateAgainstInventory = []
cardSkinsToValidateAgainstInventory = []
basicsOnly = true
for card in deck
cardId = card.id
sdkCard = SDK.GameSession.getCardCaches().getCardById(cardId)
if sdkCard.rarityId != SDK.Rarity.Fixed
basicsOnly = false
if sdkCard.factionId != deckFactionId && sdkCard.factionId != SDK.Factions.Neutral
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> found a card with faction #{sdkCard.factionId} that doesn't belong in a #{deckFactionId} faction deck - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Deck has cards from more than one faction"))
if (sdkCard.rarityId != SDK.Rarity.Fixed and sdkCard.rarityId != SDK.Rarity.TokenUnit) || sdkCard.getIsUnlockable()
cardSkinId = SDK.Cards.getCardSkinIdForCardId(cardId)
if cardSkinId?
# add skin to validate against inventory
if !_.contains(cardSkinsToValidateAgainstInventory, cardSkinId)
cardSkinsToValidateAgainstInventory.push(cardSkinId)
# add unskinned card to validate against inventory if needed
unskinnedCardId = SDK.Cards.getNonSkinnedCardId(cardId)
unskinnedSDKCard = SDK.GameSession.getCardCaches().getIsSkinned(false).getCardById(unskinnedCardId)
if unskinnedSDKCard.getRarityId() != SDK.Rarity.Fixed and unskinnedSDKCard.getRarityId() != SDK.Rarity.TokenUnit
cardsToValidateAgainstInventory.push(unskinnedCardId)
else
# add card to validate against inventory
cardsToValidateAgainstInventory.push(card.id)
# starter decks must contain all cards in level 0 faction starter deck
# normal decks must match exact deck size
maxDeckSize = if CONFIG.DECK_SIZE_INCLUDES_GENERAL then CONFIG.MAX_DECK_SIZE else CONFIG.MAX_DECK_SIZE + 1
if basicsOnly
if deck.length < CONFIG.MIN_BASICS_DECK_SIZE
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid starter deck (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Starter decks must have at least #{CONFIG.MIN_BASICS_DECK_SIZE} cards!"))
else if deck.length > maxDeckSize
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid starter deck (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Starter decks must not have more than #{maxDeckSize} cards!"))
else if deck.length != maxDeckSize
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> invalid deck length (#{deck.length}) - #{userId.blue}.".yellow
return Promise.reject(new Errors.InvalidDeckError("Deck must have #{maxDeckSize} cards"))
# ensure that player has no more than 3 of a base card (normal + prismatic) in deck
cardCountsById = _.countBy(deck, (cardData) ->
return Cards.getBaseCardId(cardData.id)
)
for k,v of cardCountsById
if v > 3
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 3 of a card"))
# Ensure that player doesn't have any cards that are in development, hidden in collection, and only one general
gameSessionCards = _.map(deck, (cardData) ->
cardId = cardData.id
return SDK.GameSession.getCardCaches().getCardById(cardId)
)
generalCount = 0
for gameSessionCard in gameSessionCards
if gameSessionCard instanceof Entity and gameSessionCard.getIsGeneral()
generalCount += 1
if not gameSessionCard.getIsAvailable(null, forceValidation)
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are not yet available - player #{userId.blue}.".red
return Promise.reject(new Errors.NotFoundError("Deck has cards that are not yet available"))
if gameSessionCard.getIsHiddenInCollection()
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are in hidden to collection - player #{userId.blue}.".red
return Promise.reject(new Errors.InvalidDeckError("Deck has cards that are in hidden to collection"))
if (gameSessionCard.getIsLegacy() || CardSetFactory.cardSetForIdentifier(gameSessionCard.getCardSetId()).isLegacy?) and GameType.getGameFormatForGameType(gameType) == GameFormat.Standard
Logger.module("UsersModule").error "isAllowedToUseDeck() -> Deck has cards (#{gameSessionCard.id}) that are in LEGACY format but game mode is STANDARD format"
return Promise.reject(new Errors.InvalidDeckError("Game Mode is STANDARD but deck contains LEGACY card"))
if generalCount != 1
return Promise.reject(new Errors.InvalidDeckError("Deck has " + generalCount + " generals"))
# ensure that player has no more than 1 of a mythron card (normal + prismatic) in deck
mythronCardCountsById = _.countBy(gameSessionCards, (card) ->
if card.getRarityId() == SDK.Rarity.Mythron
return Cards.getBaseCardId(card.getId())
else
return -1
)
for k,v of mythronCardCountsById
if k != '-1' and v > 1
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 1 of a mythron card"))
# ensure that player has no more than 1 trial card total
trialCardCount = _.countBy(gameSessionCards, (card) ->
baseCardId = Cards.getBaseCardId(card.getId())
if baseCardId in [Cards.Faction1.RightfulHeir, Cards.Faction2.DarkHeart, Cards.Faction3.KeeperOfAges, Cards.Faction4.DemonOfEternity, Cards.Faction5.Dinomancer, Cards.Faction6.VanarQuest, Cards.Neutral.Singleton]
return 'trialCard'
else
return -1
)
for k,v of trialCardCount
if k != '-1' and v > 1
return Promise.reject(new Errors.InvalidDeckError("Deck has more than 1 total trial card"))
# setup method to validate cards against user inventory
validateCards = () ->
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> doesUserHaveCards -> #{cardsToValidateAgainstInventory.length} cards to validate - #{userId.blue}.".green
# if we're playing basic cards only, mark deck as valid, and only check against inventory otherwise
if cardsToValidateAgainstInventory.length == 0
return Promise.resolve(true)
else
return InventoryModule.isAllowedToUseCards(Promise.resolve(), knex, userId, cardsToValidateAgainstInventory)
# setup method to validate skins against user inventory
validateSkins = () ->
Logger.module("UsersModule").debug "isAllowedToUseDeck() -> doesUserHaveSkins -> #{cardSkinsToValidateAgainstInventory.length} skins to validate - #{userId.blue}.".green
if cardSkinsToValidateAgainstInventory.length == 0
return Promise.resolve(true)
else
return InventoryModule.isAllowedToUseCosmetics(Promise.resolve(), knex, userId, cardSkinsToValidateAgainstInventory, SDK.CosmeticsTypeLookup.CardSkin)
return Promise.all([
validateCards(),
validateSkins()
])
else
return Promise.reject(new Error("Unknown game type: #{gameType}"))
###*
# Creates a blank faction progression (0 XP) record for a user. This is used to mark a faction as "unlocked".
# @public
# @param {String} userId User ID for which to update.
# @param {String} factionId Faction ID for which to update.
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@createFactionProgressionRecord: (userId,factionId,gameId,gameType,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not createFactionProgressionRecord(): invalid user ID - #{userId}"))
# factionId must be defined
if !factionId
return Promise.reject(new Error("Can not createFactionProgressionRecord(): invalid faction ID - #{factionId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx('users').where('id',userId).first('id').forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).first().forUpdate()
])
.spread (userRow,factionProgressionRow)->
if factionProgressionRow
throw new Errors.AlreadyExistsError()
# faction progression row
factionProgressionRow ?= { user_id:userId, faction_id:factionId }
@.factionProgressionRow = factionProgressionRow
factionProgressionRow.xp ?= 0
factionProgressionRow.game_count ?= 0
factionProgressionRow.unscored_count ?= 0
factionProgressionRow.loss_count ?= 0
factionProgressionRow.win_count ?= 0
factionProgressionRow.draw_count ?= 0
factionProgressionRow.single_player_win_count ?= 0
factionProgressionRow.friendly_win_count ?= 0
factionProgressionRow.xp_earned ?= 0
factionProgressionRow.updated_at = MOMENT_NOW_UTC.toDate()
factionProgressionRow.last_game_id = gameId
factionProgressionRow.level = SDK.FactionProgression.levelForXP(factionProgressionRow.xp)
# reward row
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"faction unlock"
game_id:gameId
unlocked_faction_id:factionId
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
return Promise.all([
tx('user_faction_progression').insert(factionProgressionRow)
tx("user_rewards").insert(rewardData)
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id)
])
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
delete @.factionProgressionRow.user_id
@.factionProgressionRow.updated_at = moment.utc(@.factionProgressionRow.updated_at).valueOf()
return FirebasePromises.set(rootRef.child('user-faction-progression').child(userId).child(factionId).child('stats'),@.factionProgressionRow)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "createFactionProgressionRecord() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
return txPromise
###*
# Update a user's per-faction progression metrics based on the outcome of a ranked game
# @public
# @param {String} userId User ID for which to update.
# @param {String} factionId Faction ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored (if a user conceded too early for example?)
# @param {Boolean} isDraw Are we updating for a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserFactionProgressionWithGameOutcome: (userId,factionId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserFactionProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# factionId must be defined
if !factionId
return Promise.reject(new Error("Can not updateUserFactionProgressionWithGameOutcome(): invalid faction ID - #{factionId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").first('id','is_bot').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).first().forUpdate()
])
.spread (userRow,factionProgressionRow)->
# Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> ACQUIRED LOCK ON #{userId}".yellow
@userRow = userRow
allPromises = []
needsInsert = _.isUndefined(factionProgressionRow)
factionProgressionRow ?= {user_id:userId,faction_id:factionId}
@.factionProgressionRow = factionProgressionRow
factionProgressionRow.xp ?= 0
factionProgressionRow.game_count ?= 0
factionProgressionRow.unscored_count ?= 0
factionProgressionRow.loss_count ?= 0
factionProgressionRow.win_count ?= 0
factionProgressionRow.draw_count ?= 0
factionProgressionRow.single_player_win_count ?= 0
factionProgressionRow.friendly_win_count ?= 0
factionProgressionRow.level ?= 0
# faction xp progression for single player and friendly games is capped at 10
# levels are indexed from 0 so we check 9 here instead of 10
if (gameType == GameType.SinglePlayer or gameType == GameType.BossBattle or gameType == GameType.Friendly) and factionProgressionRow.level >= 9
throw new Errors.MaxFactionXPForSinglePlayerReachedError()
# grab the default xp earned for a win/loss
# xp_earned = if isWinner then SDK.FactionProgression.winXP else SDK.FactionProgression.lossXP
xp_earned = SDK.FactionProgression.xpEarnedForGameOutcome(isWinner, factionProgressionRow.level)
# if this game should not earn XP for some reason (early concede for example)
if isUnscored then xp_earned = 0
xp = factionProgressionRow.xp
game_count = factionProgressionRow.game_count
win_count = factionProgressionRow.win_count
xp_cap = SDK.FactionProgression.totalXPForLevel(SDK.FactionProgression.maxLevel)
# do not commit transaction if we're at the max level
if (SDK.FactionProgression.levelForXP(xp) >= SDK.FactionProgression.maxLevel)
xp_earned = 0
# make sure user can't earn XP over cap
else if (xp_cap - xp < xp_earned)
xp_earned = xp_cap - xp
factionProgressionRow.xp_earned = xp_earned
factionProgressionRow.updated_at = MOMENT_NOW_UTC.toDate()
factionProgressionRow.last_game_id = gameId
if isUnscored
unscored_count = factionProgressionRow.unscored_count
factionProgressionRow.unscored_count += 1
else
factionProgressionRow.xp = xp + xp_earned
factionProgressionRow.level = SDK.FactionProgression.levelForXP(factionProgressionRow.xp)
factionProgressionRow.game_count += 1
if isDraw
factionProgressionRow.draw_count += 1
else if isWinner
factionProgressionRow.win_count += 1
if gameType == GameType.SinglePlayer or gameType == GameType.BossBattle
factionProgressionRow.single_player_win_count += 1
if gameType == GameType.Friendly
factionProgressionRow.friendly_win_count += 1
else
factionProgressionRow.loss_count += 1
# Logger.module("UsersModule").debug factionProgressionRow
if needsInsert
allPromises.push knex('user_faction_progression').insert(factionProgressionRow).transacting(tx)
else
allPromises.push knex('user_faction_progression').where({'user_id':userId,'faction_id':factionId}).update(factionProgressionRow).transacting(tx)
if !isUnscored and not @.factionProgressionRow.xp_earned > 0
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> F#{factionId} MAX level reached"
# update the user game params
@.updateUserGameParams =
faction_xp: @.factionProgressionRow.xp
faction_xp_earned: 0
allPromises.push knex("user_games").where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
else
level = SDK.FactionProgression.levelForXP(@.factionProgressionRow.xp)
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> At F#{factionId} L:#{level} [#{@.factionProgressionRow.xp}] earned #{@.factionProgressionRow.xp_earned} for G:#{gameId}"
progressData = {
user_id:userId
faction_id:factionId
xp_earned:@.factionProgressionRow.xp_earned
is_winner:isWinner || false
is_draw:isDraw || false
game_id:gameId
created_at:MOMENT_NOW_UTC.toDate()
is_scored:!isUnscored
}
@.updateUserGameParams =
faction_xp: @.factionProgressionRow.xp - @.factionProgressionRow.xp_earned
faction_xp_earned: @.factionProgressionRow.xp_earned
allPromises.push knex("user_faction_progression_events").insert(progressData).transacting(tx)
allPromises.push knex("user_games").where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
return Promise.all(allPromises)
.then ()->
allPromises = []
if (!isUnscored and @.factionProgressionRow) and SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned)
# Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> LEVELED up"
factionName = SDK.FactionFactory.factionForIdentifier(factionId).devName
level = SDK.FactionProgression.levelForXP(@.factionProgressionRow.xp)
rewardData = SDK.FactionProgression.rewardDataForLevel(factionId,level)
@.rewardRows = []
if rewardData?
rewardRowData =
id: generatePushId()
user_id: userId
reward_category: 'faction xp'
reward_type: "#{factionName} L#{level}"
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
is_unread:true
@.rewardRows.push(rewardRowData)
rewardData.created_at = MOMENT_NOW_UTC.valueOf()
rewardData.level = level
# update inventory
earnRewardInventoryPromise = null
if rewardData.gold?
rewardRowData.gold = rewardData.gold
# update wallet
earnRewardInventoryPromise = InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,"#{factionName} L#{level}",gameId)
else if rewardData.spirit?
rewardRowData.spirit = rewardData.spirit
# update wallet
earnRewardInventoryPromise = InventoryModule.giveUserSpirit(txPromise,tx,userId,rewardData.spirit,"#{factionName} L#{level}",gameId)
else if rewardData.cards?
cardIds = []
_.each(rewardData.cards,(c)->
_.times c.count, ()->
cardIds.push(c.id)
)
rewardRowData.cards = cardIds
# give cards
earnRewardInventoryPromise = InventoryModule.giveUserCards(txPromise,tx,userId,cardIds,'faction xp',gameId,"#{factionName} L#{level}")
else if rewardData.booster_packs?
rewardRowData.spirit_orbs = rewardData.booster_packs
# TODO: what about more than 1 booster pack?
earnRewardInventoryPromise = InventoryModule.addBoosterPackToUser(txPromise,tx,userId,1,"faction xp","#{factionName} L#{level}",{factionId:factionId,level:level,gameId:gameId})
else if rewardData.emotes?
rewardRowData.cosmetics = []
# update emotes inventory
emotes_promises = []
for emote_id in rewardData.emotes
rewardRowData.cosmetics.push(emote_id)
allPromises.push InventoryModule.giveUserCosmeticId(txPromise, tx, userId, emote_id, "faction xp reward", rewardRowData.id,null, MOMENT_NOW_UTC)
earnRewardInventoryPromise = Promise.all(emotes_promises)
# resolve master promise whan reward is saved and inventory updated
allPromises = allPromises.concat [
knex("user_rewards").insert(rewardRowData).transacting(tx),
earnRewardInventoryPromise,
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardRowData.id)
]
# let's see if we need to add any faction ribbons for this user
winCountForRibbons = @.factionProgressionRow.win_count - (@.factionProgressionRow.single_player_win_count + @.factionProgressionRow.friendly_win_count)
if isWinner and winCountForRibbons > 0 and winCountForRibbons % 100 == 0 and not @.userRow.is_bot
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} earned WIN RIBBON for faction #{factionId}"
ribbonId = "f#{factionId}_champion"
rewardRowData =
id: generatePushId()
user_id: userId
reward_category: 'ribbon'
reward_type: "#{factionName} wins"
game_id: gameId
created_at: MOMENT_NOW_UTC.toDate()
ribbons:[ribbonId]
is_unread:true
# looks like the user earned a faction ribbon!
ribbon =
user_id:userId
ribbon_id:ribbonId
game_id:gameId
created_at:MOMENT_NOW_UTC.toDate()
@.ribbon = ribbon
allPromises = allPromises.concat [
knex("user_ribbons").insert(ribbon).transacting(tx)
knex("user_rewards").insert(rewardRowData).transacting(tx),
GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardRowData.id)
]
return Promise.all(allPromises)
.then ()->
# Update quests if a faction has leveled up
if SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned)
if @.factionProgressionRow #and shouldProcessQuests # TODO: shouldprocessquests? also this may fail for people who already have faction lvl 10 by the time they reach this stage
return QuestsModule.updateQuestProgressWithProgressedFactionData(txPromise,tx,userId,@.factionProgressionRow,MOMENT_NOW_UTC)
# Not performing faction based quest update
return Promise.resolve()
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
delete @.factionProgressionRow.user_id
@.factionProgressionRow.updated_at = moment.utc(@.factionProgressionRow.updated_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child('user-faction-progression').child(userId).child(factionId).child('stats'),@.factionProgressionRow)
for key,val of @.updateUserGameParams
allPromises.push FirebasePromises.set(rootRef.child('user-games').child(userId).child(gameId).child(key),val)
if @.ribbon
ribbonData = _.omit(@.ribbon,["user_id"])
ribbonData = DataAccessHelpers.restifyData(ribbonData)
allPromises.push FirebasePromises.safeTransaction(rootRef.child('user-ribbons').child(userId).child(ribbonData.ribbon_id),(data)->
data ?= {}
data.ribbon_id ?= ribbonData.ribbon_id
data.updated_at = ribbonData.created_at
data.count ?= 0
data.count += 1
return data
)
# if @.rewardRows
# for reward in @.rewardRows
# reward_id = reward.id
# delete reward.user_id
# delete reward.id
# reward.created_at = moment.utc(reward.created_at).valueOf()
# # push rewards to firebase tree
# allPromises.push(FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(reward_id),reward))
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.catch Errors.MaxFactionXPForSinglePlayerReachedError, (e)-> tx.rollback(e)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserFactionProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()->
# Update achievements if leveled up
if SDK.FactionProgression.hasLeveledUp(@.factionProgressionRow.xp,@.factionProgressionRow.xp_earned) || @.factionProgressionRow.game_count == 1
Jobs.create("update-user-achievements",
name: "Update User Faction Achievements"
title: util.format("User %s :: Update Faction Achievements", userId)
userId: userId
factionProgressed: true
).removeOnComplete(true).save()
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} (#{@.factionProgressionRow["game_count"]}) faction progression recorded. Unscored: #{isUnscored?.toString().cyan}".green
return @.factionProgressionRow
.catch Errors.MaxFactionXPForSinglePlayerReachedError, (e)->
Logger.module("UsersModule").debug "updateUserFactionProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} for faction #{factionId} not recorded. MAX LVL 10 for single player games reached."
return null
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'faction_progression')
return txPromise
###*
# Update a user's progression metrics based on the outcome of a ranked game
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw is this game a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserProgressionWithGameOutcome: (userId,opponentId,isWinner,gameId,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# userId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid game ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
txPromise = knex.transaction (tx)->
start_of_day_int = parseInt(moment(MOMENT_NOW_UTC).startOf('day').utc().format("YYYYMMDD"))
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_progression').where('user_id',userId).first().forUpdate()
tx('user_progression_days').where({'user_id':userId,'date':start_of_day_int}).first().forUpdate()
])
.spread (userRow,progressionRow,progressionDayRow)->
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> ACQUIRED LOCK ON #{userId}".yellow
#######
#######
#######
#######
#######
#######
#######
allPromises = []
hasReachedDailyPlayRewardMaxium = false
hasReachedDailyWinRewardMaxium = false
@.hasReachedDailyWinCountBonusLimit = false
canEarnFirstWinOfTheDayReward = true
@.progressionDayRow = progressionDayRow || { user_id:userId, date:start_of_day_int }
@.progressionDayRow.game_count ?= 0
@.progressionDayRow.unscored_count ?= 0
@.progressionDayRow.game_count += 1
# controls for daily maximum of play rewards
if @.progressionDayRow.game_count - @.progressionDayRow.unscored_count > UsersModule.DAILY_REWARD_GAME_CAP
hasReachedDailyPlayRewardMaxium = true
# # controls for daily maximum of play rewards
# if counterData.win_count > UsersModule.DAILY_REWARD_WIN_CAP
# hasReachedDailyWinRewardMaxium = true
if isDraw
@.progressionDayRow.draw_count ?= 0
@.progressionDayRow.draw_count += 1
else if isWinner
# iterate win count
@.progressionDayRow.win_count ?= 0
@.progressionDayRow.win_count += 1
if @.progressionDayRow.win_count > 1
canEarnFirstWinOfTheDayReward = false
# @.hasReachedDailyWinCountBonusLimit is disabled
# if @.progressionDayRow.win_count > 14
# @.hasReachedDailyWinCountBonusLimit = true
else
# iterate loss count
@.progressionDayRow.loss_count ?= 0
@.progressionDayRow.loss_count += 1
# if it's an unscored game, iterate unscored counter
if isUnscored
@.progressionDayRow.unscored_count += 1
if progressionDayRow?
allPromises.push knex('user_progression_days').where({'user_id':userId,'date':start_of_day_int}).update(@.progressionDayRow).transacting(tx)
else
allPromises.push knex('user_progression_days').insert(@.progressionDayRow).transacting(tx)
#######
#######
#######
#######
#######
#######
#######
@.hasEarnedWinReward = false
@.hasEarnedPlayReward = false
@.hasEarnedFirstWinOfTheDayReward = false
@.progressionRow = progressionRow || { user_id:userId }
@.progressionRow.last_opponent_id = opponentId
# record total game count
@.progressionRow.game_count ?= 0
@.progressionRow.unscored_count ?= 0
@.progressionRow.last_game_id = gameId || null
@.progressionRow.updated_at = MOMENT_NOW_UTC.toDate()
# initialize last award records
@.progressionRow.last_awarded_game_count ?= 0
@.progressionRow.last_awarded_win_count ?= 0
last_daily_win_at = @.progressionRow.last_daily_win_at || 0
play_count_reward_progress = 0
win_count_reward_progress = 0
if isUnscored
@.progressionRow.unscored_count += 1
# mark all rewards as false
@.hasEarnedWinReward = false
@.hasEarnedPlayReward = false
@.hasEarnedFirstWinOfTheDayReward = false
else
@.progressionRow.game_count += 1
if not hasReachedDailyPlayRewardMaxium
play_count_reward_progress = @.progressionRow.game_count - @.progressionRow.last_awarded_game_count
if @.progressionRow.game_count > 0 and play_count_reward_progress > 0 and play_count_reward_progress % 4 == 0
@.progressionRow.last_awarded_game_count = @.progressionRow.game_count
@.hasEarnedPlayReward = true
else
@.hasEarnedPlayReward = false
else
@.progressionRow.last_awarded_game_count = @.progressionRow.game_count
@.progressionRow.play_awards_last_maxed_at = MOMENT_NOW_UTC.toDate()
@.hasEarnedPlayReward = false
if isDraw
@.progressionRow.draw_count ?= 0
@.progressionRow.draw_count += 1
else if isWinner
# set loss streak to 0
@.progressionRow.loss_streak = 0
# is this the first win of the day?
hours_since_last_win = MOMENT_NOW_UTC.diff(last_daily_win_at,'hours')
if hours_since_last_win >= UsersModule.DAILY_WIN_CYCLE_HOURS
@.hasEarnedFirstWinOfTheDayReward = true
@.progressionRow.last_daily_win_at = MOMENT_NOW_UTC.toDate()
else
@.hasEarnedFirstWinOfTheDayReward = false
# iterate win count
@.progressionRow.win_count ?= 0
@.progressionRow.win_count += 1
# iterate win streak
if gameType != GameType.Casual
@.progressionRow.win_streak ?= 0
@.progressionRow.win_streak += 1
# mark last win time
@.progressionRow.last_win_at = MOMENT_NOW_UTC.toDate()
if not hasReachedDailyWinRewardMaxium
win_count_reward_progress = @.progressionRow.win_count - @.progressionRow.last_awarded_win_count
# if we've had 3 wins since last award, the user has earned an award
if @.progressionRow.win_count - @.progressionRow.last_awarded_win_count >= CONFIG.WINS_REQUIRED_FOR_WIN_REWARD
@.hasEarnedWinReward = true
@.progressionRow.last_awarded_win_count_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.last_awarded_win_count = @.progressionRow.win_count
else
@.hasEarnedWinReward = false
else
@.progressionRow.last_awarded_win_count_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.win_awards_last_maxed_at = MOMENT_NOW_UTC.toDate()
@.progressionRow.last_awarded_win_count = @.progressionRow.win_count
@.hasEarnedWinReward = false
else
# iterate loss count
@.progressionRow.loss_count ?= 0
@.progressionRow.loss_count += 1
# only iterate loss streak for scored games
# NOTE: control flow should never allow this to be reached for unscored, but adding this just in case someone moves code around :)
if not isUnscored
@.progressionRow.loss_streak ?= 0
@.progressionRow.loss_streak += 1
if gameType != GameType.Casual
# reset win streak
@.progressionRow.win_streak = 0
if progressionRow?
allPromises.push knex('user_progression').where({'user_id':userId}).update(@.progressionRow).transacting(tx)
else
allPromises.push knex('user_progression').insert(@.progressionRow).transacting(tx)
@.updateUserGameParams =
is_daily_win: @.hasEarnedWinReward
play_count_reward_progress: play_count_reward_progress
win_count_reward_progress: win_count_reward_progress
has_maxed_play_count_rewards: hasReachedDailyPlayRewardMaxium
has_maxed_win_count_rewards: hasReachedDailyWinRewardMaxium
allPromises.push knex('user_games').where({'user_id':userId,'game_id':gameId}).update(@.updateUserGameParams).transacting(tx)
return Promise.all(allPromises)
.then ()->
hasEarnedWinReward = @.hasEarnedWinReward
hasEarnedPlayReward = @.hasEarnedPlayReward
hasEarnedFirstWinOfTheDayReward = @.hasEarnedFirstWinOfTheDayReward
# let's set up
promises = []
@.rewards = []
# if the game is "unscored", assume there are NO rewards
# otherwise, the game counter rewards might fire multiple times since game_count is not updated for unscored games
if not isUnscored
if hasEarnedFirstWinOfTheDayReward
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-WIN-OF-THE-DAY reward at #{@.progressionRow["game_count"]} games!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"daily win"
gold:CONFIG.FIRST_WIN_OF_DAY_GOLD_REWARD
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if hasEarnedPlayReward
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a PLAY-COUNT reward at #{@.progressionRow["game_count"]} games!"
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"play count"
# gold:10
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if @.progressionRow["game_count"] == 3 and not isUnscored
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-3-GAMES reward!"
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"first 3 games"
# gold:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
# if @.progressionRow["game_count"] == 10 and not isUnscored
# Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a FIRST-10-GAMES reward!"
# # set up reward data
# reward = {
# type:"first 10 games"
# gold_amount:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # set up reward data
# rewardData = {
# id:generatePushId()
# user_id:userId
# game_id:gameId
# reward_category:"progression"
# reward_type:"first 10 games"
# gold:100
# created_at:MOMENT_NOW_UTC.toDate()
# is_unread:true
# }
# # add it to the rewards array
# @.rewards.push(rewardData)
# # add the promise to our list of reward promises
# promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
# promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
if hasEarnedWinReward
gold_amount = CONFIG.WIN_BASED_GOLD_REWARD
# hasReachedDailyWinCountBonusLimit is disabled
if @.hasReachedDailyWinCountBonusLimit
gold_amount = 5
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a #{gold_amount}G WIN-COUNT reward!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"win count"
gold:gold_amount
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
@.codexChapterIdsEarned = SDK.Codex.chapterIdsAwardedForGameCount(@.progressionRow.game_count)
if @.codexChapterIdsEarned && @.codexChapterIdsEarned.length != 0
Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue} HAS earned codex chapters #{@.codexChapterIdsEarned} reward!"
for codexChapterIdEarned in @.codexChapterIdsEarned
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"codex"
reward_type:"game count"
codex_chapter:codexChapterIdEarned
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
promises.push(InventoryModule.giveUserCodexChapter(txPromise,tx,userId,codexChapterIdEarned,MOMENT_NOW_UTC))
promises.push(knex("user_rewards").insert(rewardData).transacting(tx))
promises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
return Promise.all(promises)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
delete @.progressionRow.user_id
delete @.progressionRow.last_opponent_id
if @.progressionRow.last_win_at then @.progressionRow.last_win_at = moment.utc(@.progressionRow.last_win_at).valueOf()
if @.progressionRow.last_daily_win_at then @.progressionRow.last_daily_win_at = moment.utc(@.progressionRow.last_daily_win_at).valueOf()
if @.progressionRow.last_awarded_win_count_at then @.progressionRow.last_awarded_win_count_at = moment.utc(@.progressionRow.last_awarded_win_count_at).valueOf()
if @.progressionRow.play_awards_last_maxed_at then @.progressionRow.play_awards_last_maxed_at = moment.utc(@.progressionRow.play_awards_last_maxed_at).valueOf()
if @.progressionRow.win_awards_last_maxed_at then @.progressionRow.win_awards_last_maxed_at = moment.utc(@.progressionRow.win_awards_last_maxed_at).valueOf()
if @.progressionRow.updated_at then @.progressionRow.updated_at = moment.utc().valueOf(@.progressionRow.updated_at)
allPromises.push FirebasePromises.set(rootRef.child("user-progression").child(userId).child('game-counter'),@.progressionRow)
for key,val of @.updateUserGameParams
allPromises.push FirebasePromises.set(rootRef.child('user-games').child(userId).child(gameId).child(key),val)
# for reward in @.rewards
# rewardId = reward.id
# delete reward.id
# delete reward.user_id
# if reward.created_at then moment.utc().valueOf(reward.created_at)
# allPromises.push FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(rewardId),reward)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()-> Logger.module("UsersModule").debug "updateUserProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} G:#{@.progressionRow["game_count"]} W:#{@.progressionRow["win_count"]} L:#{@.progressionRow["loss_count"]} U:#{@.progressionRow["unscored_count"]} progression recorded. Unscored: #{isUnscored?.toString().cyan}".green
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'progression')
return txPromise
###*
# Update a user's boss progression outcome of a boss battle
# @public
# @param {String} userId User ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameId Game unique ID
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw is this game a draw?
# @param {Object} gameSessionData data for the game played
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateUserBossProgressionWithGameOutcome: (userId,opponentId,isWinner,gameId,gameType,isUnscored,isDraw,gameSessionData,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid user ID - #{userId}"))
# userId must be defined
if !gameId
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid game ID - #{gameId}"))
if !gameType? or gameType != SDK.GameType.BossBattle
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid game game type - #{gameType}"))
if !isWinner
return Promise.resolve(false)
# Oppenent general must be part of the boss faction
opponentPlayerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameSessionData,opponentId)
bossId = opponentPlayerSetupData?.generalId
sdkBossData = SDK.GameSession.getCardCaches().getCardById(bossId)
if (not bossId?) or (not sdkBossData?) or (sdkBossData.getFactionId() != SDK.Factions.Boss)
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): invalid boss ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
this_obj = {}
this_obj.rewards = []
txPromise = knex.transaction (tx)->
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow) ->
@.userRow = userRow
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef) ->
@.fbRootRef = fbRootRef
bossEventsRef = @.fbRootRef.child("boss-events")
return FirebasePromises.once(bossEventsRef,'value')
.then (bossEventsSnapshot)->
bossEventsData = bossEventsSnapshot.val()
# data will have
# event-id :
# event_id
# boss_id
# event_start
# event_end
# valid_end (event_end + 30 minute buffer)
@.matchingEventData = null
for eventId,eventData of bossEventsData
if !eventData.boss_id? or parseInt(eventData.boss_id) != bossId
continue
if !eventData.event_start? or eventData.event_start > MOMENT_NOW_UTC.valueOf()
continue
if !eventData.valid_end? or eventData.valid_end < MOMENT_NOW_UTC.valueOf()
continue
# Reaching here means we have a matching event
@.matchingEventData = eventData
@.matchingEventId = eventData.event_id
break
if not @.matchingEventData?
Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> no matching boss event id for user #{userId} in game #{gameId}.".red
return Promise.reject(new Error("Can not updateUserBossProgressionWithGameOutcome(): No matching boss event - #{gameId}"))
.then ()->
return Promise.all([
@.userRow,
tx('user_bosses_defeated').where('user_id',userId).andWhere("boss_id",bossId).andWhere("boss_event_id",@.matchingEventId).first()
])
.spread (userRow,userBossDefeatedRow)->
if (userBossDefeatedRow?)
return Promise.resolve()
allPromises = []
# Insert defeated boss row
defeatedBossData =
user_id: userId
boss_id: bossId
game_id: gameId
boss_event_id: @.matchingEventId
defeated_at: MOMENT_NOW_UTC.toDate()
allPromises.push(tx('user_bosses_defeated').insert(defeatedBossData))
Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> user #{userId.blue} HAS earned a BOSS BATTLE reward!"
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
game_id:gameId
reward_category:"progression"
reward_type:"boss battle"
spirit_orbs:SDK.CardSet.Core
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
allPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
# allPromises.push(InventoryModule.giveUserGold(txPromise,tx,userId,rewardData.gold,rewardData.reward_type))
allPromises.push(InventoryModule.addBoosterPackToUser(txPromise,tx,userId,rewardData.spirit_orbs,"boss battle",@.matchingEventId))
allPromises.push(GamesModule._addRewardIdToUserGame(tx,userId,gameId,rewardData.id))
return Promise.all(allPromises)
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
@.fbRootRef = rootRef
allPromises = []
# Insert defeated boss row
defeatedBossFBData =
boss_id: bossId
boss_event_id: @.matchingEventId
defeated_at: MOMENT_NOW_UTC.valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-bosses-defeated").child(userId).child(bossId),defeatedBossFBData)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateUserBossProgressionWithGameOutcome() -> ERROR, operation timeout for u:#{userId} g:#{gameId}"
throw e
.bind this_obj
.then ()-> Logger.module("UsersModule").debug "updateUserBossProgressionWithGameOutcome() -> user #{userId.blue}".green + " game #{gameId} boss id:#{bossId}".green
.finally ()-> return GamesModule.markClientGameJobStatusAsComplete(userId,gameId,'progression')
return txPromise
###*
# Update a user's game counters
# @public
# @param {String} userId User ID for which to update.
# @param {Number} factionId Faction ID for which to update.
# @param {Number} generalId General ID for which to update.
# @param {Boolean} isWinner Did the user win the game?
# @param {String} gameType Game type (see SDK.GameType)
# @param {Boolean} isUnscored Should this game be scored or unscored if the user, for example, conceded too early?
# @param {Boolean} isDraw was game a draw?
# @param {Moment} systemTime Pass in the current system time to use. Used only for testing.
# @return {Promise} Promise that will notify when complete.
###
@updateGameCounters: (userId,factionId,generalId,isWinner,gameType,isUnscored,isDraw,systemTime) ->
# userId must be defined
if !userId
return Promise.reject(new Error("Can not updateUserProgressionWithGameOutcome(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
MOMENT_SEASON_START_UTC = MOMENT_NOW_UTC.clone().startOf('month')
this_obj = {}
return knex.transaction (tx)->
return Promise.resolve(tx("users").first('id').where('id',userId).forUpdate())
.bind this_obj
.then (userRow)->
return Promise.all([
userRow,
tx('user_game_counters').where({
'user_id': userId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_faction_counters').where({
'user_id': userId
'faction_id': factionId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_general_counters').where({
'user_id': userId
'general_id': generalId
'game_type': gameType
}).first().forUpdate(),
tx('user_game_season_counters').where({
'user_id': userId
'season_starting_at': MOMENT_SEASON_START_UTC.toDate()
'game_type': gameType
}).first().forUpdate()
])
.spread (userRow,counterRow,factionCounterRow,generalCounterRow,seasonCounterRow)->
allPromises = []
# game type counter
counter = DataAccessHelpers.updateCounterWithGameOutcome(counterRow,isWinner,isDraw,isUnscored)
counter.user_id = userId
counter.game_type = gameType
counter.created_at ?= MOMENT_NOW_UTC.toDate()
counter.updated_at = MOMENT_NOW_UTC.toDate()
if counterRow
allPromises.push knex('user_game_counters').where({
'user_id': userId
'game_type': gameType
}).update(counter).transacting(tx)
else
allPromises.push knex('user_game_counters').insert(counter).transacting(tx)
# faction counter
factionCounter = DataAccessHelpers.updateCounterWithGameOutcome(factionCounterRow,isWinner,isDraw,isUnscored)
factionCounter.user_id = userId
factionCounter.faction_id = factionId
factionCounter.game_type = gameType
factionCounter.created_at ?= MOMENT_NOW_UTC.toDate()
factionCounter.updated_at = MOMENT_NOW_UTC.toDate()
if factionCounterRow
allPromises.push knex('user_game_faction_counters').where({
'user_id': userId
'faction_id': factionId
'game_type': gameType
}).update(factionCounter).transacting(tx)
else
allPromises.push knex('user_game_faction_counters').insert(factionCounter).transacting(tx)
# general counter
generalCounter = DataAccessHelpers.updateCounterWithGameOutcome(generalCounterRow,isWinner,isDraw,isUnscored)
generalCounter.user_id = userId
generalCounter.general_id = generalId
generalCounter.game_type = gameType
generalCounter.created_at ?= MOMENT_NOW_UTC.toDate()
generalCounter.updated_at = MOMENT_NOW_UTC.toDate()
if generalCounterRow
allPromises.push knex('user_game_general_counters').where({
'user_id': userId
'general_id': generalId
'game_type': gameType
}).update(generalCounter).transacting(tx)
else
allPromises.push knex('user_game_general_counters').insert(generalCounter).transacting(tx)
# season counter
seasonCounter = DataAccessHelpers.updateCounterWithGameOutcome(seasonCounterRow,isWinner,isDraw,isUnscored)
seasonCounter.user_id = userId
seasonCounter.game_type = gameType
seasonCounter.season_starting_at ?= MOMENT_SEASON_START_UTC.toDate()
seasonCounter.created_at ?= MOMENT_NOW_UTC.toDate()
seasonCounter.updated_at = MOMENT_NOW_UTC.toDate()
if seasonCounterRow
allPromises.push knex('user_game_season_counters').where({
'user_id': userId
'season_starting_at': MOMENT_SEASON_START_UTC.toDate()
'game_type': gameType
}).update(seasonCounter).transacting(tx)
else
allPromises.push knex('user_game_season_counters').insert(seasonCounter).transacting(tx)
@.counter = counter
@.factionCounter = factionCounter
@.generalCounter = generalCounter
@.seasonCounter = seasonCounter
return Promise.all(allPromises)
# .then ()-> return DuelystFirebase.connect().getRootRef()
# .then (rootRef)->
# allPromises = []
# firebaseCounterData = DataAccessHelpers.restifyData _.clone(@.counter)
# delete firebaseCounterData.user_id
# delete firebaseCounterData.game_type
# firebaseFactionCounterData = DataAccessHelpers.restifyData _.clone(@.factionCounter)
# delete firebaseFactionCounterData.user_id
# delete firebaseFactionCounterData.faction_id
# delete firebaseFactionCounterData.game_type
# allPromises.push FirebasePromises.update(rootRef.child('user-game-counters').child(userId).child(gameType).child('stats'),firebaseCounterData)
# allPromises.push FirebasePromises.update(rootRef.child('user-game-counters').child(userId).child(gameType).child('factions').child(factionId),firebaseFactionCounterData)
# return Promise.all(allPromises)
.timeout(10000)
.catch Promise.TimeoutError, (e)->
Logger.module("UsersModule").error "updateGameCounters() -> ERROR, operation timeout for u:#{userId}"
throw e
.bind this_obj
.then ()->
Logger.module("UsersModule").debug "updateGameCounters() -> updated #{gameType} game counters for #{userId.blue}"
return {
counter:@.counter
faction_counter:@.factionCounter
general_counter:@.generalCounter
season_counter:@.seasonCounter
}
###*
# Update user's stats given a game.
# @public
# @param {String} userId User ID for which to process quests.
# @param {String} gameId Game ID for which to calculate stat changes
# @param {String} gameType Game type (see SDK.GameType)
# @param {String} gameData Plain object with game data
# @return {Promise} Promise that will post STATDATA on completion.
###
@updateUserStatsWithGame: (userId,gameId,gameType,gameData,systemTime) ->
# userId must be defined
if !userId or !gameId
return Promise.reject(new Error("Can not update user-stats : invalid user ID - #{userId} - or game ID - #{gameId}"))
MOMENT_NOW_UTC = systemTime || moment().utc()
# Begin the promise rabbit hole
return DuelystFirebase.connect().getRootRef()
.bind {}
.then (fbRootRef) ->
@fbRootRef = fbRootRef
statsRef = @fbRootRef.child("user-stats").child(userId)
return new Promise (resolve, reject) ->
statsRef.once("value", (statsSnapshot) ->
return resolve(statsSnapshot.val())
)
.then (statsData) ->
try
playerData = UtilsGameSession.getPlayerDataForId(gameData,userId)
playerSetupData = UtilsGameSession.getPlayerSetupDataForPlayerId(gameData,userId)
isWinner = playerData.isWinner
statsRef = @fbRootRef.child("user-stats").child(userId)
if !statsData
statsData = {}
# TODO: Temp until we have queue type defined in an architecture
queueName = gameType
if !statsData[queueName]
statsData[queueName] = {}
queueStatsData = statsData[queueName]
# -- First per queue stats
# Update player's global win streak
queueStatsData.winStreak ?= 0
if gameType != GameType.Casual
if isWinner
queueStatsData.winStreak += 1
else
queueStatsData.winStreak = 0
# -- Then per faction data
factionId = playerSetupData.factionId
if !queueStatsData[factionId]
queueStatsData[factionId] = {}
factionStatsData = queueStatsData[factionId]
factionStatsData.factionId = factionId
# Update per faction win count and play count
factionStatsData.playCount = (factionStatsData.playCount or 0) + 1
if (isWinner)
factionStatsData.winCount = (factionStatsData.winCount or 0) + 1
# Update cards played counts
if !factionStatsData.cardsPlayedCounts
factionStatsData.cardsPlayedCounts = {}
cardIndices = Object.keys(gameData.cardsByIndex)
for cardIndex in cardIndices
card = gameData.cardsByIndex[cardIndex]
if card.ownerId == userId
factionStatsData.cardsPlayedCounts[card.id] = (factionStatsData.cardsPlayedCounts[card.id] or 0) + 1
# Update discarded card counts
if !factionStatsData.cardsDiscardedCounts
factionStatsData.cardsDiscardedCounts = {}
# Update total turns played (this represents turns played by opponents as well)
totalTurns = 1 # for currentTurn
if gameData.turns
totalTurns += gameData.turns.length
factionStatsData.totalTurnsPlayed = (factionStatsData.totalTurnsPlayed or 0) + totalTurns
# Update play total stats
factionStatsData.totalDamageDealt = (factionStatsData.totalDamageDealt or 0) + playerData.totalDamageDealt
factionStatsData.totalDamageDealtToGeneral = (factionStatsData.totalDamageDealtToGeneral or 0) + playerData.totalDamageDealtToGeneral
factionStatsData.totalMinionsKilled = (factionStatsData.totalMinionsKilled or 0) + playerData.totalMinionsKilled
factionStatsData.totalMinionsPlayedFromHand = (factionStatsData.totalMinionsPlayedFromHand or 0) + playerData.totalMinionsPlayedFromHand
factionStatsData.totalMinionsSpawned = (factionStatsData.totalMinionsSpawned or 0) + playerData.totalMinionsSpawned
factionStatsData.totalSpellsCast = (factionStatsData.totalSpellsCast or 0) + playerData.totalSpellsCast
factionStatsData.totalSpellsPlayedFromHand = (factionStatsData.totalSpellsPlayedFromHand or 0) + playerData.totalSpellsPlayedFromHand
catch e
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> caught ERROR processing stats data for user #{userId}: #{e.message}".red
throw new Error("ERROR PROCESSING STATS DATA")
# Perform firebase transaction to update stats
return new Promise (resolve, reject) ->
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> UPDATING stats for user #{userId}"
# function to update quest list
onUpdateUserStatsTransaction = (userStatsTransactionData)->
# Don't care what the previous stats were, replace them with the updated version
userStatsTransactionData = statsData
userStatsTransactionData.updated_at = MOMENT_NOW_UTC.valueOf()
return userStatsTransactionData
# function to call when the quest update is complete
onUpdateUserStatsTransactionComplete = (error,committed,snapshot) ->
if error
return reject(error)
else if committed
Logger.module("UsersModule").debug "updateUserStatsWithGame() -> updated user-stats committed for #{userId.blue}"
return resolve(snapshot.val())
else
return reject(new Errors.FirebaseTransactionDidNotCommitError("User Stats for #{userId.blue} did NOT COMMIT"))
# update users stats
statsRef.transaction(onUpdateUserStatsTransaction,onUpdateUserStatsTransactionComplete)
###*
# Completes a challenge for a user and unlocks any rewards !if! it's not already completed
# @public
# @param {String} userId User ID.
# @param {String} challenge_type type of challenge completed
# @param {Boolean} shouldProcessQuests should we attempt to process quests as a result of this challenge completion (since beginner quests include a challenge quest)
# @return {Promise} Promise that will resolve and give rewards if challenge hasn't been completed before, will resolve false and not give rewards if it has
###
@completeChallengeWithType: (userId,challengeType,shouldProcessQuests) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "completeChallengeWithType() -> user #{userId.blue} completed challenge type #{challengeType}."
knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).first()
.bind this_obj
.then (challengeRow)->
if challengeRow and challengeRow.completed_at
Logger.module("UsersModule").debug "completeChallengeWithType() -> user #{userId.blue} has already completed challenge type #{challengeType}."
return Promise.resolve(false)
else
txPromise = knex.transaction (tx)->
# lock user record while updating data
knex("users").where({'id':userId}).first('id').forUpdate().transacting(tx)
.bind this_obj
.then ()->
# give the user their rewards
goldReward = SDK.ChallengeFactory.getGoldRewardedForChallengeType(challengeType)
cardRewards = SDK.ChallengeFactory.getCardIdsRewardedForChallengeType(challengeType)
spiritReward = SDK.ChallengeFactory.getSpiritRewardedForChallengeType(challengeType)
boosterPackRewards = SDK.ChallengeFactory.getBoosterPacksRewardedForChallengeType(challengeType)
factionUnlockedReward = SDK.ChallengeFactory.getFactionUnlockedRewardedForChallengeType(challengeType)
@.rewards = []
@.challengeRow =
user_id:userId
challenge_id:challengeType
completed_at:MOMENT_NOW_UTC.toDate()
last_attempted_at: challengeRow?.last_attempted_at || MOMENT_NOW_UTC.toDate()
reward_ids:[]
is_unread:true
rewardPromises = []
if goldReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
gold:goldReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserGold(txPromise,tx,userId,goldReward,'challenge',challengeType))
if cardRewards
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
cards:cardRewards
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserCards(txPromise,tx,userId,cardRewards,'challenge'))
if spiritReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
spirit:spiritReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
rewardPromises.push(InventoryModule.giveUserSpirit(txPromise,tx,userId,spiritReward,'challenge'))
if boosterPackRewards
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
spirit_orbs:boosterPackRewards.length
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
_.each boosterPackRewards, (boosterPackData) ->
# Bound to array of reward promises
rewardPromises.push(InventoryModule.addBoosterPackToUser(txPromise,tx,userId,1,"soft",boosterPackData))
if factionUnlockedReward
# set up reward data
rewardData = {
id:generatePushId()
user_id:userId
reward_category:"challenge"
reward_type:challengeType
unlocked_faction_id:factionUnlockedReward
created_at:MOMENT_NOW_UTC.toDate()
is_unread:true
}
# add it to the rewards array
@.rewards.push(rewardData)
# add the promise to our list of reward promises
rewardPromises.push(knex("user_rewards").insert(rewardData).transacting(tx))
@.challengeRow.reward_ids = _.map(@.rewards, (r)-> return r.id)
if challengeRow
rewardPromises.push knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(@.challengeRow).transacting(tx)
else
rewardPromises.push knex("user_challenges").insert(@.challengeRow).transacting(tx)
Promise.all(rewardPromises)
.then ()->
if @.challengeRow and shouldProcessQuests
return QuestsModule.updateQuestProgressWithCompletedChallenge(txPromise,tx,userId,challengeType,MOMENT_NOW_UTC)
else
return Promise.resolve()
.then (questProgressResponse)->
if @.challengeRow and questProgressResponse?.rewards?.length > 0
Logger.module("UsersModule").debug "completeChallengeWithType() -> user #{userId.blue} completed challenge quest rewards count: #{ questProgressResponse?.rewards.length}"
for reward in questProgressResponse.rewards
@.rewards.push(reward)
@.challengeRow.reward_ids.push(reward.id)
return knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(
reward_ids:@.challengeRow.reward_ids
).transacting(tx)
.then ()->
return Promise.all([
DuelystFirebase.connect().getRootRef(),
@.challengeRow,
@.rewards
])
.spread (rootRef,challengeRow,rewards)->
allPromises = []
if challengeRow?
delete challengeRow.user_id
# delete challengeRow.challenge_id
if challengeRow.last_attempted_at then challengeRow.last_attempted_at = moment.utc(challengeRow.last_attempted_at).valueOf()
if challengeRow.completed_at then challengeRow.completed_at = moment.utc(challengeRow.completed_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-challenge-progression").child(userId).child(challengeType),challengeRow)
@.challengeRow = challengeRow
# if rewards?
# for reward in rewards
# reward_id = reward.id
# delete reward.id
# delete reward.user_id
# reward.created_at = moment.utc(reward.created_at).valueOf()
# allPromises.push FirebasePromises.set(rootRef.child("user-rewards").child(userId).child(reward_id),reward)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
return txPromise
.then ()->
Logger.module("UsersModule").timeEnd "completeChallengeWithType() -> user #{userId.blue} completed challenge type #{challengeType}."
responseData = null
if @.challengeRow
responseData = { challenge: @.challengeRow }
if @.rewards
responseData.rewards = @.rewards
return responseData
###*
# Marks a challenge as attempted.
# @public
# @param {String} userId User ID.
# @param {String} challenge_type type of challenge
# @return {Promise} Promise that will resolve on completion
###
@markChallengeAsAttempted: (userId,challengeType) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "markChallengeAsAttempted() -> user #{userId.blue} attempted challenge type #{challengeType}."
txPromise = knex.transaction (tx)->
# lock user and challenge row
Promise.all([
knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).first().forUpdate().transacting(tx)
knex("users").where({'id':userId}).first('id').forUpdate().transacting(tx)
])
.bind this_obj
.spread (challengeRow)->
@.challengeRow = challengeRow
if @.challengeRow?
@.challengeRow.last_attempted_at = MOMENT_NOW_UTC.toDate()
return knex("user_challenges").where({'user_id':userId,'challenge_id':challengeType}).update(@.challengeRow).transacting(tx)
else
@.challengeRow =
user_id:userId
challenge_id:challengeType
last_attempted_at:MOMENT_NOW_UTC.toDate()
return knex("user_challenges").insert(@.challengeRow).transacting(tx)
.then ()-> DuelystFirebase.connect().getRootRef()
.then (rootRef)->
allPromises = []
if @.challengeRow?
delete @.challengeRow.user_id
# delete @.challengeRow.challenge_id
if @.challengeRow.last_attempted_at then @.challengeRow.last_attempted_at = moment.utc(@.challengeRow.last_attempted_at).valueOf()
if @.challengeRow.completed_at then @.challengeRow.completed_at = moment.utc(@.challengeRow.completed_at).valueOf()
allPromises.push FirebasePromises.set(rootRef.child("user-challenge-progression").child(userId).child(challengeType),@.challengeRow)
return Promise.all(allPromises)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
responseData = { challenge: @.challengeRow }
return responseData
return txPromise
###*
# Iterate core new player progression up by one point if all requirements met, or generate missing quests if any required quests are missing from current/complete quest list for this user.
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@iterateNewPlayerCoreProgression: (userId) ->
knex("user_new_player_progression").where('user_id',userId).andWhere('module_name',NewPlayerProgressionModuleLookup.Core).first()
.bind {}
.then (moduleProgression)->
stage = NewPlayerProgressionStageEnum[moduleProgression?.stage] || NewPlayerProgressionStageEnum.Tutorial
# if we're at the final stage, just return
if stage.value >= NewPlayerProgressionHelper.FinalStage.value
return Promise.resolve()
Promise.all([
knex("user_quests").where('user_id',userId).select()
knex("user_quests_complete").where('user_id',userId).select()
])
.bind @
.spread (quests,questsComplete)->
beginnerQuests = NewPlayerProgressionHelper.questsForStage(stage)
# exclude non-required beginner quests for this tage
beginnerQuests = _.filter beginnerQuests, (q)-> return q.isRequired
# if we have active quests, check that none are beginner for current stage
if quests?.length > 0
# let's see if any beginner quests for this stage are still in progress
beginnerQuestInProgress = _.find(quests,(q)->
return _.find(beginnerQuests,(bq)-> bq.id == q.quest_type_id)
)
# if any beginner quests for this stage are still in progress, DO NOTHING
if beginnerQuestInProgress
return Promise.resolve()
# let's see if all beginner quests for this stage are completed
beginnerQuestsComplete = _.filter(questsComplete,(q)->
return _.find(beginnerQuests,(bq)-> bq.id == q.quest_type_id)
)
# if any beginner quests for this stage have NOT been completed, we have a problem... looks like we need to generate these quests
if beginnerQuestsComplete?.length < beginnerQuests.length
# throw new Error("Invalid state: user never received all required stage quests")
Logger.module('SDK').warn "iterateNewPlayerCoreProgression() -> Invalid state: user #{userId.blue} never received all required stage #{stage.key} quests"
return QuestsModule.generateBeginnerQuests(userId)
.bind {}
.then (questData)->
if questData
@.questData = questData
.catch Errors.NoNeedForNewBeginnerQuestsError, (e)->
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> no need for new quests at #{nextStage.key} for #{userId.blue}"
.then ()->
@.progressionData = moduleProgression
return @
# if we're here, it means all required beginner quests have been completed up to here...
# so let's push the core stage forward
# calculate the next linear stage point for core progression
nextStage = null
for s in NewPlayerProgressionStageEnum.enums
if s.value > stage.value
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> from stage #{stage.key} to next stage #{s.key} for #{userId.blue}"
nextStage = s
break
# update current stage and generate any new beginner quests
return UsersModule.setNewPlayerFeatureProgression(userId,NewPlayerProgressionModuleLookup.Core,nextStage.key)
.bind {}
.then (progressionData) ->
@.progressionData = progressionData
return QuestsModule.generateBeginnerQuests(userId)
.then (questData)->
if questData
@.questData = questData
.catch Errors.NoNeedForNewBeginnerQuestsError, (e)->
Logger.module('SDK').debug "iterateNewPlayerCoreProgression() -> no need for new quests at #{nextStage.key} for #{userId.blue}"
.then ()->
return @
.then (responseData)->
return responseData
###*
# Sets user feature progression for a module
# @public
# @param {String} userId User ID.
# @param {String} moduleName Arbitrary name of a module
# @param {String} stage Arbitrary key for a progression item
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@setNewPlayerFeatureProgression: (userId,moduleName,stage) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setNewPlayerFeatureProgression() -> user #{userId.blue} marking module #{moduleName} as #{stage}."
if moduleName == NewPlayerProgressionModuleLookup.Core and not NewPlayerProgressionStageEnum[stage]?
return Promise.reject(new Errors.BadRequestError("Invalid core new player stage"))
txPromise = knex.transaction (tx)->
tx("user_new_player_progression").where({'user_id':userId,'module_name':moduleName}).first().forUpdate()
.bind this_obj
.then (progressionRow)->
# core stage has some special rules
if moduleName == NewPlayerProgressionModuleLookup.Core
currentStage = progressionRow?.stage || NewPlayerProgressionStageEnum.Tutorial
if NewPlayerProgressionStageEnum[stage].value < currentStage.value
throw new Errors.BadRequestError("Can not roll back to a previous core new player stage")
@.progressionRow = progressionRow
queryPromise = null
if progressionRow and progressionRow.stage == stage
Logger.module("UsersModule").error "setNewPlayerFeatureProgression() -> ERROR: requested same stage: #{stage}."
throw new Errors.BadRequestError("New player progression stage already at the requested stage")
else if progressionRow
# TODO: this never gets called, here 2 gets called twice for tutorial -> tutorialdone
@.progressionRow.stage = stage
@.progressionRow.updated_at = MOMENT_NOW_UTC.toDate()
queryPromise = tx("user_new_player_progression").where({'user_id':userId,'module_name':moduleName}).update({
stage: @.progressionRow.stage,
updated_at: @.progressionRow.updated_at
})
else
@.progressionRow =
user_id:userId
module_name:moduleName
stage:stage
queryPromise = tx("user_new_player_progression").insert(@.progressionRow)
return queryPromise
.then (updateCount)->
if updateCount
SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setNewPlayerFeatureProgression() -> user #{userId.blue} marking module #{moduleName} as #{stage}."
return @.progressionRow
return txPromise
###*
# Set a new portrait for a user
# @public
# @param {String} userId User ID.
# @param {String} portraitId Portrait ID
# @return {Promise} Promise that will resolve when complete with the module progression data
###
@setPortraitId: (userId,portraitId) ->
# userId must be defined
if !userId?
return Promise.reject(new Errors.NotFoundError("Can not setPortraitId(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setPortraitId() -> user #{userId.blue}."
txPromise = knex.transaction (tx)->
InventoryModule.isAllowedToUseCosmetic(txPromise, tx, userId, portraitId)
.bind this_obj
.then ()->
return knex("users").where({'id':userId}).update(
portrait_id:portraitId
)
.then (updateCount)->
if updateCount == 0
throw new Errors.NotFoundError("User with id #{userId} not found")
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.set(rootRef.child('users').child(userId).child('presence').child('portrait_id'),portraitId)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setPortraitId() -> user #{userId.blue}."
return portraitId
###*
# Set a the preferred Battle Map for a user
# @public
# @param {String} userId User ID.
# @param {String} battleMapId Battle Map ID
# @return {Promise} Promise that will resolve when complete
###
@setBattleMapId: (userId,battleMapId) ->
# userId must be defined
if !userId?
return Promise.reject(new Errors.NotFoundError("Can not setPortraitId(): invalid user ID - #{userId}"))
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
Logger.module("UsersModule").time "setBattleMapId() -> user #{userId.blue}."
txPromise = knex.transaction (tx)->
checkForInventoryPromise = if battleMapId != null then InventoryModule.isAllowedToUseCosmetic(txPromise, tx, userId, battleMapId) else Promise.resolve(true)
checkForInventoryPromise
.bind this_obj
.then ()->
return tx("users").where({'id':userId}).update(
battle_map_id:battleMapId
)
.then (updateCount)->
if updateCount == 0
throw new Errors.NotFoundError("User with id #{userId} not found")
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.set(rootRef.child('users').child(userId).child('battle_map_id'),battleMapId)
.then ()-> SyncModule._bumpUserTransactionCounter(tx,userId)
.then tx.commit
.catch tx.rollback
return
.bind this_obj
.then ()->
Logger.module("UsersModule").timeEnd "setBattleMapId() -> user #{userId.blue}."
return battleMapId
###*
# Add a small in-game notification for a user
# @public
# @param {String} userId User ID.
# @param {String} message What message to show
# @param {String} type Message type
# @return {Promise} Promise that will resolve when complete
###
@inGameNotify: (userId,message,type=null) ->
# TODO: Error check, if the challenge type isn't recognized we shouldn't record it etc
MOMENT_NOW_UTC = moment().utc()
this_obj = {}
return Promise.resolve()
.bind {}
.then ()-> return DuelystFirebase.connect().getRootRef()
.then (rootRef)->
return FirebasePromises.push(rootRef.child("user-notifications").child(userId),{message:message,created_at:moment().utc().valueOf(),type:type})
@___hardWipeUserData: (userId)->
Logger.module("UsersModule").time "___hardWipeUserData() -> WARNING: hard wiping #{userId.blue}".red
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef)->
return Promise.all([
FirebasePromises.remove(fbRootRef.child('user-aggregates').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-arena-run').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-challenge-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-decks').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-faction-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-games').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-games').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-game-job-status').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-inventory').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-logs').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-matchmaking-errors').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-news').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-progression').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-quests').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-ranking').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-rewards').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-stats').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-transactions').child(userId)),
FirebasePromises.remove(fbRootRef.child('user-achievements').child(userId)),
knex("user_cards").where('user_id',userId).delete(),
knex("user_card_collection").where('user_id',userId).delete(),
knex("user_card_log").where('user_id',userId).delete(),
knex("user_challenges").where('user_id',userId).delete(),
knex("user_charges").where('user_id',userId).delete(),
knex("user_currency_log").where('user_id',userId).delete(),
knex("user_decks").where('user_id',userId).delete(),
knex("user_faction_progression").where('user_id',userId).delete(),
knex("user_faction_progression_events").where('user_id',userId).delete(),
knex("user_games").where('user_id',userId).delete(),
knex("user_gauntlet_run").where('user_id',userId).delete(),
knex("user_gauntlet_run_complete").where('user_id',userId).delete(),
knex("user_gauntlet_tickets").where('user_id',userId).delete(),
knex("user_gauntlet_tickets_used").where('user_id',userId).delete(),
knex("user_progression").where('user_id',userId).delete(),
knex("user_progression_days").where('user_id',userId).delete(),
knex("user_quests").where('user_id',userId).delete(),
knex("user_quests_complete").where('user_id',userId).delete(),
knex("user_rank_events").where('user_id',userId).delete(),
knex("user_rank_history").where('user_id',userId).delete(),
knex("user_rewards").where('user_id',userId).delete(),
knex("user_spirit_orbs").where('user_id',userId).delete(),
knex("user_spirit_orbs_opened").where('user_id',userId).delete(),
knex("user_codex_inventory").where('user_id',userId).delete(),
knex("user_new_player_progression").where('user_id',userId).delete(),
knex("user_achievements").where('user_id',userId).delete(),
knex("users").where('id',userId).update({
ltv:0,
rank:30,
rank_created_at:null,
rank_starting_at:null,
rank_stars:0,
rank_stars_required:1,
rank_updated_at:null,
rank_win_streak:0,
rank_top_rank:null,
rank_is_unread:false,
top_rank:null,
top_rank_starting_at:null,
top_rank_updated_at:null,
wallet_gold:0,
wallet_spirit:0,
wallet_cores:0,
wallet_updated_at:null,
total_gold_earned:0,
total_spirit_earned:0,
daily_quests_generated_at:null,
daily_quests_updated_at:null
})
])
.then ()->
Logger.module("UsersModule").timeEnd "___hardWipeUserData() -> WARNING: hard wiping #{userId.blue}".red
###*
# Sets user feature progression for a module
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@___snapshotUserData: (userId)->
Logger.module("UsersModule").time "___snapshotUserData() -> retrieving data for user ID #{userId.blue}".green
# List of the columns we want to grab from the users table, is everything except password
userTableColumns = ["id","created_at","updated_at","last_session_at","session_count","username_updated_at",
"email_verified_at","password_updated_at","invite_code","ltv","purchase_count","last_purchase_at","rank",
"rank_created_at","rank_starting_at","rank_stars","rank_stars_required","rank_delta","rank_top_rank",
"rank_updated_at","rank_win_streak","rank_is_unread","top_rank","top_rank_starting_at","top_rank_updated_at",
"daily_quests_generated_at","daily_quests_updated_at","achievements_last_read_at","wallet_gold",
"wallet_spirit","wallet_cores","wallet_updated_at","total_gold_earned","total_spirit_earned","buddy_count",
"tx_count","synced_firebase_at","stripe_customer_id","card_last_four_digits","card_updated_at",
"top_gauntlet_win_count","portrait_id","total_gold_tips_given","referral_code","is_suspended","suspended_at",
"suspended_memo","top_rank_ladder_position","top_rank_rating","is_bot"];
return DuelystFirebase.connect().getRootRef()
.then (fbRootRef)->
return Promise.all([
FirebasePromises.once(fbRootRef.child('user-aggregates').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-arena-run').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-challenge-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-decks').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-faction-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-games').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-game-job-status').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-inventory').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-logs').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-matchmaking-errors').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-news').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-progression').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-quests').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-ranking').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-rewards').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-stats').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-transactions').child(userId),"value"),
FirebasePromises.once(fbRootRef.child('user-achievements').child(userId),"value"),
knex("user_cards").where('user_id',userId).select(),
knex("user_card_collection").where('user_id',userId).select(),
knex("user_card_log").where('user_id',userId).select(),
knex("user_challenges").where('user_id',userId).select(),
knex("user_charges").where('user_id',userId).select(),
knex("user_currency_log").where('user_id',userId).select(),
knex("user_decks").where('user_id',userId).select(),
knex("user_faction_progression").where('user_id',userId).select(),
knex("user_faction_progression_events").where('user_id',userId).select(),
knex("user_games").where('user_id',userId).select(),
knex("user_gauntlet_run").where('user_id',userId).select(),
knex("user_gauntlet_run_complete").where('user_id',userId).select(),
knex("user_gauntlet_tickets").where('user_id',userId).select(),
knex("user_gauntlet_tickets_used").where('user_id',userId).select(),
knex("user_progression").where('user_id',userId).select(),
knex("user_progression_days").where('user_id',userId).select(),
knex("user_quests").where('user_id',userId).select(),
knex("user_quests_complete").where('user_id',userId).select(),
knex("user_rank_events").where('user_id',userId).select(),
knex("user_rank_history").where('user_id',userId).select(),
knex("user_rewards").where('user_id',userId).select(),
knex("user_spirit_orbs").where('user_id',userId).select(),
knex("user_spirit_orbs_opened").where('user_id',userId).select(),
knex("user_codex_inventory").where('user_id',userId).select(),
knex("user_new_player_progression").where('user_id',userId).select(),
knex("user_achievements").where('user_id',userId).select(),
knex("user_cosmetic_chests").where('user_id',userId).select(),
knex("user_cosmetic_chests_opened").where('user_id',userId).select(),
knex("user_cosmetic_chest_keys").where('user_id',userId).select(),
knex("user_cosmetic_chest_keys_used").where('user_id',userId).select(),
knex("users").where('id',userId).first(userTableColumns)
])
.spread (fbUserAggregates,fbUserArenaRun,fbUserChallengeProgression,fbUserDecks,fbUserFactionProgression,fbUserGames,fbUserGameJobStatus,fbUserInventory,fbUserLogs,
fbUserMatchmakingErrors,fbUserNews,fbUserProgression,fbUserQuests,fbUserRanking,fbUserRewards,fbUserStats,fbUserTransactions,fbUserAchievements,
sqlUserCards,sqlUserCardCollection,sqlUserCardLog,sqlUserChallenges,sqlUserCharges,sqlUserCurrencyLog,sqlUserDecks,sqlUserFactionProgression,sqlUserFactionProgressionEvents,
sqlUserGames,sqlUserGauntletRun,sqlUserGauntletRunComplete,sqlUserGauntletTickets,sqlUserGauntletTicketsUsed,sqlUserProgression,
sqlUserProgressionDays,sqlUserQuests,sqlUserQuestsComplete,sqlUserRankEvents,sqlUserRankHistory,sqlUserRewards,sqlUserSpiritOrbs,sqlUserSpiritOrbsOpened,
sqlUserCodexInventory,sqlUserNewPlayerProgression,sqlUserAchievements,sqlUserChestRows,sqlUserChestOpenedRows,sqlUserChestKeyRows,sqlUserChestKeyUsedRows,sqlUserRow)->
userSnapshot = {
firebase: {}
sql: {}
}
userSnapshot.firebase.fbUserAggregates = fbUserAggregates?.val()
userSnapshot.firebase.fbUserArenaRun = fbUserArenaRun?.val()
userSnapshot.firebase.fbUserChallengeProgression = fbUserChallengeProgression?.val()
userSnapshot.firebase.fbUserDecks = fbUserDecks?.val()
userSnapshot.firebase.fbUserFactionProgression = fbUserFactionProgression?.val()
userSnapshot.firebase.fbUserGames = fbUserGames?.val()
userSnapshot.firebase.fbUserGameJobStatus = fbUserGameJobStatus?.val()
userSnapshot.firebase.fbUserInventory = fbUserInventory?.val()
userSnapshot.firebase.fbUserLogs = fbUserLogs?.val()
userSnapshot.firebase.fbUserMatchmakingErrors = fbUserMatchmakingErrors?.val()
userSnapshot.firebase.fbUserNews = fbUserNews?.val()
userSnapshot.firebase.fbUserProgression = fbUserProgression?.val()
userSnapshot.firebase.fbUserQuests = fbUserQuests?.val()
userSnapshot.firebase.fbUserRanking = fbUserRanking?.val()
userSnapshot.firebase.fbUserRewards = fbUserRewards?.val()
userSnapshot.firebase.fbUserStats = fbUserStats?.val()
userSnapshot.firebase.fbUserTransactions = fbUserTransactions?.val()
userSnapshot.firebase.fbUserAchievements = fbUserAchievements?.val()
userSnapshot.sql.sqlUserCards = sqlUserCards
userSnapshot.sql.sqlUserCardCollection = sqlUserCardCollection
userSnapshot.sql.sqlUserCardLog = sqlUserCardLog
userSnapshot.sql.sqlUserChallenges = sqlUserChallenges
userSnapshot.sql.sqlUserCharges = sqlUserCharges
userSnapshot.sql.sqlUserCurrencyLog = sqlUserCurrencyLog
userSnapshot.sql.sqlUserFactionProgression = sqlUserFactionProgression
userSnapshot.sql.sqlUserFactionProgressionEvents = sqlUserFactionProgressionEvents
userSnapshot.sql.sqlUserGames = sqlUserGames
userSnapshot.sql.sqlUserGauntletRun = sqlUserGauntletRun
userSnapshot.sql.sqlUserGauntletRunComplete = sqlUserGauntletRunComplete
userSnapshot.sql.sqlUserGauntletTickets = sqlUserGauntletTickets
userSnapshot.sql.sqlUserGauntletTicketsUsed = sqlUserGauntletTicketsUsed
userSnapshot.sql.sqlUserProgression = sqlUserProgression
userSnapshot.sql.sqlUserProgressionDays = sqlUserProgressionDays
userSnapshot.sql.sqlUserQuests = sqlUserQuests
userSnapshot.sql.sqlUserQuestsComplete = sqlUserQuestsComplete
userSnapshot.sql.sqlUserRankEvents = sqlUserRankEvents
userSnapshot.sql.sqlUserRankHistory = sqlUserRankHistory
userSnapshot.sql.sqlUserRewards = sqlUserRewards
userSnapshot.sql.sqlUserSpiritOrbs = sqlUserSpiritOrbs
userSnapshot.sql.sqlUserSpiritOrbsOpened = sqlUserSpiritOrbsOpened
userSnapshot.sql.sqlUserCodexInventory = sqlUserCodexInventory
userSnapshot.sql.sqlUserNewPlayerProgression = sqlUserNewPlayerProgression
userSnapshot.sql.sqlUserAchievements = sqlUserAchievements
userSnapshot.sql.sqlUserChestRows = sqlUserChestRows
userSnapshot.sql.sqlUserChestOpenedRows = sqlUserChestOpenedRows
userSnapshot.sql.sqlUserChestKeyRows = sqlUserChestKeyRows
userSnapshot.sql.sqlUserChestKeyUsedRows = sqlUserChestKeyUsedRows
userSnapshot.sql.sqlUserRow = sqlUserRow
Logger.module("UsersModule").timeEnd "___snapshotUserData() -> retrieving data for user ID #{userId.blue}".green
return userSnapshot
###*
# Tip your opponent for a specific game
# @public
# @param {String} userId User ID.
# @param {String} gameId Game ID to tip for
# @return {Promise} Promise that will resolve when complete
###
@tipAnotherPlayerForGame: (userId,gameId,goldAmount=5)->
MOMENT_NOW_UTC = moment().utc()
Promise.all([
knex("users").where('id',userId).first('username','wallet_gold')
knex("user_games").where({user_id:userId,game_id:gameId}).first()
]).spread (userRow,gameRow)->
# we need a game row
if not gameRow?
throw new Errors.NotFoundError("Player game not found")
# game must be less than a day old
timeSinceCreated = moment.duration(MOMENT_NOW_UTC.diff(moment.utc(gameRow.created_at)))
if timeSinceCreated.asDays() > 1.0
throw new Errors.BadRequestError("Game is too old")
# only the winner can tip
if not gameRow.is_winner
throw new Errors.BadRequestError("Only the winner can tip")
# we don't allow multiple tips
if gameRow.gold_tip_amount?
throw new Errors.AlreadyExistsError("Tip already given")
# we don't allow multiple tips
if userRow?.wallet_gold < goldAmount
throw new Errors.InsufficientFundsError("Not enough GOLD to tip")
# don't allow tips in friendly or sp games
if gameRow.game_type == "friendly" || gameRow.game_type == "single_player"
throw new Errors.BadRequestError("Can not tip in friendly or single player games")
# grab the opponent id so we know who to tip
playerId = gameRow.opponent_id
txPromise = knex.transaction (tx)->
Promise.all([
# debit user's gold
InventoryModule.debitGoldFromUser(txPromise,tx,userId,-goldAmount,"gold tip to #{gameId}:#{playerId}")
# give opponent gold
InventoryModule.giveUserGold(txPromise,tx,playerId,goldAmount,"gold tip from #{gameId}:#{userId}")
# update user game record
knex("user_games").where({user_id:userId,game_id:gameId}).update('gold_tip_amount',goldAmount).transacting(tx)
# update master game record
knex("games").where({id:gameId}).increment('gold_tip_amount',goldAmount).transacting(tx)
# update master game record
knex("users").where({id:userId}).increment('total_gold_tips_given',goldAmount).transacting(tx)
]).then ()->
return Promise.all([
SyncModule._bumpUserTransactionCounter(tx,userId)
SyncModule._bumpUserTransactionCounter(tx,playerId)
])
.then ()-> return UsersModule.inGameNotify(playerId,"#{userRow.username} tipped you #{goldAmount} GOLD","gold tip")
.then tx.commit
.catch tx.rollback
return txPromise
###*
# Suspend a user account
# @public
# @param {String} userId User ID.
# @param {String} reasonMemo Why is this user suspended?
# @return {Promise} Promise that will resolve when complete
###
@suspendUser: (userId,reasonMemo)->
return knex("users").where('id',userId).update({
is_suspended: true
suspended_at: moment().utc().toDate()
suspended_memo: reasonMemo
})
###*
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@isEligibleForTwitchDrop: (userId, itemId = null)->
return Promise.resolve(true)
###*
# Export a user account data as is (for user requested account export)
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@exportUser: (userId)->
return UsersModule.___snapshotUserData(userId)
.then (userData) ->
# we may want to filter out selective data at this point before exporting
return userData
.catch (e) ->
Logger.module("UsersModule").error "exportUser() -> #{e.message}".red
return null
###*
# Anonymize a user (prevents future logins and removes PID)
# @public
# @param {String} userId User ID.
# @return {Promise} Promise that will resolve when complete
###
@anonymizeUser: (userId)->
randomString = crypto.randomBytes(Math.ceil(32)).toString('hex').slice(0,64)
timestamp = moment().utc().valueOf()
randomEmail = PI:EMAIL:<EMAIL>END_PI"
randomUser = "#{timestamp}-#{randomString}-anon"
return UsersModule.userDataForId(userId)
.then (userRow) ->
if !userRow
throw new Errors.NotFoundError()
return Promise.all([
UsersModule.disassociateSteamId(userId),
UsersModule.changeEmail(userId, randomEmail),
UsersModule.changeUsername(userId, randomUser, true)
])
.catch (e) ->
# catch the error if any of the functions above fail and continue with suspending the user
Logger.module("UsersModule").error "anonymizeUser() partial failure -> #{e.message}".red
.then () ->
return UsersModule.suspendUser(userId, "User requested account deletion.")
module.exports = UsersModule
|
[
{
"context": "\n email: validEmail\n password: 'secret123'\n password_confirmation: 'secret123'\n ",
"end": 342,
"score": 0.9995144605636597,
"start": 333,
"tag": "PASSWORD",
"value": "secret123"
},
{
"context": "rd: 'secret123'\n password_confir... | test/test/unit/ng-token-auth/email-registration-submission.coffee | Neil-Ni/ng-token-auth | 1,216 | suite 'email registration submission', ->
dfd = null
suite 'successful submission', ->
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(201, {success: true})
suite 'service module', ->
setup ->
dfd = $auth.submitRegistration({
email: validEmail
password: 'secret123'
password_confirmation: 'secret123'
})
$httpBackend.flush()
test '$rootScope should broadcast success event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-success')
test 'promise is resolved', ->
resolved = false
dfd.then(-> resolved = true)
$timeout.flush()
assert(resolved)
suite 'directive access', ->
args =
email: validEmail
password: 'secret123'
password_confirmation: 'secret123'
test '$auth.submitRegistration should have been called', ->
sinon.spy $auth, 'submitRegistration'
$rootScope.submitRegistration(args)
$httpBackend.flush()
suite 'failed submission', ->
suite 'mismatched password', ->
errorResp =
success: false
errors: ['balls']
fieldErrors: {
password_confirmation: ['padword midmadch']
}
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(422, errorResp)
dfd = $auth.submitRegistration({
email: validEmail
password: 'secret123'
password_confirmation: 'bogus'
})
$httpBackend.flush()
test '$rootScope should broadcast failure event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-error', errorResp)
test 'promise is rejected', ->
caught = false
dfd.catch(-> caught = true)
$timeout.flush()
assert(caught)
suite 'existing user', ->
errorResp =
success: false
errors: ['balls']
fieldErrors: {
email: ['user exists']
}
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(422, errorResp)
dfd = $auth.submitRegistration({
email: validEmail
password: 'secret123'
password_confirmation: 'bogus'
})
$httpBackend.flush()
test '$rootScope should broadcast failure event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-error', errorResp)
test 'promise is rejected', ->
caught = false
dfd.catch(-> caught = true)
$timeout.flush()
assert(caught)
| 179851 | suite 'email registration submission', ->
dfd = null
suite 'successful submission', ->
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(201, {success: true})
suite 'service module', ->
setup ->
dfd = $auth.submitRegistration({
email: validEmail
password: '<PASSWORD>'
password_confirmation: '<PASSWORD>'
})
$httpBackend.flush()
test '$rootScope should broadcast success event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-success')
test 'promise is resolved', ->
resolved = false
dfd.then(-> resolved = true)
$timeout.flush()
assert(resolved)
suite 'directive access', ->
args =
email: validEmail
password: '<PASSWORD>'
password_confirmation: '<PASSWORD>'
test '$auth.submitRegistration should have been called', ->
sinon.spy $auth, 'submitRegistration'
$rootScope.submitRegistration(args)
$httpBackend.flush()
suite 'failed submission', ->
suite 'mismatched password', ->
errorResp =
success: false
errors: ['balls']
fieldErrors: {
password_confirmation: ['<PASSWORD>']
}
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(422, errorResp)
dfd = $auth.submitRegistration({
email: validEmail
password: '<PASSWORD>'
password_confirmation: '<PASSWORD>'
})
$httpBackend.flush()
test '$rootScope should broadcast failure event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-error', errorResp)
test 'promise is rejected', ->
caught = false
dfd.catch(-> caught = true)
$timeout.flush()
assert(caught)
suite 'existing user', ->
errorResp =
success: false
errors: ['balls']
fieldErrors: {
email: ['user exists']
}
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(422, errorResp)
dfd = $auth.submitRegistration({
email: validEmail
password: '<PASSWORD>'
password_confirmation: 'bogus'
})
$httpBackend.flush()
test '$rootScope should broadcast failure event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-error', errorResp)
test 'promise is rejected', ->
caught = false
dfd.catch(-> caught = true)
$timeout.flush()
assert(caught)
| true | suite 'email registration submission', ->
dfd = null
suite 'successful submission', ->
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(201, {success: true})
suite 'service module', ->
setup ->
dfd = $auth.submitRegistration({
email: validEmail
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_confirmation: 'PI:PASSWORD:<PASSWORD>END_PI'
})
$httpBackend.flush()
test '$rootScope should broadcast success event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-success')
test 'promise is resolved', ->
resolved = false
dfd.then(-> resolved = true)
$timeout.flush()
assert(resolved)
suite 'directive access', ->
args =
email: validEmail
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_confirmation: 'PI:PASSWORD:<PASSWORD>END_PI'
test '$auth.submitRegistration should have been called', ->
sinon.spy $auth, 'submitRegistration'
$rootScope.submitRegistration(args)
$httpBackend.flush()
suite 'failed submission', ->
suite 'mismatched password', ->
errorResp =
success: false
errors: ['balls']
fieldErrors: {
password_confirmation: ['PI:PASSWORD:<PASSWORD>END_PI']
}
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(422, errorResp)
dfd = $auth.submitRegistration({
email: validEmail
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_confirmation: 'PI:PASSWORD:<PASSWORD>END_PI'
})
$httpBackend.flush()
test '$rootScope should broadcast failure event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-error', errorResp)
test 'promise is rejected', ->
caught = false
dfd.catch(-> caught = true)
$timeout.flush()
assert(caught)
suite 'existing user', ->
errorResp =
success: false
errors: ['balls']
fieldErrors: {
email: ['user exists']
}
setup ->
$httpBackend
.expectPOST('/api/auth')
.respond(422, errorResp)
dfd = $auth.submitRegistration({
email: validEmail
password: 'PI:PASSWORD:<PASSWORD>END_PI'
password_confirmation: 'bogus'
})
$httpBackend.flush()
test '$rootScope should broadcast failure event', ->
assert $rootScope.$broadcast.calledWithMatch('auth:registration-email-error', errorResp)
test 'promise is rejected', ->
caught = false
dfd.catch(-> caught = true)
$timeout.flush()
assert(caught)
|
[
{
"context": "mple_reverse.js\n#\n\nSlack = require '..'\n\ntoken = 'xoxb-YOUR-TOKEN-HERE' # Add a bot at https://my.slack.com/services/new",
"end": 660,
"score": 0.9581296443939209,
"start": 640,
"tag": "KEY",
"value": "xoxb-YOUR-TOKEN-HERE"
},
{
"context": "WN_CHANNEL'\n\n userNam... | examples/simple_reverse.coffee | lstoll/node-slack-client | 5 | # This is a simple example of how to use the slack-client module in CoffeeScript. It creates a
# bot that responds to all messages in all channels it is in with a reversed
# string of the text received.
#
# To run, copy your token below, then, from the project root directory:
#
# To run the script directly
# npm install
# node_modules/coffee-script/bin/coffee examples/simple_reverse.coffee
#
# If you want to look at / run / modify the compiled javascript
# npm install
# node_modules/coffee-script/bin/coffee -c examples/simple_reverse.coffee
# cd examples
# node simple_reverse.js
#
Slack = require '..'
token = 'xoxb-YOUR-TOKEN-HERE' # Add a bot at https://my.slack.com/services/new/bot and copy the token here.
autoReconnect = true
autoMark = true
slack = new Slack(token, autoReconnect, autoMark)
slack.on 'open', ->
channels = []
groups = []
unreads = slack.getUnreadCount()
# Get all the channels that bot is a member of
channels = ("##{channel.name}" for id, channel of slack.channels when channel.is_member)
# Get all groups that are open and not archived
groups = (group.name for id, group of slack.groups when group.is_open and not group.is_archived)
console.log "Welcome to Slack. You are @#{slack.self.name} of #{slack.team.name}"
console.log 'You are in: ' + channels.join(', ')
console.log 'As well as: ' + groups.join(', ')
messages = if unreads is 1 then 'message' else 'messages'
console.log "You have #{unreads} unread #{messages}"
slack.on 'message', (message) ->
channel = slack.getChannelGroupOrDMByID(message.channel)
user = slack.getUserByID(message.user)
response = ''
{type, ts, text} = message
channelName = if channel?.is_channel then '#' else ''
channelName = channelName + if channel then channel.name else 'UNKNOWN_CHANNEL'
userName = if user?.name? then "@#{user.name}" else "UNKNOWN_USER"
console.log """
Received: #{type} #{channelName} #{userName} #{ts} "#{text}"
"""
# Respond to messages with the reverse of the text received.
if type is 'message' and text? and channel?
response = text.split('').reverse().join('')
channel.send response
console.log """
@#{slack.self.name} responded with "#{response}"
"""
else
#this one should probably be impossible, since we're in slack.on 'message'
typeError = if type isnt 'message' then "unexpected type #{type}." else null
#Can happen on delete/edit/a few other events
textError = if not text? then 'text was undefined.' else null
#In theory some events could happen with no channel
channelError = if not channel? then 'channel was undefined.' else null
#Space delimited string of my errors
errors = [typeError, textError, channelError].filter((element) -> element isnt null).join ' '
console.log """
@#{slack.self.name} could not respond. #{errors}
"""
slack.on 'error', (error) ->
console.error "Error: #{error}"
slack.login()
| 60246 | # This is a simple example of how to use the slack-client module in CoffeeScript. It creates a
# bot that responds to all messages in all channels it is in with a reversed
# string of the text received.
#
# To run, copy your token below, then, from the project root directory:
#
# To run the script directly
# npm install
# node_modules/coffee-script/bin/coffee examples/simple_reverse.coffee
#
# If you want to look at / run / modify the compiled javascript
# npm install
# node_modules/coffee-script/bin/coffee -c examples/simple_reverse.coffee
# cd examples
# node simple_reverse.js
#
Slack = require '..'
token = '<KEY>' # Add a bot at https://my.slack.com/services/new/bot and copy the token here.
autoReconnect = true
autoMark = true
slack = new Slack(token, autoReconnect, autoMark)
slack.on 'open', ->
channels = []
groups = []
unreads = slack.getUnreadCount()
# Get all the channels that bot is a member of
channels = ("##{channel.name}" for id, channel of slack.channels when channel.is_member)
# Get all groups that are open and not archived
groups = (group.name for id, group of slack.groups when group.is_open and not group.is_archived)
console.log "Welcome to Slack. You are @#{slack.self.name} of #{slack.team.name}"
console.log 'You are in: ' + channels.join(', ')
console.log 'As well as: ' + groups.join(', ')
messages = if unreads is 1 then 'message' else 'messages'
console.log "You have #{unreads} unread #{messages}"
slack.on 'message', (message) ->
channel = slack.getChannelGroupOrDMByID(message.channel)
user = slack.getUserByID(message.user)
response = ''
{type, ts, text} = message
channelName = if channel?.is_channel then '#' else ''
channelName = channelName + if channel then channel.name else 'UNKNOWN_CHANNEL'
userName = if user?.name? then "@#{user.name}" else "UNKNOWN_<PASSWORD>"
console.log """
Received: #{type} #{channelName} #{userName} #{ts} "#{text}"
"""
# Respond to messages with the reverse of the text received.
if type is 'message' and text? and channel?
response = text.split('').reverse().join('')
channel.send response
console.log """
@#{slack.self.name} responded with "#{response}"
"""
else
#this one should probably be impossible, since we're in slack.on 'message'
typeError = if type isnt 'message' then "unexpected type #{type}." else null
#Can happen on delete/edit/a few other events
textError = if not text? then 'text was undefined.' else null
#In theory some events could happen with no channel
channelError = if not channel? then 'channel was undefined.' else null
#Space delimited string of my errors
errors = [typeError, textError, channelError].filter((element) -> element isnt null).join ' '
console.log """
@#{slack.self.name} could not respond. #{errors}
"""
slack.on 'error', (error) ->
console.error "Error: #{error}"
slack.login()
| true | # This is a simple example of how to use the slack-client module in CoffeeScript. It creates a
# bot that responds to all messages in all channels it is in with a reversed
# string of the text received.
#
# To run, copy your token below, then, from the project root directory:
#
# To run the script directly
# npm install
# node_modules/coffee-script/bin/coffee examples/simple_reverse.coffee
#
# If you want to look at / run / modify the compiled javascript
# npm install
# node_modules/coffee-script/bin/coffee -c examples/simple_reverse.coffee
# cd examples
# node simple_reverse.js
#
Slack = require '..'
token = 'PI:KEY:<KEY>END_PI' # Add a bot at https://my.slack.com/services/new/bot and copy the token here.
autoReconnect = true
autoMark = true
slack = new Slack(token, autoReconnect, autoMark)
slack.on 'open', ->
channels = []
groups = []
unreads = slack.getUnreadCount()
# Get all the channels that bot is a member of
channels = ("##{channel.name}" for id, channel of slack.channels when channel.is_member)
# Get all groups that are open and not archived
groups = (group.name for id, group of slack.groups when group.is_open and not group.is_archived)
console.log "Welcome to Slack. You are @#{slack.self.name} of #{slack.team.name}"
console.log 'You are in: ' + channels.join(', ')
console.log 'As well as: ' + groups.join(', ')
messages = if unreads is 1 then 'message' else 'messages'
console.log "You have #{unreads} unread #{messages}"
slack.on 'message', (message) ->
channel = slack.getChannelGroupOrDMByID(message.channel)
user = slack.getUserByID(message.user)
response = ''
{type, ts, text} = message
channelName = if channel?.is_channel then '#' else ''
channelName = channelName + if channel then channel.name else 'UNKNOWN_CHANNEL'
userName = if user?.name? then "@#{user.name}" else "UNKNOWN_PI:PASSWORD:<PASSWORD>END_PI"
console.log """
Received: #{type} #{channelName} #{userName} #{ts} "#{text}"
"""
# Respond to messages with the reverse of the text received.
if type is 'message' and text? and channel?
response = text.split('').reverse().join('')
channel.send response
console.log """
@#{slack.self.name} responded with "#{response}"
"""
else
#this one should probably be impossible, since we're in slack.on 'message'
typeError = if type isnt 'message' then "unexpected type #{type}." else null
#Can happen on delete/edit/a few other events
textError = if not text? then 'text was undefined.' else null
#In theory some events could happen with no channel
channelError = if not channel? then 'channel was undefined.' else null
#Space delimited string of my errors
errors = [typeError, textError, channelError].filter((element) -> element isnt null).join ' '
console.log """
@#{slack.self.name} could not respond. #{errors}
"""
slack.on 'error', (error) ->
console.error "Error: #{error}"
slack.login()
|
[
{
"context": "port = auth.init app\nsession = exSession secret: '78UScJ80zW7XAfxwvHzsg9KpOY', resave: false, saveUninitialized: false\n\norm.pr",
"end": 861,
"score": 0.9934632182121277,
"start": 835,
"tag": "KEY",
"value": "78UScJ80zW7XAfxwvHzsg9KpOY"
}
] | server/api/app.coffee | Oziabr/privateer | 7 | _ = require 'lodash'
express = require 'express'
favicon = require 'serve-favicon'
cookieParser = require 'cookie-parser'
bodyParser = require 'body-parser'
jade = require 'jade'
exSession = require 'express-session'
path = require 'path'
logger = require 'morgan'
orm = require './orm'
router = require './router'
auth = require './auth'
authRoutes = require '../routes/auth'
filetype = require './filetype'
module.exports = app = express()
# helpers
express.request.getModel = (name) ->
return false if !(model = app.get('orm').models[name])
return model
app.set 'errorHandler', (res) -> (err) ->
# console.log 'err', _.keys err
res.render 'error', error: err
orm.init app
passport = auth.init app
session = exSession secret: '78UScJ80zW7XAfxwvHzsg9KpOY', resave: false, saveUninitialized: false
orm.process app
filetype.init app, 'public/img'
# view engine setup
app.set 'views', './server/views'
app.set 'view engine', 'jade'
app.use favicon './public/favicon.ico'
app.use logger 'dev' if process.env.NODE_ENV != 'test'
app.use express.static './public', maxAge: 86400000
app.use cookieParser()
app.use bodyParser.json()
app.use bodyParser.urlencoded extended: false
app.use session
app.use passport.initialize()
app.use passport.session()
app.use (req, res, next) ->
return next() if !req.user
res.locals.user = (req.app.get 'profiles')[req.user]
next()
router app
app.get '/', (req, res) ->
res.render 'index', locations: []
# error handlers
# app.use (req, res, next) ->
# (req.app.get 'errorHandler')(res) message: 'Not Found', status: 404
# development error handler
# will print stacktrace
if app.get('env') == 'development'
app.use (err, req, res, next) ->
res.status err.status || 500
res.render 'error',
message: err.message
error: err
# production error handler
# no stacktraces leaked to user
app.use (err, req, res, next) ->
res.status err.status || 500
res.render 'error',
message: err.message
error: {}
| 45084 | _ = require 'lodash'
express = require 'express'
favicon = require 'serve-favicon'
cookieParser = require 'cookie-parser'
bodyParser = require 'body-parser'
jade = require 'jade'
exSession = require 'express-session'
path = require 'path'
logger = require 'morgan'
orm = require './orm'
router = require './router'
auth = require './auth'
authRoutes = require '../routes/auth'
filetype = require './filetype'
module.exports = app = express()
# helpers
express.request.getModel = (name) ->
return false if !(model = app.get('orm').models[name])
return model
app.set 'errorHandler', (res) -> (err) ->
# console.log 'err', _.keys err
res.render 'error', error: err
orm.init app
passport = auth.init app
session = exSession secret: '<KEY>', resave: false, saveUninitialized: false
orm.process app
filetype.init app, 'public/img'
# view engine setup
app.set 'views', './server/views'
app.set 'view engine', 'jade'
app.use favicon './public/favicon.ico'
app.use logger 'dev' if process.env.NODE_ENV != 'test'
app.use express.static './public', maxAge: 86400000
app.use cookieParser()
app.use bodyParser.json()
app.use bodyParser.urlencoded extended: false
app.use session
app.use passport.initialize()
app.use passport.session()
app.use (req, res, next) ->
return next() if !req.user
res.locals.user = (req.app.get 'profiles')[req.user]
next()
router app
app.get '/', (req, res) ->
res.render 'index', locations: []
# error handlers
# app.use (req, res, next) ->
# (req.app.get 'errorHandler')(res) message: 'Not Found', status: 404
# development error handler
# will print stacktrace
if app.get('env') == 'development'
app.use (err, req, res, next) ->
res.status err.status || 500
res.render 'error',
message: err.message
error: err
# production error handler
# no stacktraces leaked to user
app.use (err, req, res, next) ->
res.status err.status || 500
res.render 'error',
message: err.message
error: {}
| true | _ = require 'lodash'
express = require 'express'
favicon = require 'serve-favicon'
cookieParser = require 'cookie-parser'
bodyParser = require 'body-parser'
jade = require 'jade'
exSession = require 'express-session'
path = require 'path'
logger = require 'morgan'
orm = require './orm'
router = require './router'
auth = require './auth'
authRoutes = require '../routes/auth'
filetype = require './filetype'
module.exports = app = express()
# helpers
express.request.getModel = (name) ->
return false if !(model = app.get('orm').models[name])
return model
app.set 'errorHandler', (res) -> (err) ->
# console.log 'err', _.keys err
res.render 'error', error: err
orm.init app
passport = auth.init app
session = exSession secret: 'PI:KEY:<KEY>END_PI', resave: false, saveUninitialized: false
orm.process app
filetype.init app, 'public/img'
# view engine setup
app.set 'views', './server/views'
app.set 'view engine', 'jade'
app.use favicon './public/favicon.ico'
app.use logger 'dev' if process.env.NODE_ENV != 'test'
app.use express.static './public', maxAge: 86400000
app.use cookieParser()
app.use bodyParser.json()
app.use bodyParser.urlencoded extended: false
app.use session
app.use passport.initialize()
app.use passport.session()
app.use (req, res, next) ->
return next() if !req.user
res.locals.user = (req.app.get 'profiles')[req.user]
next()
router app
app.get '/', (req, res) ->
res.render 'index', locations: []
# error handlers
# app.use (req, res, next) ->
# (req.app.get 'errorHandler')(res) message: 'Not Found', status: 404
# development error handler
# will print stacktrace
if app.get('env') == 'development'
app.use (err, req, res, next) ->
res.status err.status || 500
res.render 'error',
message: err.message
error: err
# production error handler
# no stacktraces leaked to user
app.use (err, req, res, next) ->
res.status err.status || 500
res.render 'error',
message: err.message
error: {}
|
[
{
"context": "# **Author:** Peter Urbak<br/>\n# **Version:** 2013-03-10\n\nroot = exports ? ",
"end": 25,
"score": 0.9998581409454346,
"start": 14,
"tag": "NAME",
"value": "Peter Urbak"
}
] | client_src/objectModel.coffee | dragonwasrobot/gesture-recognition | 2 | # **Author:** Peter Urbak<br/>
# **Version:** 2013-03-10
root = exports ? window
# The `ObjectModel` encapsulates the state of an object on the multi-touch
# table.
class App.ObjectModel
# ### Constructors
# Constructs an `ObjectModel`.
#
# - **object:** The JSON object.
# - **surface:** The surface <div> tag.
# - **objWidth:** The object width.
# - **objHeight:** The object height.
constructor: (object, surface, width, height) ->
@unfolded = false
@selected = false
@div = $('<div class="model"/>')
surface.append @div
@moveToPosition object.x, object.y
@div.height(@div.height() + 100) # magic.
paper = Raphael(@div.get(0), @div.width(), @div.height())
@container = paper.rect(20, 20, width, height, 6)
@container.attr('fill', 'rgb(214,135,45)')
# Moves the `ObjectModel` to the specified set of coordinates.
#
# - **x:** The x-coordinate.
# - **y:** The y-coordinate.
moveToPosition: (x, y) ->
position = @div.position()
width = @div.width()
height = @div.height()
parentWidth = @div.offsetParent().width()
parentHeight = @div.offsetParent().height()
halfWidth = ((width / parentWidth) * 100) / 2
halfHeight = ((height / parentHeight) * 100) / 2
@div.css('left', (String) ((x * 100) - halfWidth) + "%")
@div.css('top', (String) ((y * 100) - halfHeight) + "%")
# Rotates the `ObjectModel`.
#
# - **angle:** The angle to be rotated.
rotate: (angle) ->
@container.transform('r' + angle)
# Removes the `ObjectModel`.
remove: () ->
@div.remove()
@container.remove()
# Changes the color of the `ObjectModel`.
#
# - **color:** The new color of the object.
changeColor: (color) ->
newColor = 'rgb(' + color.red + ', ' + color.green + ', ' + color.blue + ')'
@container.attr('fill', newColor)
# Returns true if the object is unfolded, false otherwise.
isUnfolded: () -> @unfolded
# Folds/Unfolds the `ObjectModel`.
setUnfolded: (unfolded) -> @unfolded = unfolded
# Returns true if the object is selected, false otherwise.
isSelected: () -> @selected
# Selects/Deselects the `ObjectModel`.
setSelected: (selected) -> @selected = selected
# The `ObjectUpdate` encapsulates an update of an `ObjectModel` having a
# timestamp of the update along with a new position.
class App.ObjectUpdate
constructor: (@timestamp, @position) ->
| 32272 | # **Author:** <NAME><br/>
# **Version:** 2013-03-10
root = exports ? window
# The `ObjectModel` encapsulates the state of an object on the multi-touch
# table.
class App.ObjectModel
# ### Constructors
# Constructs an `ObjectModel`.
#
# - **object:** The JSON object.
# - **surface:** The surface <div> tag.
# - **objWidth:** The object width.
# - **objHeight:** The object height.
constructor: (object, surface, width, height) ->
@unfolded = false
@selected = false
@div = $('<div class="model"/>')
surface.append @div
@moveToPosition object.x, object.y
@div.height(@div.height() + 100) # magic.
paper = Raphael(@div.get(0), @div.width(), @div.height())
@container = paper.rect(20, 20, width, height, 6)
@container.attr('fill', 'rgb(214,135,45)')
# Moves the `ObjectModel` to the specified set of coordinates.
#
# - **x:** The x-coordinate.
# - **y:** The y-coordinate.
moveToPosition: (x, y) ->
position = @div.position()
width = @div.width()
height = @div.height()
parentWidth = @div.offsetParent().width()
parentHeight = @div.offsetParent().height()
halfWidth = ((width / parentWidth) * 100) / 2
halfHeight = ((height / parentHeight) * 100) / 2
@div.css('left', (String) ((x * 100) - halfWidth) + "%")
@div.css('top', (String) ((y * 100) - halfHeight) + "%")
# Rotates the `ObjectModel`.
#
# - **angle:** The angle to be rotated.
rotate: (angle) ->
@container.transform('r' + angle)
# Removes the `ObjectModel`.
remove: () ->
@div.remove()
@container.remove()
# Changes the color of the `ObjectModel`.
#
# - **color:** The new color of the object.
changeColor: (color) ->
newColor = 'rgb(' + color.red + ', ' + color.green + ', ' + color.blue + ')'
@container.attr('fill', newColor)
# Returns true if the object is unfolded, false otherwise.
isUnfolded: () -> @unfolded
# Folds/Unfolds the `ObjectModel`.
setUnfolded: (unfolded) -> @unfolded = unfolded
# Returns true if the object is selected, false otherwise.
isSelected: () -> @selected
# Selects/Deselects the `ObjectModel`.
setSelected: (selected) -> @selected = selected
# The `ObjectUpdate` encapsulates an update of an `ObjectModel` having a
# timestamp of the update along with a new position.
class App.ObjectUpdate
constructor: (@timestamp, @position) ->
| true | # **Author:** PI:NAME:<NAME>END_PI<br/>
# **Version:** 2013-03-10
root = exports ? window
# The `ObjectModel` encapsulates the state of an object on the multi-touch
# table.
class App.ObjectModel
# ### Constructors
# Constructs an `ObjectModel`.
#
# - **object:** The JSON object.
# - **surface:** The surface <div> tag.
# - **objWidth:** The object width.
# - **objHeight:** The object height.
constructor: (object, surface, width, height) ->
@unfolded = false
@selected = false
@div = $('<div class="model"/>')
surface.append @div
@moveToPosition object.x, object.y
@div.height(@div.height() + 100) # magic.
paper = Raphael(@div.get(0), @div.width(), @div.height())
@container = paper.rect(20, 20, width, height, 6)
@container.attr('fill', 'rgb(214,135,45)')
# Moves the `ObjectModel` to the specified set of coordinates.
#
# - **x:** The x-coordinate.
# - **y:** The y-coordinate.
moveToPosition: (x, y) ->
position = @div.position()
width = @div.width()
height = @div.height()
parentWidth = @div.offsetParent().width()
parentHeight = @div.offsetParent().height()
halfWidth = ((width / parentWidth) * 100) / 2
halfHeight = ((height / parentHeight) * 100) / 2
@div.css('left', (String) ((x * 100) - halfWidth) + "%")
@div.css('top', (String) ((y * 100) - halfHeight) + "%")
# Rotates the `ObjectModel`.
#
# - **angle:** The angle to be rotated.
rotate: (angle) ->
@container.transform('r' + angle)
# Removes the `ObjectModel`.
remove: () ->
@div.remove()
@container.remove()
# Changes the color of the `ObjectModel`.
#
# - **color:** The new color of the object.
changeColor: (color) ->
newColor = 'rgb(' + color.red + ', ' + color.green + ', ' + color.blue + ')'
@container.attr('fill', newColor)
# Returns true if the object is unfolded, false otherwise.
isUnfolded: () -> @unfolded
# Folds/Unfolds the `ObjectModel`.
setUnfolded: (unfolded) -> @unfolded = unfolded
# Returns true if the object is selected, false otherwise.
isSelected: () -> @selected
# Selects/Deselects the `ObjectModel`.
setSelected: (selected) -> @selected = selected
# The `ObjectUpdate` encapsulates an update of an `ObjectModel` having a
# timestamp of the update along with a new position.
class App.ObjectUpdate
constructor: (@timestamp, @position) ->
|
[
{
"context": "\"eventList\")}\"\n else\n events = [\n name: \"Christmas\"\n date: \"2014-12-25\"\n ]\n events\n\nPebble.",
"end": 1915,
"score": 0.9364573955535889,
"start": 1906,
"tag": "NAME",
"value": "Christmas"
}
] | src/coffee/main.coffee | VGraupera/countdown-watchface | 1 | maxTriesForSendingAppMessage = 3
timeoutForAppMessageRetry = 3000
timeoutForAppMessage = 100
appMessageQueue = []
sendAppMessageQueue = ->
if appMessageQueue.length > 0
currentAppMessage = appMessageQueue[0]
currentAppMessage.numTries = currentAppMessage.numTries or 0
if currentAppMessage.numTries < maxTriesForSendingAppMessage
console.log "Sending currentAppMessage to Pebble: " + JSON.stringify(currentAppMessage)
Pebble.sendAppMessage currentAppMessage.message, (e) ->
appMessageQueue.shift()
setTimeout (->
sendAppMessageQueue()
), timeoutForAppMessage
, (e) ->
console.log "Failed sending currentAppMessage for #{JSON.stringify(currentAppMessage)}\n
Error: #{e.data.error.message}"
currentAppMessage.numTries++
setTimeout (->
sendAppMessageQueue()
), timeoutForAppMessageRetry
else
appMessageQueue.shift()
console.log "Failed sending AppMessage bailing. " + JSON.stringify(currentAppMessage)
else
console.log "AppMessage queue is empty."
sendConfiguration = ->
console.log "Sending config ..."
events = readEvents()
appMessageQueue.push
message:
reset: 1
length: events.length
for event in events
date = new Date(event.date)
appMessageQueue.push
message:
name: event.name
target: "" + date.getTime() / 1000
vibrate = false
if localStorage.getItem("vibrate") isnt null
vibrate = JSON.parse(localStorage.getItem("vibrate"))
appMessageQueue.push
message:
vibrate: vibrate && 1 || 0
sendAppMessageQueue()
readEvents = () ->
events = []
if localStorage.getItem("eventList") isnt null
try
events = JSON.parse(localStorage.getItem("eventList"))
catch e
console.log "exception reading #{localStorage.getItem("eventList")}"
else
events = [
name: "Christmas"
date: "2014-12-25"
]
events
Pebble.addEventListener "ready", (e) ->
console.log "On ready event ..."
sendConfiguration()
Pebble.addEventListener "appmessage", (e) ->
console.log "Received from Pebble: " + JSON.stringify(e.payload)
if e.payload.update
sendConfiguration()
Pebble.addEventListener "showConfiguration", (e) ->
vibrate = localStorage.getItem("vibrate") or false
events = readEvents()
url = "http://countdown-watchface-v3.s3-website-us-west-1.amazonaws.com?events=" +
encodeURIComponent(JSON.stringify(events)) + "&vibrate=#{vibrate}"
console.log "open settings: #{url}"
Pebble.openURL url
Pebble.addEventListener "webviewclosed", (e) ->
if e.response
params = JSON.parse(decodeURIComponent(e.response))
console.log "Params received from settings page: " + JSON.stringify(params)
# cache to local storage;
localStorage.setItem "eventList", JSON.stringify(params.events)
localStorage.setItem "vibrate", params.vibrate
sendConfiguration()
| 187672 | maxTriesForSendingAppMessage = 3
timeoutForAppMessageRetry = 3000
timeoutForAppMessage = 100
appMessageQueue = []
sendAppMessageQueue = ->
if appMessageQueue.length > 0
currentAppMessage = appMessageQueue[0]
currentAppMessage.numTries = currentAppMessage.numTries or 0
if currentAppMessage.numTries < maxTriesForSendingAppMessage
console.log "Sending currentAppMessage to Pebble: " + JSON.stringify(currentAppMessage)
Pebble.sendAppMessage currentAppMessage.message, (e) ->
appMessageQueue.shift()
setTimeout (->
sendAppMessageQueue()
), timeoutForAppMessage
, (e) ->
console.log "Failed sending currentAppMessage for #{JSON.stringify(currentAppMessage)}\n
Error: #{e.data.error.message}"
currentAppMessage.numTries++
setTimeout (->
sendAppMessageQueue()
), timeoutForAppMessageRetry
else
appMessageQueue.shift()
console.log "Failed sending AppMessage bailing. " + JSON.stringify(currentAppMessage)
else
console.log "AppMessage queue is empty."
sendConfiguration = ->
console.log "Sending config ..."
events = readEvents()
appMessageQueue.push
message:
reset: 1
length: events.length
for event in events
date = new Date(event.date)
appMessageQueue.push
message:
name: event.name
target: "" + date.getTime() / 1000
vibrate = false
if localStorage.getItem("vibrate") isnt null
vibrate = JSON.parse(localStorage.getItem("vibrate"))
appMessageQueue.push
message:
vibrate: vibrate && 1 || 0
sendAppMessageQueue()
readEvents = () ->
events = []
if localStorage.getItem("eventList") isnt null
try
events = JSON.parse(localStorage.getItem("eventList"))
catch e
console.log "exception reading #{localStorage.getItem("eventList")}"
else
events = [
name: "<NAME>"
date: "2014-12-25"
]
events
Pebble.addEventListener "ready", (e) ->
console.log "On ready event ..."
sendConfiguration()
Pebble.addEventListener "appmessage", (e) ->
console.log "Received from Pebble: " + JSON.stringify(e.payload)
if e.payload.update
sendConfiguration()
Pebble.addEventListener "showConfiguration", (e) ->
vibrate = localStorage.getItem("vibrate") or false
events = readEvents()
url = "http://countdown-watchface-v3.s3-website-us-west-1.amazonaws.com?events=" +
encodeURIComponent(JSON.stringify(events)) + "&vibrate=#{vibrate}"
console.log "open settings: #{url}"
Pebble.openURL url
Pebble.addEventListener "webviewclosed", (e) ->
if e.response
params = JSON.parse(decodeURIComponent(e.response))
console.log "Params received from settings page: " + JSON.stringify(params)
# cache to local storage;
localStorage.setItem "eventList", JSON.stringify(params.events)
localStorage.setItem "vibrate", params.vibrate
sendConfiguration()
| true | maxTriesForSendingAppMessage = 3
timeoutForAppMessageRetry = 3000
timeoutForAppMessage = 100
appMessageQueue = []
sendAppMessageQueue = ->
if appMessageQueue.length > 0
currentAppMessage = appMessageQueue[0]
currentAppMessage.numTries = currentAppMessage.numTries or 0
if currentAppMessage.numTries < maxTriesForSendingAppMessage
console.log "Sending currentAppMessage to Pebble: " + JSON.stringify(currentAppMessage)
Pebble.sendAppMessage currentAppMessage.message, (e) ->
appMessageQueue.shift()
setTimeout (->
sendAppMessageQueue()
), timeoutForAppMessage
, (e) ->
console.log "Failed sending currentAppMessage for #{JSON.stringify(currentAppMessage)}\n
Error: #{e.data.error.message}"
currentAppMessage.numTries++
setTimeout (->
sendAppMessageQueue()
), timeoutForAppMessageRetry
else
appMessageQueue.shift()
console.log "Failed sending AppMessage bailing. " + JSON.stringify(currentAppMessage)
else
console.log "AppMessage queue is empty."
sendConfiguration = ->
console.log "Sending config ..."
events = readEvents()
appMessageQueue.push
message:
reset: 1
length: events.length
for event in events
date = new Date(event.date)
appMessageQueue.push
message:
name: event.name
target: "" + date.getTime() / 1000
vibrate = false
if localStorage.getItem("vibrate") isnt null
vibrate = JSON.parse(localStorage.getItem("vibrate"))
appMessageQueue.push
message:
vibrate: vibrate && 1 || 0
sendAppMessageQueue()
readEvents = () ->
events = []
if localStorage.getItem("eventList") isnt null
try
events = JSON.parse(localStorage.getItem("eventList"))
catch e
console.log "exception reading #{localStorage.getItem("eventList")}"
else
events = [
name: "PI:NAME:<NAME>END_PI"
date: "2014-12-25"
]
events
Pebble.addEventListener "ready", (e) ->
console.log "On ready event ..."
sendConfiguration()
Pebble.addEventListener "appmessage", (e) ->
console.log "Received from Pebble: " + JSON.stringify(e.payload)
if e.payload.update
sendConfiguration()
Pebble.addEventListener "showConfiguration", (e) ->
vibrate = localStorage.getItem("vibrate") or false
events = readEvents()
url = "http://countdown-watchface-v3.s3-website-us-west-1.amazonaws.com?events=" +
encodeURIComponent(JSON.stringify(events)) + "&vibrate=#{vibrate}"
console.log "open settings: #{url}"
Pebble.openURL url
Pebble.addEventListener "webviewclosed", (e) ->
if e.response
params = JSON.parse(decodeURIComponent(e.response))
console.log "Params received from settings page: " + JSON.stringify(params)
# cache to local storage;
localStorage.setItem "eventList", JSON.stringify(params.events)
localStorage.setItem "vibrate", params.vibrate
sendConfiguration()
|
[
{
"context": "nk\"\n contact: \"Kapcsolat\"\n twitter_follow: \"Követés\"\n\n forms:\n name: \"Név\"\n email: \"Email cím\"",
"end": 576,
"score": 0.9018555879592896,
"start": 569,
"tag": "USERNAME",
"value": "Követés"
},
{
"context": " fut Internet Explorer 9, vagy idős... | app/locale/hu.coffee | cochee/codecombat | 1 | module.exports = nativeDescription: "magyar", englishDescription: "Hungarian", translation:
common:
loading: "Töltés..."
modal:
close: "Mégse"
okay: "OK"
not_found:
page_not_found: "Az oldal nem található"
nav:
sign_up: "Regisztráció"
log_in: "Bejelentkezés"
log_out: "Kijelentkezés"
play: "Játék"
editor: "Szerkesztő"
blog: "Blog"
forum: "Fórum"
admin: "Admin"
home: "Kezdőlap"
contribute: "Segítségadás"
legal: "Jogi információk"
about: "Rólunk"
contact: "Kapcsolat"
twitter_follow: "Követés"
forms:
name: "Név"
email: "Email cím"
message: "Üzenet"
cancel: "Mégse"
login:
log_in: "Bejelentkezés"
sign_up: "Új fiók regisztrálása"
or: ", vagy "
recover: "meglévő fiók visszaéllítása"
signup:
description: "Teljesen ingyenes. Csak néhány dologra lesz szükségünk, s kezdheted is:"
email_announcements: "Szeretnél kapni hírlevelet?"
coppa: "13 elmúltál? (Vagy az USA-n kívül élsz?)"
coppa_why: "(Miért?)"
creating: "Fiók létrehozása"
sign_up: "Regisztráció"
or: "vagy "
log_in: "belépés meglévő fiókkal"
home:
slogan: "Tanulj meg JavaScript nyelven programozni, miközben játszol!"
no_ie: "A CodeCombat nem fut Internet Explorer 9, vagy idősebb böngészőben. Bocsi!"
no_mobile: "A CodeCombat nem mobil eszközökre lett tervezve. Valószínűleg nem működik helyesen."
play: "Játsz!"
play:
choose_your_level: "Válaszd ki a pályát!"
adventurer_prefix: "Továbbugorhatsz bármelyik pályára, amit lent látsz. Vagy megbeszélheted a pályát a többiekkel "
adventurer_forum: "a Kalandozók Fórumá"
adventurer_suffix: " n."
campaign_beginner: "Kezdő Kampány"
campaign_beginner_description: "... amelyben megtanulhatod a programozás varázslatait."
campaign_dev: "Véletlenszerű Nehezebb Pályák"
campaign_dev_description: "... amelyben egy kicsit nehezebb dolgokkat nézhetsz szembe."
campaign_multiplayer: "Multiplayer Arénák"
campaign_multiplayer_description: "... amelyben a kódod nekifeszülhet más játékosok kódjának"
campaign_player_created: "Játékosok pályái"
campaign_player_created_description: "...melyekben <a href=\"/contribute#artisan\">Művészi Varázsló</a> társaid ellen kűzdhetsz."
level_difficulty: "Nehézség: "
contact:
contact_us: "Lépj kapcsolatba velünk"
welcome: "Jó hallani felőled! Az alábbi űrlappal tudsz levelet küldeni nekünk."
contribute_prefix: "Ha szívesen közreműködnél, nézz rá a "
contribute_page: "közreműködők lapjára"
contribute_suffix: "!"
forum_prefix: "Ha publikus dologról van szó, megpróbálhatod a "
forum_page: "fórumban"
forum_suffix: " is."
sending: "Küldés..."
send: "Visszajelzés küldése"
diplomat_suggestion:
title: "Segítsd lefordítani a CodeCombat-ot!"
sub_heading: "Szükségünk van a segítségedre!"
pitch_body: "Az oldalt angol nyelven fejlesztettük, de máris rengeteg játékosunk van szerte a világból. Nagyon sokan szeretnének közülük magyarul játszani, s nem beszélnek angolul. Ha te beszélsz angolul is, magyarul is, kérlek jelentkezz Diplomatának, s segíts lefordítani mind a honlapot, mind a pályákat magyarra."
missing_translations: "Addig, amíg nincs minden lefordítva magyarra, angol szöveget fogsz látni ott, ahol még nincs fordítás."
learn_more: "Tudj meg többet a Diplomatákról!"
subscribe_as_diplomat: "Jelentkezz Diplomatának"
account_settings:
title: "Fiók beállítások"
not_logged_in: "Jelentkezz be, vagy hozz létre egy fiókot, hogy változtathass a beállításokon!"
autosave: "A változtatásokat automatikusan elmentjük."
me_tab: "Rólad"
picture_tab: "Kép"
wizard_tab: "Varázsló"
password_tab: "Jelszó"
emails_tab: "Levelek"
language_tab: "Nyelv"
gravatar_select: "Válassz egy Gravatar képet!"
gravatar_add_photos: "Adj képeket a Gravatar fiókodhoz, hogy választhass képeket."
gravatar_add_more_photos: "Adj több képet a Gravatar fiókodhoz, hogy itt is elérd őket"
wizard_color: "Varázslód színe"
new_password: "Új jelszó"
new_password_verify: "Mégegyszer"
email_subscriptions: "Hírlevél feliratkozások"
email_announcements: "Bejelentések"
email_announcements_description: "Szeretnél levelet kapni a legújabb fejlesztéseinkről?"
contributor_emails: "Hozzájárulóknak szóló levelek"
contribute_prefix: "Folyamatosan keresünk embereket, hogy csatlakozzanak hozzánk. Nézz rá a "
contribute_page: "segítők oldalára"
contribute_suffix: " információkért."
email_toggle: "Az összes megjelőlése"
language: "Nyelv"
saving: "Mentés..."
error_saving: "Hiba a mentés során"
saved: "Változtatások elmentve"
password_mismatch: "A jelszavak nem egyeznek."
account_profile:
edit_settings: "Beállítások szerkesztése"
# profile_for_prefix: ""
# profile_for_suffix: ""
profile: "Profil"
# user_not_found: ""
gravatar_not_found_mine: "Nem találtunk profilt ezzel a címmel:"
gravatar_signup_prefix: "Regisztrálj a "
gravatar_signup_suffix: " oldalon!"
# gravatar_not_found_other: ""
# gravatar_contact: ""
# gravatar_websites: ""
# gravatar_accounts: ""
# gravatar_profile_link: ""
play_level:
level_load_error: "A pályát nem sikerült betölteni."
done: "Kész"
grid: "Rács"
customize_wizard: "Varázsló testreszabása"
home: "Kezdőlap"
guide: "Segítség"
multiplayer: "Többjátékos"
restart: "Előről"
goals: "Célok"
action_timeline: "Tettvonal"
click_to_select: "Kattints egy egységre, hogy kijelöld!"
reload_title: "Újra kezded mindet?"
reload_really: "Biztos vagy benne, hogy előről szeretnéd kezdeni az egész pályát?"
reload_confirm: "Előről az egészet"
victory_title_prefix: ""
victory_title_suffix: "Kész"
victory_sign_up: "Regisztrálj a friss infókért"
victory_sign_up_poke: "Szeretnéd, ha levelet küldenénk neked az újításokról? Regisztrálj ingyen egy fiókot, s nem maradsz le semmirtől!"
victory_rate_the_level: "Értékeld a pályát: "
victory_play_next_level: "Következő pálya"
victory_go_home: "Vissza a kezdőoldalra"
victory_review: "Mondd el a véleményedet!"
victory_hour_of_code_done: "Készen vagy?"
victory_hour_of_code_done_yes: "Igen, ez volt életem kódja!"
multiplayer_title: "Többjátékos beállítások"
multiplayer_link_description: "Add oda ezt a linket bárkinek, s csatlakozhatnak hozzád."
multiplayer_hint_label: "Tipp:"
multiplayer_hint: " Kattints a linkre, s Ctrl+C-vel (vagy ⌘+C-vel) másold a vágólapra!"
multiplayer_coming_soon: "További beállítások érkeznek hamarosan!"
# guide_title: ""
# tome_minion_spells: ""
# tome_read_only_spells: ""
# tome_other_units: ""
# tome_cast_button_castable: ""
# tome_cast_button_casting: ""
# tome_cast_button_cast: ""
# tome_autocast_delay: ""
# tome_autocast_1: ""
# tome_autocast_3: ""
# tome_autocast_5: ""
# tome_autocast_manual: ""
# tome_select_spell: ""
# tome_select_a_thang: ""
# tome_available_spells: ""
# hud_continue: ""
| 38090 | module.exports = nativeDescription: "magyar", englishDescription: "Hungarian", translation:
common:
loading: "Töltés..."
modal:
close: "Mégse"
okay: "OK"
not_found:
page_not_found: "Az oldal nem található"
nav:
sign_up: "Regisztráció"
log_in: "Bejelentkezés"
log_out: "Kijelentkezés"
play: "Játék"
editor: "Szerkesztő"
blog: "Blog"
forum: "Fórum"
admin: "Admin"
home: "Kezdőlap"
contribute: "Segítségadás"
legal: "Jogi információk"
about: "Rólunk"
contact: "Kapcsolat"
twitter_follow: "Követés"
forms:
name: "Név"
email: "Email cím"
message: "Üzenet"
cancel: "Mégse"
login:
log_in: "Bejelentkezés"
sign_up: "Új fiók regisztrálása"
or: ", vagy "
recover: "meglévő fiók visszaéllítása"
signup:
description: "Teljesen ingyenes. Csak néhány dologra lesz szükségünk, s kezdheted is:"
email_announcements: "Szeretnél kapni hírlevelet?"
coppa: "13 elmúltál? (Vagy az USA-n kívül élsz?)"
coppa_why: "(Miért?)"
creating: "Fiók létrehozása"
sign_up: "Regisztráció"
or: "vagy "
log_in: "belépés meglévő fiókkal"
home:
slogan: "Tanulj meg JavaScript nyelven programozni, miközben játszol!"
no_ie: "A CodeCombat nem fut Internet Explorer 9, vagy idősebb böngészőben. <NAME>!"
no_mobile: "A CodeCombat nem mobil eszközökre lett tervezve. Valószínűleg nem működik helyesen."
play: "Játsz!"
play:
choose_your_level: "Válaszd ki a pályát!"
adventurer_prefix: "Továbbugorhatsz bármelyik pályára, amit lent látsz. Vagy megbeszélheted a pályát a többiekkel "
adventurer_forum: "a Kalandozók Fórumá"
adventurer_suffix: " n."
campaign_beginner: "Kezdő Kampány"
campaign_beginner_description: "... amelyben megtanulhatod a programozás varázslatait."
campaign_dev: "Véletlenszerű Nehezebb Pályák"
campaign_dev_description: "... amelyben egy kicsit nehezebb dolgokkat nézhetsz szembe."
campaign_multiplayer: "Multiplayer Arénák"
campaign_multiplayer_description: "... amelyben a kódod nekifeszülhet más játékosok kódjának"
campaign_player_created: "Játékosok pályái"
campaign_player_created_description: "...melyekben <a href=\"/contribute#artisan\">Művészi Varázsló</a> társaid ellen kűzdhetsz."
level_difficulty: "Nehézség: "
contact:
contact_us: "Lépj kapcsolatba velünk"
welcome: "<NAME>őled! Az alábbi űrlappal tudsz levelet küldeni nekünk."
contribute_prefix: "Ha szívesen közreműködnél, nézz rá a "
contribute_page: "közreműködők lapjára"
contribute_suffix: "!"
forum_prefix: "Ha publikus dologról van szó, megpróbálhatod a "
forum_page: "fórumban"
forum_suffix: " is."
sending: "Küldés..."
send: "Visszajelzés küldése"
diplomat_suggestion:
title: "Segítsd lefordítani a CodeCombat-ot!"
sub_heading: "Szükségünk van a segítségedre!"
pitch_body: "Az oldalt angol nyelven fejlesztettük, de máris rengeteg játékosunk van szerte a világból. Nagyon sokan szeretnének közülük magyarul játszani, s nem beszélnek angolul. Ha te beszélsz angolul is, magyarul is, kérlek jelentkezz Diplomatának, s segíts lefordítani mind a honlapot, mind a pályákat magyarra."
missing_translations: "Addig, amíg nincs minden lefordítva magyarra, angol szöveget fogsz látni ott, ahol még nincs fordítás."
learn_more: "Tudj meg többet a Diplomatákról!"
subscribe_as_diplomat: "Jelentkezz Diplomatának"
account_settings:
title: "Fiók beállítások"
not_logged_in: "Jelentkezz be, vagy hozz létre egy fiókot, hogy változtathass a beállításokon!"
autosave: "A változtatásokat automatikusan elmentjük."
me_tab: "Rólad"
picture_tab: "Kép"
wizard_tab: "Varázsló"
password_tab: "<PASSWORD>"
emails_tab: "Levelek"
language_tab: "Nyelv"
gravatar_select: "Válassz egy Gravatar képet!"
gravatar_add_photos: "Adj képeket a Gravatar fiókodhoz, hogy választhass képeket."
gravatar_add_more_photos: "Adj több képet a Gravatar fiókodhoz, hogy itt is elérd őket"
wizard_color: "Varázslód színe"
new_password: "<PASSWORD>"
new_password_verify: "<PASSWORD>"
email_subscriptions: "Hírlevél feliratkozások"
email_announcements: "Bejelentések"
email_announcements_description: "Szeretnél levelet kapni a legújabb fejlesztéseinkről?"
contributor_emails: "Hozzájárulóknak szóló levelek"
contribute_prefix: "Folyamatosan keresünk embereket, hogy csatlakozzanak hozzánk. Nézz rá a "
contribute_page: "segítők oldalára"
contribute_suffix: " információkért."
email_toggle: "Az összes megjelőlése"
language: "Nyelv"
saving: "Mentés..."
error_saving: "Hiba a mentés során"
saved: "Változtatások elmentve"
password_mismatch: "<PASSWORD>."
account_profile:
edit_settings: "Beállítások szerkesztése"
# profile_for_prefix: ""
# profile_for_suffix: ""
profile: "Profil"
# user_not_found: ""
gravatar_not_found_mine: "Nem találtunk profilt ezzel a címmel:"
gravatar_signup_prefix: "Regisztrálj a "
gravatar_signup_suffix: " oldalon!"
# gravatar_not_found_other: ""
# gravatar_contact: ""
# gravatar_websites: ""
# gravatar_accounts: ""
# gravatar_profile_link: ""
play_level:
level_load_error: "A pályát nem sikerült betölteni."
done: "Kész"
grid: "Rács"
customize_wizard: "Varázsló testreszabása"
home: "Kezdőlap"
guide: "Segítség"
multiplayer: "Többjátékos"
restart: "Előről"
goals: "Célok"
action_timeline: "Tettvonal"
click_to_select: "Kattints egy egységre, hogy kijelöld!"
reload_title: "Újra kezded mindet?"
reload_really: "Biztos vagy benne, hogy előről szeretnéd kezdeni az egész pályát?"
reload_confirm: "Előről az egészet"
victory_title_prefix: ""
victory_title_suffix: "Kész"
victory_sign_up: "Regisztrálj a friss infókért"
victory_sign_up_poke: "Szeretnéd, ha levelet küldenénk neked az újításokról? Regisztrálj ingyen egy fiókot, s nem maradsz le semmirtől!"
victory_rate_the_level: "Értékeld a pályát: "
victory_play_next_level: "Következő pálya"
victory_go_home: "Vissza a kezdőoldalra"
victory_review: "Mondd el a véleményedet!"
victory_hour_of_code_done: "Készen vagy?"
victory_hour_of_code_done_yes: "Igen, ez volt életem kódja!"
multiplayer_title: "Többjátékos beállítások"
multiplayer_link_description: "Add oda ezt a linket bárkinek, s csatlakozhatnak hozzád."
multiplayer_hint_label: "Tipp:"
multiplayer_hint: " Kattints a linkre, s Ctrl+C-vel (vagy ⌘+C-vel) másold a vágólapra!"
multiplayer_coming_soon: "További beállítások érkeznek hamarosan!"
# guide_title: ""
# tome_minion_spells: ""
# tome_read_only_spells: ""
# tome_other_units: ""
# tome_cast_button_castable: ""
# tome_cast_button_casting: ""
# tome_cast_button_cast: ""
# tome_autocast_delay: ""
# tome_autocast_1: ""
# tome_autocast_3: ""
# tome_autocast_5: ""
# tome_autocast_manual: ""
# tome_select_spell: ""
# tome_select_a_thang: ""
# tome_available_spells: ""
# hud_continue: ""
| true | module.exports = nativeDescription: "magyar", englishDescription: "Hungarian", translation:
common:
loading: "Töltés..."
modal:
close: "Mégse"
okay: "OK"
not_found:
page_not_found: "Az oldal nem található"
nav:
sign_up: "Regisztráció"
log_in: "Bejelentkezés"
log_out: "Kijelentkezés"
play: "Játék"
editor: "Szerkesztő"
blog: "Blog"
forum: "Fórum"
admin: "Admin"
home: "Kezdőlap"
contribute: "Segítségadás"
legal: "Jogi információk"
about: "Rólunk"
contact: "Kapcsolat"
twitter_follow: "Követés"
forms:
name: "Név"
email: "Email cím"
message: "Üzenet"
cancel: "Mégse"
login:
log_in: "Bejelentkezés"
sign_up: "Új fiók regisztrálása"
or: ", vagy "
recover: "meglévő fiók visszaéllítása"
signup:
description: "Teljesen ingyenes. Csak néhány dologra lesz szükségünk, s kezdheted is:"
email_announcements: "Szeretnél kapni hírlevelet?"
coppa: "13 elmúltál? (Vagy az USA-n kívül élsz?)"
coppa_why: "(Miért?)"
creating: "Fiók létrehozása"
sign_up: "Regisztráció"
or: "vagy "
log_in: "belépés meglévő fiókkal"
home:
slogan: "Tanulj meg JavaScript nyelven programozni, miközben játszol!"
no_ie: "A CodeCombat nem fut Internet Explorer 9, vagy idősebb böngészőben. PI:NAME:<NAME>END_PI!"
no_mobile: "A CodeCombat nem mobil eszközökre lett tervezve. Valószínűleg nem működik helyesen."
play: "Játsz!"
play:
choose_your_level: "Válaszd ki a pályát!"
adventurer_prefix: "Továbbugorhatsz bármelyik pályára, amit lent látsz. Vagy megbeszélheted a pályát a többiekkel "
adventurer_forum: "a Kalandozók Fórumá"
adventurer_suffix: " n."
campaign_beginner: "Kezdő Kampány"
campaign_beginner_description: "... amelyben megtanulhatod a programozás varázslatait."
campaign_dev: "Véletlenszerű Nehezebb Pályák"
campaign_dev_description: "... amelyben egy kicsit nehezebb dolgokkat nézhetsz szembe."
campaign_multiplayer: "Multiplayer Arénák"
campaign_multiplayer_description: "... amelyben a kódod nekifeszülhet más játékosok kódjának"
campaign_player_created: "Játékosok pályái"
campaign_player_created_description: "...melyekben <a href=\"/contribute#artisan\">Művészi Varázsló</a> társaid ellen kűzdhetsz."
level_difficulty: "Nehézség: "
contact:
contact_us: "Lépj kapcsolatba velünk"
welcome: "PI:NAME:<NAME>END_PIőled! Az alábbi űrlappal tudsz levelet küldeni nekünk."
contribute_prefix: "Ha szívesen közreműködnél, nézz rá a "
contribute_page: "közreműködők lapjára"
contribute_suffix: "!"
forum_prefix: "Ha publikus dologról van szó, megpróbálhatod a "
forum_page: "fórumban"
forum_suffix: " is."
sending: "Küldés..."
send: "Visszajelzés küldése"
diplomat_suggestion:
title: "Segítsd lefordítani a CodeCombat-ot!"
sub_heading: "Szükségünk van a segítségedre!"
pitch_body: "Az oldalt angol nyelven fejlesztettük, de máris rengeteg játékosunk van szerte a világból. Nagyon sokan szeretnének közülük magyarul játszani, s nem beszélnek angolul. Ha te beszélsz angolul is, magyarul is, kérlek jelentkezz Diplomatának, s segíts lefordítani mind a honlapot, mind a pályákat magyarra."
missing_translations: "Addig, amíg nincs minden lefordítva magyarra, angol szöveget fogsz látni ott, ahol még nincs fordítás."
learn_more: "Tudj meg többet a Diplomatákról!"
subscribe_as_diplomat: "Jelentkezz Diplomatának"
account_settings:
title: "Fiók beállítások"
not_logged_in: "Jelentkezz be, vagy hozz létre egy fiókot, hogy változtathass a beállításokon!"
autosave: "A változtatásokat automatikusan elmentjük."
me_tab: "Rólad"
picture_tab: "Kép"
wizard_tab: "Varázsló"
password_tab: "PI:PASSWORD:<PASSWORD>END_PI"
emails_tab: "Levelek"
language_tab: "Nyelv"
gravatar_select: "Válassz egy Gravatar képet!"
gravatar_add_photos: "Adj képeket a Gravatar fiókodhoz, hogy választhass képeket."
gravatar_add_more_photos: "Adj több képet a Gravatar fiókodhoz, hogy itt is elérd őket"
wizard_color: "Varázslód színe"
new_password: "PI:PASSWORD:<PASSWORD>END_PI"
new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI"
email_subscriptions: "Hírlevél feliratkozások"
email_announcements: "Bejelentések"
email_announcements_description: "Szeretnél levelet kapni a legújabb fejlesztéseinkről?"
contributor_emails: "Hozzájárulóknak szóló levelek"
contribute_prefix: "Folyamatosan keresünk embereket, hogy csatlakozzanak hozzánk. Nézz rá a "
contribute_page: "segítők oldalára"
contribute_suffix: " információkért."
email_toggle: "Az összes megjelőlése"
language: "Nyelv"
saving: "Mentés..."
error_saving: "Hiba a mentés során"
saved: "Változtatások elmentve"
password_mismatch: "PI:PASSWORD:<PASSWORD>END_PI."
account_profile:
edit_settings: "Beállítások szerkesztése"
# profile_for_prefix: ""
# profile_for_suffix: ""
profile: "Profil"
# user_not_found: ""
gravatar_not_found_mine: "Nem találtunk profilt ezzel a címmel:"
gravatar_signup_prefix: "Regisztrálj a "
gravatar_signup_suffix: " oldalon!"
# gravatar_not_found_other: ""
# gravatar_contact: ""
# gravatar_websites: ""
# gravatar_accounts: ""
# gravatar_profile_link: ""
play_level:
level_load_error: "A pályát nem sikerült betölteni."
done: "Kész"
grid: "Rács"
customize_wizard: "Varázsló testreszabása"
home: "Kezdőlap"
guide: "Segítség"
multiplayer: "Többjátékos"
restart: "Előről"
goals: "Célok"
action_timeline: "Tettvonal"
click_to_select: "Kattints egy egységre, hogy kijelöld!"
reload_title: "Újra kezded mindet?"
reload_really: "Biztos vagy benne, hogy előről szeretnéd kezdeni az egész pályát?"
reload_confirm: "Előről az egészet"
victory_title_prefix: ""
victory_title_suffix: "Kész"
victory_sign_up: "Regisztrálj a friss infókért"
victory_sign_up_poke: "Szeretnéd, ha levelet küldenénk neked az újításokról? Regisztrálj ingyen egy fiókot, s nem maradsz le semmirtől!"
victory_rate_the_level: "Értékeld a pályát: "
victory_play_next_level: "Következő pálya"
victory_go_home: "Vissza a kezdőoldalra"
victory_review: "Mondd el a véleményedet!"
victory_hour_of_code_done: "Készen vagy?"
victory_hour_of_code_done_yes: "Igen, ez volt életem kódja!"
multiplayer_title: "Többjátékos beállítások"
multiplayer_link_description: "Add oda ezt a linket bárkinek, s csatlakozhatnak hozzád."
multiplayer_hint_label: "Tipp:"
multiplayer_hint: " Kattints a linkre, s Ctrl+C-vel (vagy ⌘+C-vel) másold a vágólapra!"
multiplayer_coming_soon: "További beállítások érkeznek hamarosan!"
# guide_title: ""
# tome_minion_spells: ""
# tome_read_only_spells: ""
# tome_other_units: ""
# tome_cast_button_castable: ""
# tome_cast_button_casting: ""
# tome_cast_button_cast: ""
# tome_autocast_delay: ""
# tome_autocast_1: ""
# tome_autocast_3: ""
# tome_autocast_5: ""
# tome_autocast_manual: ""
# tome_select_spell: ""
# tome_select_a_thang: ""
# tome_available_spells: ""
# hud_continue: ""
|
[
{
"context": "essage, neighbor) ->\n if neighbor.name is \"Tom\"\n @dick.receive message, \"Tom\"\n ",
"end": 268,
"score": 0.9988376498222351,
"start": 265,
"tag": "NAME",
"value": "Tom"
},
{
"context": "name is \"Tom\"\n @dick.receive message, \"T... | GoF/idiomatic/Behavioral/Mediator/CoffeeScript/API/mediator.coffee | irynaO/JavaScript-Design-Patterns | 293 | 'use strict'
neighbors = require './colleagues'
# ==============================
# MEDIATOR (HARRY)
# ==============================
module.exports =
tom: neighbors.tom
dick: neighbors.dick
send: (message, neighbor) ->
if neighbor.name is "Tom"
@dick.receive message, "Tom"
else if neighbor.name is "Dick"
@tom.receive message, "Dick"
else
throw
type: "Not found",
message: "The given person has not been found in the neighborhood."
| 33113 | 'use strict'
neighbors = require './colleagues'
# ==============================
# MEDIATOR (HARRY)
# ==============================
module.exports =
tom: neighbors.tom
dick: neighbors.dick
send: (message, neighbor) ->
if neighbor.name is "<NAME>"
@dick.receive message, "<NAME>"
else if neighbor.name is "<NAME>"
@tom.receive message, "<NAME>"
else
throw
type: "Not found",
message: "The given person has not been found in the neighborhood."
| true | 'use strict'
neighbors = require './colleagues'
# ==============================
# MEDIATOR (HARRY)
# ==============================
module.exports =
tom: neighbors.tom
dick: neighbors.dick
send: (message, neighbor) ->
if neighbor.name is "PI:NAME:<NAME>END_PI"
@dick.receive message, "PI:NAME:<NAME>END_PI"
else if neighbor.name is "PI:NAME:<NAME>END_PI"
@tom.receive message, "PI:NAME:<NAME>END_PI"
else
throw
type: "Not found",
message: "The given person has not been found in the neighborhood."
|
[
{
"context": "ила, а проигрывает тот, кто их соблюдает. (доктор Хауз)\"",
"end": 98,
"score": 0.7393889427185059,
"start": 94,
"tag": "NAME",
"value": "Хауз"
}
] | quote.coffee | agershun/minday | 0 | add "В жизни выигрывает тот, кто знает правила, а проигрывает тот, кто их соблюдает. (доктор Хауз)" | 18296 | add "В жизни выигрывает тот, кто знает правила, а проигрывает тот, кто их соблюдает. (доктор <NAME>)" | true | add "В жизни выигрывает тот, кто знает правила, а проигрывает тот, кто их соблюдает. (доктор PI:NAME:<NAME>END_PI)" |
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999123811721802,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/radar-chart.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @RadarChart
constructor: (area, @options = {}) ->
@margins =
top: 30
right: 30
bottom: 0
left: 30
@options.scale ||= d3.scaleLinear()
@area = d3.select area
@svg = @area.append 'svg'
# angle between two neighboring axes
@angleStep = (Math.PI * 2) / @options.axes
@svgWrapper = @svg.append 'g'
group = @svgWrapper.append 'g'
@circles = for i in [0..@options.ticks - 1]
group.append 'circle'
.classed "#{@options.className}__circle", true
@axes = for i in [0..@options.axes - 1]
group = @svgWrapper.append 'g'
axis: group.append('line').classed("#{@options.className}__axis", true)
dots: for i in [0..@options.dots - 1]
group.append('circle').classed("#{@options.className}__dot", true)
label: group.append('text').classed("#{@options.className}__label", true)
@centerDot = @svgWrapper.append 'circle'
.classed "#{@options.className}__dot", true
@selectedArea = @svgWrapper.append 'path'
.classed "#{@options.className}__area", true
@pointsGroup = @svgWrapper.append 'g'
loadData: (data) =>
@values = data
@resize true
setDimensions: ->
areaDims = @area.node().getBoundingClientRect()
width = areaDims.width
if @options.maxWidth and width > @options.maxWidth
width = @options.maxWidth
@diameter = width - (@margins.left + @margins.right)
@radius = @diameter / 2
@dotRadius = width / 200
@center =
x: @radius
y: @radius
setScalesRange: ->
@options.scale
.range [0, @radius]
.domain @options.domain
setSvgSize: ->
@svg
.attr 'width', @diameter + (@margins.left + @margins.right)
.attr 'height', @diameter + (@margins.top + @margins.bottom)
setWrapperSize: ->
@svgWrapper
.attr 'transform', "translate(#{@margins.left}, #{@margins.top})"
setCirclesSize: ->
len = @radius / @options.ticks
for circle, i in @circles
circle
.attr 'cx', @center.x
.attr 'cy', @center.y
.attr 'r', len * (i + 1)
@centerDot
.attr 'cx', @center.x
.attr 'cy', @center.y
.attr 'r', @dotRadius
setAxesSize: ->
@angleStep = (Math.PI * 2) / @options.axes
angle = Math.PI / 2 # the first axis is rotated 90 degrees from the x axis
len = @radius / @options.dots; # distance between two neighboring dots
x1 = @center.x
y1 = @center.y
x2 = @center.x
y2 = @center.y - @radius
for axis, i in @axes
axis.axis
.attr 'x1', x1
.attr 'y1', y1
.attr 'x2', x2
.attr 'y2', y2
[x2, y2] = @_rotatePoint x1, y1, x2, y2, @angleStep
for dot, j in axis.dots
[x, y] = @_extendPoint @center.x, @center.y, len * (j + 1), angle
dot
.attr 'cx', x
.attr 'cy', y
.attr 'r', @dotRadius
[x, y] = @_extendPoint @center.x, @center.y, @radius + 10, angle
axis.label
.attr 'x', x
.attr 'y', y
.attr 'text-anchor', if x > @center.x then 'start' else if x < @center.x then 'end' else 'middle'
.text @values[i].label
angle += @angleStep
calculatePoints: ->
@data = @values.map (v, i) =>
len = @options.scale v.value
angle = (Math.PI / 2) + @angleStep * i
[x, y] = @_extendPoint @center.x, @center.y, len, angle
x: x
y: y
drawArea: (animateArea) ->
line = d3.line()
.x (d) -> d.x
.y (d) -> d.y
.interpolate 'linear-closed'
area = @selectedArea
if animateArea
area = area.transition()
area.attr 'd', line @data
_extendPoint: (cx, cy, length, angle) ->
s = Math.sin angle
c = Math.cos angle
[cx + length * c, cy - length * s]
_rotatePoint: (x1, y1, x2, y2, angle) ->
s = Math.sin angle
c = Math.cos angle
x2 -= x1
y2 -= y1
[x1 + (x2 * c + y2 * s), y1 + (y2 * c - x2 * s)]
resize: (animate) =>
@setDimensions()
@setScalesRange()
@setSvgSize()
@setWrapperSize()
@setCirclesSize()
@setAxesSize()
@calculatePoints()
@drawArea animate
| 217304 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @RadarChart
constructor: (area, @options = {}) ->
@margins =
top: 30
right: 30
bottom: 0
left: 30
@options.scale ||= d3.scaleLinear()
@area = d3.select area
@svg = @area.append 'svg'
# angle between two neighboring axes
@angleStep = (Math.PI * 2) / @options.axes
@svgWrapper = @svg.append 'g'
group = @svgWrapper.append 'g'
@circles = for i in [0..@options.ticks - 1]
group.append 'circle'
.classed "#{@options.className}__circle", true
@axes = for i in [0..@options.axes - 1]
group = @svgWrapper.append 'g'
axis: group.append('line').classed("#{@options.className}__axis", true)
dots: for i in [0..@options.dots - 1]
group.append('circle').classed("#{@options.className}__dot", true)
label: group.append('text').classed("#{@options.className}__label", true)
@centerDot = @svgWrapper.append 'circle'
.classed "#{@options.className}__dot", true
@selectedArea = @svgWrapper.append 'path'
.classed "#{@options.className}__area", true
@pointsGroup = @svgWrapper.append 'g'
loadData: (data) =>
@values = data
@resize true
setDimensions: ->
areaDims = @area.node().getBoundingClientRect()
width = areaDims.width
if @options.maxWidth and width > @options.maxWidth
width = @options.maxWidth
@diameter = width - (@margins.left + @margins.right)
@radius = @diameter / 2
@dotRadius = width / 200
@center =
x: @radius
y: @radius
setScalesRange: ->
@options.scale
.range [0, @radius]
.domain @options.domain
setSvgSize: ->
@svg
.attr 'width', @diameter + (@margins.left + @margins.right)
.attr 'height', @diameter + (@margins.top + @margins.bottom)
setWrapperSize: ->
@svgWrapper
.attr 'transform', "translate(#{@margins.left}, #{@margins.top})"
setCirclesSize: ->
len = @radius / @options.ticks
for circle, i in @circles
circle
.attr 'cx', @center.x
.attr 'cy', @center.y
.attr 'r', len * (i + 1)
@centerDot
.attr 'cx', @center.x
.attr 'cy', @center.y
.attr 'r', @dotRadius
setAxesSize: ->
@angleStep = (Math.PI * 2) / @options.axes
angle = Math.PI / 2 # the first axis is rotated 90 degrees from the x axis
len = @radius / @options.dots; # distance between two neighboring dots
x1 = @center.x
y1 = @center.y
x2 = @center.x
y2 = @center.y - @radius
for axis, i in @axes
axis.axis
.attr 'x1', x1
.attr 'y1', y1
.attr 'x2', x2
.attr 'y2', y2
[x2, y2] = @_rotatePoint x1, y1, x2, y2, @angleStep
for dot, j in axis.dots
[x, y] = @_extendPoint @center.x, @center.y, len * (j + 1), angle
dot
.attr 'cx', x
.attr 'cy', y
.attr 'r', @dotRadius
[x, y] = @_extendPoint @center.x, @center.y, @radius + 10, angle
axis.label
.attr 'x', x
.attr 'y', y
.attr 'text-anchor', if x > @center.x then 'start' else if x < @center.x then 'end' else 'middle'
.text @values[i].label
angle += @angleStep
calculatePoints: ->
@data = @values.map (v, i) =>
len = @options.scale v.value
angle = (Math.PI / 2) + @angleStep * i
[x, y] = @_extendPoint @center.x, @center.y, len, angle
x: x
y: y
drawArea: (animateArea) ->
line = d3.line()
.x (d) -> d.x
.y (d) -> d.y
.interpolate 'linear-closed'
area = @selectedArea
if animateArea
area = area.transition()
area.attr 'd', line @data
_extendPoint: (cx, cy, length, angle) ->
s = Math.sin angle
c = Math.cos angle
[cx + length * c, cy - length * s]
_rotatePoint: (x1, y1, x2, y2, angle) ->
s = Math.sin angle
c = Math.cos angle
x2 -= x1
y2 -= y1
[x1 + (x2 * c + y2 * s), y1 + (y2 * c - x2 * s)]
resize: (animate) =>
@setDimensions()
@setScalesRange()
@setSvgSize()
@setWrapperSize()
@setCirclesSize()
@setAxesSize()
@calculatePoints()
@drawArea animate
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
class @RadarChart
constructor: (area, @options = {}) ->
@margins =
top: 30
right: 30
bottom: 0
left: 30
@options.scale ||= d3.scaleLinear()
@area = d3.select area
@svg = @area.append 'svg'
# angle between two neighboring axes
@angleStep = (Math.PI * 2) / @options.axes
@svgWrapper = @svg.append 'g'
group = @svgWrapper.append 'g'
@circles = for i in [0..@options.ticks - 1]
group.append 'circle'
.classed "#{@options.className}__circle", true
@axes = for i in [0..@options.axes - 1]
group = @svgWrapper.append 'g'
axis: group.append('line').classed("#{@options.className}__axis", true)
dots: for i in [0..@options.dots - 1]
group.append('circle').classed("#{@options.className}__dot", true)
label: group.append('text').classed("#{@options.className}__label", true)
@centerDot = @svgWrapper.append 'circle'
.classed "#{@options.className}__dot", true
@selectedArea = @svgWrapper.append 'path'
.classed "#{@options.className}__area", true
@pointsGroup = @svgWrapper.append 'g'
loadData: (data) =>
@values = data
@resize true
setDimensions: ->
areaDims = @area.node().getBoundingClientRect()
width = areaDims.width
if @options.maxWidth and width > @options.maxWidth
width = @options.maxWidth
@diameter = width - (@margins.left + @margins.right)
@radius = @diameter / 2
@dotRadius = width / 200
@center =
x: @radius
y: @radius
setScalesRange: ->
@options.scale
.range [0, @radius]
.domain @options.domain
setSvgSize: ->
@svg
.attr 'width', @diameter + (@margins.left + @margins.right)
.attr 'height', @diameter + (@margins.top + @margins.bottom)
setWrapperSize: ->
@svgWrapper
.attr 'transform', "translate(#{@margins.left}, #{@margins.top})"
setCirclesSize: ->
len = @radius / @options.ticks
for circle, i in @circles
circle
.attr 'cx', @center.x
.attr 'cy', @center.y
.attr 'r', len * (i + 1)
@centerDot
.attr 'cx', @center.x
.attr 'cy', @center.y
.attr 'r', @dotRadius
setAxesSize: ->
@angleStep = (Math.PI * 2) / @options.axes
angle = Math.PI / 2 # the first axis is rotated 90 degrees from the x axis
len = @radius / @options.dots; # distance between two neighboring dots
x1 = @center.x
y1 = @center.y
x2 = @center.x
y2 = @center.y - @radius
for axis, i in @axes
axis.axis
.attr 'x1', x1
.attr 'y1', y1
.attr 'x2', x2
.attr 'y2', y2
[x2, y2] = @_rotatePoint x1, y1, x2, y2, @angleStep
for dot, j in axis.dots
[x, y] = @_extendPoint @center.x, @center.y, len * (j + 1), angle
dot
.attr 'cx', x
.attr 'cy', y
.attr 'r', @dotRadius
[x, y] = @_extendPoint @center.x, @center.y, @radius + 10, angle
axis.label
.attr 'x', x
.attr 'y', y
.attr 'text-anchor', if x > @center.x then 'start' else if x < @center.x then 'end' else 'middle'
.text @values[i].label
angle += @angleStep
calculatePoints: ->
@data = @values.map (v, i) =>
len = @options.scale v.value
angle = (Math.PI / 2) + @angleStep * i
[x, y] = @_extendPoint @center.x, @center.y, len, angle
x: x
y: y
drawArea: (animateArea) ->
line = d3.line()
.x (d) -> d.x
.y (d) -> d.y
.interpolate 'linear-closed'
area = @selectedArea
if animateArea
area = area.transition()
area.attr 'd', line @data
_extendPoint: (cx, cy, length, angle) ->
s = Math.sin angle
c = Math.cos angle
[cx + length * c, cy - length * s]
_rotatePoint: (x1, y1, x2, y2, angle) ->
s = Math.sin angle
c = Math.cos angle
x2 -= x1
y2 -= y1
[x1 + (x2 * c + y2 * s), y1 + (y2 * c - x2 * s)]
resize: (animate) =>
@setDimensions()
@setScalesRange()
@setSvgSize()
@setWrapperSize()
@setCirclesSize()
@setAxesSize()
@calculatePoints()
@drawArea animate
|
[
{
"context": "ogin.Username\":\n locator: \"id\"\n value: \"username\"\n \"login.Password\":\n locator: \"id\"\n ",
"end": 622,
"score": 0.9987456798553467,
"start": 614,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ogin.Password\":\n locator: \... | tests/testx/objects/navigation.coffee | ICTU/docker-dashboard | 33 | module.exports =
# Navigation bar links
"menu.Apps":
locator: "linkText"
value: "Apps"
"menu.Instances":
locator: "linkText"
value: "Instances"
"menu.AppStore":
locator: "linkText"
value: "App Store"
"menu.Storage":
locator: "linkText"
value: "Storage"
"menu.Configuration":
locator: "linkText"
value: "Configuration"
"menu.Status":
locator: "linkText"
value: "Status"
"menu.Login":
locator: "css"
value: "i.glyphicon-user"
# Login box
"login.Username":
locator: "id"
value: "username"
"login.Password":
locator: "id"
value: "password"
"login.Submit":
locator: "id"
value: "btnLogin"
"login.GravatarLink": (username) ->
locator: "xpath"
value: "//a[img[@class='avatar'] and text()='#{username}']"
# Toolbox links
"toolbox.NewApp":
locator: "linkText"
value: "New App"
"toolbox.NewInstance":
locator: "linkText"
value: "New Instance"
# Page Headers
"page.title":
locator: "css"
value: ".pageTitle"
"statusHeader":
locator: "xpath"
value: "//div[@class='container statusPage']//h3[contains(text(), 'Status')]"
| 73996 | module.exports =
# Navigation bar links
"menu.Apps":
locator: "linkText"
value: "Apps"
"menu.Instances":
locator: "linkText"
value: "Instances"
"menu.AppStore":
locator: "linkText"
value: "App Store"
"menu.Storage":
locator: "linkText"
value: "Storage"
"menu.Configuration":
locator: "linkText"
value: "Configuration"
"menu.Status":
locator: "linkText"
value: "Status"
"menu.Login":
locator: "css"
value: "i.glyphicon-user"
# Login box
"login.Username":
locator: "id"
value: "username"
"login.Password":
locator: "id"
value: "<PASSWORD>"
"login.Submit":
locator: "id"
value: "btnLogin"
"login.GravatarLink": (username) ->
locator: "xpath"
value: "//a[img[@class='avatar'] and text()='#{username}']"
# Toolbox links
"toolbox.NewApp":
locator: "linkText"
value: "New App"
"toolbox.NewInstance":
locator: "linkText"
value: "New Instance"
# Page Headers
"page.title":
locator: "css"
value: ".pageTitle"
"statusHeader":
locator: "xpath"
value: "//div[@class='container statusPage']//h3[contains(text(), 'Status')]"
| true | module.exports =
# Navigation bar links
"menu.Apps":
locator: "linkText"
value: "Apps"
"menu.Instances":
locator: "linkText"
value: "Instances"
"menu.AppStore":
locator: "linkText"
value: "App Store"
"menu.Storage":
locator: "linkText"
value: "Storage"
"menu.Configuration":
locator: "linkText"
value: "Configuration"
"menu.Status":
locator: "linkText"
value: "Status"
"menu.Login":
locator: "css"
value: "i.glyphicon-user"
# Login box
"login.Username":
locator: "id"
value: "username"
"login.Password":
locator: "id"
value: "PI:PASSWORD:<PASSWORD>END_PI"
"login.Submit":
locator: "id"
value: "btnLogin"
"login.GravatarLink": (username) ->
locator: "xpath"
value: "//a[img[@class='avatar'] and text()='#{username}']"
# Toolbox links
"toolbox.NewApp":
locator: "linkText"
value: "New App"
"toolbox.NewInstance":
locator: "linkText"
value: "New Instance"
# Page Headers
"page.title":
locator: "css"
value: ".pageTitle"
"statusHeader":
locator: "xpath"
value: "//div[@class='container statusPage']//h3[contains(text(), 'Status')]"
|
[
{
"context": ": [\n \"linter\"\n ]\n projectHome: \"/Users/dhiller/Projects\"\n restorePreviousWindowsOnStart: \"no\"",
"end": 195,
"score": 0.9980665445327759,
"start": 188,
"tag": "USERNAME",
"value": "dhiller"
},
{
"context": "bLength: 4\n \"exception-reporting\":\n... | .atom/config.cson | dhiller/dotfiles | 0 | "*":
"atom-ide-ui":
use: {}
core:
customFileTypes:
"text.ignore": [
".dockerignore"
]
disabledPackages: [
"linter"
]
projectHome: "/Users/dhiller/Projects"
restorePreviousWindowsOnStart: "no"
telemetryConsent: "limited"
editor:
fontSize: 20
preferredLineLength: 120
softWrap: true
softWrapAtPreferredLineLength: true
tabLength: 4
"exception-reporting":
userId: "b60981ac-d180-4766-84a3-ce1ce12923a2"
"one-dark-ui":
fontSize: 16
| 61828 | "*":
"atom-ide-ui":
use: {}
core:
customFileTypes:
"text.ignore": [
".dockerignore"
]
disabledPackages: [
"linter"
]
projectHome: "/Users/dhiller/Projects"
restorePreviousWindowsOnStart: "no"
telemetryConsent: "limited"
editor:
fontSize: 20
preferredLineLength: 120
softWrap: true
softWrapAtPreferredLineLength: true
tabLength: 4
"exception-reporting":
userId: "b<PASSWORD>"
"one-dark-ui":
fontSize: 16
| true | "*":
"atom-ide-ui":
use: {}
core:
customFileTypes:
"text.ignore": [
".dockerignore"
]
disabledPackages: [
"linter"
]
projectHome: "/Users/dhiller/Projects"
restorePreviousWindowsOnStart: "no"
telemetryConsent: "limited"
editor:
fontSize: 20
preferredLineLength: 120
softWrap: true
softWrapAtPreferredLineLength: true
tabLength: 4
"exception-reporting":
userId: "bPI:PASSWORD:<PASSWORD>END_PI"
"one-dark-ui":
fontSize: 16
|
[
{
"context": ").\",\"detail\":{\"email\":[\"is invalid\"],\"password\":[\"is too short (minimum is 6 characters)\"]}}\"\"\", message: 'Email is inval",
"end": 991,
"score": 0.8358497619628906,
"start": 970,
"tag": "PASSWORD",
"value": "is too short (minimum"
},
{
"context": " invalid... | src/desktop/components/form/test/fixture.coffee | kanaabe/force | 377 | module.exports =
template: "
<form>
<div class='js-form-errors'></div>
<label for='name'>Name</label>
<input id='name' name='name' pattern='.{6,}' title='6 characters minimum'>
<input name='email' type='email' required>
<textarea name='comment' required></textarea>
<input name='yes' type='checkbox' checked>
<input name='no' type='checkbox'>
<button>Submit</button>
</form>
"
confirmables: "
<input type='password' name='password'>
<input type='password' name='password_confirmation' data-confirm='password'>
<input type='foobar' name='foobar'>
<input type='foobar' name='foobar_confirmation' data-confirm='foobar'>
"
# Example errors encounted in the wild and the messages they should be transformed into
errors: [
{ error: """{"type":"param_error","message":"Email is invalid,Password is too short (minimum is 6 characters).","detail":{"email":["is invalid"],"password":["is too short (minimum is 6 characters)"]}}""", message: 'Email is invalid; Password is too short (minimum is 6 characters)' }
{ error: """{"type":"param_error","message":"Password is too short (minimum is 6 characters).","detail":{"password":["is too short (minimum is 6 characters)"]}}""", message: 'Password is too short (minimum is 6 characters)' }
{ error: """{"error":"User Already Exists"}""", message: 'User Already Exists' },
{ error: """{"error":"User Already Exists","text":"A user with this email has already signed up with Twitter.","providers":["Twitter"]}""", message: 'A user with this email has already signed up with Twitter.' }
{ error: """{"error":"User Already Exists","text":"A user with this email has already signed up with Facebook.","providers":["Facebook"]}""", message: 'A user with this email has already signed up with Facebook.' }
{ error: """{"error":{"message":"invalidemailorpassword","stack":""}}""", message: 'invalidemailorpassword' }
{ error: """{"type":"param_error","message":"Handle is too short (minimum is 3 characters),Handle can only have letters, numbers, '-', and '_'.","detail":{"handle":["is too short (minimum is 3 characters)","can only have letters, numbers, '-', and '_'"]}}""", message: "Handle is too short (minimum is 3 characters); can only have letters, numbers, '-', and '_'" }
{ error: """{"type":"other_error","message":"hostname \"api.mailchimp.com\" does not match the server certificate","backtrace":[]}""", message: 'There was an error' }
{ error: """{"type":"param_error","message":"Password confirmation doesn't match Password.","detail":{"password_confirmation":["doesn't match Password"]}}""", message: "Password confirmation doesn't match Password" }
]
| 1306 | module.exports =
template: "
<form>
<div class='js-form-errors'></div>
<label for='name'>Name</label>
<input id='name' name='name' pattern='.{6,}' title='6 characters minimum'>
<input name='email' type='email' required>
<textarea name='comment' required></textarea>
<input name='yes' type='checkbox' checked>
<input name='no' type='checkbox'>
<button>Submit</button>
</form>
"
confirmables: "
<input type='password' name='password'>
<input type='password' name='password_confirmation' data-confirm='password'>
<input type='foobar' name='foobar'>
<input type='foobar' name='foobar_confirmation' data-confirm='foobar'>
"
# Example errors encounted in the wild and the messages they should be transformed into
errors: [
{ error: """{"type":"param_error","message":"Email is invalid,Password is too short (minimum is 6 characters).","detail":{"email":["is invalid"],"password":["<PASSWORD> is 6 <PASSWORD>)"]}}""", message: 'Email is invalid; Password is too short (minimum is 6 characters)' }
{ error: """{"type":"param_error","message":"Password is too short (minimum is 6 characters).","detail":{"password":["<PASSWORD> (minimum is 6 characters)"]}}""", message: 'Password is too short (minimum is 6 characters)' }
{ error: """{"error":"User Already Exists"}""", message: 'User Already Exists' },
{ error: """{"error":"User Already Exists","text":"A user with this email has already signed up with Twitter.","providers":["Twitter"]}""", message: 'A user with this email has already signed up with Twitter.' }
{ error: """{"error":"User Already Exists","text":"A user with this email has already signed up with Facebook.","providers":["Facebook"]}""", message: 'A user with this email has already signed up with Facebook.' }
{ error: """{"error":{"message":"invalidemailorpassword","stack":""}}""", message: 'invalidemailorpassword' }
{ error: """{"type":"param_error","message":"Handle is too short (minimum is 3 characters),Handle can only have letters, numbers, '-', and '_'.","detail":{"handle":["is too short (minimum is 3 characters)","can only have letters, numbers, '-', and '_'"]}}""", message: "Handle is too short (minimum is 3 characters); can only have letters, numbers, '-', and '_'" }
{ error: """{"type":"other_error","message":"hostname \"api.mailchimp.com\" does not match the server certificate","backtrace":[]}""", message: 'There was an error' }
{ error: """{"type":"param_error","message":"Password confirmation doesn't match Password.","detail":{"password_confirmation":["<PASSWORD>"]}}""", message: "Password confirmation doesn't match Password" }
]
| true | module.exports =
template: "
<form>
<div class='js-form-errors'></div>
<label for='name'>Name</label>
<input id='name' name='name' pattern='.{6,}' title='6 characters minimum'>
<input name='email' type='email' required>
<textarea name='comment' required></textarea>
<input name='yes' type='checkbox' checked>
<input name='no' type='checkbox'>
<button>Submit</button>
</form>
"
confirmables: "
<input type='password' name='password'>
<input type='password' name='password_confirmation' data-confirm='password'>
<input type='foobar' name='foobar'>
<input type='foobar' name='foobar_confirmation' data-confirm='foobar'>
"
# Example errors encounted in the wild and the messages they should be transformed into
errors: [
{ error: """{"type":"param_error","message":"Email is invalid,Password is too short (minimum is 6 characters).","detail":{"email":["is invalid"],"password":["PI:PASSWORD:<PASSWORD>END_PI is 6 PI:PASSWORD:<PASSWORD>END_PI)"]}}""", message: 'Email is invalid; Password is too short (minimum is 6 characters)' }
{ error: """{"type":"param_error","message":"Password is too short (minimum is 6 characters).","detail":{"password":["PI:PASSWORD:<PASSWORD>END_PI (minimum is 6 characters)"]}}""", message: 'Password is too short (minimum is 6 characters)' }
{ error: """{"error":"User Already Exists"}""", message: 'User Already Exists' },
{ error: """{"error":"User Already Exists","text":"A user with this email has already signed up with Twitter.","providers":["Twitter"]}""", message: 'A user with this email has already signed up with Twitter.' }
{ error: """{"error":"User Already Exists","text":"A user with this email has already signed up with Facebook.","providers":["Facebook"]}""", message: 'A user with this email has already signed up with Facebook.' }
{ error: """{"error":{"message":"invalidemailorpassword","stack":""}}""", message: 'invalidemailorpassword' }
{ error: """{"type":"param_error","message":"Handle is too short (minimum is 3 characters),Handle can only have letters, numbers, '-', and '_'.","detail":{"handle":["is too short (minimum is 3 characters)","can only have letters, numbers, '-', and '_'"]}}""", message: "Handle is too short (minimum is 3 characters); can only have letters, numbers, '-', and '_'" }
{ error: """{"type":"other_error","message":"hostname \"api.mailchimp.com\" does not match the server certificate","backtrace":[]}""", message: 'There was an error' }
{ error: """{"type":"param_error","message":"Password confirmation doesn't match Password.","detail":{"password_confirmation":["PI:PASSWORD:<PASSWORD>END_PI"]}}""", message: "Password confirmation doesn't match Password" }
]
|
[
{
"context": "w(<Book book={title: \"The Dispossessed\", author: \"Ursula K. LeGuin\", isbn: \"1234\", description: \"Hard to say without",
"end": 314,
"score": 0.9998878240585327,
"start": 298,
"tag": "NAME",
"value": "Ursula K. LeGuin"
},
{
"context": " expect(book.find('p.autho... | test/pages/book.test.coffee | rachel-carvalho/next-sample | 0 | import {shallow} from 'enzyme'
import voidify from '../support/voidify'
import Error from 'next/error'
import Book from '../../pages/book'
import books from '../../data/books'
describe 'book page', voidify ->
it 'renders', ->
book = shallow(<Book book={title: "The Dispossessed", author: "Ursula K. LeGuin", isbn: "1234", description: "Hard to say without spoiling the book."} />)
expect(book.find('Head title').text()).toEqual 'The Dispossessed'
expect(book.find('h1').text()).toEqual 'The Dispossessed'
expect(book.find('p.author').text()).toEqual 'Ursula K. LeGuin'
expect(book.find('span').text()).toEqual 'ISBN 1234'
expect(book.find('p').at(1).text()).toEqual 'Hard to say without spoiling the book.'
it 'renders error when book is empty', ->
book = shallow(<Book />)
expect(book.matchesElement(<Error />)).toBeTruthy()
expect(book.equals(<Error statusCode={404} />)).toBeTruthy()
describe '@getInitialProps', voidify ->
it 'returns book: undefined when query is not present', ->
await expect(Book.getInitialProps({})).resolves.toEqual book: undefined
it 'returns book: undefined when query.isbn is not present', ->
await expect(Book.getInitialProps(query: {})).resolves.toEqual book: undefined
it 'returns book: undefined when query.isbn is not in books array', ->
await expect(Book.getInitialProps(query: { isbn: '123' })).resolves.toEqual book: undefined
it 'sets status code as 404 when book is not found', ->
res = statusCode: 200
await Book.getInitialProps({res})
expect(res.statusCode).toEqual 404
it 'returns a book when query.isbn is in books array', ->
[book] = books
await expect(Book.getInitialProps(query: { isbn: book.isbn })).resolves.toEqual {book}
| 44764 | import {shallow} from 'enzyme'
import voidify from '../support/voidify'
import Error from 'next/error'
import Book from '../../pages/book'
import books from '../../data/books'
describe 'book page', voidify ->
it 'renders', ->
book = shallow(<Book book={title: "The Dispossessed", author: "<NAME>", isbn: "1234", description: "Hard to say without spoiling the book."} />)
expect(book.find('Head title').text()).toEqual 'The Dispossessed'
expect(book.find('h1').text()).toEqual 'The Dispossessed'
expect(book.find('p.author').text()).toEqual '<NAME>'
expect(book.find('span').text()).toEqual 'ISBN 1234'
expect(book.find('p').at(1).text()).toEqual 'Hard to say without spoiling the book.'
it 'renders error when book is empty', ->
book = shallow(<Book />)
expect(book.matchesElement(<Error />)).toBeTruthy()
expect(book.equals(<Error statusCode={404} />)).toBeTruthy()
describe '@getInitialProps', voidify ->
it 'returns book: undefined when query is not present', ->
await expect(Book.getInitialProps({})).resolves.toEqual book: undefined
it 'returns book: undefined when query.isbn is not present', ->
await expect(Book.getInitialProps(query: {})).resolves.toEqual book: undefined
it 'returns book: undefined when query.isbn is not in books array', ->
await expect(Book.getInitialProps(query: { isbn: '123' })).resolves.toEqual book: undefined
it 'sets status code as 404 when book is not found', ->
res = statusCode: 200
await Book.getInitialProps({res})
expect(res.statusCode).toEqual 404
it 'returns a book when query.isbn is in books array', ->
[book] = books
await expect(Book.getInitialProps(query: { isbn: book.isbn })).resolves.toEqual {book}
| true | import {shallow} from 'enzyme'
import voidify from '../support/voidify'
import Error from 'next/error'
import Book from '../../pages/book'
import books from '../../data/books'
describe 'book page', voidify ->
it 'renders', ->
book = shallow(<Book book={title: "The Dispossessed", author: "PI:NAME:<NAME>END_PI", isbn: "1234", description: "Hard to say without spoiling the book."} />)
expect(book.find('Head title').text()).toEqual 'The Dispossessed'
expect(book.find('h1').text()).toEqual 'The Dispossessed'
expect(book.find('p.author').text()).toEqual 'PI:NAME:<NAME>END_PI'
expect(book.find('span').text()).toEqual 'ISBN 1234'
expect(book.find('p').at(1).text()).toEqual 'Hard to say without spoiling the book.'
it 'renders error when book is empty', ->
book = shallow(<Book />)
expect(book.matchesElement(<Error />)).toBeTruthy()
expect(book.equals(<Error statusCode={404} />)).toBeTruthy()
describe '@getInitialProps', voidify ->
it 'returns book: undefined when query is not present', ->
await expect(Book.getInitialProps({})).resolves.toEqual book: undefined
it 'returns book: undefined when query.isbn is not present', ->
await expect(Book.getInitialProps(query: {})).resolves.toEqual book: undefined
it 'returns book: undefined when query.isbn is not in books array', ->
await expect(Book.getInitialProps(query: { isbn: '123' })).resolves.toEqual book: undefined
it 'sets status code as 404 when book is not found', ->
res = statusCode: 200
await Book.getInitialProps({res})
expect(res.statusCode).toEqual 404
it 'returns a book when query.isbn is in books array', ->
[book] = books
await expect(Book.getInitialProps(query: { isbn: book.isbn })).resolves.toEqual {book}
|
[
{
"context": " else\n authorNode =\n 'name': author\n 'group': 2\n source = nodesLi",
"end": 1145,
"score": 0.5370376706123352,
"start": 1139,
"tag": "NAME",
"value": "author"
}
] | src/client/visualization/visualization.coffee | yournal/YournalProject | 1 | module = angular.module 'yournal.visualization', [
'yournal.directives.fisheye'
]
module.config [
'$stateProvider',
($stateProvider) ->
$stateProvider.state('visualization',
url: '/visualization'
templateUrl: 'public/yournal/js/visualization/visualization.html'
controller: 'yournal.visualization.VisualisationCtrl'
resolve:
articles: ['$rootScope', 'Article', ($rootScope, Article) ->
$rootScope.loading = true
Article.all().$promise
]
)
]
module.controller 'yournal.visualization.VisualisationCtrl', [
'$scope',
'articles',
($scope, articles) ->
nodesList = []
linksList = []
authors = {}
for article in articles
articleNode =
'name': article.title
'year': article.year
'volume': article.volume
'issue': article.issue
'section': article.section
'group': 1
'_id': article._id
target = nodesList.push(articleNode) - 1
for author in article.authors
if authors[author]?
source = authors[author]
else
authorNode =
'name': author
'group': 2
source = nodesList.push(authorNode) - 1
authors[author] = source
linkNode =
'source': source
'target': target,
'value': 1
linksList.push linkNode
$scope.data =
nodes: nodesList
links: linksList
]
| 168220 | module = angular.module 'yournal.visualization', [
'yournal.directives.fisheye'
]
module.config [
'$stateProvider',
($stateProvider) ->
$stateProvider.state('visualization',
url: '/visualization'
templateUrl: 'public/yournal/js/visualization/visualization.html'
controller: 'yournal.visualization.VisualisationCtrl'
resolve:
articles: ['$rootScope', 'Article', ($rootScope, Article) ->
$rootScope.loading = true
Article.all().$promise
]
)
]
module.controller 'yournal.visualization.VisualisationCtrl', [
'$scope',
'articles',
($scope, articles) ->
nodesList = []
linksList = []
authors = {}
for article in articles
articleNode =
'name': article.title
'year': article.year
'volume': article.volume
'issue': article.issue
'section': article.section
'group': 1
'_id': article._id
target = nodesList.push(articleNode) - 1
for author in article.authors
if authors[author]?
source = authors[author]
else
authorNode =
'name': <NAME>
'group': 2
source = nodesList.push(authorNode) - 1
authors[author] = source
linkNode =
'source': source
'target': target,
'value': 1
linksList.push linkNode
$scope.data =
nodes: nodesList
links: linksList
]
| true | module = angular.module 'yournal.visualization', [
'yournal.directives.fisheye'
]
module.config [
'$stateProvider',
($stateProvider) ->
$stateProvider.state('visualization',
url: '/visualization'
templateUrl: 'public/yournal/js/visualization/visualization.html'
controller: 'yournal.visualization.VisualisationCtrl'
resolve:
articles: ['$rootScope', 'Article', ($rootScope, Article) ->
$rootScope.loading = true
Article.all().$promise
]
)
]
module.controller 'yournal.visualization.VisualisationCtrl', [
'$scope',
'articles',
($scope, articles) ->
nodesList = []
linksList = []
authors = {}
for article in articles
articleNode =
'name': article.title
'year': article.year
'volume': article.volume
'issue': article.issue
'section': article.section
'group': 1
'_id': article._id
target = nodesList.push(articleNode) - 1
for author in article.authors
if authors[author]?
source = authors[author]
else
authorNode =
'name': PI:NAME:<NAME>END_PI
'group': 2
source = nodesList.push(authorNode) - 1
authors[author] = source
linkNode =
'source': source
'target': target,
'value': 1
linksList.push linkNode
$scope.data =
nodes: nodesList
links: linksList
]
|
[
{
"context": ",'E','F','F#','G','G#','A','A#','B']\nflatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']\n\nclass Note\n constructor: (val, temp) ->\n i",
"end": 184,
"score": 0.9542474746704102,
"start": 148,
"tag": "KEY",
"value": "C','F','Bb','Eb','Ab','Db','Gb', 'Cb"
}
] | src/note.coffee | jeffreypierce/temper | 2 | notesFlat = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']
notesSharp = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
flatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']
class Note
constructor: (val, temp) ->
if window?
@_play = temp.play
@_pluck = temp.pluck
@rootFrequency = temp.rootFrequency()
@temperament = temp._temperament
referenceFrequency = =>
@rootFrequency * Math.pow 2, @octave
noteFromName = (noteName) =>
getFrequencyFromNoteLetter = =>
noteArray = @getNoteArray @letter
position = noteArray.indexOf @letter
ratio = utils.ratioFromCents temperaments[@temperament][position]
utils.normalize ratio * referenceFrequency()
parsed = /// ([A-Ga-g]) # match letter
([b#]?) # match accidental
(\d+) # match octave
///.exec noteName
if parsed?
@octave = parseInt parsed[3], 10
@accidental = parsed[2]
@letter = parsed[1].toUpperCase()
@letter += @accidental if @accidental?
@frequency = utils.normalize getFrequencyFromNoteLetter()
@name = val
@centOffset = 0
else
throw new TypeError "Note name #{noteName} is not a valid argument"
noteFromFreq = (freq) =>
getNoteLetterFromFrequency = =>
baseFreq = Math.log @frequency / referenceFrequency()
# equal temperament naming
noteNumber = Math.round baseFreq / Math.log Math.pow(2, 1 / 12)
@octave += 1 if noteNumber is 12
noteArray = @getNoteArray()
noteArray[noteNumber % 12]
if 20000 > freq > 0
@octave = Math.floor Math.log(freq / @rootFrequency) / Math.log 2
@frequency = utils.normalize freq
@letter = getNoteLetterFromFrequency()
@name = @letter + @octave.toString()
accidental = @name.match /[b#]/
@accidental = if accidental? then accidental else ""
trueFreq = temper @name
@centOffset = utils.centOffset @frequency, trueFreq.tonic.frequency,
else
throw new RangeError "Frequency #{freq} is not valid"
noteFromName val if utils.type(val) is "string"
noteFromFreq val if utils.type(val) is "number"
@midiNote = Math.round 12 * Math.log(@frequency / 440) / Math.log(2) + 69
getNoteArray: (letter) ->
if flatKeys.indexOf(letter) > -1 then notesFlat else notesSharp
if window?
Note::play = (length) ->
@_play.call this, length
Note::pluck= (length) ->
@_pluck.call this, length
| 76514 | notesFlat = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']
notesSharp = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
flatKeys = ['<KEY>']
class Note
constructor: (val, temp) ->
if window?
@_play = temp.play
@_pluck = temp.pluck
@rootFrequency = temp.rootFrequency()
@temperament = temp._temperament
referenceFrequency = =>
@rootFrequency * Math.pow 2, @octave
noteFromName = (noteName) =>
getFrequencyFromNoteLetter = =>
noteArray = @getNoteArray @letter
position = noteArray.indexOf @letter
ratio = utils.ratioFromCents temperaments[@temperament][position]
utils.normalize ratio * referenceFrequency()
parsed = /// ([A-Ga-g]) # match letter
([b#]?) # match accidental
(\d+) # match octave
///.exec noteName
if parsed?
@octave = parseInt parsed[3], 10
@accidental = parsed[2]
@letter = parsed[1].toUpperCase()
@letter += @accidental if @accidental?
@frequency = utils.normalize getFrequencyFromNoteLetter()
@name = val
@centOffset = 0
else
throw new TypeError "Note name #{noteName} is not a valid argument"
noteFromFreq = (freq) =>
getNoteLetterFromFrequency = =>
baseFreq = Math.log @frequency / referenceFrequency()
# equal temperament naming
noteNumber = Math.round baseFreq / Math.log Math.pow(2, 1 / 12)
@octave += 1 if noteNumber is 12
noteArray = @getNoteArray()
noteArray[noteNumber % 12]
if 20000 > freq > 0
@octave = Math.floor Math.log(freq / @rootFrequency) / Math.log 2
@frequency = utils.normalize freq
@letter = getNoteLetterFromFrequency()
@name = @letter + @octave.toString()
accidental = @name.match /[b#]/
@accidental = if accidental? then accidental else ""
trueFreq = temper @name
@centOffset = utils.centOffset @frequency, trueFreq.tonic.frequency,
else
throw new RangeError "Frequency #{freq} is not valid"
noteFromName val if utils.type(val) is "string"
noteFromFreq val if utils.type(val) is "number"
@midiNote = Math.round 12 * Math.log(@frequency / 440) / Math.log(2) + 69
getNoteArray: (letter) ->
if flatKeys.indexOf(letter) > -1 then notesFlat else notesSharp
if window?
Note::play = (length) ->
@_play.call this, length
Note::pluck= (length) ->
@_pluck.call this, length
| true | notesFlat = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']
notesSharp = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
flatKeys = ['PI:KEY:<KEY>END_PI']
class Note
constructor: (val, temp) ->
if window?
@_play = temp.play
@_pluck = temp.pluck
@rootFrequency = temp.rootFrequency()
@temperament = temp._temperament
referenceFrequency = =>
@rootFrequency * Math.pow 2, @octave
noteFromName = (noteName) =>
getFrequencyFromNoteLetter = =>
noteArray = @getNoteArray @letter
position = noteArray.indexOf @letter
ratio = utils.ratioFromCents temperaments[@temperament][position]
utils.normalize ratio * referenceFrequency()
parsed = /// ([A-Ga-g]) # match letter
([b#]?) # match accidental
(\d+) # match octave
///.exec noteName
if parsed?
@octave = parseInt parsed[3], 10
@accidental = parsed[2]
@letter = parsed[1].toUpperCase()
@letter += @accidental if @accidental?
@frequency = utils.normalize getFrequencyFromNoteLetter()
@name = val
@centOffset = 0
else
throw new TypeError "Note name #{noteName} is not a valid argument"
noteFromFreq = (freq) =>
getNoteLetterFromFrequency = =>
baseFreq = Math.log @frequency / referenceFrequency()
# equal temperament naming
noteNumber = Math.round baseFreq / Math.log Math.pow(2, 1 / 12)
@octave += 1 if noteNumber is 12
noteArray = @getNoteArray()
noteArray[noteNumber % 12]
if 20000 > freq > 0
@octave = Math.floor Math.log(freq / @rootFrequency) / Math.log 2
@frequency = utils.normalize freq
@letter = getNoteLetterFromFrequency()
@name = @letter + @octave.toString()
accidental = @name.match /[b#]/
@accidental = if accidental? then accidental else ""
trueFreq = temper @name
@centOffset = utils.centOffset @frequency, trueFreq.tonic.frequency,
else
throw new RangeError "Frequency #{freq} is not valid"
noteFromName val if utils.type(val) is "string"
noteFromFreq val if utils.type(val) is "number"
@midiNote = Math.round 12 * Math.log(@frequency / 440) / Math.log(2) + 69
getNoteArray: (letter) ->
if flatKeys.indexOf(letter) > -1 then notesFlat else notesSharp
if window?
Note::play = (length) ->
@_play.call this, length
Note::pluck= (length) ->
@_pluck.call this, length
|
[
{
"context": "enario names\n nodeMap = {\n \"1\":\"533de20aa498867c56c6cba5\"\n \"2\":\"533de20aa498867c56c6cba7\"\n ",
"end": 2715,
"score": 0.9979583621025085,
"start": 2691,
"tag": "KEY",
"value": "533de20aa498867c56c6cba5"
},
{
"context": " \"1\"... | scripts/arrayHabitatTab.coffee | mcclintock-lab/training-reports-v2 | 0 | ReportTab = require 'reportTab'
templates = require '../templates/templates.js'
ids = require './ids.coffee'
for key, value of ids
window[key] = value
class ArrayHabitatTab extends ReportTab
name: 'Habitat'
className: 'habitat'
template: templates.arrayHabitats
dependencies: [
'BarbudaHabitat'
'MarxanAnalysis'
]
timeout: 240000
render: () ->
data = @recordSet('MarxanAnalysis', 'MarxanAnalysis').toArray()
sanctuaries = @getChildren SANCTUARY_ID
if sanctuaries.length
sanctuary = @recordSet('BarbudaHabitat', 'Habitats', SANCTUARY_ID)
.toArray()
for row in sanctuary
if parseFloat(row.Percent) >= 33
row.meetsGoal = true
moorings = @getChildren MOORING_ID
if moorings.length
mooringData = @recordSet('BarbudaHabitat', 'Habitats', MOORING_ID)
.toArray()
noNetZones = @getChildren NO_NET_ZONES_ID
if noNetZones.length
noNetZonesData = @recordSet('BarbudaHabitat', 'Habitats',
NO_NET_ZONES_ID).toArray()
context =
sketch: @model.forTemplate()
sketchClass: @sketchClass.forTemplate()
attributes: @model.getAttributes()
admin: @project.isAdmin window.user
numSanctuaries: sanctuaries.length
sanctuaries: sanctuaries.length > 0
sanctuaryHabitat: sanctuary
sanctuaryPlural: sanctuaries.length > 1
moorings: moorings.length > 0
numMoorings: moorings.length
mooringData: mooringData
mooringPlural: moorings.length > 1
hasNoNetZones: noNetZones.length > 0
numNoNetZones: noNetZones.length
noNetZonesData: noNetZonesData
noNetZonesPlural: noNetZones.length > 1
marxanAnalyses: _.map(@recordSet("MarxanAnalysis", "MarxanAnalysis")
.toArray(), (f) -> f.NAME)
@$el.html @template.render(context, templates)
@enableLayerTogglers(@$el)
@$('.chosen').chosen({disable_search_threshold: 10, width:'400px'})
@$('.chosen').change () =>
_.defer @renderMarxanAnalysis
tooltip = d3.select("body")
.append("div")
.attr("class", "chart-tooltip")
.attr("id", "chart-tooltip")
.text("data")
@renderMarxanAnalysis(tooltip)
calc_ttip = (xloc, data, tooltip) ->
tdiv = tooltip[0][0].getBoundingClientRect()
tleft = tdiv.left
tw = tdiv.width
return xloc-(tw+10) if (xloc+tw > tleft+tw)
return xloc+10
renderMarxanAnalysis: () =>
tooltip = d3.select('.chart-tooltip')
if window.d3
pointSelect = null
labelSelect = null
name = @$('.chosen').val()
try
#hook up the checkboxes for marxan scenario names
nodeMap = {
"1":"533de20aa498867c56c6cba5"
"2":"533de20aa498867c56c6cba7"
"3":"533de20aa498867c56c6cba9"
"4":"533de20aa498867c56c6cbab"
"5":"533de20aa498867c56c6cbad"
"6":"533de20aa498867c56c6cbaf"
"7":"533de20aa498867c56c6cbb1"
"8":"533de20aa498867c56c6cbb3"
}
scenarioName = name.substring(0,1)
nodeId = nodeMap[scenarioName]
toc = window.app.getToc()
view = toc.getChildViewById(nodeId)
node = view.model
isVisible = node.get('visible')
@$('.marxan-node').attr('data-toggle-node', nodeId)
@$('.marxan-node').data('tocItem', view)
@$('.marxan-node').attr('checked', isVisible)
@$('.marxan-node').attr('data-visible', isVisible)
@$('.marxan-node').text('show \'Scenario '+scenarioName+'\' marxan layer')
catch e
console.log("error", e)
records = @recordSet("MarxanAnalysis", "MarxanAnalysis").toArray()
quantile_range = {"Q0":"very low", "Q20": "low","Q40": "mid","Q60": "high","Q80": "very high"}
data = _.find records, (record) -> record.NAME is name
scores_data = []
proposals_data = []
for rec in records
if rec.NAME == name
scores_data.push(rec)
proposals_data.push(rec)
_.sortBy proposals_data, (r) -> window.app.sketches.get(r.SC_ID).attributes.name
histo = data.HISTO.slice(1, data.HISTO.length - 1).split(/\s/)
histo = _.filter histo, (s) -> s.length > 0
histo = _.map histo, (val) ->
parseInt(val)
quantiles = _.filter(_.keys(data), (key) -> key.indexOf('Q') is 0)
for q, i in quantiles
if parseFloat(data[q]) > parseFloat(data.SCORE) or i is quantiles.length - 1
max_q = quantiles[i]
min_q = quantiles[i - 1] or "Q0" # quantiles[i]
quantile_desc = quantile_range[min_q]
break
scores_table = "<table><thead><tr><th>Proposal</th><th>Score</th><th>Quantile</th><th>Quantile %</tr></thead><tbody>"
for rec in proposals_data
rec_name = window.app.sketches.get(rec.SC_ID).attributes.name
rec_score = rec.SCORE
scores_table+="<tr><td>#{rec_name}</td><td>#{rec_score}</td><td>#{quantile_desc}</td><td>#{min_q.replace('Q', '')}%-#{max_q.replace('Q', '')}%</td></tr></tbody><table>"
@$('.proposalResults').html scores_table
@$('.scenarioDescription').html data.MARX_DESC
domain = _.map quantiles, (q) -> data[q]
domain.push 100
domain.unshift 0
color = d3.scale.linear()
.domain(domain)
.range(["#47ae43", "#6c0", "#ee0", "#eb4", "#ecbb89", "#eeaba0"].reverse())
quantiles = _.map quantiles, (key) ->
max = parseFloat(data[key])
min = parseFloat(data[quantiles[_.indexOf(quantiles, key) - 1]] or 0)
{
range: "#{parseInt(key.replace('Q', '')) - 20}-#{key.replace('Q', '')}%"
name: key
start: min
end: max
bg: color((max + min) / 2)
}
@$('.viz').html('')
el = @$('.viz')[0]
x = d3.scale.linear()
.domain([0, 100])
.range([0, 400])
# Histogram
margin =
top: 5
right: 20
bottom: 30
left: 45
width = 400 - margin.left - margin.right
height = 350 - margin.top - margin.bottom
x = d3.scale.linear()
.domain([0, 100])
.range([0, width])
y = d3.scale.linear()
.range([height, 0])
.domain([0, d3.max(histo)+50])
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
svg = d3.select(@$('.viz')[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(#{margin.left}, #{margin.top})")
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0,#{height})")
.call(xAxis)
.append("text")
.attr("x", width / 2)
.attr("dy", "3em")
.style("text-anchor", "middle")
.text("Score")
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of Planning Units")
svg.selectAll(".bar")
.data(histo)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d, i) -> x(i))
.attr("width", (width / 100))
.attr("y", (d) -> y(d))
.attr("height", (d) -> height - y(d))
.style 'fill', (d, i) ->
q = _.find quantiles, (q) ->
i >= q.start and i <= q.end
q?.bg or "steelblue"
#sort the overlapping scores into a map of scores->array of proposal ids
score_map = []
for sdata in scores_data
curr_score = Math.round(sdata.SCORE)
curr_proposal = sdata.PROPOSAL
scores = Object.keys(score_map)
if curr_score.toString() in scores
prop_ids = score_map[curr_score]
prop_ids.push(curr_proposal)
score_map[curr_score] = prop_ids
else
score_map[curr_score] = [curr_proposal]
for sdata, proposals of score_map
svg.selectAll(".score"+sdata)
.data([sdata])
.enter().append("text")
.attr("class", "score")
.attr("x", (d) -> (x(d) - 8 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 1) + 'px')
.text("▼")
.style('cursor', 'pointer')
.on("mouseover", (d) -> show_tooltip(tooltip, d, score_map))
.on("mouseout", (d) -> hide_tooltip(tooltip))
.on("mousemove", (d) -> tooltip.style("top", (event.pageY-10)+"px").style("left",(calc_ttip(event.pageX, d, tooltip))+"px"))
for sdata, proposals of score_map
svg.selectAll('.scoreText'+sdata)
.data([sdata])
.enter().append("text")
.attr("class", "scoreText")
.attr("x", (d) -> (x(d) - 6 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 18) + 'px')
.attr("id", (d) -> "s"+d)
.style("font-size", '12px')
.style('cursor', 'pointer')
.on("mouseover", (d) -> show_tooltip(tooltip, d, score_map))
.on("mouseout", (d) -> hide_tooltip(tooltip))
.on("mousemove", (d) -> tooltip.style("top", (event.pageY-10)+"px").style("left",(calc_ttip(event.pageX, d, tooltip))+"px"))
.text( (d, props) ->
return proposals.length+" Proposals" if (proposals.length > 1)
return window.app.sketches.get(proposals[0]).attributes.name
)
@$('.viz').append '<div class="legends"></div>'
for quantile in quantiles
@$('.viz .legends').append """
<div class="legend"><span style="background-color:#{quantile.bg};"> </span>#{quantile.range}</div>
"""
@$('.viz').append '<br style="clear:both;">'
show_tooltip = (tooltip, data, score_map) ->
tooltip.style("visibility", "visible").html(get_proposal_html(data, score_map[data]))
return
get_proposal_html = (data, proposals) ->
if proposals.length == 1
return "<b>"+window.app.sketches.get(proposals[0]).attributes.name+"</b> has a score of <b>"+data+"</b>"
else
msg = "The following proposals have a score of <b>"+data+"</b>:<ul>"
for p in proposals
msg+="<li><b>"+window.app.sketches.get(p).attributes.name+"</b></li>"
msg+="</ul>"
return msg
hide_tooltip = (tooltip) ->
tooltip.style("visibility", "hidden")
return
calc_ttip = (xloc, data, tooltip) ->
tdiv = tooltip[0][0].getBoundingClientRect()
tleft = tdiv.left
tw = tdiv.width
return xloc-(tw+10) if (xloc+tw > tleft+tw)
return xloc+10
module.exports = ArrayHabitatTab | 96752 | ReportTab = require 'reportTab'
templates = require '../templates/templates.js'
ids = require './ids.coffee'
for key, value of ids
window[key] = value
class ArrayHabitatTab extends ReportTab
name: 'Habitat'
className: 'habitat'
template: templates.arrayHabitats
dependencies: [
'BarbudaHabitat'
'MarxanAnalysis'
]
timeout: 240000
render: () ->
data = @recordSet('MarxanAnalysis', 'MarxanAnalysis').toArray()
sanctuaries = @getChildren SANCTUARY_ID
if sanctuaries.length
sanctuary = @recordSet('BarbudaHabitat', 'Habitats', SANCTUARY_ID)
.toArray()
for row in sanctuary
if parseFloat(row.Percent) >= 33
row.meetsGoal = true
moorings = @getChildren MOORING_ID
if moorings.length
mooringData = @recordSet('BarbudaHabitat', 'Habitats', MOORING_ID)
.toArray()
noNetZones = @getChildren NO_NET_ZONES_ID
if noNetZones.length
noNetZonesData = @recordSet('BarbudaHabitat', 'Habitats',
NO_NET_ZONES_ID).toArray()
context =
sketch: @model.forTemplate()
sketchClass: @sketchClass.forTemplate()
attributes: @model.getAttributes()
admin: @project.isAdmin window.user
numSanctuaries: sanctuaries.length
sanctuaries: sanctuaries.length > 0
sanctuaryHabitat: sanctuary
sanctuaryPlural: sanctuaries.length > 1
moorings: moorings.length > 0
numMoorings: moorings.length
mooringData: mooringData
mooringPlural: moorings.length > 1
hasNoNetZones: noNetZones.length > 0
numNoNetZones: noNetZones.length
noNetZonesData: noNetZonesData
noNetZonesPlural: noNetZones.length > 1
marxanAnalyses: _.map(@recordSet("MarxanAnalysis", "MarxanAnalysis")
.toArray(), (f) -> f.NAME)
@$el.html @template.render(context, templates)
@enableLayerTogglers(@$el)
@$('.chosen').chosen({disable_search_threshold: 10, width:'400px'})
@$('.chosen').change () =>
_.defer @renderMarxanAnalysis
tooltip = d3.select("body")
.append("div")
.attr("class", "chart-tooltip")
.attr("id", "chart-tooltip")
.text("data")
@renderMarxanAnalysis(tooltip)
calc_ttip = (xloc, data, tooltip) ->
tdiv = tooltip[0][0].getBoundingClientRect()
tleft = tdiv.left
tw = tdiv.width
return xloc-(tw+10) if (xloc+tw > tleft+tw)
return xloc+10
renderMarxanAnalysis: () =>
tooltip = d3.select('.chart-tooltip')
if window.d3
pointSelect = null
labelSelect = null
name = @$('.chosen').val()
try
#hook up the checkboxes for marxan scenario names
nodeMap = {
"1":"<KEY>"
"2":"<KEY>"
"3":"<KEY>"
"4":"<KEY>"
"5":"<KEY>"
"6":"<KEY>"
"7":"<KEY>"
"8":"<KEY>"
}
scenarioName = name.substring(0,1)
nodeId = nodeMap[scenarioName]
toc = window.app.getToc()
view = toc.getChildViewById(nodeId)
node = view.model
isVisible = node.get('visible')
@$('.marxan-node').attr('data-toggle-node', nodeId)
@$('.marxan-node').data('tocItem', view)
@$('.marxan-node').attr('checked', isVisible)
@$('.marxan-node').attr('data-visible', isVisible)
@$('.marxan-node').text('show \'Scenario '+scenarioName+'\' marxan layer')
catch e
console.log("error", e)
records = @recordSet("MarxanAnalysis", "MarxanAnalysis").toArray()
quantile_range = {"Q0":"very low", "Q20": "low","Q40": "mid","Q60": "high","Q80": "very high"}
data = _.find records, (record) -> record.NAME is name
scores_data = []
proposals_data = []
for rec in records
if rec.NAME == name
scores_data.push(rec)
proposals_data.push(rec)
_.sortBy proposals_data, (r) -> window.app.sketches.get(r.SC_ID).attributes.name
histo = data.HISTO.slice(1, data.HISTO.length - 1).split(/\s/)
histo = _.filter histo, (s) -> s.length > 0
histo = _.map histo, (val) ->
parseInt(val)
quantiles = _.filter(_.keys(data), (key) -> key.indexOf('Q') is 0)
for q, i in quantiles
if parseFloat(data[q]) > parseFloat(data.SCORE) or i is quantiles.length - 1
max_q = quantiles[i]
min_q = quantiles[i - 1] or "Q0" # quantiles[i]
quantile_desc = quantile_range[min_q]
break
scores_table = "<table><thead><tr><th>Proposal</th><th>Score</th><th>Quantile</th><th>Quantile %</tr></thead><tbody>"
for rec in proposals_data
rec_name = window.app.sketches.get(rec.SC_ID).attributes.name
rec_score = rec.SCORE
scores_table+="<tr><td>#{rec_name}</td><td>#{rec_score}</td><td>#{quantile_desc}</td><td>#{min_q.replace('Q', '')}%-#{max_q.replace('Q', '')}%</td></tr></tbody><table>"
@$('.proposalResults').html scores_table
@$('.scenarioDescription').html data.MARX_DESC
domain = _.map quantiles, (q) -> data[q]
domain.push 100
domain.unshift 0
color = d3.scale.linear()
.domain(domain)
.range(["#47ae43", "#6c0", "#ee0", "#eb4", "#ecbb89", "#eeaba0"].reverse())
quantiles = _.map quantiles, (key) ->
max = parseFloat(data[key])
min = parseFloat(data[quantiles[_.indexOf(quantiles, key) - 1]] or 0)
{
range: "#{parseInt(key.replace('Q', '')) - 20}-#{key.replace('Q', '')}%"
name: key
start: min
end: max
bg: color((max + min) / 2)
}
@$('.viz').html('')
el = @$('.viz')[0]
x = d3.scale.linear()
.domain([0, 100])
.range([0, 400])
# Histogram
margin =
top: 5
right: 20
bottom: 30
left: 45
width = 400 - margin.left - margin.right
height = 350 - margin.top - margin.bottom
x = d3.scale.linear()
.domain([0, 100])
.range([0, width])
y = d3.scale.linear()
.range([height, 0])
.domain([0, d3.max(histo)+50])
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
svg = d3.select(@$('.viz')[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(#{margin.left}, #{margin.top})")
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0,#{height})")
.call(xAxis)
.append("text")
.attr("x", width / 2)
.attr("dy", "3em")
.style("text-anchor", "middle")
.text("Score")
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of Planning Units")
svg.selectAll(".bar")
.data(histo)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d, i) -> x(i))
.attr("width", (width / 100))
.attr("y", (d) -> y(d))
.attr("height", (d) -> height - y(d))
.style 'fill', (d, i) ->
q = _.find quantiles, (q) ->
i >= q.start and i <= q.end
q?.bg or "steelblue"
#sort the overlapping scores into a map of scores->array of proposal ids
score_map = []
for sdata in scores_data
curr_score = Math.round(sdata.SCORE)
curr_proposal = sdata.PROPOSAL
scores = Object.keys(score_map)
if curr_score.toString() in scores
prop_ids = score_map[curr_score]
prop_ids.push(curr_proposal)
score_map[curr_score] = prop_ids
else
score_map[curr_score] = [curr_proposal]
for sdata, proposals of score_map
svg.selectAll(".score"+sdata)
.data([sdata])
.enter().append("text")
.attr("class", "score")
.attr("x", (d) -> (x(d) - 8 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 1) + 'px')
.text("▼")
.style('cursor', 'pointer')
.on("mouseover", (d) -> show_tooltip(tooltip, d, score_map))
.on("mouseout", (d) -> hide_tooltip(tooltip))
.on("mousemove", (d) -> tooltip.style("top", (event.pageY-10)+"px").style("left",(calc_ttip(event.pageX, d, tooltip))+"px"))
for sdata, proposals of score_map
svg.selectAll('.scoreText'+sdata)
.data([sdata])
.enter().append("text")
.attr("class", "scoreText")
.attr("x", (d) -> (x(d) - 6 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 18) + 'px')
.attr("id", (d) -> "s"+d)
.style("font-size", '12px')
.style('cursor', 'pointer')
.on("mouseover", (d) -> show_tooltip(tooltip, d, score_map))
.on("mouseout", (d) -> hide_tooltip(tooltip))
.on("mousemove", (d) -> tooltip.style("top", (event.pageY-10)+"px").style("left",(calc_ttip(event.pageX, d, tooltip))+"px"))
.text( (d, props) ->
return proposals.length+" Proposals" if (proposals.length > 1)
return window.app.sketches.get(proposals[0]).attributes.name
)
@$('.viz').append '<div class="legends"></div>'
for quantile in quantiles
@$('.viz .legends').append """
<div class="legend"><span style="background-color:#{quantile.bg};"> </span>#{quantile.range}</div>
"""
@$('.viz').append '<br style="clear:both;">'
show_tooltip = (tooltip, data, score_map) ->
tooltip.style("visibility", "visible").html(get_proposal_html(data, score_map[data]))
return
get_proposal_html = (data, proposals) ->
if proposals.length == 1
return "<b>"+window.app.sketches.get(proposals[0]).attributes.name+"</b> has a score of <b>"+data+"</b>"
else
msg = "The following proposals have a score of <b>"+data+"</b>:<ul>"
for p in proposals
msg+="<li><b>"+window.app.sketches.get(p).attributes.name+"</b></li>"
msg+="</ul>"
return msg
hide_tooltip = (tooltip) ->
tooltip.style("visibility", "hidden")
return
calc_ttip = (xloc, data, tooltip) ->
tdiv = tooltip[0][0].getBoundingClientRect()
tleft = tdiv.left
tw = tdiv.width
return xloc-(tw+10) if (xloc+tw > tleft+tw)
return xloc+10
module.exports = ArrayHabitatTab | true | ReportTab = require 'reportTab'
templates = require '../templates/templates.js'
ids = require './ids.coffee'
for key, value of ids
window[key] = value
class ArrayHabitatTab extends ReportTab
name: 'Habitat'
className: 'habitat'
template: templates.arrayHabitats
dependencies: [
'BarbudaHabitat'
'MarxanAnalysis'
]
timeout: 240000
render: () ->
data = @recordSet('MarxanAnalysis', 'MarxanAnalysis').toArray()
sanctuaries = @getChildren SANCTUARY_ID
if sanctuaries.length
sanctuary = @recordSet('BarbudaHabitat', 'Habitats', SANCTUARY_ID)
.toArray()
for row in sanctuary
if parseFloat(row.Percent) >= 33
row.meetsGoal = true
moorings = @getChildren MOORING_ID
if moorings.length
mooringData = @recordSet('BarbudaHabitat', 'Habitats', MOORING_ID)
.toArray()
noNetZones = @getChildren NO_NET_ZONES_ID
if noNetZones.length
noNetZonesData = @recordSet('BarbudaHabitat', 'Habitats',
NO_NET_ZONES_ID).toArray()
context =
sketch: @model.forTemplate()
sketchClass: @sketchClass.forTemplate()
attributes: @model.getAttributes()
admin: @project.isAdmin window.user
numSanctuaries: sanctuaries.length
sanctuaries: sanctuaries.length > 0
sanctuaryHabitat: sanctuary
sanctuaryPlural: sanctuaries.length > 1
moorings: moorings.length > 0
numMoorings: moorings.length
mooringData: mooringData
mooringPlural: moorings.length > 1
hasNoNetZones: noNetZones.length > 0
numNoNetZones: noNetZones.length
noNetZonesData: noNetZonesData
noNetZonesPlural: noNetZones.length > 1
marxanAnalyses: _.map(@recordSet("MarxanAnalysis", "MarxanAnalysis")
.toArray(), (f) -> f.NAME)
@$el.html @template.render(context, templates)
@enableLayerTogglers(@$el)
@$('.chosen').chosen({disable_search_threshold: 10, width:'400px'})
@$('.chosen').change () =>
_.defer @renderMarxanAnalysis
tooltip = d3.select("body")
.append("div")
.attr("class", "chart-tooltip")
.attr("id", "chart-tooltip")
.text("data")
@renderMarxanAnalysis(tooltip)
calc_ttip = (xloc, data, tooltip) ->
tdiv = tooltip[0][0].getBoundingClientRect()
tleft = tdiv.left
tw = tdiv.width
return xloc-(tw+10) if (xloc+tw > tleft+tw)
return xloc+10
renderMarxanAnalysis: () =>
tooltip = d3.select('.chart-tooltip')
if window.d3
pointSelect = null
labelSelect = null
name = @$('.chosen').val()
try
#hook up the checkboxes for marxan scenario names
nodeMap = {
"1":"PI:KEY:<KEY>END_PI"
"2":"PI:KEY:<KEY>END_PI"
"3":"PI:KEY:<KEY>END_PI"
"4":"PI:KEY:<KEY>END_PI"
"5":"PI:KEY:<KEY>END_PI"
"6":"PI:KEY:<KEY>END_PI"
"7":"PI:KEY:<KEY>END_PI"
"8":"PI:KEY:<KEY>END_PI"
}
scenarioName = name.substring(0,1)
nodeId = nodeMap[scenarioName]
toc = window.app.getToc()
view = toc.getChildViewById(nodeId)
node = view.model
isVisible = node.get('visible')
@$('.marxan-node').attr('data-toggle-node', nodeId)
@$('.marxan-node').data('tocItem', view)
@$('.marxan-node').attr('checked', isVisible)
@$('.marxan-node').attr('data-visible', isVisible)
@$('.marxan-node').text('show \'Scenario '+scenarioName+'\' marxan layer')
catch e
console.log("error", e)
records = @recordSet("MarxanAnalysis", "MarxanAnalysis").toArray()
quantile_range = {"Q0":"very low", "Q20": "low","Q40": "mid","Q60": "high","Q80": "very high"}
data = _.find records, (record) -> record.NAME is name
scores_data = []
proposals_data = []
for rec in records
if rec.NAME == name
scores_data.push(rec)
proposals_data.push(rec)
_.sortBy proposals_data, (r) -> window.app.sketches.get(r.SC_ID).attributes.name
histo = data.HISTO.slice(1, data.HISTO.length - 1).split(/\s/)
histo = _.filter histo, (s) -> s.length > 0
histo = _.map histo, (val) ->
parseInt(val)
quantiles = _.filter(_.keys(data), (key) -> key.indexOf('Q') is 0)
for q, i in quantiles
if parseFloat(data[q]) > parseFloat(data.SCORE) or i is quantiles.length - 1
max_q = quantiles[i]
min_q = quantiles[i - 1] or "Q0" # quantiles[i]
quantile_desc = quantile_range[min_q]
break
scores_table = "<table><thead><tr><th>Proposal</th><th>Score</th><th>Quantile</th><th>Quantile %</tr></thead><tbody>"
for rec in proposals_data
rec_name = window.app.sketches.get(rec.SC_ID).attributes.name
rec_score = rec.SCORE
scores_table+="<tr><td>#{rec_name}</td><td>#{rec_score}</td><td>#{quantile_desc}</td><td>#{min_q.replace('Q', '')}%-#{max_q.replace('Q', '')}%</td></tr></tbody><table>"
@$('.proposalResults').html scores_table
@$('.scenarioDescription').html data.MARX_DESC
domain = _.map quantiles, (q) -> data[q]
domain.push 100
domain.unshift 0
color = d3.scale.linear()
.domain(domain)
.range(["#47ae43", "#6c0", "#ee0", "#eb4", "#ecbb89", "#eeaba0"].reverse())
quantiles = _.map quantiles, (key) ->
max = parseFloat(data[key])
min = parseFloat(data[quantiles[_.indexOf(quantiles, key) - 1]] or 0)
{
range: "#{parseInt(key.replace('Q', '')) - 20}-#{key.replace('Q', '')}%"
name: key
start: min
end: max
bg: color((max + min) / 2)
}
@$('.viz').html('')
el = @$('.viz')[0]
x = d3.scale.linear()
.domain([0, 100])
.range([0, 400])
# Histogram
margin =
top: 5
right: 20
bottom: 30
left: 45
width = 400 - margin.left - margin.right
height = 350 - margin.top - margin.bottom
x = d3.scale.linear()
.domain([0, 100])
.range([0, width])
y = d3.scale.linear()
.range([height, 0])
.domain([0, d3.max(histo)+50])
xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
yAxis = d3.svg.axis()
.scale(y)
.orient("left")
svg = d3.select(@$('.viz')[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(#{margin.left}, #{margin.top})")
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0,#{height})")
.call(xAxis)
.append("text")
.attr("x", width / 2)
.attr("dy", "3em")
.style("text-anchor", "middle")
.text("Score")
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number of Planning Units")
svg.selectAll(".bar")
.data(histo)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d, i) -> x(i))
.attr("width", (width / 100))
.attr("y", (d) -> y(d))
.attr("height", (d) -> height - y(d))
.style 'fill', (d, i) ->
q = _.find quantiles, (q) ->
i >= q.start and i <= q.end
q?.bg or "steelblue"
#sort the overlapping scores into a map of scores->array of proposal ids
score_map = []
for sdata in scores_data
curr_score = Math.round(sdata.SCORE)
curr_proposal = sdata.PROPOSAL
scores = Object.keys(score_map)
if curr_score.toString() in scores
prop_ids = score_map[curr_score]
prop_ids.push(curr_proposal)
score_map[curr_score] = prop_ids
else
score_map[curr_score] = [curr_proposal]
for sdata, proposals of score_map
svg.selectAll(".score"+sdata)
.data([sdata])
.enter().append("text")
.attr("class", "score")
.attr("x", (d) -> (x(d) - 8 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 1) + 'px')
.text("▼")
.style('cursor', 'pointer')
.on("mouseover", (d) -> show_tooltip(tooltip, d, score_map))
.on("mouseout", (d) -> hide_tooltip(tooltip))
.on("mousemove", (d) -> tooltip.style("top", (event.pageY-10)+"px").style("left",(calc_ttip(event.pageX, d, tooltip))+"px"))
for sdata, proposals of score_map
svg.selectAll('.scoreText'+sdata)
.data([sdata])
.enter().append("text")
.attr("class", "scoreText")
.attr("x", (d) -> (x(d) - 6 )+ 'px')
.attr("y", (d) -> (y(histo[d]) - 18) + 'px')
.attr("id", (d) -> "s"+d)
.style("font-size", '12px')
.style('cursor', 'pointer')
.on("mouseover", (d) -> show_tooltip(tooltip, d, score_map))
.on("mouseout", (d) -> hide_tooltip(tooltip))
.on("mousemove", (d) -> tooltip.style("top", (event.pageY-10)+"px").style("left",(calc_ttip(event.pageX, d, tooltip))+"px"))
.text( (d, props) ->
return proposals.length+" Proposals" if (proposals.length > 1)
return window.app.sketches.get(proposals[0]).attributes.name
)
@$('.viz').append '<div class="legends"></div>'
for quantile in quantiles
@$('.viz .legends').append """
<div class="legend"><span style="background-color:#{quantile.bg};"> </span>#{quantile.range}</div>
"""
@$('.viz').append '<br style="clear:both;">'
show_tooltip = (tooltip, data, score_map) ->
tooltip.style("visibility", "visible").html(get_proposal_html(data, score_map[data]))
return
get_proposal_html = (data, proposals) ->
if proposals.length == 1
return "<b>"+window.app.sketches.get(proposals[0]).attributes.name+"</b> has a score of <b>"+data+"</b>"
else
msg = "The following proposals have a score of <b>"+data+"</b>:<ul>"
for p in proposals
msg+="<li><b>"+window.app.sketches.get(p).attributes.name+"</b></li>"
msg+="</ul>"
return msg
hide_tooltip = (tooltip) ->
tooltip.style("visibility", "hidden")
return
calc_ttip = (xloc, data, tooltip) ->
tdiv = tooltip[0][0].getBoundingClientRect()
tleft = tdiv.left
tw = tdiv.width
return xloc-(tw+10) if (xloc+tw > tleft+tw)
return xloc+10
module.exports = ArrayHabitatTab |
[
{
"context": "n(h, 'parseDelta').and.callThrough()\n key = 'left'; delta = { '50%': 0 }\n md._getDelta key, de",
"end": 18166,
"score": 0.7837406396865845,
"start": 18162,
"tag": "KEY",
"value": "left"
},
{
"context": " to props', ->\n md = new Module\n key = 'lef... | assets/dragsport/vendor/mojs-master/spec/module.coffee | MCPU15/dragsport | 24 | Module = mojs.Module
h = mojs.h
oldFun = Module::_declareDefaults
describe 'module class ->', ->
it 'set the _defaults up', ->
defaults = {
stroke: 'transparent',
strokeOpacity: 1,
strokeLinecap: '',
strokeWidth: 2,
strokeDasharray: 0,
strokeDashoffset: 0,
fill: 'deeppink',
fillOpacity: 1,
left: 0,
top: 0,
x: 0,
y: 0,
rx: 0,
ry: 0,
angle: 0,
scale: 1,
opacity: 1,
points: 3,
radius: { 0: 50 },
radiusX: null,
radiusY: null,
isShowStart: false,
isSoftHide: true,
isShowEnd: false,
size: null,
sizeGap: 0,
callbacksContext: null
}
Module::_declareDefaults = -> this._defaults = defaults
describe 'init ->', ->
it 'should save options to _o', ->
options = {}
md = new Module options
expect(md._o).toBe options
it 'should create _arrayPropertyMap', ->
md = new Module
expect(md._arrayPropertyMap['strokeDasharray']).toBe 1
expect(md._arrayPropertyMap['strokeDashoffset']).toBe 1
expect(md._arrayPropertyMap['origin']).toBe 1
it 'should create _arrayPropertyMap', ->
md = new Module
expect(md._skipPropsDelta.callbacksContext).toBe 1
expect(md._skipPropsDelta.timeline).toBe 1
expect(md._skipPropsDelta.prevChainModule).toBe 1
it 'should fallback to empty object for _o', ->
md = new Module
expect(Object.keys(md._o).length).toBe 0
expect(typeof md._o).toBe 'object'
# not null
expect(md._o).toBe md._o
it 'should call _declareDefaults method', ->
spyOn(Module.prototype, '_declareDefaults').and.callThrough()
md = new Module
expect(Module.prototype._declareDefaults).toHaveBeenCalled()
it 'should call _extendDefaults method', ->
spyOn(Module.prototype, '_extendDefaults').and.callThrough()
md = new Module
expect(Module.prototype._extendDefaults).toHaveBeenCalled()
it 'should call _vars method', ->
spyOn(Module.prototype, '_vars').and.callThrough()
md = new Module
expect(Module.prototype._vars).toHaveBeenCalled()
it 'should call _render method', ->
spyOn(Module.prototype, '_render').and.callThrough()
md = new Module
expect(Module.prototype._render).toHaveBeenCalled()
it 'should create _index property', ->
index = 5
md = new Module index: index
expect(md._index).toBe index
it 'should fallback to 0 for _index property', ->
md = new Module
expect(md._index).toBe 0
describe '_declareDefaults method ->', ->
it 'should create _defaults object', ->
spyOn(Module.prototype, '_declareDefaults').and.callThrough()
md = new Module
expect(Module.prototype._declareDefaults).toHaveBeenCalled()
expect(typeof md._defaults).toBe 'object'
# not null
expect(md._defaults).toBe md._defaults
describe '_vars method ->', ->
it 'should set _progress property to 0', ->
md = new Module
expect(md._progress).toBe 0
it 'should create _strokeDasharrayBuffer array', ->
md = new Module
expect(md._strokeDasharrayBuffer.length).toBe 0
expect(h.isArray(md._strokeDasharrayBuffer)).toBe true
describe '_assignProp method ->', ->
it 'should set property on _props object', ->
value = 2
md = new Module
md._assignProp 'a', value
expect(md._props.a).toBe value
describe '_setProp method ->', ->
it 'should set new tween options', ->
t = new Module duration: 100, delay: 0
t._setProp duration: 1000, delay: 200
expect(t._props.duration).toBe 1000
expect(t._props.delay).toBe 200
it 'should work with arguments', ->
t = new Module duration: 100
t._setProp 'duration', 1000
expect(t._props.duration).toBe 1000
describe '_hide method ->' , ->
it 'should set `display` of `el` to `none`', ->
byte = new Module isSoftHide: false
byte.el = document.createElement 'div'
byte.el.style[ 'display' ] = 'block'
byte._hide()
expect( byte.el.style[ 'display' ] ).toBe 'none'
it 'should set `_isShown` to false', ->
byte = new Module isSoftHide: false
byte.el = document.createElement 'div'
byte._isShown = true
byte._hide()
expect( byte._isShown ).toBe false
describe 'isSoftHide option ->', ->
# nope
# it 'should set `opacity` of `el` to `0`', ->
# byte = new Module radius: 25, isSoftHide: true
# byte.el = document.createElement 'div'
# byte.el.style[ 'opacity' ] = '.5'
# byte._hide()
# expect( byte.el.style[ 'opacity' ] ).toBe '0'
it 'should set scale to 0', ->
byte = new Module
radius: 25,
isSoftHide: true
byte.el = document.createElement 'div'
byte._hide()
style = byte.el.style
tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ]
expect( tr ).toBe 'scale(0)'
describe '_show method ->' , ->
it 'should set `display` of `el` to `block`', ->
byte = new Module radius: 25, isSoftHide: false
byte.el = document.createElement 'div'
byte.el.style[ 'display' ] = 'none'
byte._show()
expect( byte.el.style[ 'display' ] ).toBe 'block'
it 'should set `_isShown` to true', ->
byte = new Module radius: 25, isSoftHide: false
byte._isShown = true
byte._show()
expect( byte._isShown ).toBe true
describe 'isSoftHide option ->', ->
# nope
# it 'should set `opacity` of `el` to `_props.opacity`', ->
# byte = new Module radius: 25, isSoftHide: true, opacity: .2
# byte.el = document.createElement 'div'
# byte.el.style[ 'opacity' ] = '0'
# byte._show()
# expect( byte.el.style[ 'opacity' ] ).toBe "#{byte._props.opacity}"
it 'should set `transform` to normal', ->
byte = new Module radius: 25, isSoftHide: true, opacity: .2
byte.el = document.createElement 'div'
byte.el.style[ 'opacity' ] = '0'
byte.el.style[ 'transform' ] = 'none'
spyOn byte, '_showByTransform'
byte._show()
# style = byte.el.style
# tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ]
expect( byte._showByTransform ).toHaveBeenCalled()
# old
# describe '_show method ->', ->
# it 'should set display: block to el', ->
# md = new Module
# md.el = document.createElement 'div'
# md._show()
# expect(md.el.style.display).toBe 'block'
# expect(md._isShown).toBe true
# it 'should return if isShow is already true', ->
# md = new Module
# md.el = document.createElement 'div'
# md._show()
# md.el.style.display = 'inline'
# md._show()
# expect(md.el.style.display).toBe 'inline'
# it 'not to throw', ->
# byte = new Module radius: {'25': 75}
# expect(-> byte._show()).not.toThrow()
# old
# describe '_hide method ->', ->
# it 'should set display: block to el', ->
# md = new Module
# md.el = document.createElement 'div'
# md._hide()
# expect(md.el.style.display).toBe 'none'
# expect(md._isShown).toBe false
# it 'not to throw', ->
# byte = new Module radius: {'25': 75}
# expect(-> byte._hide()).not.toThrow()
describe '_parseOptionString method ->', ->
tr = new Module
it 'should parse stagger values', ->
string = 'stagger(200)'
spyOn(h, 'parseStagger').and.callThrough()
result = tr._parseOptionString string
expect(h.parseStagger).toHaveBeenCalledWith string, 0
expect(result).toBe h.parseStagger(string, 0)
it 'should parse rand values', ->
string = 'rand(0,1)'
spyOn(h, 'parseRand').and.callThrough()
result = tr._parseOptionString string
expect(h.parseRand).toHaveBeenCalledWith string
describe '_parsePositionOption method ->', ->
tr = new Module
it 'should parse position option', ->
key = 'x'; value = '100%'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parsePositionOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result).toBe h.parseUnit(value).string
it 'should leave the value unattended if not pos property', ->
tr._props.x = '100%'
key = 'fill'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parsePositionOption key
expect(h.parseUnit).not.toHaveBeenCalledWith()
expect(result).toBe tr._props[key]
describe '_parseStrokeDashOption method ->', ->
tr = new Module
it 'should parse strokeDash option', ->
key = 'strokeDasharray'; value = 200
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result[0].unit).toBe h.parseUnit(value).unit
expect(result[0].isStrict).toBe h.parseUnit(value).isStrict
expect(result[0].value).toBe h.parseUnit(value).value
expect(result[0].string).toBe h.parseUnit(value).string
expect(result[1]).not.toBeDefined()
it 'should parse strokeDash option string', ->
key = 'strokeDasharray'; value = '200 100'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith '200'
expect(h.parseUnit).toHaveBeenCalledWith '100'
expect(result[0].unit).toBe h.parseUnit(200).unit
expect(result[0].isStrict).toBe h.parseUnit(200).isStrict
expect(result[0].value).toBe h.parseUnit(200).value
expect(result[0].string).toBe h.parseUnit(200).string
expect(result[1].unit).toBe h.parseUnit(100).unit
expect(result[1].isStrict).toBe h.parseUnit(100).isStrict
expect(result[1].value).toBe h.parseUnit(100).value
expect(result[1].string).toBe h.parseUnit(100).string
expect(result[2]).not.toBeDefined()
it 'should parse strokeDashoffset option', ->
key = 'strokeDashoffset'; value = '100%'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result[0].unit).toBe h.parseUnit(value).unit
expect(result[0].isStrict).toBe h.parseUnit(value).isStrict
expect(result[0].value).toBe h.parseUnit(value).value
expect(result[0].string).toBe h.parseUnit(value).string
expect(result[1]).not.toBeDefined()
it 'should leave the value unattended if not strokeDash.. property', ->
tr._props.x = '100%'
key = 'fill'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key
expect(h.parseUnit).not.toHaveBeenCalledWith()
expect(result).toBe tr._props[key]
describe '_isDelta method ->', ->
it 'should detect if value is not a delta value', ->
byte = new Module radius: 45, stroke: 'deeppink': 'pink'
expect(byte._isDelta(45)) .toBe false
expect(byte._isDelta('45')) .toBe false
expect(byte._isDelta(['45'])).toBe false
expect(byte._isDelta({ unit: 'px', value: 20 })).toBe false
expect(byte._isDelta({ 20: 30 })).toBe true
describe '_parseOption method ->', ->
it 'should parse delta value', ->
md = new Module
spyOn md, '_getDelta'
name = 'x'; delta = { 20: 30 }
md._parseOption name, delta
expect(md._getDelta).toHaveBeenCalledWith name, delta
expect(md._props[name])
.toBe md._parseProperty( name, h.getDeltaEnd( delta ) )
it 'should parse option string', ->
md = new Module
spyOn md, '_getDelta'
spyOn(md, '_parseOptionString').and.callThrough()
name = 'delay'; value = 'stagger(400, 200)'
md._parseOption name, value
expect(md._getDelta).not.toHaveBeenCalledWith name, value
expect(md._parseOptionString).toHaveBeenCalledWith value
expect(md._props[name]).toBe 400
it 'should parse position option', ->
md = new Module
spyOn(md, '_parsePositionOption').and.callThrough()
name = 'x'; value = '20%'
md._parseOption name, value
expect(md._parsePositionOption).toHaveBeenCalledWith name, value
expect(md._props[name]).toBe value
it 'should parse strokeDasharray option', ->
md = new Module
spyOn(md, '_parseStrokeDashOption').and.callThrough()
name = 'strokeDasharray'; value = '200 100% 200'
parsed = md._parseStrokeDashOption name, value
md._parseOption name, value
expect(md._parseStrokeDashOption).toHaveBeenCalledWith name, value
expect(md._props[name]).toEqual parsed
describe '_extendDefaults method ->', ->
it 'should create _props object', ->
spyOn(Module.prototype, '_extendDefaults').and.callThrough()
md = new Module
expect(Module.prototype._extendDefaults).toHaveBeenCalled()
expect(typeof md._props).toBe 'object'
expect(md._props).toBe md._props
it 'should extend defaults object to properties', ->
md = new Module radius: 45, radiusX: 50
expect(md._props.radius) .toBe(45)
expect(md._props.radiusX).toBe(50)
it 'should extend defaults object to properties if 0', ->
md = new Module radius: 0
expect(md._props.radius).toBe(0)
it 'should extend defaults object to properties if object was passed', ->
md = new Module radius: {45: 55}
expect(md._props.radius).toBe(55)
# probably nope
# it 'should ignore properties defined in skipProps object', ->
# md = new Module radius: 45
# md._skipProps = radius: 1
# md._o.radius = 50
# md._extendDefaults()
# expect(md._props.radius).not.toBe(50)
it 'should extend defaults object to properties if array was passed', ->
array = [50, 100]
md = new Module radius: array
spyOn(md, '_assignProp').and.callThrough()
md._extendDefaults()
expect(md._props.radius.join ', ').toBe '50, 100'
expect(md._assignProp).toHaveBeenCalledWith 'radius', array
it 'should extend defaults object to properties if rand was passed', ->
md = new Module radius: 'rand(0, 10)'
spyOn(md, '_assignProp').and.callThrough()
md._extendDefaults()
expect(md._props.radius).toBeDefined()
expect(md._props.radius).toBeGreaterThan -1
expect(md._props.radius).not.toBeGreaterThan 10
expect(md._assignProp).toHaveBeenCalled()
describe 'stagger values', ->
it 'should extend defaults object to properties if stagger was passed', ->
md = new Module radius: 'stagger(200)'
spyOn(md, '_assignProp').and.callThrough()
md._index = 2
md._extendDefaults()
expect(md._props.radius).toBe 400
expect(md._assignProp).toHaveBeenCalledWith 'radius', 400
describe '_setProgress method ->', ->
it 'should set transition progress', ->
byte = new Module radius: {'25.50': -75.50}
byte._setProgress .5
expect(byte._progress).toBe .5
it 'should set value progress', ->
byte = new Module radius: {'25': 75}
byte._setProgress .5
expect(byte._props.radius).toBe 50
it 'should call _calcCurrentProps', ->
byte = new Module radius: {'25': 75}
spyOn byte, '_calcCurrentProps'
byte._setProgress .5, .35
expect(byte._calcCurrentProps).toHaveBeenCalledWith .5, .35
it 'should set color value progress and only int', ->
byte = new Module stroke: {'#000': 'rgb(255,255,255)'}
colorDelta = byte._deltas.stroke
byte._setProgress .5
expect(byte._props.stroke).toBe 'rgba(127,127,127,1)'
it 'should set color value progress for delta starting with 0', ->
byte = new Module stroke: {'#000': 'rgb(0,255,255)'}
colorDelta = byte._deltas.stroke
byte._setProgress .5
expect(byte._props.stroke).toBe 'rgba(0,127,127,1)'
describe '_tuneNewOptions method', ->
it 'should rewrite options from passed object to _o and _props', ->
md = new Module radius: 45, radiusX: 50
md._tuneNewOptions radius: 20
expect(md._o.radius) .toBe(20)
expect(md._props.radius) .toBe(20)
it 'should extend defaults object to properties if 0', ->
md = new Module radius: 40
md._tuneNewOptions radius: 0
expect(md._props.radius).toBe(0)
it 'should call _hide method', ->
md = new Module radius: 45
spyOn(md, '_hide').and.callThrough()
md._tuneNewOptions radius: 20
expect(md._hide).toHaveBeenCalled()
# probably nope
# it 'should ignore properties defined in skipProps object', ->
# md = new Module radius: 45
# md._skipProps = radius: 1
# md._tuneNewOptions radius: 20
# expect(md._props.radius).toBe(45)
it 'should extend defaults object to properties if array was passed', ->
md = new Module radius: 50
md._tuneNewOptions 'radius': [50, 100]
expect(md._props.radius.join ', ').toBe '50, 100'
it 'should extend defaults object to properties if rand was passed', ->
md = new Module radius: 20
md._tuneNewOptions 'radius': 'rand(0, 10)'
expect(md._props.radius).toBeDefined()
expect(md._props.radius).toBeGreaterThan -1
expect(md._props.radius).not.toBeGreaterThan 10
it 'should extend defaults object to properties if stagger was passed', ->
md = new Module radius: 20
md._index = 2
md._tuneNewOptions radius: 'stagger(200)'
expect(md._props.radius).toBe 400
describe '_getDelta method ->', ->
it 'should warn if delta is top or left', ->
md = new Module
spyOn h, 'warn'
md._getDelta 'left', { '50%': 0 }
expect(h.warn).toHaveBeenCalled()
it 'should call h.parseDelta', ->
md = new Module
md._index = 3
spyOn(h, 'parseDelta').and.callThrough()
key = 'left'; delta = { '50%': 0 }
md._getDelta key, delta
expect(h.parseDelta).toHaveBeenCalledWith key, delta, md._index
it 'should set end value to props', ->
md = new Module
key = 'left'; delta = { '50%': 0 }
md._getDelta key, delta
expect(md._props.left).toBe 0
describe '_parsePreArrayProperty method ->', ->
it 'should call _parseOptionString method', ->
md = new Module
key = 'left'; value = '50%'
spyOn(md, '_parseOptionString').and.callThrough()
md._parsePreArrayProperty( key, value )
expect(md._parseOptionString).toHaveBeenCalledWith value
it 'should pass results of the prev call to _parsePositionOption method', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parsePositionOption').and.callThrough()
result = md._parsePreArrayProperty( key, value )
expect(md._parsePositionOption)
.toHaveBeenCalledWith key, md._parseOptionString(value)
value = md._parseOptionString(value)
value = md._parsePositionOption(key, value)
expect(result).toBe value
describe '_parseProperty method ->', ->
it 'should call h.parseEl method is name is `parent`', ->
md = new Module
key = 'parent'; value = 'body'
spyOn(h, 'parseEl').and.callThrough()
result = md._parseProperty( key, value )
expect(h.parseEl).toHaveBeenCalledWith value
expect(result).toBe document.body
it 'should call _parsePreArrayProperty method', ->
md = new Module
key = 'left'; value = '50%'
spyOn(md, '_parsePreArrayProperty').and.callThrough()
md._parseProperty( key, value )
expect(md._parsePreArrayProperty).toHaveBeenCalledWith key, value
it 'should pass results of prev call to _parseStrokeDashOption method', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parseStrokeDashOption').and.callThrough()
md._parseProperty( key, value )
value = md._parsePreArrayProperty(key, value)
expect(md._parseStrokeDashOption)
.toHaveBeenCalledWith key, value
it 'should return result', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parseStrokeDashOption').and.callThrough()
result = md._parseProperty( key, value )
value = md._parsePreArrayProperty(key, value)
value = md._parseStrokeDashOption(key, value)
expect(result).toBe value
describe '_parseDeltaValues method ->', ->
it 'should parse delta values', ->
md = new Module
delta = { 'stagger(100, 0)': 200 }
deltaResult = md._parseDeltaValues( 'left', delta )
expect(deltaResult).toEqual { '100px': '200px' }
it 'should not arr values parse delta values', ->
md = new Module
delta = { 'stagger(100, 0)': 200 }
deltaResult = md._parseDeltaValues( 'strokeDasharray', delta )
expect(deltaResult).toEqual { '100': 200 }
it 'should create new delta object', ->
md = new Module
delta = { 2: 1 }
deltaResult = md._parseDeltaValues( 'opacity', delta )
expect(deltaResult).toEqual { 2: 1 }
expect(deltaResult).not.toBe delta
describe '_preparsePropValue ->', ->
it 'should parse non ∆ values', ->
md = new Module
spyOn(md, '_parsePreArrayProperty').and.callThrough()
spyOn(md, '_parseDeltaValues').and.callThrough()
result = md._preparsePropValue('left', 20)
expect(md._parsePreArrayProperty).toHaveBeenCalledWith 'left', 20
expect(md._parseDeltaValues).not.toHaveBeenCalled()
expect(result).toBe '20px'
it 'should parse ∆ values', ->
md = new Module
spyOn(md, '_parseDeltaValues').and.callThrough()
key = 'left'; delta = { 20: 100 }
result = md._preparsePropValue(key, delta)
expect(md._parseDeltaValues).toHaveBeenCalledWith key, delta
expect(result['20px']).toBe '100px'
describe '_calcCurrentProps method', ->
it 'should calc color with alpha', ->
md = new Module
md._deltas = {
fill: h.parseDelta( 'fill', { 'rgba(0,0,0,0)' : 'rgba(0,0,0,1)' }, 0 )
}
md._calcCurrentProps .5, .5
expect( md._props.fill ).toBe 'rgba(0,0,0,0.5)'
it 'clean the _defaults up', ->
Module::_declareDefaults = oldFun
| 71273 | Module = mojs.Module
h = mojs.h
oldFun = Module::_declareDefaults
describe 'module class ->', ->
it 'set the _defaults up', ->
defaults = {
stroke: 'transparent',
strokeOpacity: 1,
strokeLinecap: '',
strokeWidth: 2,
strokeDasharray: 0,
strokeDashoffset: 0,
fill: 'deeppink',
fillOpacity: 1,
left: 0,
top: 0,
x: 0,
y: 0,
rx: 0,
ry: 0,
angle: 0,
scale: 1,
opacity: 1,
points: 3,
radius: { 0: 50 },
radiusX: null,
radiusY: null,
isShowStart: false,
isSoftHide: true,
isShowEnd: false,
size: null,
sizeGap: 0,
callbacksContext: null
}
Module::_declareDefaults = -> this._defaults = defaults
describe 'init ->', ->
it 'should save options to _o', ->
options = {}
md = new Module options
expect(md._o).toBe options
it 'should create _arrayPropertyMap', ->
md = new Module
expect(md._arrayPropertyMap['strokeDasharray']).toBe 1
expect(md._arrayPropertyMap['strokeDashoffset']).toBe 1
expect(md._arrayPropertyMap['origin']).toBe 1
it 'should create _arrayPropertyMap', ->
md = new Module
expect(md._skipPropsDelta.callbacksContext).toBe 1
expect(md._skipPropsDelta.timeline).toBe 1
expect(md._skipPropsDelta.prevChainModule).toBe 1
it 'should fallback to empty object for _o', ->
md = new Module
expect(Object.keys(md._o).length).toBe 0
expect(typeof md._o).toBe 'object'
# not null
expect(md._o).toBe md._o
it 'should call _declareDefaults method', ->
spyOn(Module.prototype, '_declareDefaults').and.callThrough()
md = new Module
expect(Module.prototype._declareDefaults).toHaveBeenCalled()
it 'should call _extendDefaults method', ->
spyOn(Module.prototype, '_extendDefaults').and.callThrough()
md = new Module
expect(Module.prototype._extendDefaults).toHaveBeenCalled()
it 'should call _vars method', ->
spyOn(Module.prototype, '_vars').and.callThrough()
md = new Module
expect(Module.prototype._vars).toHaveBeenCalled()
it 'should call _render method', ->
spyOn(Module.prototype, '_render').and.callThrough()
md = new Module
expect(Module.prototype._render).toHaveBeenCalled()
it 'should create _index property', ->
index = 5
md = new Module index: index
expect(md._index).toBe index
it 'should fallback to 0 for _index property', ->
md = new Module
expect(md._index).toBe 0
describe '_declareDefaults method ->', ->
it 'should create _defaults object', ->
spyOn(Module.prototype, '_declareDefaults').and.callThrough()
md = new Module
expect(Module.prototype._declareDefaults).toHaveBeenCalled()
expect(typeof md._defaults).toBe 'object'
# not null
expect(md._defaults).toBe md._defaults
describe '_vars method ->', ->
it 'should set _progress property to 0', ->
md = new Module
expect(md._progress).toBe 0
it 'should create _strokeDasharrayBuffer array', ->
md = new Module
expect(md._strokeDasharrayBuffer.length).toBe 0
expect(h.isArray(md._strokeDasharrayBuffer)).toBe true
describe '_assignProp method ->', ->
it 'should set property on _props object', ->
value = 2
md = new Module
md._assignProp 'a', value
expect(md._props.a).toBe value
describe '_setProp method ->', ->
it 'should set new tween options', ->
t = new Module duration: 100, delay: 0
t._setProp duration: 1000, delay: 200
expect(t._props.duration).toBe 1000
expect(t._props.delay).toBe 200
it 'should work with arguments', ->
t = new Module duration: 100
t._setProp 'duration', 1000
expect(t._props.duration).toBe 1000
describe '_hide method ->' , ->
it 'should set `display` of `el` to `none`', ->
byte = new Module isSoftHide: false
byte.el = document.createElement 'div'
byte.el.style[ 'display' ] = 'block'
byte._hide()
expect( byte.el.style[ 'display' ] ).toBe 'none'
it 'should set `_isShown` to false', ->
byte = new Module isSoftHide: false
byte.el = document.createElement 'div'
byte._isShown = true
byte._hide()
expect( byte._isShown ).toBe false
describe 'isSoftHide option ->', ->
# nope
# it 'should set `opacity` of `el` to `0`', ->
# byte = new Module radius: 25, isSoftHide: true
# byte.el = document.createElement 'div'
# byte.el.style[ 'opacity' ] = '.5'
# byte._hide()
# expect( byte.el.style[ 'opacity' ] ).toBe '0'
it 'should set scale to 0', ->
byte = new Module
radius: 25,
isSoftHide: true
byte.el = document.createElement 'div'
byte._hide()
style = byte.el.style
tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ]
expect( tr ).toBe 'scale(0)'
describe '_show method ->' , ->
it 'should set `display` of `el` to `block`', ->
byte = new Module radius: 25, isSoftHide: false
byte.el = document.createElement 'div'
byte.el.style[ 'display' ] = 'none'
byte._show()
expect( byte.el.style[ 'display' ] ).toBe 'block'
it 'should set `_isShown` to true', ->
byte = new Module radius: 25, isSoftHide: false
byte._isShown = true
byte._show()
expect( byte._isShown ).toBe true
describe 'isSoftHide option ->', ->
# nope
# it 'should set `opacity` of `el` to `_props.opacity`', ->
# byte = new Module radius: 25, isSoftHide: true, opacity: .2
# byte.el = document.createElement 'div'
# byte.el.style[ 'opacity' ] = '0'
# byte._show()
# expect( byte.el.style[ 'opacity' ] ).toBe "#{byte._props.opacity}"
it 'should set `transform` to normal', ->
byte = new Module radius: 25, isSoftHide: true, opacity: .2
byte.el = document.createElement 'div'
byte.el.style[ 'opacity' ] = '0'
byte.el.style[ 'transform' ] = 'none'
spyOn byte, '_showByTransform'
byte._show()
# style = byte.el.style
# tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ]
expect( byte._showByTransform ).toHaveBeenCalled()
# old
# describe '_show method ->', ->
# it 'should set display: block to el', ->
# md = new Module
# md.el = document.createElement 'div'
# md._show()
# expect(md.el.style.display).toBe 'block'
# expect(md._isShown).toBe true
# it 'should return if isShow is already true', ->
# md = new Module
# md.el = document.createElement 'div'
# md._show()
# md.el.style.display = 'inline'
# md._show()
# expect(md.el.style.display).toBe 'inline'
# it 'not to throw', ->
# byte = new Module radius: {'25': 75}
# expect(-> byte._show()).not.toThrow()
# old
# describe '_hide method ->', ->
# it 'should set display: block to el', ->
# md = new Module
# md.el = document.createElement 'div'
# md._hide()
# expect(md.el.style.display).toBe 'none'
# expect(md._isShown).toBe false
# it 'not to throw', ->
# byte = new Module radius: {'25': 75}
# expect(-> byte._hide()).not.toThrow()
describe '_parseOptionString method ->', ->
tr = new Module
it 'should parse stagger values', ->
string = 'stagger(200)'
spyOn(h, 'parseStagger').and.callThrough()
result = tr._parseOptionString string
expect(h.parseStagger).toHaveBeenCalledWith string, 0
expect(result).toBe h.parseStagger(string, 0)
it 'should parse rand values', ->
string = 'rand(0,1)'
spyOn(h, 'parseRand').and.callThrough()
result = tr._parseOptionString string
expect(h.parseRand).toHaveBeenCalledWith string
describe '_parsePositionOption method ->', ->
tr = new Module
it 'should parse position option', ->
key = 'x'; value = '100%'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parsePositionOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result).toBe h.parseUnit(value).string
it 'should leave the value unattended if not pos property', ->
tr._props.x = '100%'
key = 'fill'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parsePositionOption key
expect(h.parseUnit).not.toHaveBeenCalledWith()
expect(result).toBe tr._props[key]
describe '_parseStrokeDashOption method ->', ->
tr = new Module
it 'should parse strokeDash option', ->
key = 'strokeDasharray'; value = 200
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result[0].unit).toBe h.parseUnit(value).unit
expect(result[0].isStrict).toBe h.parseUnit(value).isStrict
expect(result[0].value).toBe h.parseUnit(value).value
expect(result[0].string).toBe h.parseUnit(value).string
expect(result[1]).not.toBeDefined()
it 'should parse strokeDash option string', ->
key = 'strokeDasharray'; value = '200 100'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith '200'
expect(h.parseUnit).toHaveBeenCalledWith '100'
expect(result[0].unit).toBe h.parseUnit(200).unit
expect(result[0].isStrict).toBe h.parseUnit(200).isStrict
expect(result[0].value).toBe h.parseUnit(200).value
expect(result[0].string).toBe h.parseUnit(200).string
expect(result[1].unit).toBe h.parseUnit(100).unit
expect(result[1].isStrict).toBe h.parseUnit(100).isStrict
expect(result[1].value).toBe h.parseUnit(100).value
expect(result[1].string).toBe h.parseUnit(100).string
expect(result[2]).not.toBeDefined()
it 'should parse strokeDashoffset option', ->
key = 'strokeDashoffset'; value = '100%'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result[0].unit).toBe h.parseUnit(value).unit
expect(result[0].isStrict).toBe h.parseUnit(value).isStrict
expect(result[0].value).toBe h.parseUnit(value).value
expect(result[0].string).toBe h.parseUnit(value).string
expect(result[1]).not.toBeDefined()
it 'should leave the value unattended if not strokeDash.. property', ->
tr._props.x = '100%'
key = 'fill'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key
expect(h.parseUnit).not.toHaveBeenCalledWith()
expect(result).toBe tr._props[key]
describe '_isDelta method ->', ->
it 'should detect if value is not a delta value', ->
byte = new Module radius: 45, stroke: 'deeppink': 'pink'
expect(byte._isDelta(45)) .toBe false
expect(byte._isDelta('45')) .toBe false
expect(byte._isDelta(['45'])).toBe false
expect(byte._isDelta({ unit: 'px', value: 20 })).toBe false
expect(byte._isDelta({ 20: 30 })).toBe true
describe '_parseOption method ->', ->
it 'should parse delta value', ->
md = new Module
spyOn md, '_getDelta'
name = 'x'; delta = { 20: 30 }
md._parseOption name, delta
expect(md._getDelta).toHaveBeenCalledWith name, delta
expect(md._props[name])
.toBe md._parseProperty( name, h.getDeltaEnd( delta ) )
it 'should parse option string', ->
md = new Module
spyOn md, '_getDelta'
spyOn(md, '_parseOptionString').and.callThrough()
name = 'delay'; value = 'stagger(400, 200)'
md._parseOption name, value
expect(md._getDelta).not.toHaveBeenCalledWith name, value
expect(md._parseOptionString).toHaveBeenCalledWith value
expect(md._props[name]).toBe 400
it 'should parse position option', ->
md = new Module
spyOn(md, '_parsePositionOption').and.callThrough()
name = 'x'; value = '20%'
md._parseOption name, value
expect(md._parsePositionOption).toHaveBeenCalledWith name, value
expect(md._props[name]).toBe value
it 'should parse strokeDasharray option', ->
md = new Module
spyOn(md, '_parseStrokeDashOption').and.callThrough()
name = 'strokeDasharray'; value = '200 100% 200'
parsed = md._parseStrokeDashOption name, value
md._parseOption name, value
expect(md._parseStrokeDashOption).toHaveBeenCalledWith name, value
expect(md._props[name]).toEqual parsed
describe '_extendDefaults method ->', ->
it 'should create _props object', ->
spyOn(Module.prototype, '_extendDefaults').and.callThrough()
md = new Module
expect(Module.prototype._extendDefaults).toHaveBeenCalled()
expect(typeof md._props).toBe 'object'
expect(md._props).toBe md._props
it 'should extend defaults object to properties', ->
md = new Module radius: 45, radiusX: 50
expect(md._props.radius) .toBe(45)
expect(md._props.radiusX).toBe(50)
it 'should extend defaults object to properties if 0', ->
md = new Module radius: 0
expect(md._props.radius).toBe(0)
it 'should extend defaults object to properties if object was passed', ->
md = new Module radius: {45: 55}
expect(md._props.radius).toBe(55)
# probably nope
# it 'should ignore properties defined in skipProps object', ->
# md = new Module radius: 45
# md._skipProps = radius: 1
# md._o.radius = 50
# md._extendDefaults()
# expect(md._props.radius).not.toBe(50)
it 'should extend defaults object to properties if array was passed', ->
array = [50, 100]
md = new Module radius: array
spyOn(md, '_assignProp').and.callThrough()
md._extendDefaults()
expect(md._props.radius.join ', ').toBe '50, 100'
expect(md._assignProp).toHaveBeenCalledWith 'radius', array
it 'should extend defaults object to properties if rand was passed', ->
md = new Module radius: 'rand(0, 10)'
spyOn(md, '_assignProp').and.callThrough()
md._extendDefaults()
expect(md._props.radius).toBeDefined()
expect(md._props.radius).toBeGreaterThan -1
expect(md._props.radius).not.toBeGreaterThan 10
expect(md._assignProp).toHaveBeenCalled()
describe 'stagger values', ->
it 'should extend defaults object to properties if stagger was passed', ->
md = new Module radius: 'stagger(200)'
spyOn(md, '_assignProp').and.callThrough()
md._index = 2
md._extendDefaults()
expect(md._props.radius).toBe 400
expect(md._assignProp).toHaveBeenCalledWith 'radius', 400
describe '_setProgress method ->', ->
it 'should set transition progress', ->
byte = new Module radius: {'25.50': -75.50}
byte._setProgress .5
expect(byte._progress).toBe .5
it 'should set value progress', ->
byte = new Module radius: {'25': 75}
byte._setProgress .5
expect(byte._props.radius).toBe 50
it 'should call _calcCurrentProps', ->
byte = new Module radius: {'25': 75}
spyOn byte, '_calcCurrentProps'
byte._setProgress .5, .35
expect(byte._calcCurrentProps).toHaveBeenCalledWith .5, .35
it 'should set color value progress and only int', ->
byte = new Module stroke: {'#000': 'rgb(255,255,255)'}
colorDelta = byte._deltas.stroke
byte._setProgress .5
expect(byte._props.stroke).toBe 'rgba(127,127,127,1)'
it 'should set color value progress for delta starting with 0', ->
byte = new Module stroke: {'#000': 'rgb(0,255,255)'}
colorDelta = byte._deltas.stroke
byte._setProgress .5
expect(byte._props.stroke).toBe 'rgba(0,127,127,1)'
describe '_tuneNewOptions method', ->
it 'should rewrite options from passed object to _o and _props', ->
md = new Module radius: 45, radiusX: 50
md._tuneNewOptions radius: 20
expect(md._o.radius) .toBe(20)
expect(md._props.radius) .toBe(20)
it 'should extend defaults object to properties if 0', ->
md = new Module radius: 40
md._tuneNewOptions radius: 0
expect(md._props.radius).toBe(0)
it 'should call _hide method', ->
md = new Module radius: 45
spyOn(md, '_hide').and.callThrough()
md._tuneNewOptions radius: 20
expect(md._hide).toHaveBeenCalled()
# probably nope
# it 'should ignore properties defined in skipProps object', ->
# md = new Module radius: 45
# md._skipProps = radius: 1
# md._tuneNewOptions radius: 20
# expect(md._props.radius).toBe(45)
it 'should extend defaults object to properties if array was passed', ->
md = new Module radius: 50
md._tuneNewOptions 'radius': [50, 100]
expect(md._props.radius.join ', ').toBe '50, 100'
it 'should extend defaults object to properties if rand was passed', ->
md = new Module radius: 20
md._tuneNewOptions 'radius': 'rand(0, 10)'
expect(md._props.radius).toBeDefined()
expect(md._props.radius).toBeGreaterThan -1
expect(md._props.radius).not.toBeGreaterThan 10
it 'should extend defaults object to properties if stagger was passed', ->
md = new Module radius: 20
md._index = 2
md._tuneNewOptions radius: 'stagger(200)'
expect(md._props.radius).toBe 400
describe '_getDelta method ->', ->
it 'should warn if delta is top or left', ->
md = new Module
spyOn h, 'warn'
md._getDelta 'left', { '50%': 0 }
expect(h.warn).toHaveBeenCalled()
it 'should call h.parseDelta', ->
md = new Module
md._index = 3
spyOn(h, 'parseDelta').and.callThrough()
key = '<KEY>'; delta = { '50%': 0 }
md._getDelta key, delta
expect(h.parseDelta).toHaveBeenCalledWith key, delta, md._index
it 'should set end value to props', ->
md = new Module
key = '<KEY>'; delta = { '50%': 0 }
md._getDelta key, delta
expect(md._props.left).toBe 0
describe '_parsePreArrayProperty method ->', ->
it 'should call _parseOptionString method', ->
md = new Module
key = 'left'; value = '50%'
spyOn(md, '_parseOptionString').and.callThrough()
md._parsePreArrayProperty( key, value )
expect(md._parseOptionString).toHaveBeenCalledWith value
it 'should pass results of the prev call to _parsePositionOption method', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parsePositionOption').and.callThrough()
result = md._parsePreArrayProperty( key, value )
expect(md._parsePositionOption)
.toHaveBeenCalledWith key, md._parseOptionString(value)
value = md._parseOptionString(value)
value = md._parsePositionOption(key, value)
expect(result).toBe value
describe '_parseProperty method ->', ->
it 'should call h.parseEl method is name is `parent`', ->
md = new Module
key = 'parent'; value = 'body'
spyOn(h, 'parseEl').and.callThrough()
result = md._parseProperty( key, value )
expect(h.parseEl).toHaveBeenCalledWith value
expect(result).toBe document.body
it 'should call _parsePreArrayProperty method', ->
md = new Module
key = 'left'; value = '50%'
spyOn(md, '_parsePreArrayProperty').and.callThrough()
md._parseProperty( key, value )
expect(md._parsePreArrayProperty).toHaveBeenCalledWith key, value
it 'should pass results of prev call to _parseStrokeDashOption method', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parseStrokeDashOption').and.callThrough()
md._parseProperty( key, value )
value = md._parsePreArrayProperty(key, value)
expect(md._parseStrokeDashOption)
.toHaveBeenCalledWith key, value
it 'should return result', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parseStrokeDashOption').and.callThrough()
result = md._parseProperty( key, value )
value = md._parsePreArrayProperty(key, value)
value = md._parseStrokeDashOption(key, value)
expect(result).toBe value
describe '_parseDeltaValues method ->', ->
it 'should parse delta values', ->
md = new Module
delta = { 'stagger(100, 0)': 200 }
deltaResult = md._parseDeltaValues( 'left', delta )
expect(deltaResult).toEqual { '100px': '200px' }
it 'should not arr values parse delta values', ->
md = new Module
delta = { 'stagger(100, 0)': 200 }
deltaResult = md._parseDeltaValues( 'strokeDasharray', delta )
expect(deltaResult).toEqual { '100': 200 }
it 'should create new delta object', ->
md = new Module
delta = { 2: 1 }
deltaResult = md._parseDeltaValues( 'opacity', delta )
expect(deltaResult).toEqual { 2: 1 }
expect(deltaResult).not.toBe delta
describe '_preparsePropValue ->', ->
it 'should parse non ∆ values', ->
md = new Module
spyOn(md, '_parsePreArrayProperty').and.callThrough()
spyOn(md, '_parseDeltaValues').and.callThrough()
result = md._preparsePropValue('left', 20)
expect(md._parsePreArrayProperty).toHaveBeenCalledWith 'left', 20
expect(md._parseDeltaValues).not.toHaveBeenCalled()
expect(result).toBe '20px'
it 'should parse ∆ values', ->
md = new Module
spyOn(md, '_parseDeltaValues').and.callThrough()
key = '<KEY>'; delta = { 20: 100 }
result = md._preparsePropValue(key, delta)
expect(md._parseDeltaValues).toHaveBeenCalledWith key, delta
expect(result['20px']).toBe '100px'
describe '_calcCurrentProps method', ->
it 'should calc color with alpha', ->
md = new Module
md._deltas = {
fill: h.parseDelta( 'fill', { 'rgba(0,0,0,0)' : 'rgba(0,0,0,1)' }, 0 )
}
md._calcCurrentProps .5, .5
expect( md._props.fill ).toBe 'rgba(0,0,0,0.5)'
it 'clean the _defaults up', ->
Module::_declareDefaults = oldFun
| true | Module = mojs.Module
h = mojs.h
oldFun = Module::_declareDefaults
describe 'module class ->', ->
it 'set the _defaults up', ->
defaults = {
stroke: 'transparent',
strokeOpacity: 1,
strokeLinecap: '',
strokeWidth: 2,
strokeDasharray: 0,
strokeDashoffset: 0,
fill: 'deeppink',
fillOpacity: 1,
left: 0,
top: 0,
x: 0,
y: 0,
rx: 0,
ry: 0,
angle: 0,
scale: 1,
opacity: 1,
points: 3,
radius: { 0: 50 },
radiusX: null,
radiusY: null,
isShowStart: false,
isSoftHide: true,
isShowEnd: false,
size: null,
sizeGap: 0,
callbacksContext: null
}
Module::_declareDefaults = -> this._defaults = defaults
describe 'init ->', ->
it 'should save options to _o', ->
options = {}
md = new Module options
expect(md._o).toBe options
it 'should create _arrayPropertyMap', ->
md = new Module
expect(md._arrayPropertyMap['strokeDasharray']).toBe 1
expect(md._arrayPropertyMap['strokeDashoffset']).toBe 1
expect(md._arrayPropertyMap['origin']).toBe 1
it 'should create _arrayPropertyMap', ->
md = new Module
expect(md._skipPropsDelta.callbacksContext).toBe 1
expect(md._skipPropsDelta.timeline).toBe 1
expect(md._skipPropsDelta.prevChainModule).toBe 1
it 'should fallback to empty object for _o', ->
md = new Module
expect(Object.keys(md._o).length).toBe 0
expect(typeof md._o).toBe 'object'
# not null
expect(md._o).toBe md._o
it 'should call _declareDefaults method', ->
spyOn(Module.prototype, '_declareDefaults').and.callThrough()
md = new Module
expect(Module.prototype._declareDefaults).toHaveBeenCalled()
it 'should call _extendDefaults method', ->
spyOn(Module.prototype, '_extendDefaults').and.callThrough()
md = new Module
expect(Module.prototype._extendDefaults).toHaveBeenCalled()
it 'should call _vars method', ->
spyOn(Module.prototype, '_vars').and.callThrough()
md = new Module
expect(Module.prototype._vars).toHaveBeenCalled()
it 'should call _render method', ->
spyOn(Module.prototype, '_render').and.callThrough()
md = new Module
expect(Module.prototype._render).toHaveBeenCalled()
it 'should create _index property', ->
index = 5
md = new Module index: index
expect(md._index).toBe index
it 'should fallback to 0 for _index property', ->
md = new Module
expect(md._index).toBe 0
describe '_declareDefaults method ->', ->
it 'should create _defaults object', ->
spyOn(Module.prototype, '_declareDefaults').and.callThrough()
md = new Module
expect(Module.prototype._declareDefaults).toHaveBeenCalled()
expect(typeof md._defaults).toBe 'object'
# not null
expect(md._defaults).toBe md._defaults
describe '_vars method ->', ->
it 'should set _progress property to 0', ->
md = new Module
expect(md._progress).toBe 0
it 'should create _strokeDasharrayBuffer array', ->
md = new Module
expect(md._strokeDasharrayBuffer.length).toBe 0
expect(h.isArray(md._strokeDasharrayBuffer)).toBe true
describe '_assignProp method ->', ->
it 'should set property on _props object', ->
value = 2
md = new Module
md._assignProp 'a', value
expect(md._props.a).toBe value
describe '_setProp method ->', ->
it 'should set new tween options', ->
t = new Module duration: 100, delay: 0
t._setProp duration: 1000, delay: 200
expect(t._props.duration).toBe 1000
expect(t._props.delay).toBe 200
it 'should work with arguments', ->
t = new Module duration: 100
t._setProp 'duration', 1000
expect(t._props.duration).toBe 1000
describe '_hide method ->' , ->
it 'should set `display` of `el` to `none`', ->
byte = new Module isSoftHide: false
byte.el = document.createElement 'div'
byte.el.style[ 'display' ] = 'block'
byte._hide()
expect( byte.el.style[ 'display' ] ).toBe 'none'
it 'should set `_isShown` to false', ->
byte = new Module isSoftHide: false
byte.el = document.createElement 'div'
byte._isShown = true
byte._hide()
expect( byte._isShown ).toBe false
describe 'isSoftHide option ->', ->
# nope
# it 'should set `opacity` of `el` to `0`', ->
# byte = new Module radius: 25, isSoftHide: true
# byte.el = document.createElement 'div'
# byte.el.style[ 'opacity' ] = '.5'
# byte._hide()
# expect( byte.el.style[ 'opacity' ] ).toBe '0'
it 'should set scale to 0', ->
byte = new Module
radius: 25,
isSoftHide: true
byte.el = document.createElement 'div'
byte._hide()
style = byte.el.style
tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ]
expect( tr ).toBe 'scale(0)'
describe '_show method ->' , ->
it 'should set `display` of `el` to `block`', ->
byte = new Module radius: 25, isSoftHide: false
byte.el = document.createElement 'div'
byte.el.style[ 'display' ] = 'none'
byte._show()
expect( byte.el.style[ 'display' ] ).toBe 'block'
it 'should set `_isShown` to true', ->
byte = new Module radius: 25, isSoftHide: false
byte._isShown = true
byte._show()
expect( byte._isShown ).toBe true
describe 'isSoftHide option ->', ->
# nope
# it 'should set `opacity` of `el` to `_props.opacity`', ->
# byte = new Module radius: 25, isSoftHide: true, opacity: .2
# byte.el = document.createElement 'div'
# byte.el.style[ 'opacity' ] = '0'
# byte._show()
# expect( byte.el.style[ 'opacity' ] ).toBe "#{byte._props.opacity}"
it 'should set `transform` to normal', ->
byte = new Module radius: 25, isSoftHide: true, opacity: .2
byte.el = document.createElement 'div'
byte.el.style[ 'opacity' ] = '0'
byte.el.style[ 'transform' ] = 'none'
spyOn byte, '_showByTransform'
byte._show()
# style = byte.el.style
# tr = style[ 'transform' ] || style[ "#{h.prefix.css}transform" ]
expect( byte._showByTransform ).toHaveBeenCalled()
# old
# describe '_show method ->', ->
# it 'should set display: block to el', ->
# md = new Module
# md.el = document.createElement 'div'
# md._show()
# expect(md.el.style.display).toBe 'block'
# expect(md._isShown).toBe true
# it 'should return if isShow is already true', ->
# md = new Module
# md.el = document.createElement 'div'
# md._show()
# md.el.style.display = 'inline'
# md._show()
# expect(md.el.style.display).toBe 'inline'
# it 'not to throw', ->
# byte = new Module radius: {'25': 75}
# expect(-> byte._show()).not.toThrow()
# old
# describe '_hide method ->', ->
# it 'should set display: block to el', ->
# md = new Module
# md.el = document.createElement 'div'
# md._hide()
# expect(md.el.style.display).toBe 'none'
# expect(md._isShown).toBe false
# it 'not to throw', ->
# byte = new Module radius: {'25': 75}
# expect(-> byte._hide()).not.toThrow()
describe '_parseOptionString method ->', ->
tr = new Module
it 'should parse stagger values', ->
string = 'stagger(200)'
spyOn(h, 'parseStagger').and.callThrough()
result = tr._parseOptionString string
expect(h.parseStagger).toHaveBeenCalledWith string, 0
expect(result).toBe h.parseStagger(string, 0)
it 'should parse rand values', ->
string = 'rand(0,1)'
spyOn(h, 'parseRand').and.callThrough()
result = tr._parseOptionString string
expect(h.parseRand).toHaveBeenCalledWith string
describe '_parsePositionOption method ->', ->
tr = new Module
it 'should parse position option', ->
key = 'x'; value = '100%'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parsePositionOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result).toBe h.parseUnit(value).string
it 'should leave the value unattended if not pos property', ->
tr._props.x = '100%'
key = 'fill'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parsePositionOption key
expect(h.parseUnit).not.toHaveBeenCalledWith()
expect(result).toBe tr._props[key]
describe '_parseStrokeDashOption method ->', ->
tr = new Module
it 'should parse strokeDash option', ->
key = 'strokeDasharray'; value = 200
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result[0].unit).toBe h.parseUnit(value).unit
expect(result[0].isStrict).toBe h.parseUnit(value).isStrict
expect(result[0].value).toBe h.parseUnit(value).value
expect(result[0].string).toBe h.parseUnit(value).string
expect(result[1]).not.toBeDefined()
it 'should parse strokeDash option string', ->
key = 'strokeDasharray'; value = '200 100'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith '200'
expect(h.parseUnit).toHaveBeenCalledWith '100'
expect(result[0].unit).toBe h.parseUnit(200).unit
expect(result[0].isStrict).toBe h.parseUnit(200).isStrict
expect(result[0].value).toBe h.parseUnit(200).value
expect(result[0].string).toBe h.parseUnit(200).string
expect(result[1].unit).toBe h.parseUnit(100).unit
expect(result[1].isStrict).toBe h.parseUnit(100).isStrict
expect(result[1].value).toBe h.parseUnit(100).value
expect(result[1].string).toBe h.parseUnit(100).string
expect(result[2]).not.toBeDefined()
it 'should parse strokeDashoffset option', ->
key = 'strokeDashoffset'; value = '100%'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key, value
expect(h.parseUnit).toHaveBeenCalledWith value
expect(result[0].unit).toBe h.parseUnit(value).unit
expect(result[0].isStrict).toBe h.parseUnit(value).isStrict
expect(result[0].value).toBe h.parseUnit(value).value
expect(result[0].string).toBe h.parseUnit(value).string
expect(result[1]).not.toBeDefined()
it 'should leave the value unattended if not strokeDash.. property', ->
tr._props.x = '100%'
key = 'fill'
spyOn(h, 'parseUnit').and.callThrough()
result = tr._parseStrokeDashOption key
expect(h.parseUnit).not.toHaveBeenCalledWith()
expect(result).toBe tr._props[key]
describe '_isDelta method ->', ->
it 'should detect if value is not a delta value', ->
byte = new Module radius: 45, stroke: 'deeppink': 'pink'
expect(byte._isDelta(45)) .toBe false
expect(byte._isDelta('45')) .toBe false
expect(byte._isDelta(['45'])).toBe false
expect(byte._isDelta({ unit: 'px', value: 20 })).toBe false
expect(byte._isDelta({ 20: 30 })).toBe true
describe '_parseOption method ->', ->
it 'should parse delta value', ->
md = new Module
spyOn md, '_getDelta'
name = 'x'; delta = { 20: 30 }
md._parseOption name, delta
expect(md._getDelta).toHaveBeenCalledWith name, delta
expect(md._props[name])
.toBe md._parseProperty( name, h.getDeltaEnd( delta ) )
it 'should parse option string', ->
md = new Module
spyOn md, '_getDelta'
spyOn(md, '_parseOptionString').and.callThrough()
name = 'delay'; value = 'stagger(400, 200)'
md._parseOption name, value
expect(md._getDelta).not.toHaveBeenCalledWith name, value
expect(md._parseOptionString).toHaveBeenCalledWith value
expect(md._props[name]).toBe 400
it 'should parse position option', ->
md = new Module
spyOn(md, '_parsePositionOption').and.callThrough()
name = 'x'; value = '20%'
md._parseOption name, value
expect(md._parsePositionOption).toHaveBeenCalledWith name, value
expect(md._props[name]).toBe value
it 'should parse strokeDasharray option', ->
md = new Module
spyOn(md, '_parseStrokeDashOption').and.callThrough()
name = 'strokeDasharray'; value = '200 100% 200'
parsed = md._parseStrokeDashOption name, value
md._parseOption name, value
expect(md._parseStrokeDashOption).toHaveBeenCalledWith name, value
expect(md._props[name]).toEqual parsed
describe '_extendDefaults method ->', ->
it 'should create _props object', ->
spyOn(Module.prototype, '_extendDefaults').and.callThrough()
md = new Module
expect(Module.prototype._extendDefaults).toHaveBeenCalled()
expect(typeof md._props).toBe 'object'
expect(md._props).toBe md._props
it 'should extend defaults object to properties', ->
md = new Module radius: 45, radiusX: 50
expect(md._props.radius) .toBe(45)
expect(md._props.radiusX).toBe(50)
it 'should extend defaults object to properties if 0', ->
md = new Module radius: 0
expect(md._props.radius).toBe(0)
it 'should extend defaults object to properties if object was passed', ->
md = new Module radius: {45: 55}
expect(md._props.radius).toBe(55)
# probably nope
# it 'should ignore properties defined in skipProps object', ->
# md = new Module radius: 45
# md._skipProps = radius: 1
# md._o.radius = 50
# md._extendDefaults()
# expect(md._props.radius).not.toBe(50)
it 'should extend defaults object to properties if array was passed', ->
array = [50, 100]
md = new Module radius: array
spyOn(md, '_assignProp').and.callThrough()
md._extendDefaults()
expect(md._props.radius.join ', ').toBe '50, 100'
expect(md._assignProp).toHaveBeenCalledWith 'radius', array
it 'should extend defaults object to properties if rand was passed', ->
md = new Module radius: 'rand(0, 10)'
spyOn(md, '_assignProp').and.callThrough()
md._extendDefaults()
expect(md._props.radius).toBeDefined()
expect(md._props.radius).toBeGreaterThan -1
expect(md._props.radius).not.toBeGreaterThan 10
expect(md._assignProp).toHaveBeenCalled()
describe 'stagger values', ->
it 'should extend defaults object to properties if stagger was passed', ->
md = new Module radius: 'stagger(200)'
spyOn(md, '_assignProp').and.callThrough()
md._index = 2
md._extendDefaults()
expect(md._props.radius).toBe 400
expect(md._assignProp).toHaveBeenCalledWith 'radius', 400
describe '_setProgress method ->', ->
it 'should set transition progress', ->
byte = new Module radius: {'25.50': -75.50}
byte._setProgress .5
expect(byte._progress).toBe .5
it 'should set value progress', ->
byte = new Module radius: {'25': 75}
byte._setProgress .5
expect(byte._props.radius).toBe 50
it 'should call _calcCurrentProps', ->
byte = new Module radius: {'25': 75}
spyOn byte, '_calcCurrentProps'
byte._setProgress .5, .35
expect(byte._calcCurrentProps).toHaveBeenCalledWith .5, .35
it 'should set color value progress and only int', ->
byte = new Module stroke: {'#000': 'rgb(255,255,255)'}
colorDelta = byte._deltas.stroke
byte._setProgress .5
expect(byte._props.stroke).toBe 'rgba(127,127,127,1)'
it 'should set color value progress for delta starting with 0', ->
byte = new Module stroke: {'#000': 'rgb(0,255,255)'}
colorDelta = byte._deltas.stroke
byte._setProgress .5
expect(byte._props.stroke).toBe 'rgba(0,127,127,1)'
describe '_tuneNewOptions method', ->
it 'should rewrite options from passed object to _o and _props', ->
md = new Module radius: 45, radiusX: 50
md._tuneNewOptions radius: 20
expect(md._o.radius) .toBe(20)
expect(md._props.radius) .toBe(20)
it 'should extend defaults object to properties if 0', ->
md = new Module radius: 40
md._tuneNewOptions radius: 0
expect(md._props.radius).toBe(0)
it 'should call _hide method', ->
md = new Module radius: 45
spyOn(md, '_hide').and.callThrough()
md._tuneNewOptions radius: 20
expect(md._hide).toHaveBeenCalled()
# probably nope
# it 'should ignore properties defined in skipProps object', ->
# md = new Module radius: 45
# md._skipProps = radius: 1
# md._tuneNewOptions radius: 20
# expect(md._props.radius).toBe(45)
it 'should extend defaults object to properties if array was passed', ->
md = new Module radius: 50
md._tuneNewOptions 'radius': [50, 100]
expect(md._props.radius.join ', ').toBe '50, 100'
it 'should extend defaults object to properties if rand was passed', ->
md = new Module radius: 20
md._tuneNewOptions 'radius': 'rand(0, 10)'
expect(md._props.radius).toBeDefined()
expect(md._props.radius).toBeGreaterThan -1
expect(md._props.radius).not.toBeGreaterThan 10
it 'should extend defaults object to properties if stagger was passed', ->
md = new Module radius: 20
md._index = 2
md._tuneNewOptions radius: 'stagger(200)'
expect(md._props.radius).toBe 400
describe '_getDelta method ->', ->
it 'should warn if delta is top or left', ->
md = new Module
spyOn h, 'warn'
md._getDelta 'left', { '50%': 0 }
expect(h.warn).toHaveBeenCalled()
it 'should call h.parseDelta', ->
md = new Module
md._index = 3
spyOn(h, 'parseDelta').and.callThrough()
key = 'PI:KEY:<KEY>END_PI'; delta = { '50%': 0 }
md._getDelta key, delta
expect(h.parseDelta).toHaveBeenCalledWith key, delta, md._index
it 'should set end value to props', ->
md = new Module
key = 'PI:KEY:<KEY>END_PI'; delta = { '50%': 0 }
md._getDelta key, delta
expect(md._props.left).toBe 0
describe '_parsePreArrayProperty method ->', ->
it 'should call _parseOptionString method', ->
md = new Module
key = 'left'; value = '50%'
spyOn(md, '_parseOptionString').and.callThrough()
md._parsePreArrayProperty( key, value )
expect(md._parseOptionString).toHaveBeenCalledWith value
it 'should pass results of the prev call to _parsePositionOption method', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parsePositionOption').and.callThrough()
result = md._parsePreArrayProperty( key, value )
expect(md._parsePositionOption)
.toHaveBeenCalledWith key, md._parseOptionString(value)
value = md._parseOptionString(value)
value = md._parsePositionOption(key, value)
expect(result).toBe value
describe '_parseProperty method ->', ->
it 'should call h.parseEl method is name is `parent`', ->
md = new Module
key = 'parent'; value = 'body'
spyOn(h, 'parseEl').and.callThrough()
result = md._parseProperty( key, value )
expect(h.parseEl).toHaveBeenCalledWith value
expect(result).toBe document.body
it 'should call _parsePreArrayProperty method', ->
md = new Module
key = 'left'; value = '50%'
spyOn(md, '_parsePreArrayProperty').and.callThrough()
md._parseProperty( key, value )
expect(md._parsePreArrayProperty).toHaveBeenCalledWith key, value
it 'should pass results of prev call to _parseStrokeDashOption method', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parseStrokeDashOption').and.callThrough()
md._parseProperty( key, value )
value = md._parsePreArrayProperty(key, value)
expect(md._parseStrokeDashOption)
.toHaveBeenCalledWith key, value
it 'should return result', ->
md = new Module
key = 'left'; value = 'stagger(200, 100)'
spyOn(md, '_parseStrokeDashOption').and.callThrough()
result = md._parseProperty( key, value )
value = md._parsePreArrayProperty(key, value)
value = md._parseStrokeDashOption(key, value)
expect(result).toBe value
describe '_parseDeltaValues method ->', ->
it 'should parse delta values', ->
md = new Module
delta = { 'stagger(100, 0)': 200 }
deltaResult = md._parseDeltaValues( 'left', delta )
expect(deltaResult).toEqual { '100px': '200px' }
it 'should not arr values parse delta values', ->
md = new Module
delta = { 'stagger(100, 0)': 200 }
deltaResult = md._parseDeltaValues( 'strokeDasharray', delta )
expect(deltaResult).toEqual { '100': 200 }
it 'should create new delta object', ->
md = new Module
delta = { 2: 1 }
deltaResult = md._parseDeltaValues( 'opacity', delta )
expect(deltaResult).toEqual { 2: 1 }
expect(deltaResult).not.toBe delta
describe '_preparsePropValue ->', ->
it 'should parse non ∆ values', ->
md = new Module
spyOn(md, '_parsePreArrayProperty').and.callThrough()
spyOn(md, '_parseDeltaValues').and.callThrough()
result = md._preparsePropValue('left', 20)
expect(md._parsePreArrayProperty).toHaveBeenCalledWith 'left', 20
expect(md._parseDeltaValues).not.toHaveBeenCalled()
expect(result).toBe '20px'
it 'should parse ∆ values', ->
md = new Module
spyOn(md, '_parseDeltaValues').and.callThrough()
key = 'PI:KEY:<KEY>END_PI'; delta = { 20: 100 }
result = md._preparsePropValue(key, delta)
expect(md._parseDeltaValues).toHaveBeenCalledWith key, delta
expect(result['20px']).toBe '100px'
describe '_calcCurrentProps method', ->
it 'should calc color with alpha', ->
md = new Module
md._deltas = {
fill: h.parseDelta( 'fill', { 'rgba(0,0,0,0)' : 'rgba(0,0,0,1)' }, 0 )
}
md._calcCurrentProps .5, .5
expect( md._props.fill ).toBe 'rgba(0,0,0,0.5)'
it 'clean the _defaults up', ->
Module::_declareDefaults = oldFun
|
[
{
"context": "\n# * grunt-coffee-requires\n# * https://github.com/MarkForged/grunt-coffee-requires\n# *\n# * Copyright (c) 2014 ",
"end": 61,
"score": 0.9997045993804932,
"start": 51,
"tag": "USERNAME",
"value": "MarkForged"
},
{
"context": "d/grunt-coffee-requires\n# *\n# * Copyrigh... | tasks/coffee_requires.coffee | benforged/grunt-coffee-requires | 0 | #
# * grunt-coffee-requires
# * https://github.com/MarkForged/grunt-coffee-requires
# *
# * Copyright (c) 2014 David Benhaim
# * Licensed under the MIT license.
#
{compile} = require 'coffee-script'
path = require "path"
BrowserStripper = require "../src/browser_stripper"
RequiresTree = require('../src/requires_tree')
module.exports = (grunt) ->
# Please see the Grunt documentation for more information regarding task
# creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask "coffee_requires", "A grunt plugin that concatenates and compiles a coffeescript project into javascript with node.js requires statements", ->
# Merge task-specific and/or target-specific options with these defaults.
options = @options(
compile: true
bare: false
header: ""
footer: ""
delimiter: "\n"
)
# done = @async()
unless @files.length is 1
grunt.fail.fatal(new Error("Please specify only one root file - got #{@files.length}"))
# Iterate over all specified file groups.
@file = @files[0]
unless @file.src.length is 1
grunt.fail.fatal(new Error("Please specify only one root file - got #{@file.src.length}"))
entry_point = @file.src[0]
rt = new RequiresTree(path.basename(entry_point), path.dirname(path.resolve(entry_point)))
dependencies = rt.compute()
dependencies.push path.join(path.dirname(path.resolve(entry_point)), path.basename(entry_point))
bs = new BrowserStripper dependencies, @file.dest, options
bs.process()
if options.compile and grunt.file.exists(@file.dest)
src = grunt.file.read(@file.dest)
try
compiled = compile(src, {
sourceMap: options.sourceMap
bare: options.bare
})
catch e
grunt.log.error("#{e.message}(file: #{@file.dest}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
grunt.log.ok("Compiled #{@file.dest}")
if options.sourceMap
{js: compiled, v3SourceMap} = compiled
v3SourceMap = JSON.parse(v3SourceMap)
v3SourceMap.sourceRoot = path.relative(fileOutDir, cwd)
v3SourceMap.file = path.basename(outFile)
v3SourceMap.sources[0] = path.relative(cwd, file)
v3SourceMap = JSON.stringify(v3SourceMap)
compiled += "\n\n//@ sourceMappingURL=#{path.basename(outFile)}.map"
grunt.file.write("#{@file.dest}.map", v3SourceMap)
grunt.log.ok("File #{@file.dest}.map was created")
grunt.file.write(@file.dest, compiled)
grunt.log.ok("File #{@file.dest} was created")
return
return | 122172 | #
# * grunt-coffee-requires
# * https://github.com/MarkForged/grunt-coffee-requires
# *
# * Copyright (c) 2014 <NAME>
# * Licensed under the MIT license.
#
{compile} = require 'coffee-script'
path = require "path"
BrowserStripper = require "../src/browser_stripper"
RequiresTree = require('../src/requires_tree')
module.exports = (grunt) ->
# Please see the Grunt documentation for more information regarding task
# creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask "coffee_requires", "A grunt plugin that concatenates and compiles a coffeescript project into javascript with node.js requires statements", ->
# Merge task-specific and/or target-specific options with these defaults.
options = @options(
compile: true
bare: false
header: ""
footer: ""
delimiter: "\n"
)
# done = @async()
unless @files.length is 1
grunt.fail.fatal(new Error("Please specify only one root file - got #{@files.length}"))
# Iterate over all specified file groups.
@file = @files[0]
unless @file.src.length is 1
grunt.fail.fatal(new Error("Please specify only one root file - got #{@file.src.length}"))
entry_point = @file.src[0]
rt = new RequiresTree(path.basename(entry_point), path.dirname(path.resolve(entry_point)))
dependencies = rt.compute()
dependencies.push path.join(path.dirname(path.resolve(entry_point)), path.basename(entry_point))
bs = new BrowserStripper dependencies, @file.dest, options
bs.process()
if options.compile and grunt.file.exists(@file.dest)
src = grunt.file.read(@file.dest)
try
compiled = compile(src, {
sourceMap: options.sourceMap
bare: options.bare
})
catch e
grunt.log.error("#{e.message}(file: #{@file.dest}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
grunt.log.ok("Compiled #{@file.dest}")
if options.sourceMap
{js: compiled, v3SourceMap} = compiled
v3SourceMap = JSON.parse(v3SourceMap)
v3SourceMap.sourceRoot = path.relative(fileOutDir, cwd)
v3SourceMap.file = path.basename(outFile)
v3SourceMap.sources[0] = path.relative(cwd, file)
v3SourceMap = JSON.stringify(v3SourceMap)
compiled += "\n\n//@ sourceMappingURL=#{path.basename(outFile)}.map"
grunt.file.write("#{@file.dest}.map", v3SourceMap)
grunt.log.ok("File #{@file.dest}.map was created")
grunt.file.write(@file.dest, compiled)
grunt.log.ok("File #{@file.dest} was created")
return
return | true | #
# * grunt-coffee-requires
# * https://github.com/MarkForged/grunt-coffee-requires
# *
# * Copyright (c) 2014 PI:NAME:<NAME>END_PI
# * Licensed under the MIT license.
#
{compile} = require 'coffee-script'
path = require "path"
BrowserStripper = require "../src/browser_stripper"
RequiresTree = require('../src/requires_tree')
module.exports = (grunt) ->
# Please see the Grunt documentation for more information regarding task
# creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask "coffee_requires", "A grunt plugin that concatenates and compiles a coffeescript project into javascript with node.js requires statements", ->
# Merge task-specific and/or target-specific options with these defaults.
options = @options(
compile: true
bare: false
header: ""
footer: ""
delimiter: "\n"
)
# done = @async()
unless @files.length is 1
grunt.fail.fatal(new Error("Please specify only one root file - got #{@files.length}"))
# Iterate over all specified file groups.
@file = @files[0]
unless @file.src.length is 1
grunt.fail.fatal(new Error("Please specify only one root file - got #{@file.src.length}"))
entry_point = @file.src[0]
rt = new RequiresTree(path.basename(entry_point), path.dirname(path.resolve(entry_point)))
dependencies = rt.compute()
dependencies.push path.join(path.dirname(path.resolve(entry_point)), path.basename(entry_point))
bs = new BrowserStripper dependencies, @file.dest, options
bs.process()
if options.compile and grunt.file.exists(@file.dest)
src = grunt.file.read(@file.dest)
try
compiled = compile(src, {
sourceMap: options.sourceMap
bare: options.bare
})
catch e
grunt.log.error("#{e.message}(file: #{@file.dest}, line: #{e.location.last_line + 1}, column: #{e.location.last_column})")
throw e
grunt.log.ok("Compiled #{@file.dest}")
if options.sourceMap
{js: compiled, v3SourceMap} = compiled
v3SourceMap = JSON.parse(v3SourceMap)
v3SourceMap.sourceRoot = path.relative(fileOutDir, cwd)
v3SourceMap.file = path.basename(outFile)
v3SourceMap.sources[0] = path.relative(cwd, file)
v3SourceMap = JSON.stringify(v3SourceMap)
compiled += "\n\n//@ sourceMappingURL=#{path.basename(outFile)}.map"
grunt.file.write("#{@file.dest}.map", v3SourceMap)
grunt.log.ok("File #{@file.dest}.map was created")
grunt.file.write(@file.dest, compiled)
grunt.log.ok("File #{@file.dest} was created")
return
return |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.