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": "rticular style for multiline comments\n * # @author Teddy Katz\n###\n'use strict'\n\nastUtils = require '../eslint-a",
"end": 97,
"score": 0.9997865557670593,
"start": 87,
"tag": "NAME",
"value": "Teddy Katz"
}
] | src/rules/multiline-comment-style.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
* # @fileoverview enforce a particular style for multiline comments
* # @author Teddy Katz
###
'use strict'
astUtils = require '../eslint-ast-utils'
###
* ------------------------------------------------------------------------------
* Rule Definition
* ------------------------------------------------------------------------------
###
module.exports =
meta:
docs:
description: 'enforce a particular style for multiline comments'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/multiline-comment-style'
fixable: 'whitespace'
schema: [
enum: ['hashed-block', 'starred-block', 'separate-lines', 'bare-block']
]
create: (context) ->
sourceCode = context.getSourceCode()
option = context.options[0] or 'hashed-block'
EXPECTED_BLOCK_ERROR =
'Expected a block comment instead of consecutive line comments.'
START_NEWLINE_ERROR = "Expected a linebreak after '###'."
END_NEWLINE_ERROR = "Expected a linebreak before '###'."
MISSING_HASH_ERROR = "Expected a '#' at the start of this line."
MISSING_STAR_ERROR = "Expected a '*' at the start of this line."
ALIGNMENT_ERROR =
'Expected this line to be aligned with the start of the comment.'
EXPECTED_LINES_ERROR =
'Expected multiple line comments instead of a block comment.'
###
* ----------------------------------------------------------------------
* Helpers
* ----------------------------------------------------------------------
###
###*
* # Gets a list of comment lines in a group
* # @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
* # @returns {string[]} A list of comment lines
###
getCommentLines = (commentGroup) ->
if commentGroup[0].type is 'Line'
return commentGroup.map (comment) ->
comment.value
commentGroup[0].value
.split astUtils.LINEBREAK_MATCHER
.map (line) -> line.replace /^\s*[*#]?/, ''
###*
* # Converts a comment into starred-block form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
###
convertToStarredBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
starredLines = commentLinesList.map (line) -> "#{initialOffset} *#{line}"
"\n#{starredLines.join '\n'}\n#{initialOffset}"
convertToHashedBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
hashedLines = commentLinesList.map (line) -> "#{initialOffset}##{line}"
"\n#{hashedLines.join '\n'}\n#{initialOffset}"
###*
* # Converts a comment into separate-line form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in separate-line form
###
convertToSeparateLines = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
separateLines = commentLinesList.map (line) -> "# #{line.trim()}"
separateLines.join "\n#{initialOffset}"
###*
* # Converts a comment into bare-block form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in bare-block form
###
convertToBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
blockLines = commentLinesList.map (line) -> line.trim()
"### #{blockLines.join "\n#{initialOffset} "} ###"
###*
* # Check a comment is JSDoc form
* # @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
* # @returns {boolean} if commentGroup is JSDoc form, return true
###
isJSDoc = (commentGroup) ->
lines = commentGroup[0].value.split astUtils.LINEBREAK_MATCHER
commentGroup[0].type is 'Block' and
/^\*\s*$/.test(lines[0]) and
lines
.slice 1, -1
.every((line) -> /^\s*[ #]/.test line) and
/^\s*$/.test lines[lines.length - 1]
###*
* # Each method checks a group of comments to see if it's valid according to the given option.
* # @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
* # block comment or multiple line comments.
* # @returns {void}
###
commentGroupCheckers =
'hashed-block': (commentGroup) ->
commentLines = getCommentLines commentGroup
return if commentLines.some (value) -> value.includes '###'
if commentGroup.length > 1
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
hashedBlock = "####{convertToHashedBlock(
commentGroup[0]
commentLines
)}###"
if commentLines.some((value) -> value.startsWith '#')
null
else
fixer.replaceTextRange range, hashedBlock
else
block = commentGroup[0]
lines = block.value.split astUtils.LINEBREAK_MATCHER
lineIndent = sourceCode.text.slice(
block.range[0] - block.loc.start.column
block.range[0]
)
expectedLinePrefix = "#{lineIndent}#"
unless /^\*?\s*$/.test lines[0]
start =
if block.value.startsWith '*'
block.range[0] + 1
else
block.range[0]
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: START_NEWLINE_ERROR
fix: (fixer) ->
fixer.insertTextAfterRange(
[start, start + '###'.length]
"\n#{expectedLinePrefix}"
)
unless /^\s*$/.test lines[lines.length - 1]
context.report
loc:
start:
line: block.loc.end.line, column: block.loc.end.column - 2
end: block.loc.end
message: END_NEWLINE_ERROR
fix: (fixer) ->
fixer.replaceTextRange(
[block.range[1] - '###'.length, block.range[1]]
"\n#{lineIndent}###"
)
lineNumber = block.loc.start.line + 1
while lineNumber <= block.loc.end.line
lineText = sourceCode.lines[lineNumber - 1]
unless (
if lineNumber is block.loc.end.line
lineText.startsWith "#{lineIndent}#"
else
lineText.startsWith expectedLinePrefix
)
context.report
loc:
start: line: lineNumber, column: 0
end:
line: lineNumber
column: sourceCode.lines[lineNumber - 1].length
message:
if lineNumber is block.loc.end.line or /^\s*#/.test lineText
ALIGNMENT_ERROR
else
MISSING_HASH_ERROR
# eslint-disable-next-line coffee/no-loop-func
fix: (fixer) ->
lineStartIndex = sourceCode.getIndexFromLoc(
line: lineNumber, column: 0
)
linePrefixLength =
lineText.match(/^\s*(?:#(?!##))? ?/)[0].length
commentStartIndex = lineStartIndex + linePrefixLength
replacementText =
if lineNumber is block.loc.end.line
lineIndent
else if lineText.length is linePrefixLength
expectedLinePrefix
else
"#{expectedLinePrefix} "
fixer.replaceTextRange(
[lineStartIndex, commentStartIndex]
replacementText
)
lineNumber++
'starred-block': (commentGroup) ->
commentLines = getCommentLines commentGroup
return if commentLines.some (value) -> value.includes '###'
if commentGroup.length > 1
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
starredBlock = "####{convertToStarredBlock(
commentGroup[0]
commentLines
)}###"
if commentLines.some((value) -> value.startsWith '#')
null
else
fixer.replaceTextRange range, starredBlock
else
block = commentGroup[0]
lines = block.value.split astUtils.LINEBREAK_MATCHER
lineIndent = sourceCode.text.slice(
block.range[0] - block.loc.start.column
block.range[0]
)
expectedLinePrefix = "#{lineIndent} *"
unless /^\*?\s*$/.test lines[0]
start =
if block.value.startsWith '*'
block.range[0] + 1
else
block.range[0]
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: START_NEWLINE_ERROR
fix: (fixer) ->
fixer.insertTextAfterRange(
[start, start + '###'.length]
"\n#{expectedLinePrefix}"
)
unless /^\s*$/.test lines[lines.length - 1]
context.report
loc:
start:
line: block.loc.end.line, column: block.loc.end.column - 2
end: block.loc.end
message: END_NEWLINE_ERROR
fix: (fixer) ->
fixer.replaceTextRange(
[block.range[1] - '###'.length, block.range[1]]
"\n#{lineIndent}###"
)
lineNumber = block.loc.start.line + 1
while lineNumber <= block.loc.end.line
lineText = sourceCode.lines[lineNumber - 1]
unless (
if lineNumber is block.loc.end.line
lineText.startsWith("#{lineIndent}#") or
lineText.startsWith "#{lineIndent} *"
else
lineText.startsWith expectedLinePrefix
)
context.report
loc:
start: line: lineNumber, column: 0
end:
line: lineNumber
column: sourceCode.lines[lineNumber - 1].length
message:
if lineNumber is block.loc.end.line or /^\s*\*/.test lineText
ALIGNMENT_ERROR
else
MISSING_STAR_ERROR
# eslint-disable-next-line coffee/no-loop-func
fix: (fixer) ->
lineStartIndex = sourceCode.getIndexFromLoc(
line: lineNumber, column: 0
)
linePrefixLength = lineText.match(/^\s*\*? ?/)[0].length
commentStartIndex = lineStartIndex + linePrefixLength
replacementText =
if lineNumber is block.loc.end.line
lineIndent
else if lineText.length is linePrefixLength
expectedLinePrefix
else
"#{expectedLinePrefix} "
fixer.replaceTextRange(
[lineStartIndex, commentStartIndex]
replacementText
)
lineNumber++
'separate-lines': (commentGroup) ->
if not isJSDoc(commentGroup) and commentGroup[0].type is 'Block'
commentLines = getCommentLines commentGroup
block = commentGroup[0]
tokenAfter = sourceCode.getTokenAfter block, includeComments: yes
return if (
tokenAfter and block.loc.end.line is tokenAfter.loc.start.line
)
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line, column: block.loc.start.column + 2
message: EXPECTED_LINES_ERROR
fix: (fixer) ->
fixer.replaceText(
block
convertToSeparateLines block, commentLines.filter (line) -> line
)
'bare-block': (commentGroup) ->
unless isJSDoc commentGroup
commentLines = getCommentLines commentGroup
# disallows consecutive line comments in favor of using a block comment.
if (
commentGroup[0].type is 'Line' and
commentLines.length > 1 and
not commentLines.some((value) -> value.includes '###')
)
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
block = convertToBlock(
commentGroup[0]
commentLines.filter (line) -> line
)
fixer.replaceTextRange range, block
# prohibits block comments from having a * at the beginning of each line.
if commentGroup[0].type is 'Block'
block = commentGroup[0]
lines =
block.value
.split astUtils.LINEBREAK_MATCHER
.filter (line) -> line.trim()
if lines.length > 0 and lines.every((line) -> /^\s*[*#]/.test line)
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
fixer.replaceText(
block
convertToBlock block, commentLines.filter (line) -> line
)
###
* ----------------------------------------------------------------------
* Public
* ----------------------------------------------------------------------
###
Program: ->
sourceCode
.getAllComments()
.filter (comment) -> comment.type isnt 'Shebang'
.filter (comment) ->
not astUtils.COMMENTS_IGNORE_PATTERN.test comment.value
.filter (comment) ->
tokenBefore = sourceCode.getTokenBefore comment, includeComments: yes
not tokenBefore or tokenBefore.loc.end.line < comment.loc.start.line
.reduce(
(commentGroups, comment, index, commentList) ->
tokenBefore = sourceCode.getTokenBefore comment, includeComments: yes
if (
comment.type is 'Line' and
index and
commentList[index - 1].type is 'Line' and
tokenBefore and
tokenBefore.loc.end.line is comment.loc.start.line - 1 and
tokenBefore is commentList[index - 1]
)
commentGroups[commentGroups.length - 1].push comment
else
commentGroups.push [comment]
commentGroups
,
[]
)
.filter (commentGroup) ->
not (
commentGroup.length is 1 and
commentGroup[0].loc.start.line is commentGroup[0].loc.end.line
)
.forEach commentGroupCheckers[option]
| 65607 | ###*
* # @fileoverview enforce a particular style for multiline comments
* # @author <NAME>
###
'use strict'
astUtils = require '../eslint-ast-utils'
###
* ------------------------------------------------------------------------------
* Rule Definition
* ------------------------------------------------------------------------------
###
module.exports =
meta:
docs:
description: 'enforce a particular style for multiline comments'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/multiline-comment-style'
fixable: 'whitespace'
schema: [
enum: ['hashed-block', 'starred-block', 'separate-lines', 'bare-block']
]
create: (context) ->
sourceCode = context.getSourceCode()
option = context.options[0] or 'hashed-block'
EXPECTED_BLOCK_ERROR =
'Expected a block comment instead of consecutive line comments.'
START_NEWLINE_ERROR = "Expected a linebreak after '###'."
END_NEWLINE_ERROR = "Expected a linebreak before '###'."
MISSING_HASH_ERROR = "Expected a '#' at the start of this line."
MISSING_STAR_ERROR = "Expected a '*' at the start of this line."
ALIGNMENT_ERROR =
'Expected this line to be aligned with the start of the comment.'
EXPECTED_LINES_ERROR =
'Expected multiple line comments instead of a block comment.'
###
* ----------------------------------------------------------------------
* Helpers
* ----------------------------------------------------------------------
###
###*
* # Gets a list of comment lines in a group
* # @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
* # @returns {string[]} A list of comment lines
###
getCommentLines = (commentGroup) ->
if commentGroup[0].type is 'Line'
return commentGroup.map (comment) ->
comment.value
commentGroup[0].value
.split astUtils.LINEBREAK_MATCHER
.map (line) -> line.replace /^\s*[*#]?/, ''
###*
* # Converts a comment into starred-block form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
###
convertToStarredBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
starredLines = commentLinesList.map (line) -> "#{initialOffset} *#{line}"
"\n#{starredLines.join '\n'}\n#{initialOffset}"
convertToHashedBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
hashedLines = commentLinesList.map (line) -> "#{initialOffset}##{line}"
"\n#{hashedLines.join '\n'}\n#{initialOffset}"
###*
* # Converts a comment into separate-line form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in separate-line form
###
convertToSeparateLines = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
separateLines = commentLinesList.map (line) -> "# #{line.trim()}"
separateLines.join "\n#{initialOffset}"
###*
* # Converts a comment into bare-block form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in bare-block form
###
convertToBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
blockLines = commentLinesList.map (line) -> line.trim()
"### #{blockLines.join "\n#{initialOffset} "} ###"
###*
* # Check a comment is JSDoc form
* # @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
* # @returns {boolean} if commentGroup is JSDoc form, return true
###
isJSDoc = (commentGroup) ->
lines = commentGroup[0].value.split astUtils.LINEBREAK_MATCHER
commentGroup[0].type is 'Block' and
/^\*\s*$/.test(lines[0]) and
lines
.slice 1, -1
.every((line) -> /^\s*[ #]/.test line) and
/^\s*$/.test lines[lines.length - 1]
###*
* # Each method checks a group of comments to see if it's valid according to the given option.
* # @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
* # block comment or multiple line comments.
* # @returns {void}
###
commentGroupCheckers =
'hashed-block': (commentGroup) ->
commentLines = getCommentLines commentGroup
return if commentLines.some (value) -> value.includes '###'
if commentGroup.length > 1
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
hashedBlock = "####{convertToHashedBlock(
commentGroup[0]
commentLines
)}###"
if commentLines.some((value) -> value.startsWith '#')
null
else
fixer.replaceTextRange range, hashedBlock
else
block = commentGroup[0]
lines = block.value.split astUtils.LINEBREAK_MATCHER
lineIndent = sourceCode.text.slice(
block.range[0] - block.loc.start.column
block.range[0]
)
expectedLinePrefix = "#{lineIndent}#"
unless /^\*?\s*$/.test lines[0]
start =
if block.value.startsWith '*'
block.range[0] + 1
else
block.range[0]
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: START_NEWLINE_ERROR
fix: (fixer) ->
fixer.insertTextAfterRange(
[start, start + '###'.length]
"\n#{expectedLinePrefix}"
)
unless /^\s*$/.test lines[lines.length - 1]
context.report
loc:
start:
line: block.loc.end.line, column: block.loc.end.column - 2
end: block.loc.end
message: END_NEWLINE_ERROR
fix: (fixer) ->
fixer.replaceTextRange(
[block.range[1] - '###'.length, block.range[1]]
"\n#{lineIndent}###"
)
lineNumber = block.loc.start.line + 1
while lineNumber <= block.loc.end.line
lineText = sourceCode.lines[lineNumber - 1]
unless (
if lineNumber is block.loc.end.line
lineText.startsWith "#{lineIndent}#"
else
lineText.startsWith expectedLinePrefix
)
context.report
loc:
start: line: lineNumber, column: 0
end:
line: lineNumber
column: sourceCode.lines[lineNumber - 1].length
message:
if lineNumber is block.loc.end.line or /^\s*#/.test lineText
ALIGNMENT_ERROR
else
MISSING_HASH_ERROR
# eslint-disable-next-line coffee/no-loop-func
fix: (fixer) ->
lineStartIndex = sourceCode.getIndexFromLoc(
line: lineNumber, column: 0
)
linePrefixLength =
lineText.match(/^\s*(?:#(?!##))? ?/)[0].length
commentStartIndex = lineStartIndex + linePrefixLength
replacementText =
if lineNumber is block.loc.end.line
lineIndent
else if lineText.length is linePrefixLength
expectedLinePrefix
else
"#{expectedLinePrefix} "
fixer.replaceTextRange(
[lineStartIndex, commentStartIndex]
replacementText
)
lineNumber++
'starred-block': (commentGroup) ->
commentLines = getCommentLines commentGroup
return if commentLines.some (value) -> value.includes '###'
if commentGroup.length > 1
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
starredBlock = "####{convertToStarredBlock(
commentGroup[0]
commentLines
)}###"
if commentLines.some((value) -> value.startsWith '#')
null
else
fixer.replaceTextRange range, starredBlock
else
block = commentGroup[0]
lines = block.value.split astUtils.LINEBREAK_MATCHER
lineIndent = sourceCode.text.slice(
block.range[0] - block.loc.start.column
block.range[0]
)
expectedLinePrefix = "#{lineIndent} *"
unless /^\*?\s*$/.test lines[0]
start =
if block.value.startsWith '*'
block.range[0] + 1
else
block.range[0]
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: START_NEWLINE_ERROR
fix: (fixer) ->
fixer.insertTextAfterRange(
[start, start + '###'.length]
"\n#{expectedLinePrefix}"
)
unless /^\s*$/.test lines[lines.length - 1]
context.report
loc:
start:
line: block.loc.end.line, column: block.loc.end.column - 2
end: block.loc.end
message: END_NEWLINE_ERROR
fix: (fixer) ->
fixer.replaceTextRange(
[block.range[1] - '###'.length, block.range[1]]
"\n#{lineIndent}###"
)
lineNumber = block.loc.start.line + 1
while lineNumber <= block.loc.end.line
lineText = sourceCode.lines[lineNumber - 1]
unless (
if lineNumber is block.loc.end.line
lineText.startsWith("#{lineIndent}#") or
lineText.startsWith "#{lineIndent} *"
else
lineText.startsWith expectedLinePrefix
)
context.report
loc:
start: line: lineNumber, column: 0
end:
line: lineNumber
column: sourceCode.lines[lineNumber - 1].length
message:
if lineNumber is block.loc.end.line or /^\s*\*/.test lineText
ALIGNMENT_ERROR
else
MISSING_STAR_ERROR
# eslint-disable-next-line coffee/no-loop-func
fix: (fixer) ->
lineStartIndex = sourceCode.getIndexFromLoc(
line: lineNumber, column: 0
)
linePrefixLength = lineText.match(/^\s*\*? ?/)[0].length
commentStartIndex = lineStartIndex + linePrefixLength
replacementText =
if lineNumber is block.loc.end.line
lineIndent
else if lineText.length is linePrefixLength
expectedLinePrefix
else
"#{expectedLinePrefix} "
fixer.replaceTextRange(
[lineStartIndex, commentStartIndex]
replacementText
)
lineNumber++
'separate-lines': (commentGroup) ->
if not isJSDoc(commentGroup) and commentGroup[0].type is 'Block'
commentLines = getCommentLines commentGroup
block = commentGroup[0]
tokenAfter = sourceCode.getTokenAfter block, includeComments: yes
return if (
tokenAfter and block.loc.end.line is tokenAfter.loc.start.line
)
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line, column: block.loc.start.column + 2
message: EXPECTED_LINES_ERROR
fix: (fixer) ->
fixer.replaceText(
block
convertToSeparateLines block, commentLines.filter (line) -> line
)
'bare-block': (commentGroup) ->
unless isJSDoc commentGroup
commentLines = getCommentLines commentGroup
# disallows consecutive line comments in favor of using a block comment.
if (
commentGroup[0].type is 'Line' and
commentLines.length > 1 and
not commentLines.some((value) -> value.includes '###')
)
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
block = convertToBlock(
commentGroup[0]
commentLines.filter (line) -> line
)
fixer.replaceTextRange range, block
# prohibits block comments from having a * at the beginning of each line.
if commentGroup[0].type is 'Block'
block = commentGroup[0]
lines =
block.value
.split astUtils.LINEBREAK_MATCHER
.filter (line) -> line.trim()
if lines.length > 0 and lines.every((line) -> /^\s*[*#]/.test line)
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
fixer.replaceText(
block
convertToBlock block, commentLines.filter (line) -> line
)
###
* ----------------------------------------------------------------------
* Public
* ----------------------------------------------------------------------
###
Program: ->
sourceCode
.getAllComments()
.filter (comment) -> comment.type isnt 'Shebang'
.filter (comment) ->
not astUtils.COMMENTS_IGNORE_PATTERN.test comment.value
.filter (comment) ->
tokenBefore = sourceCode.getTokenBefore comment, includeComments: yes
not tokenBefore or tokenBefore.loc.end.line < comment.loc.start.line
.reduce(
(commentGroups, comment, index, commentList) ->
tokenBefore = sourceCode.getTokenBefore comment, includeComments: yes
if (
comment.type is 'Line' and
index and
commentList[index - 1].type is 'Line' and
tokenBefore and
tokenBefore.loc.end.line is comment.loc.start.line - 1 and
tokenBefore is commentList[index - 1]
)
commentGroups[commentGroups.length - 1].push comment
else
commentGroups.push [comment]
commentGroups
,
[]
)
.filter (commentGroup) ->
not (
commentGroup.length is 1 and
commentGroup[0].loc.start.line is commentGroup[0].loc.end.line
)
.forEach commentGroupCheckers[option]
| true | ###*
* # @fileoverview enforce a particular style for multiline comments
* # @author PI:NAME:<NAME>END_PI
###
'use strict'
astUtils = require '../eslint-ast-utils'
###
* ------------------------------------------------------------------------------
* Rule Definition
* ------------------------------------------------------------------------------
###
module.exports =
meta:
docs:
description: 'enforce a particular style for multiline comments'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/multiline-comment-style'
fixable: 'whitespace'
schema: [
enum: ['hashed-block', 'starred-block', 'separate-lines', 'bare-block']
]
create: (context) ->
sourceCode = context.getSourceCode()
option = context.options[0] or 'hashed-block'
EXPECTED_BLOCK_ERROR =
'Expected a block comment instead of consecutive line comments.'
START_NEWLINE_ERROR = "Expected a linebreak after '###'."
END_NEWLINE_ERROR = "Expected a linebreak before '###'."
MISSING_HASH_ERROR = "Expected a '#' at the start of this line."
MISSING_STAR_ERROR = "Expected a '*' at the start of this line."
ALIGNMENT_ERROR =
'Expected this line to be aligned with the start of the comment.'
EXPECTED_LINES_ERROR =
'Expected multiple line comments instead of a block comment.'
###
* ----------------------------------------------------------------------
* Helpers
* ----------------------------------------------------------------------
###
###*
* # Gets a list of comment lines in a group
* # @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
* # @returns {string[]} A list of comment lines
###
getCommentLines = (commentGroup) ->
if commentGroup[0].type is 'Line'
return commentGroup.map (comment) ->
comment.value
commentGroup[0].value
.split astUtils.LINEBREAK_MATCHER
.map (line) -> line.replace /^\s*[*#]?/, ''
###*
* # Converts a comment into starred-block form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in starred-block form, excluding start and end markers
###
convertToStarredBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
starredLines = commentLinesList.map (line) -> "#{initialOffset} *#{line}"
"\n#{starredLines.join '\n'}\n#{initialOffset}"
convertToHashedBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
hashedLines = commentLinesList.map (line) -> "#{initialOffset}##{line}"
"\n#{hashedLines.join '\n'}\n#{initialOffset}"
###*
* # Converts a comment into separate-line form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in separate-line form
###
convertToSeparateLines = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
separateLines = commentLinesList.map (line) -> "# #{line.trim()}"
separateLines.join "\n#{initialOffset}"
###*
* # Converts a comment into bare-block form
* # @param {Token} firstComment The first comment of the group being converted
* # @param {string[]} commentLinesList A list of lines to appear in the new starred-block comment
* # @returns {string} A representation of the comment value in bare-block form
###
convertToBlock = (firstComment, commentLinesList) ->
initialOffset = sourceCode.text.slice(
firstComment.range[0] - firstComment.loc.start.column
firstComment.range[0]
)
blockLines = commentLinesList.map (line) -> line.trim()
"### #{blockLines.join "\n#{initialOffset} "} ###"
###*
* # Check a comment is JSDoc form
* # @param {Token[]} commentGroup A group of comments, containing either multiple line comments or a single block comment
* # @returns {boolean} if commentGroup is JSDoc form, return true
###
isJSDoc = (commentGroup) ->
lines = commentGroup[0].value.split astUtils.LINEBREAK_MATCHER
commentGroup[0].type is 'Block' and
/^\*\s*$/.test(lines[0]) and
lines
.slice 1, -1
.every((line) -> /^\s*[ #]/.test line) and
/^\s*$/.test lines[lines.length - 1]
###*
* # Each method checks a group of comments to see if it's valid according to the given option.
* # @param {Token[]} commentGroup A list of comments that appear together. This will either contain a single
* # block comment or multiple line comments.
* # @returns {void}
###
commentGroupCheckers =
'hashed-block': (commentGroup) ->
commentLines = getCommentLines commentGroup
return if commentLines.some (value) -> value.includes '###'
if commentGroup.length > 1
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
hashedBlock = "####{convertToHashedBlock(
commentGroup[0]
commentLines
)}###"
if commentLines.some((value) -> value.startsWith '#')
null
else
fixer.replaceTextRange range, hashedBlock
else
block = commentGroup[0]
lines = block.value.split astUtils.LINEBREAK_MATCHER
lineIndent = sourceCode.text.slice(
block.range[0] - block.loc.start.column
block.range[0]
)
expectedLinePrefix = "#{lineIndent}#"
unless /^\*?\s*$/.test lines[0]
start =
if block.value.startsWith '*'
block.range[0] + 1
else
block.range[0]
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: START_NEWLINE_ERROR
fix: (fixer) ->
fixer.insertTextAfterRange(
[start, start + '###'.length]
"\n#{expectedLinePrefix}"
)
unless /^\s*$/.test lines[lines.length - 1]
context.report
loc:
start:
line: block.loc.end.line, column: block.loc.end.column - 2
end: block.loc.end
message: END_NEWLINE_ERROR
fix: (fixer) ->
fixer.replaceTextRange(
[block.range[1] - '###'.length, block.range[1]]
"\n#{lineIndent}###"
)
lineNumber = block.loc.start.line + 1
while lineNumber <= block.loc.end.line
lineText = sourceCode.lines[lineNumber - 1]
unless (
if lineNumber is block.loc.end.line
lineText.startsWith "#{lineIndent}#"
else
lineText.startsWith expectedLinePrefix
)
context.report
loc:
start: line: lineNumber, column: 0
end:
line: lineNumber
column: sourceCode.lines[lineNumber - 1].length
message:
if lineNumber is block.loc.end.line or /^\s*#/.test lineText
ALIGNMENT_ERROR
else
MISSING_HASH_ERROR
# eslint-disable-next-line coffee/no-loop-func
fix: (fixer) ->
lineStartIndex = sourceCode.getIndexFromLoc(
line: lineNumber, column: 0
)
linePrefixLength =
lineText.match(/^\s*(?:#(?!##))? ?/)[0].length
commentStartIndex = lineStartIndex + linePrefixLength
replacementText =
if lineNumber is block.loc.end.line
lineIndent
else if lineText.length is linePrefixLength
expectedLinePrefix
else
"#{expectedLinePrefix} "
fixer.replaceTextRange(
[lineStartIndex, commentStartIndex]
replacementText
)
lineNumber++
'starred-block': (commentGroup) ->
commentLines = getCommentLines commentGroup
return if commentLines.some (value) -> value.includes '###'
if commentGroup.length > 1
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
starredBlock = "####{convertToStarredBlock(
commentGroup[0]
commentLines
)}###"
if commentLines.some((value) -> value.startsWith '#')
null
else
fixer.replaceTextRange range, starredBlock
else
block = commentGroup[0]
lines = block.value.split astUtils.LINEBREAK_MATCHER
lineIndent = sourceCode.text.slice(
block.range[0] - block.loc.start.column
block.range[0]
)
expectedLinePrefix = "#{lineIndent} *"
unless /^\*?\s*$/.test lines[0]
start =
if block.value.startsWith '*'
block.range[0] + 1
else
block.range[0]
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: START_NEWLINE_ERROR
fix: (fixer) ->
fixer.insertTextAfterRange(
[start, start + '###'.length]
"\n#{expectedLinePrefix}"
)
unless /^\s*$/.test lines[lines.length - 1]
context.report
loc:
start:
line: block.loc.end.line, column: block.loc.end.column - 2
end: block.loc.end
message: END_NEWLINE_ERROR
fix: (fixer) ->
fixer.replaceTextRange(
[block.range[1] - '###'.length, block.range[1]]
"\n#{lineIndent}###"
)
lineNumber = block.loc.start.line + 1
while lineNumber <= block.loc.end.line
lineText = sourceCode.lines[lineNumber - 1]
unless (
if lineNumber is block.loc.end.line
lineText.startsWith("#{lineIndent}#") or
lineText.startsWith "#{lineIndent} *"
else
lineText.startsWith expectedLinePrefix
)
context.report
loc:
start: line: lineNumber, column: 0
end:
line: lineNumber
column: sourceCode.lines[lineNumber - 1].length
message:
if lineNumber is block.loc.end.line or /^\s*\*/.test lineText
ALIGNMENT_ERROR
else
MISSING_STAR_ERROR
# eslint-disable-next-line coffee/no-loop-func
fix: (fixer) ->
lineStartIndex = sourceCode.getIndexFromLoc(
line: lineNumber, column: 0
)
linePrefixLength = lineText.match(/^\s*\*? ?/)[0].length
commentStartIndex = lineStartIndex + linePrefixLength
replacementText =
if lineNumber is block.loc.end.line
lineIndent
else if lineText.length is linePrefixLength
expectedLinePrefix
else
"#{expectedLinePrefix} "
fixer.replaceTextRange(
[lineStartIndex, commentStartIndex]
replacementText
)
lineNumber++
'separate-lines': (commentGroup) ->
if not isJSDoc(commentGroup) and commentGroup[0].type is 'Block'
commentLines = getCommentLines commentGroup
block = commentGroup[0]
tokenAfter = sourceCode.getTokenAfter block, includeComments: yes
return if (
tokenAfter and block.loc.end.line is tokenAfter.loc.start.line
)
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line, column: block.loc.start.column + 2
message: EXPECTED_LINES_ERROR
fix: (fixer) ->
fixer.replaceText(
block
convertToSeparateLines block, commentLines.filter (line) -> line
)
'bare-block': (commentGroup) ->
unless isJSDoc commentGroup
commentLines = getCommentLines commentGroup
# disallows consecutive line comments in favor of using a block comment.
if (
commentGroup[0].type is 'Line' and
commentLines.length > 1 and
not commentLines.some((value) -> value.includes '###')
)
context.report
loc:
start: commentGroup[0].loc.start
end: commentGroup[commentGroup.length - 1].loc.end
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
range = [
commentGroup[0].range[0]
commentGroup[commentGroup.length - 1].range[1]
]
block = convertToBlock(
commentGroup[0]
commentLines.filter (line) -> line
)
fixer.replaceTextRange range, block
# prohibits block comments from having a * at the beginning of each line.
if commentGroup[0].type is 'Block'
block = commentGroup[0]
lines =
block.value
.split astUtils.LINEBREAK_MATCHER
.filter (line) -> line.trim()
if lines.length > 0 and lines.every((line) -> /^\s*[*#]/.test line)
context.report
loc:
start: block.loc.start
end:
line: block.loc.start.line
column: block.loc.start.column + 2
message: EXPECTED_BLOCK_ERROR
fix: (fixer) ->
fixer.replaceText(
block
convertToBlock block, commentLines.filter (line) -> line
)
###
* ----------------------------------------------------------------------
* Public
* ----------------------------------------------------------------------
###
Program: ->
sourceCode
.getAllComments()
.filter (comment) -> comment.type isnt 'Shebang'
.filter (comment) ->
not astUtils.COMMENTS_IGNORE_PATTERN.test comment.value
.filter (comment) ->
tokenBefore = sourceCode.getTokenBefore comment, includeComments: yes
not tokenBefore or tokenBefore.loc.end.line < comment.loc.start.line
.reduce(
(commentGroups, comment, index, commentList) ->
tokenBefore = sourceCode.getTokenBefore comment, includeComments: yes
if (
comment.type is 'Line' and
index and
commentList[index - 1].type is 'Line' and
tokenBefore and
tokenBefore.loc.end.line is comment.loc.start.line - 1 and
tokenBefore is commentList[index - 1]
)
commentGroups[commentGroups.length - 1].push comment
else
commentGroups.push [comment]
commentGroups
,
[]
)
.filter (commentGroup) ->
not (
commentGroup.length is 1 and
commentGroup[0].loc.start.line is commentGroup[0].loc.end.line
)
.forEach commentGroupCheckers[option]
|
[
{
"context": "ld.equal 10\n results[0].name.should.equal 'Halley Johnson'\n done()\n\n it 'can return authors by mu",
"end": 608,
"score": 0.9997381567955017,
"start": 594,
"tag": "NAME",
"value": "Halley Johnson"
},
{
"context": "_id: ObjectId('5086df098523e60002000018'), name: \"Eve\" },\n { _id: ObjectId('55356a9deca560a0137b",
"end": 773,
"score": 0.999651312828064,
"start": 770,
"tag": "NAME",
"value": "Eve"
},
{
"context": "_id: ObjectId('55356a9deca560a0137bb4a7'), name: \"Kana\" }\n ], ->\n Author.where {\n ",
"end": 842,
"score": 0.9996739029884338,
"start": 838,
"tag": "NAME",
"value": "Kana"
},
{
"context": "equal 2\n results[0].name.should.equal 'Kana'\n results[1].name.should.equal 'Eve'\n ",
"end": 1165,
"score": 0.9996691346168518,
"start": 1161,
"tag": "NAME",
"value": "Kana"
},
{
"context": " 'Kana'\n results[1].name.should.equal 'Eve'\n done()\n\n describe '#find', ->\n\n ",
"end": 1212,
"score": 0.9995943307876587,
"start": 1209,
"tag": "NAME",
"value": "Eve"
},
{
"context": "e', (done) ->\n fabricate 'authors', { name: 'Kana Abe' }, ->\n Author.find 'Kana Abe', (err, auth",
"end": 1631,
"score": 0.9998549222946167,
"start": 1623,
"tag": "NAME",
"value": "Kana Abe"
},
{
"context": "s', { name: 'Kana Abe' }, ->\n Author.find 'Kana Abe', (err, author) ->\n author.name.should.e",
"end": 1668,
"score": 0.9998371601104736,
"start": 1660,
"tag": "NAME",
"value": "Kana Abe"
},
{
"context": "r, author) ->\n author.name.should.equal 'Kana Abe'\n done()\n\n describe '#save', ->\n\n it",
"end": 1732,
"score": 0.9998756647109985,
"start": 1724,
"tag": "NAME",
"value": "Kana Abe"
},
{
"context": "ta', (done) ->\n Author.save {\n name: 'Owen Dodd'\n image_url: 'https://artsy-media/owen.jpg",
"end": 1870,
"score": 0.9998851418495178,
"start": 1861,
"tag": "NAME",
"value": "Owen Dodd"
},
{
"context": "ps://artsy-media/owen.jpg'\n twitter_handle: '@owendodd'\n bio: 'Designer based in NYC'\n }, (e",
"end": 1956,
"score": 0.9994458556175232,
"start": 1946,
"tag": "USERNAME",
"value": "'@owendodd"
},
{
"context": "err, author) ->\n author.name.should.equal 'Owen Dodd'\n author.image_url.should.equal 'https://a",
"end": 2064,
"score": 0.9998775720596313,
"start": 2055,
"tag": "NAME",
"value": "Owen Dodd"
},
{
"context": "en.jpg'\n author.twitter_handle.should.equal '@owendodd'\n author.bio.should.equal 'Designer based ",
"end": 2188,
"score": 0.9994641542434692,
"start": 2178,
"tag": "USERNAME",
"value": "'@owendodd"
}
] | src/api/apps/authors/test/model.test.coffee | craigspaeth/positron | 76 | _ = require 'underscore'
moment = require 'moment'
{ db, fabricate, empty, fixtures } = require '../../../test/helpers/db'
Author = require '../model'
{ ObjectId } = require 'mongojs'
describe 'Author', ->
beforeEach (done) ->
empty ->
fabricate 'authors', _.times(10, -> {}), ->
done()
describe '#where', ->
it 'can return all authors along with total and counts', (done) ->
Author.where { count: true }, (err, res) ->
{ total, count, results } = res
total.should.equal 10
count.should.equal 10
results[0].name.should.equal 'Halley Johnson'
done()
it 'can return authors by multiple ids', (done) ->
fabricate 'authors', [
{ _id: ObjectId('5086df098523e60002000018'), name: "Eve" },
{ _id: ObjectId('55356a9deca560a0137bb4a7'), name: "Kana" }
], ->
Author.where {
count: true
ids: ['5086df098523e60002000018', '55356a9deca560a0137bb4a7']
}, (err, res) ->
{ total, count, results } = res
total.should.equal 12
count.should.equal 2
results[0].name.should.equal 'Kana'
results[1].name.should.equal 'Eve'
done()
describe '#find', ->
it 'finds an author by an id string', (done) ->
fabricate 'authors', { _id: ObjectId('5086df098523e60002000018') }, ->
Author.find '5086df098523e60002000018', (err, author) ->
author._id.toString().should.equal '5086df098523e60002000018'
done()
it 'finds the author by name', (done) ->
fabricate 'authors', { name: 'Kana Abe' }, ->
Author.find 'Kana Abe', (err, author) ->
author.name.should.equal 'Kana Abe'
done()
describe '#save', ->
it 'saves valid author input data', (done) ->
Author.save {
name: 'Owen Dodd'
image_url: 'https://artsy-media/owen.jpg'
twitter_handle: '@owendodd'
bio: 'Designer based in NYC'
}, (err, author) ->
author.name.should.equal 'Owen Dodd'
author.image_url.should.equal 'https://artsy-media/owen.jpg'
author.twitter_handle.should.equal '@owendodd'
author.bio.should.equal 'Designer based in NYC'
db.authors.count (err, count) ->
count.should.equal 11
done()
it 'can return a validation error', (done) ->
Author.save {
name: 500
id: '5936f5530fae440cda9ae052'
}, (err, author) ->
err.details[0].message.should.containEql '"name" must be a string'
done()
describe '#present', ->
it 'converts _id to id', (done) ->
db.authors.findOne (err, author) ->
data = Author.present author
(typeof data.id).should.equal 'string'
done()
| 11120 | _ = require 'underscore'
moment = require 'moment'
{ db, fabricate, empty, fixtures } = require '../../../test/helpers/db'
Author = require '../model'
{ ObjectId } = require 'mongojs'
describe 'Author', ->
beforeEach (done) ->
empty ->
fabricate 'authors', _.times(10, -> {}), ->
done()
describe '#where', ->
it 'can return all authors along with total and counts', (done) ->
Author.where { count: true }, (err, res) ->
{ total, count, results } = res
total.should.equal 10
count.should.equal 10
results[0].name.should.equal '<NAME>'
done()
it 'can return authors by multiple ids', (done) ->
fabricate 'authors', [
{ _id: ObjectId('5086df098523e60002000018'), name: "<NAME>" },
{ _id: ObjectId('55356a9deca560a0137bb4a7'), name: "<NAME>" }
], ->
Author.where {
count: true
ids: ['5086df098523e60002000018', '55356a9deca560a0137bb4a7']
}, (err, res) ->
{ total, count, results } = res
total.should.equal 12
count.should.equal 2
results[0].name.should.equal '<NAME>'
results[1].name.should.equal '<NAME>'
done()
describe '#find', ->
it 'finds an author by an id string', (done) ->
fabricate 'authors', { _id: ObjectId('5086df098523e60002000018') }, ->
Author.find '5086df098523e60002000018', (err, author) ->
author._id.toString().should.equal '5086df098523e60002000018'
done()
it 'finds the author by name', (done) ->
fabricate 'authors', { name: '<NAME>' }, ->
Author.find '<NAME>', (err, author) ->
author.name.should.equal '<NAME>'
done()
describe '#save', ->
it 'saves valid author input data', (done) ->
Author.save {
name: '<NAME>'
image_url: 'https://artsy-media/owen.jpg'
twitter_handle: '@owendodd'
bio: 'Designer based in NYC'
}, (err, author) ->
author.name.should.equal '<NAME>'
author.image_url.should.equal 'https://artsy-media/owen.jpg'
author.twitter_handle.should.equal '@owendodd'
author.bio.should.equal 'Designer based in NYC'
db.authors.count (err, count) ->
count.should.equal 11
done()
it 'can return a validation error', (done) ->
Author.save {
name: 500
id: '5936f5530fae440cda9ae052'
}, (err, author) ->
err.details[0].message.should.containEql '"name" must be a string'
done()
describe '#present', ->
it 'converts _id to id', (done) ->
db.authors.findOne (err, author) ->
data = Author.present author
(typeof data.id).should.equal 'string'
done()
| true | _ = require 'underscore'
moment = require 'moment'
{ db, fabricate, empty, fixtures } = require '../../../test/helpers/db'
Author = require '../model'
{ ObjectId } = require 'mongojs'
describe 'Author', ->
beforeEach (done) ->
empty ->
fabricate 'authors', _.times(10, -> {}), ->
done()
describe '#where', ->
it 'can return all authors along with total and counts', (done) ->
Author.where { count: true }, (err, res) ->
{ total, count, results } = res
total.should.equal 10
count.should.equal 10
results[0].name.should.equal 'PI:NAME:<NAME>END_PI'
done()
it 'can return authors by multiple ids', (done) ->
fabricate 'authors', [
{ _id: ObjectId('5086df098523e60002000018'), name: "PI:NAME:<NAME>END_PI" },
{ _id: ObjectId('55356a9deca560a0137bb4a7'), name: "PI:NAME:<NAME>END_PI" }
], ->
Author.where {
count: true
ids: ['5086df098523e60002000018', '55356a9deca560a0137bb4a7']
}, (err, res) ->
{ total, count, results } = res
total.should.equal 12
count.should.equal 2
results[0].name.should.equal 'PI:NAME:<NAME>END_PI'
results[1].name.should.equal 'PI:NAME:<NAME>END_PI'
done()
describe '#find', ->
it 'finds an author by an id string', (done) ->
fabricate 'authors', { _id: ObjectId('5086df098523e60002000018') }, ->
Author.find '5086df098523e60002000018', (err, author) ->
author._id.toString().should.equal '5086df098523e60002000018'
done()
it 'finds the author by name', (done) ->
fabricate 'authors', { name: 'PI:NAME:<NAME>END_PI' }, ->
Author.find 'PI:NAME:<NAME>END_PI', (err, author) ->
author.name.should.equal 'PI:NAME:<NAME>END_PI'
done()
describe '#save', ->
it 'saves valid author input data', (done) ->
Author.save {
name: 'PI:NAME:<NAME>END_PI'
image_url: 'https://artsy-media/owen.jpg'
twitter_handle: '@owendodd'
bio: 'Designer based in NYC'
}, (err, author) ->
author.name.should.equal 'PI:NAME:<NAME>END_PI'
author.image_url.should.equal 'https://artsy-media/owen.jpg'
author.twitter_handle.should.equal '@owendodd'
author.bio.should.equal 'Designer based in NYC'
db.authors.count (err, count) ->
count.should.equal 11
done()
it 'can return a validation error', (done) ->
Author.save {
name: 500
id: '5936f5530fae440cda9ae052'
}, (err, author) ->
err.details[0].message.should.containEql '"name" must be a string'
done()
describe '#present', ->
it 'converts _id to id', (done) ->
db.authors.findOne (err, author) ->
data = Author.present author
(typeof data.id).should.equal 'string'
done()
|
[
{
"context": "re', ($cookieStore) -> \n cookieStorageUserKey = 'puffbirdApplicationUser'\n currentUser = null\n\n getCurrentUser: ->\n s",
"end": 121,
"score": 0.9974266290664673,
"start": 98,
"tag": "KEY",
"value": "puffbirdApplicationUser"
}
] | public/coffeescripts/services/account/identityService.coffee | deniskyashif/puffbird | 6 | puffbird.factory 'identityService', ['$cookieStore', ($cookieStore) ->
cookieStorageUserKey = 'puffbirdApplicationUser'
currentUser = null
getCurrentUser: ->
savedUser = $cookieStore.get cookieStorageUserKey
if savedUser then savedUser else currentUser
setCurrentUser: (user) ->
if user
$cookieStore.put cookieStorageUserKey, user
else
$cookieStore.remove cookieStorageUserKey
currentUser = user
isAuthenticated: ->
!!@.getCurrentUser()
] | 158959 | puffbird.factory 'identityService', ['$cookieStore', ($cookieStore) ->
cookieStorageUserKey = '<KEY>'
currentUser = null
getCurrentUser: ->
savedUser = $cookieStore.get cookieStorageUserKey
if savedUser then savedUser else currentUser
setCurrentUser: (user) ->
if user
$cookieStore.put cookieStorageUserKey, user
else
$cookieStore.remove cookieStorageUserKey
currentUser = user
isAuthenticated: ->
!!@.getCurrentUser()
] | true | puffbird.factory 'identityService', ['$cookieStore', ($cookieStore) ->
cookieStorageUserKey = 'PI:KEY:<KEY>END_PI'
currentUser = null
getCurrentUser: ->
savedUser = $cookieStore.get cookieStorageUserKey
if savedUser then savedUser else currentUser
setCurrentUser: (user) ->
if user
$cookieStore.put cookieStorageUserKey, user
else
$cookieStore.remove cookieStorageUserKey
currentUser = user
isAuthenticated: ->
!!@.getCurrentUser()
] |
[
{
"context": "# ### Fishes forget their rivers and lakes, said Chuang Tzu. Spaces or contexts give meanings to ideas and li",
"end": 59,
"score": 0.9997344017028809,
"start": 49,
"tag": "NAME",
"value": "Chuang Tzu"
}
] | src/coffee/core/Space.coffee | williamngan/pt | 1,005 | # ### Fishes forget their rivers and lakes, said Chuang Tzu. Spaces or contexts give meanings to ideas and lives, but are often overlooked. In Pt, space represents an abstract context in which a point can be made visible in one form or another, and can be specified as an html canvas, a soundscape, or a graffiti robot on a wall. Space is where a concept meets its expression.
class Space
# ## Create a Space which is the context for displaying and animating elements. Extend this to create specific Spaces, for example, a space for HTML Canvas or SVG.
# @param `id` an id property to identify this space
constructor : ( id ) ->
if typeof id != 'string' or id.length == 0
throw "id parameter is not valid"
return false
# ## A property to identify this space by name
@id = id
# ## A property to indicate the size of this space as a Vector
@size = new Vector()
# ## A property to indicate the center of this space as a Vector
@center = new Vector()
# animation properties
@_timePrev = 0 # record prev time
@_timeDiff = 0 # record prev time difference
@_timeEnd = -1 # end in milliseconds, -1 to play forever, 0 to end immediately
# ## A set of items in this space. An item should implement a function `animate()` and optionally another callback `onSpaceResize(w,h,evt)`, and will be assigned a property `animateID` automatically. (See `add()`)
@items = {}
# item properties
@_animID = -1
@_animCount = 0 # player key as increment
@_animPause = false
@_refresh = true # refresh on each frame
# ## set whether the rendering should be repainted on each frame
# @param `b` a boolean value to set whether to repaint each frame
# @demo space.refresh
# @return this space
refresh: (b) ->
@_refresh = b
return @
# ## set custom render function (on resize and other events)
# @return this space
render: ( context ) ->
return @
# ## resize the space. (not implemented)
resize: (w, h) ->
# ## clear all contents in the space (not implemented)
clear: () ->
# ## Add an item to this space. An item must define a callback function `animate( time, fps, context )` and will be assigned a property `animateID` automatically. An item can also optionally define a callback function `onSpaceResize( w, h, evt )`. Subclasses of Space may define other callback functions.
# @param an object with an `animate( time, fps, context )` function, and optionall a `onSpaceResize( w, h, evt )` function
# @demo space.add
# @return this space
add : (item) ->
if item.animate? and typeof item.animate is 'function'
k = @_animCount++
@items[k] = item
item.animateID = k
# if player has onSpaceResize defined, call the function
if item.onSpaceResize? then item.onSpaceResize(@size.x, @size.y)
else
throw "a player object for Space.add must define animate()"
return @
# ## Remove an item from this Space
# @param an object with an auto-assigned `animateID` property
# @return this space
remove : (item) ->
delete @items[ item.animateID ]
return @
# ## Remove all items from this Space
# @return this space
removeAll : () ->
@items = {}
return @
# ## Main play loop. This implements window.requestAnimationFrame and calls it recursively. Override this `play()` function to implemenet your own animation loop.
# @param `time` current time
# @return this space
play : (time=0) ->
# use fat arrow here, because rAF callback will change @ to window
@_animID = requestAnimationFrame( (t) => @play(t) )
# if pause
if @_animPause then return
# calc time passed since prev frame
@_timeDiff = time - @_timePrev
# animate this frame
try
@_playItems( time )
catch err
cancelAnimationFrame( @_animID )
console.error( err.stack )
throw err
# store time
@_timePrev = time
return @
# Main animate function. This calls all the items to perform
# @param `time` current time
# @return this space
_playItems : (time) ->
# clear before draw if refresh is true
if @_refresh then @clear()
# animate all players
for k, v of @items
v.animate( time, @_timeDiff, @ctx )
# stop if time ended
if @_timeEnd >= 0 and time > @_timeEnd
cancelAnimationFrame( @_animID )
return @
# ## Pause the animation
# @param `toggle` a boolean value to set if this function call should be a toggle (between pause and resume)
# @return this space
pause: ( toggle=false) ->
@_animPause = if toggle then !@_animPause else true
return @
# ## Resume the paused animation
# @return this space
resume: () ->
@_animPause = false
return @
# ## Specify when the animation should stop: immediately, after a time period, or never stops.
# @param `t` a value in millisecond to specify a time period to play before stopping, or `-1` to play forever, or `0` to end immediately. Default is 0 which will stop the animation immediately.
# @return this space
stop : ( t=0 ) ->
@_timeEnd = t
return @
# ## Play animation loop, and then stop after `duration` time has passed.
# @param `duration` a value in millisecond to specify a time period to play before stopping, or `-1` to play forever
playTime: (duration=5000) ->
@play()
@stop( duration )
# ## Bind event listener in canvas element, for events such as mouse events
# @param `evt` Event object
# @param `callback` a callback function for this event
bindCanvas: ( evt, callback ) ->
if @space.addEventListener then @space.addEventListener( evt, callback )
# ## A convenient method to bind (or unbind) all mouse events in canvas element. All item added to `items` property that implements an `onMouseAction` callback will receive mouse event callbacks. The types of mouse actions are: "up", "down", "move", "drag", "drop", "over", and "out".
# @param `bind` a boolean value to bind mouse events if set to `true`. If `false`, all mouse events will be unbound. Default is true.
# @demo canvasspace.bindMouse
bindMouse: ( _bind=true ) ->
if @space.addEventListener and @space.removeEventListener
if _bind
@space.addEventListener( "mousedown", @_mouseDown.bind(@) )
@space.addEventListener( "mouseup", @_mouseUp.bind(@) )
@space.addEventListener( "mouseover", @_mouseOver.bind(@) )
@space.addEventListener( "mouseout", @_mouseOut.bind(@) )
@space.addEventListener( "mousemove", @_mouseMove.bind(@) )
else
@space.removeEventListener( "mousedown", @_mouseDown.bind(@) )
@space.removeEventListener( "mouseup", @_mouseUp.bind(@) )
@space.removeEventListener( "mouseover", @_mouseOver.bind(@) )
@space.removeEventListener( "mouseout", @_mouseOut.bind(@) )
@space.removeEventListener( "mousemove", @_mouseMove.bind(@) )
# ## A convenient method to bind (or unbind) all mobile touch events in canvas element. All item added to `items` property that implements an `onTouchAction` callback will receive touch event callbacks. The types of touch actions are the same as the mouse actions: "up", "down", "move", and "out".
# @param `bind` a boolean value to bind touch events if set to `true`. If `false`, all touch events will be unbound. Default is true.
bindTouch: ( _bind=true ) ->
if @space.addEventListener and @space.removeEventListener
if _bind
@space.addEventListener( "touchstart", @_mouseDown.bind(@) )
@space.addEventListener( "touchend", @_mouseUp.bind(@) )
@space.addEventListener( "touchmove",
((evt) =>
evt.preventDefault();
@_mouseMove(evt)
) )
@space.addEventListener( "touchcancel", @_mouseOut.bind(@) )
else
@space.removeEventListener( "touchstart", @_mouseDown.bind(@) )
@space.removeEventListener( "touchend", @_mouseUp.bind(@) )
@space.removeEventListener( "touchmove", @_mouseMove.bind(@) )
@space.removeEventListener( "touchcancel", @_mouseOut.bind(@) )
# ## A convenient method to convert the touch points in a touch event to an array of `Vectors`.
# @param evt a touch event which contains touches, changedTouches, and targetTouches list.
# @param which a string to select a touches list: "touches", "changedTouches", or "targetTouches". Default is "touches"
# @return an array of Vectors, whose origin position (0,0) is offset to the top-left of this space.
touchesToPoints: ( evt, which="touches" ) ->
if (!evt or !evt[which]) then return []
return ( new Vector(t.pageX - this.boundRect.left, t.pageY - this.boundRect.top) for t in evt[which] )
# go through all item in `items` and call its onMouseAction callback function
_mouseAction: (type, evt) ->
if (evt.touches || evt.changedTouches)
for k, v of @items
if v.onTouchAction?
_c = evt.changedTouches and evt.changedTouches.length > 0
px = if (_c) then evt.changedTouches.item(0).pageX else 0;
py = if (_c) then evt.changedTouches.item(0).pageY else 0;
v.onTouchAction( type, px, py, evt )
else
for k, v of @items
if v.onMouseAction?
px = evt.offsetX || evt.layerX;
py = evt.offsetY || evt.layerY;
v.onMouseAction( type, px, py, evt )
# mouse down action
_mouseDown: (evt) ->
@_mouseAction( "down", evt )
@_mdown = true
# mouse up action
_mouseUp: (evt) ->
@_mouseAction( "up", evt )
if @_mdrag then @_mouseAction( "drop", evt )
@_mdown = false
@_mdrag = false
# mouse move action
_mouseMove: (evt) ->
@_mouseAction( "move", evt )
if @_mdown
@_mdrag = true
@_mouseAction( "drag", evt )
# mouse over action
_mouseOver: (evt) ->
@_mouseAction( "over", evt )
# mouse out action
_mouseOut: (evt) ->
@_mouseAction( "out", evt )
if @_mdrag then @_mouseAction( "drop", evt )
@_mdrag = false
# namespace
this.Space = Space
| 158912 | # ### Fishes forget their rivers and lakes, said <NAME>. Spaces or contexts give meanings to ideas and lives, but are often overlooked. In Pt, space represents an abstract context in which a point can be made visible in one form or another, and can be specified as an html canvas, a soundscape, or a graffiti robot on a wall. Space is where a concept meets its expression.
class Space
# ## Create a Space which is the context for displaying and animating elements. Extend this to create specific Spaces, for example, a space for HTML Canvas or SVG.
# @param `id` an id property to identify this space
constructor : ( id ) ->
if typeof id != 'string' or id.length == 0
throw "id parameter is not valid"
return false
# ## A property to identify this space by name
@id = id
# ## A property to indicate the size of this space as a Vector
@size = new Vector()
# ## A property to indicate the center of this space as a Vector
@center = new Vector()
# animation properties
@_timePrev = 0 # record prev time
@_timeDiff = 0 # record prev time difference
@_timeEnd = -1 # end in milliseconds, -1 to play forever, 0 to end immediately
# ## A set of items in this space. An item should implement a function `animate()` and optionally another callback `onSpaceResize(w,h,evt)`, and will be assigned a property `animateID` automatically. (See `add()`)
@items = {}
# item properties
@_animID = -1
@_animCount = 0 # player key as increment
@_animPause = false
@_refresh = true # refresh on each frame
# ## set whether the rendering should be repainted on each frame
# @param `b` a boolean value to set whether to repaint each frame
# @demo space.refresh
# @return this space
refresh: (b) ->
@_refresh = b
return @
# ## set custom render function (on resize and other events)
# @return this space
render: ( context ) ->
return @
# ## resize the space. (not implemented)
resize: (w, h) ->
# ## clear all contents in the space (not implemented)
clear: () ->
# ## Add an item to this space. An item must define a callback function `animate( time, fps, context )` and will be assigned a property `animateID` automatically. An item can also optionally define a callback function `onSpaceResize( w, h, evt )`. Subclasses of Space may define other callback functions.
# @param an object with an `animate( time, fps, context )` function, and optionall a `onSpaceResize( w, h, evt )` function
# @demo space.add
# @return this space
add : (item) ->
if item.animate? and typeof item.animate is 'function'
k = @_animCount++
@items[k] = item
item.animateID = k
# if player has onSpaceResize defined, call the function
if item.onSpaceResize? then item.onSpaceResize(@size.x, @size.y)
else
throw "a player object for Space.add must define animate()"
return @
# ## Remove an item from this Space
# @param an object with an auto-assigned `animateID` property
# @return this space
remove : (item) ->
delete @items[ item.animateID ]
return @
# ## Remove all items from this Space
# @return this space
removeAll : () ->
@items = {}
return @
# ## Main play loop. This implements window.requestAnimationFrame and calls it recursively. Override this `play()` function to implemenet your own animation loop.
# @param `time` current time
# @return this space
play : (time=0) ->
# use fat arrow here, because rAF callback will change @ to window
@_animID = requestAnimationFrame( (t) => @play(t) )
# if pause
if @_animPause then return
# calc time passed since prev frame
@_timeDiff = time - @_timePrev
# animate this frame
try
@_playItems( time )
catch err
cancelAnimationFrame( @_animID )
console.error( err.stack )
throw err
# store time
@_timePrev = time
return @
# Main animate function. This calls all the items to perform
# @param `time` current time
# @return this space
_playItems : (time) ->
# clear before draw if refresh is true
if @_refresh then @clear()
# animate all players
for k, v of @items
v.animate( time, @_timeDiff, @ctx )
# stop if time ended
if @_timeEnd >= 0 and time > @_timeEnd
cancelAnimationFrame( @_animID )
return @
# ## Pause the animation
# @param `toggle` a boolean value to set if this function call should be a toggle (between pause and resume)
# @return this space
pause: ( toggle=false) ->
@_animPause = if toggle then !@_animPause else true
return @
# ## Resume the paused animation
# @return this space
resume: () ->
@_animPause = false
return @
# ## Specify when the animation should stop: immediately, after a time period, or never stops.
# @param `t` a value in millisecond to specify a time period to play before stopping, or `-1` to play forever, or `0` to end immediately. Default is 0 which will stop the animation immediately.
# @return this space
stop : ( t=0 ) ->
@_timeEnd = t
return @
# ## Play animation loop, and then stop after `duration` time has passed.
# @param `duration` a value in millisecond to specify a time period to play before stopping, or `-1` to play forever
playTime: (duration=5000) ->
@play()
@stop( duration )
# ## Bind event listener in canvas element, for events such as mouse events
# @param `evt` Event object
# @param `callback` a callback function for this event
bindCanvas: ( evt, callback ) ->
if @space.addEventListener then @space.addEventListener( evt, callback )
# ## A convenient method to bind (or unbind) all mouse events in canvas element. All item added to `items` property that implements an `onMouseAction` callback will receive mouse event callbacks. The types of mouse actions are: "up", "down", "move", "drag", "drop", "over", and "out".
# @param `bind` a boolean value to bind mouse events if set to `true`. If `false`, all mouse events will be unbound. Default is true.
# @demo canvasspace.bindMouse
bindMouse: ( _bind=true ) ->
if @space.addEventListener and @space.removeEventListener
if _bind
@space.addEventListener( "mousedown", @_mouseDown.bind(@) )
@space.addEventListener( "mouseup", @_mouseUp.bind(@) )
@space.addEventListener( "mouseover", @_mouseOver.bind(@) )
@space.addEventListener( "mouseout", @_mouseOut.bind(@) )
@space.addEventListener( "mousemove", @_mouseMove.bind(@) )
else
@space.removeEventListener( "mousedown", @_mouseDown.bind(@) )
@space.removeEventListener( "mouseup", @_mouseUp.bind(@) )
@space.removeEventListener( "mouseover", @_mouseOver.bind(@) )
@space.removeEventListener( "mouseout", @_mouseOut.bind(@) )
@space.removeEventListener( "mousemove", @_mouseMove.bind(@) )
# ## A convenient method to bind (or unbind) all mobile touch events in canvas element. All item added to `items` property that implements an `onTouchAction` callback will receive touch event callbacks. The types of touch actions are the same as the mouse actions: "up", "down", "move", and "out".
# @param `bind` a boolean value to bind touch events if set to `true`. If `false`, all touch events will be unbound. Default is true.
bindTouch: ( _bind=true ) ->
if @space.addEventListener and @space.removeEventListener
if _bind
@space.addEventListener( "touchstart", @_mouseDown.bind(@) )
@space.addEventListener( "touchend", @_mouseUp.bind(@) )
@space.addEventListener( "touchmove",
((evt) =>
evt.preventDefault();
@_mouseMove(evt)
) )
@space.addEventListener( "touchcancel", @_mouseOut.bind(@) )
else
@space.removeEventListener( "touchstart", @_mouseDown.bind(@) )
@space.removeEventListener( "touchend", @_mouseUp.bind(@) )
@space.removeEventListener( "touchmove", @_mouseMove.bind(@) )
@space.removeEventListener( "touchcancel", @_mouseOut.bind(@) )
# ## A convenient method to convert the touch points in a touch event to an array of `Vectors`.
# @param evt a touch event which contains touches, changedTouches, and targetTouches list.
# @param which a string to select a touches list: "touches", "changedTouches", or "targetTouches". Default is "touches"
# @return an array of Vectors, whose origin position (0,0) is offset to the top-left of this space.
touchesToPoints: ( evt, which="touches" ) ->
if (!evt or !evt[which]) then return []
return ( new Vector(t.pageX - this.boundRect.left, t.pageY - this.boundRect.top) for t in evt[which] )
# go through all item in `items` and call its onMouseAction callback function
_mouseAction: (type, evt) ->
if (evt.touches || evt.changedTouches)
for k, v of @items
if v.onTouchAction?
_c = evt.changedTouches and evt.changedTouches.length > 0
px = if (_c) then evt.changedTouches.item(0).pageX else 0;
py = if (_c) then evt.changedTouches.item(0).pageY else 0;
v.onTouchAction( type, px, py, evt )
else
for k, v of @items
if v.onMouseAction?
px = evt.offsetX || evt.layerX;
py = evt.offsetY || evt.layerY;
v.onMouseAction( type, px, py, evt )
# mouse down action
_mouseDown: (evt) ->
@_mouseAction( "down", evt )
@_mdown = true
# mouse up action
_mouseUp: (evt) ->
@_mouseAction( "up", evt )
if @_mdrag then @_mouseAction( "drop", evt )
@_mdown = false
@_mdrag = false
# mouse move action
_mouseMove: (evt) ->
@_mouseAction( "move", evt )
if @_mdown
@_mdrag = true
@_mouseAction( "drag", evt )
# mouse over action
_mouseOver: (evt) ->
@_mouseAction( "over", evt )
# mouse out action
_mouseOut: (evt) ->
@_mouseAction( "out", evt )
if @_mdrag then @_mouseAction( "drop", evt )
@_mdrag = false
# namespace
this.Space = Space
| true | # ### Fishes forget their rivers and lakes, said PI:NAME:<NAME>END_PI. Spaces or contexts give meanings to ideas and lives, but are often overlooked. In Pt, space represents an abstract context in which a point can be made visible in one form or another, and can be specified as an html canvas, a soundscape, or a graffiti robot on a wall. Space is where a concept meets its expression.
class Space
# ## Create a Space which is the context for displaying and animating elements. Extend this to create specific Spaces, for example, a space for HTML Canvas or SVG.
# @param `id` an id property to identify this space
constructor : ( id ) ->
if typeof id != 'string' or id.length == 0
throw "id parameter is not valid"
return false
# ## A property to identify this space by name
@id = id
# ## A property to indicate the size of this space as a Vector
@size = new Vector()
# ## A property to indicate the center of this space as a Vector
@center = new Vector()
# animation properties
@_timePrev = 0 # record prev time
@_timeDiff = 0 # record prev time difference
@_timeEnd = -1 # end in milliseconds, -1 to play forever, 0 to end immediately
# ## A set of items in this space. An item should implement a function `animate()` and optionally another callback `onSpaceResize(w,h,evt)`, and will be assigned a property `animateID` automatically. (See `add()`)
@items = {}
# item properties
@_animID = -1
@_animCount = 0 # player key as increment
@_animPause = false
@_refresh = true # refresh on each frame
# ## set whether the rendering should be repainted on each frame
# @param `b` a boolean value to set whether to repaint each frame
# @demo space.refresh
# @return this space
refresh: (b) ->
@_refresh = b
return @
# ## set custom render function (on resize and other events)
# @return this space
render: ( context ) ->
return @
# ## resize the space. (not implemented)
resize: (w, h) ->
# ## clear all contents in the space (not implemented)
clear: () ->
# ## Add an item to this space. An item must define a callback function `animate( time, fps, context )` and will be assigned a property `animateID` automatically. An item can also optionally define a callback function `onSpaceResize( w, h, evt )`. Subclasses of Space may define other callback functions.
# @param an object with an `animate( time, fps, context )` function, and optionall a `onSpaceResize( w, h, evt )` function
# @demo space.add
# @return this space
add : (item) ->
if item.animate? and typeof item.animate is 'function'
k = @_animCount++
@items[k] = item
item.animateID = k
# if player has onSpaceResize defined, call the function
if item.onSpaceResize? then item.onSpaceResize(@size.x, @size.y)
else
throw "a player object for Space.add must define animate()"
return @
# ## Remove an item from this Space
# @param an object with an auto-assigned `animateID` property
# @return this space
remove : (item) ->
delete @items[ item.animateID ]
return @
# ## Remove all items from this Space
# @return this space
removeAll : () ->
@items = {}
return @
# ## Main play loop. This implements window.requestAnimationFrame and calls it recursively. Override this `play()` function to implemenet your own animation loop.
# @param `time` current time
# @return this space
play : (time=0) ->
# use fat arrow here, because rAF callback will change @ to window
@_animID = requestAnimationFrame( (t) => @play(t) )
# if pause
if @_animPause then return
# calc time passed since prev frame
@_timeDiff = time - @_timePrev
# animate this frame
try
@_playItems( time )
catch err
cancelAnimationFrame( @_animID )
console.error( err.stack )
throw err
# store time
@_timePrev = time
return @
# Main animate function. This calls all the items to perform
# @param `time` current time
# @return this space
_playItems : (time) ->
# clear before draw if refresh is true
if @_refresh then @clear()
# animate all players
for k, v of @items
v.animate( time, @_timeDiff, @ctx )
# stop if time ended
if @_timeEnd >= 0 and time > @_timeEnd
cancelAnimationFrame( @_animID )
return @
# ## Pause the animation
# @param `toggle` a boolean value to set if this function call should be a toggle (between pause and resume)
# @return this space
pause: ( toggle=false) ->
@_animPause = if toggle then !@_animPause else true
return @
# ## Resume the paused animation
# @return this space
resume: () ->
@_animPause = false
return @
# ## Specify when the animation should stop: immediately, after a time period, or never stops.
# @param `t` a value in millisecond to specify a time period to play before stopping, or `-1` to play forever, or `0` to end immediately. Default is 0 which will stop the animation immediately.
# @return this space
stop : ( t=0 ) ->
@_timeEnd = t
return @
# ## Play animation loop, and then stop after `duration` time has passed.
# @param `duration` a value in millisecond to specify a time period to play before stopping, or `-1` to play forever
playTime: (duration=5000) ->
@play()
@stop( duration )
# ## Bind event listener in canvas element, for events such as mouse events
# @param `evt` Event object
# @param `callback` a callback function for this event
bindCanvas: ( evt, callback ) ->
if @space.addEventListener then @space.addEventListener( evt, callback )
# ## A convenient method to bind (or unbind) all mouse events in canvas element. All item added to `items` property that implements an `onMouseAction` callback will receive mouse event callbacks. The types of mouse actions are: "up", "down", "move", "drag", "drop", "over", and "out".
# @param `bind` a boolean value to bind mouse events if set to `true`. If `false`, all mouse events will be unbound. Default is true.
# @demo canvasspace.bindMouse
bindMouse: ( _bind=true ) ->
if @space.addEventListener and @space.removeEventListener
if _bind
@space.addEventListener( "mousedown", @_mouseDown.bind(@) )
@space.addEventListener( "mouseup", @_mouseUp.bind(@) )
@space.addEventListener( "mouseover", @_mouseOver.bind(@) )
@space.addEventListener( "mouseout", @_mouseOut.bind(@) )
@space.addEventListener( "mousemove", @_mouseMove.bind(@) )
else
@space.removeEventListener( "mousedown", @_mouseDown.bind(@) )
@space.removeEventListener( "mouseup", @_mouseUp.bind(@) )
@space.removeEventListener( "mouseover", @_mouseOver.bind(@) )
@space.removeEventListener( "mouseout", @_mouseOut.bind(@) )
@space.removeEventListener( "mousemove", @_mouseMove.bind(@) )
# ## A convenient method to bind (or unbind) all mobile touch events in canvas element. All item added to `items` property that implements an `onTouchAction` callback will receive touch event callbacks. The types of touch actions are the same as the mouse actions: "up", "down", "move", and "out".
# @param `bind` a boolean value to bind touch events if set to `true`. If `false`, all touch events will be unbound. Default is true.
bindTouch: ( _bind=true ) ->
if @space.addEventListener and @space.removeEventListener
if _bind
@space.addEventListener( "touchstart", @_mouseDown.bind(@) )
@space.addEventListener( "touchend", @_mouseUp.bind(@) )
@space.addEventListener( "touchmove",
((evt) =>
evt.preventDefault();
@_mouseMove(evt)
) )
@space.addEventListener( "touchcancel", @_mouseOut.bind(@) )
else
@space.removeEventListener( "touchstart", @_mouseDown.bind(@) )
@space.removeEventListener( "touchend", @_mouseUp.bind(@) )
@space.removeEventListener( "touchmove", @_mouseMove.bind(@) )
@space.removeEventListener( "touchcancel", @_mouseOut.bind(@) )
# ## A convenient method to convert the touch points in a touch event to an array of `Vectors`.
# @param evt a touch event which contains touches, changedTouches, and targetTouches list.
# @param which a string to select a touches list: "touches", "changedTouches", or "targetTouches". Default is "touches"
# @return an array of Vectors, whose origin position (0,0) is offset to the top-left of this space.
touchesToPoints: ( evt, which="touches" ) ->
if (!evt or !evt[which]) then return []
return ( new Vector(t.pageX - this.boundRect.left, t.pageY - this.boundRect.top) for t in evt[which] )
# go through all item in `items` and call its onMouseAction callback function
_mouseAction: (type, evt) ->
if (evt.touches || evt.changedTouches)
for k, v of @items
if v.onTouchAction?
_c = evt.changedTouches and evt.changedTouches.length > 0
px = if (_c) then evt.changedTouches.item(0).pageX else 0;
py = if (_c) then evt.changedTouches.item(0).pageY else 0;
v.onTouchAction( type, px, py, evt )
else
for k, v of @items
if v.onMouseAction?
px = evt.offsetX || evt.layerX;
py = evt.offsetY || evt.layerY;
v.onMouseAction( type, px, py, evt )
# mouse down action
_mouseDown: (evt) ->
@_mouseAction( "down", evt )
@_mdown = true
# mouse up action
_mouseUp: (evt) ->
@_mouseAction( "up", evt )
if @_mdrag then @_mouseAction( "drop", evt )
@_mdown = false
@_mdrag = false
# mouse move action
_mouseMove: (evt) ->
@_mouseAction( "move", evt )
if @_mdown
@_mdrag = true
@_mouseAction( "drag", evt )
# mouse over action
_mouseOver: (evt) ->
@_mouseAction( "over", evt )
# mouse out action
_mouseOut: (evt) ->
@_mouseAction( "out", evt )
if @_mdrag then @_mouseAction( "drop", evt )
@_mdrag = false
# namespace
this.Space = Space
|
[
{
"context": "\t$ resin config write --type raspberry-pi username johndoe\n\t\t\t$ resin config write --type raspberry-pi --dri",
"end": 2141,
"score": 0.9989538192749023,
"start": 2134,
"tag": "USERNAME",
"value": "johndoe"
},
{
"context": "te --type raspberry-pi --drive /dev/disk2 username johndoe\n\t\t\t$ resin config write --type raspberry-pi files",
"end": 2221,
"score": 0.9988367557525635,
"start": 2214,
"tag": "USERNAME",
"value": "johndoe"
},
{
"context": "p MyApp --network wifi --wifiSsid mySsid --wifiKey abcdefgh --appUpdatePollInterval 1\n\t'''\n\toptions: [\n\t\tcomm",
"end": 7098,
"score": 0.9989531636238098,
"start": 7090,
"tag": "KEY",
"value": "abcdefgh"
}
] | lib/actions/config.coffee | vtmf/resion | 0 | ###
Copyright 2016-2017 Resin.io
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.
###
commandOptions = require('./command-options')
{ normalizeUuidProp } = require('../utils/normalization')
exports.read =
signature: 'config read'
description: 'read a device configuration'
help: '''
Use this command to read the config.json file from the mounted filesystem (e.g. SD card) of a provisioned device"
Examples:
$ resin config read --type raspberry-pi
$ resin config read --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
prettyjson = require('prettyjson')
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
return config.read(drive, options.type)
.tap (configJSON) ->
console.info(prettyjson.render(configJSON))
.nodeify(done)
exports.write =
signature: 'config write <key> <value>'
description: 'write a device configuration'
help: '''
Use this command to write the config.json file to the mounted filesystem (e.g. SD card) of a provisioned device
Examples:
$ resin config write --type raspberry-pi username johndoe
$ resin config write --type raspberry-pi --drive /dev/disk2 username johndoe
$ resin config write --type raspberry-pi files.network/settings "..."
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
_ = require('lodash')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
config.read(drive, options.type).then (configJSON) ->
console.info("Setting #{params.key} to #{params.value}")
_.set(configJSON, params.key, params.value)
return configJSON
.tap ->
return umountAsync(drive)
.then (configJSON) ->
return config.write(drive, options.type, configJSON)
.tap ->
console.info('Done')
.nodeify(done)
exports.inject =
signature: 'config inject <file>'
description: 'inject a device configuration file'
help: '''
Use this command to inject a config.json file to the mounted filesystem
(e.g. SD card or mounted resinOS image) of a provisioned device"
Examples:
$ resin config inject my/config.json --type raspberry-pi
$ resin config inject my/config.json --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
readFileAsync = Promise.promisify(require('fs').readFile)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
readFileAsync(params.file, 'utf8').then(JSON.parse).then (configJSON) ->
return config.write(drive, options.type, configJSON)
.tap ->
console.info('Done')
.nodeify(done)
exports.reconfigure =
signature: 'config reconfigure'
description: 'reconfigure a provisioned device'
help: '''
Use this command to reconfigure a provisioned device
Examples:
$ resin config reconfigure --type raspberry-pi
$ resin config reconfigure --type raspberry-pi --advanced
$ resin config reconfigure --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
{
signature: 'advanced'
description: 'show advanced commands'
boolean: true
alias: 'v'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
capitanoRunAsync = Promise.promisify(require('capitano').run)
umountAsync = Promise.promisify(require('umount').umount)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
config.read(drive, options.type).get('uuid')
.tap ->
umountAsync(drive)
.then (uuid) ->
configureCommand = "os configure #{drive} --device #{uuid}"
if options.advanced
configureCommand += ' --advanced'
return capitanoRunAsync(configureCommand)
.then ->
console.info('Done')
.nodeify(done)
exports.generate =
signature: 'config generate'
description: 'generate a config.json file'
help: '''
Use this command to generate a config.json for a device or application.
This is interactive by default, but you can do this automatically without interactivity
by specifying an option for each question on the command line, if you know the questions
that will be asked for the relevant device type.
Examples:
$ resin config generate --device 7cf02a6
$ resin config generate --device 7cf02a6 --generate-device-api-key
$ resin config generate --device 7cf02a6 --device-api-key <existingDeviceKey>
$ resin config generate --device 7cf02a6 --output config.json
$ resin config generate --app MyApp
$ resin config generate --app MyApp --output config.json
$ resin config generate --app MyApp --network wifi --wifiSsid mySsid --wifiKey abcdefgh --appUpdatePollInterval 1
'''
options: [
commandOptions.optionalApplication
commandOptions.optionalDevice
commandOptions.optionalDeviceApiKey
{
signature: 'generate-device-api-key'
description: 'generate a fresh device key for the device'
boolean: true
}
{
signature: 'output'
description: 'output'
parameter: 'output'
alias: 'o'
}
# Options for non-interactive configuration
{
signature: 'network'
description: 'the network type to use: ethernet or wifi'
parameter: 'network'
}
{
signature: 'wifiSsid'
description: 'the wifi ssid to use (used only if --network is set to wifi)'
parameter: 'wifiSsid'
}
{
signature: 'wifiKey'
description: 'the wifi key to use (used only if --network is set to wifi)'
parameter: 'wifiKey'
}
{
signature: 'appUpdatePollInterval'
description: 'how frequently (in minutes) to poll for application updates'
parameter: 'appUpdatePollInterval'
}
]
permission: 'user'
action: (params, options, done) ->
normalizeUuidProp(options, 'device')
Promise = require('bluebird')
writeFileAsync = Promise.promisify(require('fs').writeFile)
resin = require('resin-sdk-preconfigured')
form = require('resin-cli-form')
deviceConfig = require('resin-device-config')
prettyjson = require('prettyjson')
{ generateDeviceConfig, generateApplicationConfig } = require('../utils/config')
{ exitWithExpectedError } = require('../utils/patterns')
if not options.device? and not options.application?
exitWithExpectedError '''
You have to pass either a device or an application.
See the help page for examples:
$ resin help config generate
'''
Promise.try ->
if options.device?
return resin.models.device.get(options.device)
return resin.models.application.get(options.application)
.then (resource) ->
resin.models.device.getManifestBySlug(resource.device_type)
.get('options')
.then (formOptions) ->
# Pass params as an override: if there is any param with exactly the same name as a
# required option, that value is used (and the corresponding question is not asked)
form.run(formOptions, override: options)
.then (answers) ->
if resource.uuid?
generateDeviceConfig(resource, options.deviceApiKey || options['generate-device-api-key'], answers)
else
generateApplicationConfig(resource, answers)
.then (config) ->
deviceConfig.validate(config)
if options.output?
return writeFileAsync(options.output, JSON.stringify(config))
console.log(prettyjson.render(config))
.nodeify(done)
| 21796 | ###
Copyright 2016-2017 Resin.io
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.
###
commandOptions = require('./command-options')
{ normalizeUuidProp } = require('../utils/normalization')
exports.read =
signature: 'config read'
description: 'read a device configuration'
help: '''
Use this command to read the config.json file from the mounted filesystem (e.g. SD card) of a provisioned device"
Examples:
$ resin config read --type raspberry-pi
$ resin config read --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
prettyjson = require('prettyjson')
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
return config.read(drive, options.type)
.tap (configJSON) ->
console.info(prettyjson.render(configJSON))
.nodeify(done)
exports.write =
signature: 'config write <key> <value>'
description: 'write a device configuration'
help: '''
Use this command to write the config.json file to the mounted filesystem (e.g. SD card) of a provisioned device
Examples:
$ resin config write --type raspberry-pi username johndoe
$ resin config write --type raspberry-pi --drive /dev/disk2 username johndoe
$ resin config write --type raspberry-pi files.network/settings "..."
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
_ = require('lodash')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
config.read(drive, options.type).then (configJSON) ->
console.info("Setting #{params.key} to #{params.value}")
_.set(configJSON, params.key, params.value)
return configJSON
.tap ->
return umountAsync(drive)
.then (configJSON) ->
return config.write(drive, options.type, configJSON)
.tap ->
console.info('Done')
.nodeify(done)
exports.inject =
signature: 'config inject <file>'
description: 'inject a device configuration file'
help: '''
Use this command to inject a config.json file to the mounted filesystem
(e.g. SD card or mounted resinOS image) of a provisioned device"
Examples:
$ resin config inject my/config.json --type raspberry-pi
$ resin config inject my/config.json --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
readFileAsync = Promise.promisify(require('fs').readFile)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
readFileAsync(params.file, 'utf8').then(JSON.parse).then (configJSON) ->
return config.write(drive, options.type, configJSON)
.tap ->
console.info('Done')
.nodeify(done)
exports.reconfigure =
signature: 'config reconfigure'
description: 'reconfigure a provisioned device'
help: '''
Use this command to reconfigure a provisioned device
Examples:
$ resin config reconfigure --type raspberry-pi
$ resin config reconfigure --type raspberry-pi --advanced
$ resin config reconfigure --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
{
signature: 'advanced'
description: 'show advanced commands'
boolean: true
alias: 'v'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
capitanoRunAsync = Promise.promisify(require('capitano').run)
umountAsync = Promise.promisify(require('umount').umount)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
config.read(drive, options.type).get('uuid')
.tap ->
umountAsync(drive)
.then (uuid) ->
configureCommand = "os configure #{drive} --device #{uuid}"
if options.advanced
configureCommand += ' --advanced'
return capitanoRunAsync(configureCommand)
.then ->
console.info('Done')
.nodeify(done)
exports.generate =
signature: 'config generate'
description: 'generate a config.json file'
help: '''
Use this command to generate a config.json for a device or application.
This is interactive by default, but you can do this automatically without interactivity
by specifying an option for each question on the command line, if you know the questions
that will be asked for the relevant device type.
Examples:
$ resin config generate --device 7cf02a6
$ resin config generate --device 7cf02a6 --generate-device-api-key
$ resin config generate --device 7cf02a6 --device-api-key <existingDeviceKey>
$ resin config generate --device 7cf02a6 --output config.json
$ resin config generate --app MyApp
$ resin config generate --app MyApp --output config.json
$ resin config generate --app MyApp --network wifi --wifiSsid mySsid --wifiKey <KEY> --appUpdatePollInterval 1
'''
options: [
commandOptions.optionalApplication
commandOptions.optionalDevice
commandOptions.optionalDeviceApiKey
{
signature: 'generate-device-api-key'
description: 'generate a fresh device key for the device'
boolean: true
}
{
signature: 'output'
description: 'output'
parameter: 'output'
alias: 'o'
}
# Options for non-interactive configuration
{
signature: 'network'
description: 'the network type to use: ethernet or wifi'
parameter: 'network'
}
{
signature: 'wifiSsid'
description: 'the wifi ssid to use (used only if --network is set to wifi)'
parameter: 'wifiSsid'
}
{
signature: 'wifiKey'
description: 'the wifi key to use (used only if --network is set to wifi)'
parameter: 'wifiKey'
}
{
signature: 'appUpdatePollInterval'
description: 'how frequently (in minutes) to poll for application updates'
parameter: 'appUpdatePollInterval'
}
]
permission: 'user'
action: (params, options, done) ->
normalizeUuidProp(options, 'device')
Promise = require('bluebird')
writeFileAsync = Promise.promisify(require('fs').writeFile)
resin = require('resin-sdk-preconfigured')
form = require('resin-cli-form')
deviceConfig = require('resin-device-config')
prettyjson = require('prettyjson')
{ generateDeviceConfig, generateApplicationConfig } = require('../utils/config')
{ exitWithExpectedError } = require('../utils/patterns')
if not options.device? and not options.application?
exitWithExpectedError '''
You have to pass either a device or an application.
See the help page for examples:
$ resin help config generate
'''
Promise.try ->
if options.device?
return resin.models.device.get(options.device)
return resin.models.application.get(options.application)
.then (resource) ->
resin.models.device.getManifestBySlug(resource.device_type)
.get('options')
.then (formOptions) ->
# Pass params as an override: if there is any param with exactly the same name as a
# required option, that value is used (and the corresponding question is not asked)
form.run(formOptions, override: options)
.then (answers) ->
if resource.uuid?
generateDeviceConfig(resource, options.deviceApiKey || options['generate-device-api-key'], answers)
else
generateApplicationConfig(resource, answers)
.then (config) ->
deviceConfig.validate(config)
if options.output?
return writeFileAsync(options.output, JSON.stringify(config))
console.log(prettyjson.render(config))
.nodeify(done)
| true | ###
Copyright 2016-2017 Resin.io
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.
###
commandOptions = require('./command-options')
{ normalizeUuidProp } = require('../utils/normalization')
exports.read =
signature: 'config read'
description: 'read a device configuration'
help: '''
Use this command to read the config.json file from the mounted filesystem (e.g. SD card) of a provisioned device"
Examples:
$ resin config read --type raspberry-pi
$ resin config read --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
prettyjson = require('prettyjson')
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
return config.read(drive, options.type)
.tap (configJSON) ->
console.info(prettyjson.render(configJSON))
.nodeify(done)
exports.write =
signature: 'config write <key> <value>'
description: 'write a device configuration'
help: '''
Use this command to write the config.json file to the mounted filesystem (e.g. SD card) of a provisioned device
Examples:
$ resin config write --type raspberry-pi username johndoe
$ resin config write --type raspberry-pi --drive /dev/disk2 username johndoe
$ resin config write --type raspberry-pi files.network/settings "..."
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
_ = require('lodash')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
config.read(drive, options.type).then (configJSON) ->
console.info("Setting #{params.key} to #{params.value}")
_.set(configJSON, params.key, params.value)
return configJSON
.tap ->
return umountAsync(drive)
.then (configJSON) ->
return config.write(drive, options.type, configJSON)
.tap ->
console.info('Done')
.nodeify(done)
exports.inject =
signature: 'config inject <file>'
description: 'inject a device configuration file'
help: '''
Use this command to inject a config.json file to the mounted filesystem
(e.g. SD card or mounted resinOS image) of a provisioned device"
Examples:
$ resin config inject my/config.json --type raspberry-pi
$ resin config inject my/config.json --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
umountAsync = Promise.promisify(require('umount').umount)
readFileAsync = Promise.promisify(require('fs').readFile)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
readFileAsync(params.file, 'utf8').then(JSON.parse).then (configJSON) ->
return config.write(drive, options.type, configJSON)
.tap ->
console.info('Done')
.nodeify(done)
exports.reconfigure =
signature: 'config reconfigure'
description: 'reconfigure a provisioned device'
help: '''
Use this command to reconfigure a provisioned device
Examples:
$ resin config reconfigure --type raspberry-pi
$ resin config reconfigure --type raspberry-pi --advanced
$ resin config reconfigure --type raspberry-pi --drive /dev/disk2
'''
options: [
{
signature: 'type'
description: 'device type (Check available types with `resin devices supported`)'
parameter: 'type'
alias: 't'
required: 'You have to specify a device type'
}
{
signature: 'drive'
description: 'drive'
parameter: 'drive'
alias: 'd'
}
{
signature: 'advanced'
description: 'show advanced commands'
boolean: true
alias: 'v'
}
]
permission: 'user'
root: true
action: (params, options, done) ->
Promise = require('bluebird')
config = require('resin-config-json')
visuals = require('resin-cli-visuals')
capitanoRunAsync = Promise.promisify(require('capitano').run)
umountAsync = Promise.promisify(require('umount').umount)
Promise.try ->
return options.drive or visuals.drive('Select the device drive')
.tap(umountAsync)
.then (drive) ->
config.read(drive, options.type).get('uuid')
.tap ->
umountAsync(drive)
.then (uuid) ->
configureCommand = "os configure #{drive} --device #{uuid}"
if options.advanced
configureCommand += ' --advanced'
return capitanoRunAsync(configureCommand)
.then ->
console.info('Done')
.nodeify(done)
exports.generate =
signature: 'config generate'
description: 'generate a config.json file'
help: '''
Use this command to generate a config.json for a device or application.
This is interactive by default, but you can do this automatically without interactivity
by specifying an option for each question on the command line, if you know the questions
that will be asked for the relevant device type.
Examples:
$ resin config generate --device 7cf02a6
$ resin config generate --device 7cf02a6 --generate-device-api-key
$ resin config generate --device 7cf02a6 --device-api-key <existingDeviceKey>
$ resin config generate --device 7cf02a6 --output config.json
$ resin config generate --app MyApp
$ resin config generate --app MyApp --output config.json
$ resin config generate --app MyApp --network wifi --wifiSsid mySsid --wifiKey PI:KEY:<KEY>END_PI --appUpdatePollInterval 1
'''
options: [
commandOptions.optionalApplication
commandOptions.optionalDevice
commandOptions.optionalDeviceApiKey
{
signature: 'generate-device-api-key'
description: 'generate a fresh device key for the device'
boolean: true
}
{
signature: 'output'
description: 'output'
parameter: 'output'
alias: 'o'
}
# Options for non-interactive configuration
{
signature: 'network'
description: 'the network type to use: ethernet or wifi'
parameter: 'network'
}
{
signature: 'wifiSsid'
description: 'the wifi ssid to use (used only if --network is set to wifi)'
parameter: 'wifiSsid'
}
{
signature: 'wifiKey'
description: 'the wifi key to use (used only if --network is set to wifi)'
parameter: 'wifiKey'
}
{
signature: 'appUpdatePollInterval'
description: 'how frequently (in minutes) to poll for application updates'
parameter: 'appUpdatePollInterval'
}
]
permission: 'user'
action: (params, options, done) ->
normalizeUuidProp(options, 'device')
Promise = require('bluebird')
writeFileAsync = Promise.promisify(require('fs').writeFile)
resin = require('resin-sdk-preconfigured')
form = require('resin-cli-form')
deviceConfig = require('resin-device-config')
prettyjson = require('prettyjson')
{ generateDeviceConfig, generateApplicationConfig } = require('../utils/config')
{ exitWithExpectedError } = require('../utils/patterns')
if not options.device? and not options.application?
exitWithExpectedError '''
You have to pass either a device or an application.
See the help page for examples:
$ resin help config generate
'''
Promise.try ->
if options.device?
return resin.models.device.get(options.device)
return resin.models.application.get(options.application)
.then (resource) ->
resin.models.device.getManifestBySlug(resource.device_type)
.get('options')
.then (formOptions) ->
# Pass params as an override: if there is any param with exactly the same name as a
# required option, that value is used (and the corresponding question is not asked)
form.run(formOptions, override: options)
.then (answers) ->
if resource.uuid?
generateDeviceConfig(resource, options.deviceApiKey || options['generate-device-api-key'], answers)
else
generateApplicationConfig(resource, answers)
.then (config) ->
deviceConfig.validate(config)
if options.output?
return writeFileAsync(options.output, JSON.stringify(config))
console.log(prettyjson.render(config))
.nodeify(done)
|
[
{
"context": " -> expect(@subject.raw).toEqual\n author: \"Full Name\"\n authorUrl: \"https://twitter.com/fullname",
"end": 329,
"score": 0.9929788112640381,
"start": 320,
"tag": "NAME",
"value": "Full Name"
},
{
"context": "ull Name\"\n authorUrl: \"https://twitter.com/fullname\"\n title: \"my blog\"\n description: \"t",
"end": 379,
"score": 0.999596893787384,
"start": 371,
"tag": "USERNAME",
"value": "fullname"
}
] | spec/config_spec.coffee | testdouble/grunt-markdown-blog | 12 | Config = require("../lib/config")
describe "Config", ->
Given -> @options = layouts: {}, paths: {}, pathRoots: {}
When -> @subject = new Config(@options)
describe "#constructor", ->
describe "has defaults", ->
When -> @subject = new Config()
Then -> expect(@subject.raw).toEqual
author: "Full Name"
authorUrl: "https://twitter.com/fullname"
title: "my blog"
description: "the blog where I write things"
url: "https://www.myblog.com"
feedCount: 10
dateFormat: "MMMM Do YYYY"
layouts:
wrapper: "app/templates/wrapper.pug"
index: "app/templates/index.pug"
post: "app/templates/post.pug"
page: "app/templates/page.pug"
archive: "app/templates/archive.pug"
paths:
posts: "app/posts/*.md"
pages: "app/pages/**/*.md"
index: "index.html"
archive: "archive.html"
rss: "index.xml"
json: "index.json"
pathRoots:
posts: "posts"
pages: "pages"
dest: "dist"
context:
js: "app.js"
css: "app.css"
describe "does not merge recursively", ->
Given -> Config.defaults =
author: "author"
description: "description"
layouts:
wrapper: "wrapper.pug"
index: "index.pug"
post: "post.pug"
page: "page.pug"
archive: "archive.pug"
When -> @subject = new Config
author: "top level"
layouts:
wrapper: "string"
index: undefined
post: null
page: false
archive: undefined
Then -> expect(@subject.raw).toEqual
author: "top level"
description: "description"
layouts:
wrapper: "string"
index: undefined
post: null
page: false
archive: undefined
describe "#forArchive", ->
Given -> @options.paths.archive = @htmlPath = "htmlPath"
Given -> @options.layouts.archive = @layoutPath = "layoutPath"
When -> @archiveConfig = @subject.forArchive()
Then -> expect(@archiveConfig).toEqual {@htmlPath, @layoutPath}
describe "#forFeed", ->
Given -> @options.paths.rss = @rssPath = "some/path"
Given -> @options.feedCount = @postCount = 2
When -> @feedConfig = @subject.forFeed()
Then -> expect(@feedConfig).toEqual {@rssPath, @postCount}
describe "#forIndex", ->
Given -> @options.paths.index = @htmlPath = "htmlPath"
Given -> @options.layouts.index = @layoutPath = "layoutPath"
When -> @indexConfig = @subject.forIndex()
Then -> expect(@indexConfig).toEqual {@htmlPath, @layoutPath}
describe "#forPages", ->
Given -> @options.pathRoots.pages = @htmlDir = "htmlDir"
Given -> @options.layouts.page = @layoutPath = "layoutPath"
When -> @pagesConfig = @subject.forPages()
context "with single page source", ->
Given -> @options.paths.pages = @path = "some/path/**/*"
Then -> expect(@pagesConfig).toEqual {
@htmlDir
@layoutPath
src: [@path]
}
context "with multiple page sources", ->
Given -> @options.paths.pages = ["a", null, undefined, "", "b"]
Then -> expect(@pagesConfig).toEqual {
@htmlDir
@layoutPath
src: ["a", "b"]
}
describe "#forPosts", ->
Given -> @options.pathRoots.posts = @htmlDir = "htmlDir"
Given -> @options.layouts.post = @layoutPath = "layoutPath"
Given -> @options.dateFormat = @dateFormat = "dateFormat"
When -> @postsConfig = @subject.forPosts()
context "with single post source", ->
Given -> @options.paths.posts = @path = "some/path/**/*"
Then -> expect(@postsConfig).toEqual {
@htmlDir
@layoutPath
@dateFormat
src: [@path]
}
context "with multiple post sources", ->
Given -> @options.paths.posts = ["a", null, undefined, "", "b"]
Then -> expect(@postsConfig).toEqual {
@htmlDir
@layoutPath
@dateFormat
src: ["a", "b"]
}
describe "#forSiteWrapper", ->
Given -> @options.layouts.wrapper = @layoutPath = "wrapper"
Given -> @options.context = @context = "context"
When -> @wrapperConfig = @subject.forSiteWrapper()
Then -> expect(@wrapperConfig).toEqual {@layoutPath, @context}
describe "#destDir", ->
Given -> @options.dest = @dest = "dest"
When -> @destDir = @subject.destDir()
Then -> @destDir == @dest
| 180963 | Config = require("../lib/config")
describe "Config", ->
Given -> @options = layouts: {}, paths: {}, pathRoots: {}
When -> @subject = new Config(@options)
describe "#constructor", ->
describe "has defaults", ->
When -> @subject = new Config()
Then -> expect(@subject.raw).toEqual
author: "<NAME>"
authorUrl: "https://twitter.com/fullname"
title: "my blog"
description: "the blog where I write things"
url: "https://www.myblog.com"
feedCount: 10
dateFormat: "MMMM Do YYYY"
layouts:
wrapper: "app/templates/wrapper.pug"
index: "app/templates/index.pug"
post: "app/templates/post.pug"
page: "app/templates/page.pug"
archive: "app/templates/archive.pug"
paths:
posts: "app/posts/*.md"
pages: "app/pages/**/*.md"
index: "index.html"
archive: "archive.html"
rss: "index.xml"
json: "index.json"
pathRoots:
posts: "posts"
pages: "pages"
dest: "dist"
context:
js: "app.js"
css: "app.css"
describe "does not merge recursively", ->
Given -> Config.defaults =
author: "author"
description: "description"
layouts:
wrapper: "wrapper.pug"
index: "index.pug"
post: "post.pug"
page: "page.pug"
archive: "archive.pug"
When -> @subject = new Config
author: "top level"
layouts:
wrapper: "string"
index: undefined
post: null
page: false
archive: undefined
Then -> expect(@subject.raw).toEqual
author: "top level"
description: "description"
layouts:
wrapper: "string"
index: undefined
post: null
page: false
archive: undefined
describe "#forArchive", ->
Given -> @options.paths.archive = @htmlPath = "htmlPath"
Given -> @options.layouts.archive = @layoutPath = "layoutPath"
When -> @archiveConfig = @subject.forArchive()
Then -> expect(@archiveConfig).toEqual {@htmlPath, @layoutPath}
describe "#forFeed", ->
Given -> @options.paths.rss = @rssPath = "some/path"
Given -> @options.feedCount = @postCount = 2
When -> @feedConfig = @subject.forFeed()
Then -> expect(@feedConfig).toEqual {@rssPath, @postCount}
describe "#forIndex", ->
Given -> @options.paths.index = @htmlPath = "htmlPath"
Given -> @options.layouts.index = @layoutPath = "layoutPath"
When -> @indexConfig = @subject.forIndex()
Then -> expect(@indexConfig).toEqual {@htmlPath, @layoutPath}
describe "#forPages", ->
Given -> @options.pathRoots.pages = @htmlDir = "htmlDir"
Given -> @options.layouts.page = @layoutPath = "layoutPath"
When -> @pagesConfig = @subject.forPages()
context "with single page source", ->
Given -> @options.paths.pages = @path = "some/path/**/*"
Then -> expect(@pagesConfig).toEqual {
@htmlDir
@layoutPath
src: [@path]
}
context "with multiple page sources", ->
Given -> @options.paths.pages = ["a", null, undefined, "", "b"]
Then -> expect(@pagesConfig).toEqual {
@htmlDir
@layoutPath
src: ["a", "b"]
}
describe "#forPosts", ->
Given -> @options.pathRoots.posts = @htmlDir = "htmlDir"
Given -> @options.layouts.post = @layoutPath = "layoutPath"
Given -> @options.dateFormat = @dateFormat = "dateFormat"
When -> @postsConfig = @subject.forPosts()
context "with single post source", ->
Given -> @options.paths.posts = @path = "some/path/**/*"
Then -> expect(@postsConfig).toEqual {
@htmlDir
@layoutPath
@dateFormat
src: [@path]
}
context "with multiple post sources", ->
Given -> @options.paths.posts = ["a", null, undefined, "", "b"]
Then -> expect(@postsConfig).toEqual {
@htmlDir
@layoutPath
@dateFormat
src: ["a", "b"]
}
describe "#forSiteWrapper", ->
Given -> @options.layouts.wrapper = @layoutPath = "wrapper"
Given -> @options.context = @context = "context"
When -> @wrapperConfig = @subject.forSiteWrapper()
Then -> expect(@wrapperConfig).toEqual {@layoutPath, @context}
describe "#destDir", ->
Given -> @options.dest = @dest = "dest"
When -> @destDir = @subject.destDir()
Then -> @destDir == @dest
| true | Config = require("../lib/config")
describe "Config", ->
Given -> @options = layouts: {}, paths: {}, pathRoots: {}
When -> @subject = new Config(@options)
describe "#constructor", ->
describe "has defaults", ->
When -> @subject = new Config()
Then -> expect(@subject.raw).toEqual
author: "PI:NAME:<NAME>END_PI"
authorUrl: "https://twitter.com/fullname"
title: "my blog"
description: "the blog where I write things"
url: "https://www.myblog.com"
feedCount: 10
dateFormat: "MMMM Do YYYY"
layouts:
wrapper: "app/templates/wrapper.pug"
index: "app/templates/index.pug"
post: "app/templates/post.pug"
page: "app/templates/page.pug"
archive: "app/templates/archive.pug"
paths:
posts: "app/posts/*.md"
pages: "app/pages/**/*.md"
index: "index.html"
archive: "archive.html"
rss: "index.xml"
json: "index.json"
pathRoots:
posts: "posts"
pages: "pages"
dest: "dist"
context:
js: "app.js"
css: "app.css"
describe "does not merge recursively", ->
Given -> Config.defaults =
author: "author"
description: "description"
layouts:
wrapper: "wrapper.pug"
index: "index.pug"
post: "post.pug"
page: "page.pug"
archive: "archive.pug"
When -> @subject = new Config
author: "top level"
layouts:
wrapper: "string"
index: undefined
post: null
page: false
archive: undefined
Then -> expect(@subject.raw).toEqual
author: "top level"
description: "description"
layouts:
wrapper: "string"
index: undefined
post: null
page: false
archive: undefined
describe "#forArchive", ->
Given -> @options.paths.archive = @htmlPath = "htmlPath"
Given -> @options.layouts.archive = @layoutPath = "layoutPath"
When -> @archiveConfig = @subject.forArchive()
Then -> expect(@archiveConfig).toEqual {@htmlPath, @layoutPath}
describe "#forFeed", ->
Given -> @options.paths.rss = @rssPath = "some/path"
Given -> @options.feedCount = @postCount = 2
When -> @feedConfig = @subject.forFeed()
Then -> expect(@feedConfig).toEqual {@rssPath, @postCount}
describe "#forIndex", ->
Given -> @options.paths.index = @htmlPath = "htmlPath"
Given -> @options.layouts.index = @layoutPath = "layoutPath"
When -> @indexConfig = @subject.forIndex()
Then -> expect(@indexConfig).toEqual {@htmlPath, @layoutPath}
describe "#forPages", ->
Given -> @options.pathRoots.pages = @htmlDir = "htmlDir"
Given -> @options.layouts.page = @layoutPath = "layoutPath"
When -> @pagesConfig = @subject.forPages()
context "with single page source", ->
Given -> @options.paths.pages = @path = "some/path/**/*"
Then -> expect(@pagesConfig).toEqual {
@htmlDir
@layoutPath
src: [@path]
}
context "with multiple page sources", ->
Given -> @options.paths.pages = ["a", null, undefined, "", "b"]
Then -> expect(@pagesConfig).toEqual {
@htmlDir
@layoutPath
src: ["a", "b"]
}
describe "#forPosts", ->
Given -> @options.pathRoots.posts = @htmlDir = "htmlDir"
Given -> @options.layouts.post = @layoutPath = "layoutPath"
Given -> @options.dateFormat = @dateFormat = "dateFormat"
When -> @postsConfig = @subject.forPosts()
context "with single post source", ->
Given -> @options.paths.posts = @path = "some/path/**/*"
Then -> expect(@postsConfig).toEqual {
@htmlDir
@layoutPath
@dateFormat
src: [@path]
}
context "with multiple post sources", ->
Given -> @options.paths.posts = ["a", null, undefined, "", "b"]
Then -> expect(@postsConfig).toEqual {
@htmlDir
@layoutPath
@dateFormat
src: ["a", "b"]
}
describe "#forSiteWrapper", ->
Given -> @options.layouts.wrapper = @layoutPath = "wrapper"
Given -> @options.context = @context = "context"
When -> @wrapperConfig = @subject.forSiteWrapper()
Then -> expect(@wrapperConfig).toEqual {@layoutPath, @context}
describe "#destDir", ->
Given -> @options.dest = @dest = "dest"
When -> @destDir = @subject.destDir()
Then -> @destDir == @dest
|
[
{
"context": "binddn: 'cn=admin,dc=example,dc=org'\n passwd: 'admin'\n config:\n binddn: 'cn=admin,cn=config'\n ",
"end": 213,
"score": 0.9967052340507507,
"start": 208,
"tag": "PASSWORD",
"value": "admin"
},
{
"context": " binddn: 'cn=admin,cn=config'\n passwd: 'config'\n suffix_dn: 'dc=example,dc=org'\n config: [\n ",
"end": 283,
"score": 0.9974155426025391,
"start": 277,
"tag": "PASSWORD",
"value": "config"
},
{
"context": "al'\n ,\n label: 'remote'\n ssh:\n host: '127.0.0.1', username: process.env.USER,\n private_key_p",
"end": 406,
"score": 0.9997504353523254,
"start": 397,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | packages/ldap/env/openldap/test.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
module.exports =
tags:
api: true
ldap: true
ldap_acl: true
ldap_index: true
ldap_user: true
ldap:
uri: 'ldap://openldap:389'
binddn: 'cn=admin,dc=example,dc=org'
passwd: 'admin'
config:
binddn: 'cn=admin,cn=config'
passwd: 'config'
suffix_dn: 'dc=example,dc=org'
config: [
label: 'local'
,
label: 'remote'
ssh:
host: '127.0.0.1', username: process.env.USER,
private_key_path: '~/.ssh/id_rsa'
]
| 191649 |
module.exports =
tags:
api: true
ldap: true
ldap_acl: true
ldap_index: true
ldap_user: true
ldap:
uri: 'ldap://openldap:389'
binddn: 'cn=admin,dc=example,dc=org'
passwd: '<PASSWORD>'
config:
binddn: 'cn=admin,cn=config'
passwd: '<PASSWORD>'
suffix_dn: 'dc=example,dc=org'
config: [
label: 'local'
,
label: 'remote'
ssh:
host: '127.0.0.1', username: process.env.USER,
private_key_path: '~/.ssh/id_rsa'
]
| true |
module.exports =
tags:
api: true
ldap: true
ldap_acl: true
ldap_index: true
ldap_user: true
ldap:
uri: 'ldap://openldap:389'
binddn: 'cn=admin,dc=example,dc=org'
passwd: 'PI:PASSWORD:<PASSWORD>END_PI'
config:
binddn: 'cn=admin,cn=config'
passwd: 'PI:PASSWORD:<PASSWORD>END_PI'
suffix_dn: 'dc=example,dc=org'
config: [
label: 'local'
,
label: 'remote'
ssh:
host: '127.0.0.1', username: process.env.USER,
private_key_path: '~/.ssh/id_rsa'
]
|
[
{
"context": "->\n @blipData =\n name: 'name'\n snapshot:\n wa",
"end": 309,
"score": 0.6085079312324524,
"start": 305,
"tag": "NAME",
"value": "name"
}
] | src/tests/client/blip/test_model.coffee | LaPingvino/rizzoma | 88 | sinon = require('sinon')
testCase = require('nodeunit').testCase
Request = require('../../../share/communication').Request
BlipModel = require('../../../client/blip/model').BlipModel
module.exports =
BlipModelTest: testCase
setUp: (callback) ->
@blipData =
name: 'name'
snapshot:
waveId: 'waveId'
submitOp: ->
callback()
tearDown: (callback) ->
callback()
testInit: (test) ->
blipModel = new BlipModel @blipData
test.equal blipModel.id, @blipData.name
test.equal blipModel.waveId, @blipData.snapshot.waveId
test.equal blipModel._doc, @blipData
test.done()
testSubmitOps: (test) ->
blipModel = new BlipModel @blipData
ops = [
{p: [0], x: 'x'},
{p: [1], y: 1},
{p: ['2'], z: 'z'},
{p: [3], a: {a: 'a'}},
{p: [4], b: {b: {c: {d: 'd'}}}}
]
blipDataMock = sinon.mock @blipData
blipDataMock
.expects('submitOp')
.withArgs([
{p: ['content', 0], x: 'x'},
{p: ['content', 1], y: 1},
{p: ['content', '2'], z: 'z'},
{p: ['content', 3], a: {a: 'a'}},
{p: ['content', 4], b: {b: {c: {d: 'd'}}}}
])
blipModel.submitOps(ops)
blipDataMock.verify()
blipDataMock.restore()
test.done()
| 205928 | sinon = require('sinon')
testCase = require('nodeunit').testCase
Request = require('../../../share/communication').Request
BlipModel = require('../../../client/blip/model').BlipModel
module.exports =
BlipModelTest: testCase
setUp: (callback) ->
@blipData =
name: '<NAME>'
snapshot:
waveId: 'waveId'
submitOp: ->
callback()
tearDown: (callback) ->
callback()
testInit: (test) ->
blipModel = new BlipModel @blipData
test.equal blipModel.id, @blipData.name
test.equal blipModel.waveId, @blipData.snapshot.waveId
test.equal blipModel._doc, @blipData
test.done()
testSubmitOps: (test) ->
blipModel = new BlipModel @blipData
ops = [
{p: [0], x: 'x'},
{p: [1], y: 1},
{p: ['2'], z: 'z'},
{p: [3], a: {a: 'a'}},
{p: [4], b: {b: {c: {d: 'd'}}}}
]
blipDataMock = sinon.mock @blipData
blipDataMock
.expects('submitOp')
.withArgs([
{p: ['content', 0], x: 'x'},
{p: ['content', 1], y: 1},
{p: ['content', '2'], z: 'z'},
{p: ['content', 3], a: {a: 'a'}},
{p: ['content', 4], b: {b: {c: {d: 'd'}}}}
])
blipModel.submitOps(ops)
blipDataMock.verify()
blipDataMock.restore()
test.done()
| true | sinon = require('sinon')
testCase = require('nodeunit').testCase
Request = require('../../../share/communication').Request
BlipModel = require('../../../client/blip/model').BlipModel
module.exports =
BlipModelTest: testCase
setUp: (callback) ->
@blipData =
name: 'PI:NAME:<NAME>END_PI'
snapshot:
waveId: 'waveId'
submitOp: ->
callback()
tearDown: (callback) ->
callback()
testInit: (test) ->
blipModel = new BlipModel @blipData
test.equal blipModel.id, @blipData.name
test.equal blipModel.waveId, @blipData.snapshot.waveId
test.equal blipModel._doc, @blipData
test.done()
testSubmitOps: (test) ->
blipModel = new BlipModel @blipData
ops = [
{p: [0], x: 'x'},
{p: [1], y: 1},
{p: ['2'], z: 'z'},
{p: [3], a: {a: 'a'}},
{p: [4], b: {b: {c: {d: 'd'}}}}
]
blipDataMock = sinon.mock @blipData
blipDataMock
.expects('submitOp')
.withArgs([
{p: ['content', 0], x: 'x'},
{p: ['content', 1], y: 1},
{p: ['content', '2'], z: 'z'},
{p: ['content', 3], a: {a: 'a'}},
{p: ['content', 4], b: {b: {c: {d: 'd'}}}}
])
blipModel.submitOps(ops)
blipDataMock.verify()
blipDataMock.restore()
test.done()
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.999862790107727,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | vendor/assets/javascripts/hallo/widgets/dropdownbutton.coffee | spanner/bop | 0 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallodropdownbutton',
button: null
options:
uuid: ''
label: null
icon: null
editable: null
target: ''
cssClass: null
_create: ->
@options.icon ?= "icon-#{@options.label.toLowerCase()}"
_init: ->
target = jQuery @options.target
target.css 'position', 'absolute'
target.addClass 'dropdown-menu'
target.hide()
@button = @_prepareButton() unless @button
@button.bind 'click', =>
if target.hasClass 'open'
@_hideTarget()
return
@_showTarget()
target.bind 'click', =>
@_hideTarget()
@options.editable.element.bind 'hallodeactivated', =>
@_hideTarget()
@element.append @button
_showTarget: ->
target = jQuery @options.target
@_updateTargetPosition()
target.addClass 'open'
console.log "showtarget", @button, target
@button.find('.icon-caret-right').removeClass('icon-caret-right').addClass('icon-caret-down')
target.show()
_hideTarget: ->
target = jQuery @options.target
target.removeClass 'open'
@button.find('.icon-caret-down').removeClass('icon-caret-down').addClass('icon-caret-right')
target.hide()
_updateTargetPosition: ->
target = jQuery @options.target
{top, left} = @button.position()
top += @button.outerHeight() - 4
target.css 'top', top
target.css 'left', left
target.css 'width', @button.outerWidth() - 2
_prepareButton: ->
id = "#{@options.uuid}-#{@options.label}"
classes = [
'ui-button'
'ui-widget'
'ui-state-default'
'ui-corner-all'
'ui-button-text-only'
]
buttonEl = jQuery "<button id=\"#{id}\"
class=\"#{classes.join(' ')}\">
<span class=\"#{@options.icon}\">#{@options.label}</span>
</button>"
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.button()
)(jQuery)
| 217345 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallodropdownbutton',
button: null
options:
uuid: ''
label: null
icon: null
editable: null
target: ''
cssClass: null
_create: ->
@options.icon ?= "icon-#{@options.label.toLowerCase()}"
_init: ->
target = jQuery @options.target
target.css 'position', 'absolute'
target.addClass 'dropdown-menu'
target.hide()
@button = @_prepareButton() unless @button
@button.bind 'click', =>
if target.hasClass 'open'
@_hideTarget()
return
@_showTarget()
target.bind 'click', =>
@_hideTarget()
@options.editable.element.bind 'hallodeactivated', =>
@_hideTarget()
@element.append @button
_showTarget: ->
target = jQuery @options.target
@_updateTargetPosition()
target.addClass 'open'
console.log "showtarget", @button, target
@button.find('.icon-caret-right').removeClass('icon-caret-right').addClass('icon-caret-down')
target.show()
_hideTarget: ->
target = jQuery @options.target
target.removeClass 'open'
@button.find('.icon-caret-down').removeClass('icon-caret-down').addClass('icon-caret-right')
target.hide()
_updateTargetPosition: ->
target = jQuery @options.target
{top, left} = @button.position()
top += @button.outerHeight() - 4
target.css 'top', top
target.css 'left', left
target.css 'width', @button.outerWidth() - 2
_prepareButton: ->
id = "#{@options.uuid}-#{@options.label}"
classes = [
'ui-button'
'ui-widget'
'ui-state-default'
'ui-corner-all'
'ui-button-text-only'
]
buttonEl = jQuery "<button id=\"#{id}\"
class=\"#{classes.join(' ')}\">
<span class=\"#{@options.icon}\">#{@options.label}</span>
</button>"
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.button()
)(jQuery)
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
((jQuery) ->
jQuery.widget 'IKS.hallodropdownbutton',
button: null
options:
uuid: ''
label: null
icon: null
editable: null
target: ''
cssClass: null
_create: ->
@options.icon ?= "icon-#{@options.label.toLowerCase()}"
_init: ->
target = jQuery @options.target
target.css 'position', 'absolute'
target.addClass 'dropdown-menu'
target.hide()
@button = @_prepareButton() unless @button
@button.bind 'click', =>
if target.hasClass 'open'
@_hideTarget()
return
@_showTarget()
target.bind 'click', =>
@_hideTarget()
@options.editable.element.bind 'hallodeactivated', =>
@_hideTarget()
@element.append @button
_showTarget: ->
target = jQuery @options.target
@_updateTargetPosition()
target.addClass 'open'
console.log "showtarget", @button, target
@button.find('.icon-caret-right').removeClass('icon-caret-right').addClass('icon-caret-down')
target.show()
_hideTarget: ->
target = jQuery @options.target
target.removeClass 'open'
@button.find('.icon-caret-down').removeClass('icon-caret-down').addClass('icon-caret-right')
target.hide()
_updateTargetPosition: ->
target = jQuery @options.target
{top, left} = @button.position()
top += @button.outerHeight() - 4
target.css 'top', top
target.css 'left', left
target.css 'width', @button.outerWidth() - 2
_prepareButton: ->
id = "#{@options.uuid}-#{@options.label}"
classes = [
'ui-button'
'ui-widget'
'ui-state-default'
'ui-corner-all'
'ui-button-text-only'
]
buttonEl = jQuery "<button id=\"#{id}\"
class=\"#{classes.join(' ')}\">
<span class=\"#{@options.icon}\">#{@options.label}</span>
</button>"
buttonEl.addClass @options.cssClass if @options.cssClass
buttonEl.button()
)(jQuery)
|
[
{
"context": "ls'\n price: 250\n name: 'Калифорния'\n ,\n id: 'canada'\n ",
"end": 5015,
"score": 0.7489256262779236,
"start": 5005,
"tag": "NAME",
"value": "Калифорния"
},
{
"context": "ls'\n price: 270\n name: 'Канада'\n ,\n id: 'philadelphia'\n ",
"end": 5141,
"score": 0.7707831859588623,
"start": 5135,
"tag": "NAME",
"value": "Канада"
},
{
"context": "ls'\n price: 250\n name: 'Филадельфия'\n ,\n id: 'kunsei'\n ",
"end": 5278,
"score": 0.943673312664032,
"start": 5267,
"tag": "NAME",
"value": "Филадельфия"
},
{
"context": "ls'\n price: 200\n name: 'Кунсей'\n ,\n id: 'olivier'\n ",
"end": 5404,
"score": 0.9591476917266846,
"start": 5398,
"tag": "NAME",
"value": "Кунсей"
},
{
"context": " name: 'Кунсей'\n ,\n id: 'olivier'\n section: 'salads'\n pr",
"end": 5446,
"score": 0.7091238498687744,
"start": 5439,
"tag": "NAME",
"value": "olivier"
},
{
"context": "ads'\n price: 85\n name: 'Оливье'\n ,\n id: 'herring'\n ",
"end": 5531,
"score": 0.9593034982681274,
"start": 5525,
"tag": "NAME",
"value": "Оливье"
},
{
"context": "ds'\n price: 120\n name: 'Греческий'\n ,\n id: 'pascarbonara'\n ",
"end": 5934,
"score": 0.9559615850448608,
"start": 5925,
"tag": "NAME",
"value": "Греческий"
},
{
"context": "ot'\n price: 170\n name: 'Паста Карбонара'\n ,\n id: 'passalmon'\n ",
"end": 6073,
"score": 0.9998310804367065,
"start": 6058,
"tag": "NAME",
"value": "Паста Карбонара"
},
{
"context": "ot'\n price: 195\n name: 'Паста с лососем'\n ,\n id: 'wokch",
"end": 6199,
"score": 0.7652249336242676,
"start": 6194,
"tag": "NAME",
"value": "Паста"
}
] | examples/globus/public/javascripts/client.coffee | ulitiy/WidLib | 1 | $ ->
time = ->
d = new Date()
utc = d.getTime() + (d.getTimezoneOffset() * 60000)
new Date(utc + (3600000*6))
offlineMode = ->
el = document.getElementById("widlib")
el.innerHTML = '<a href="http://gurman-ufa.ru" target="_blank"><img src="/images/offline.jpg"></a>' if ltie? || !client.loaded
setTimeout ->
offlineMode()
, 1500
if ltie?
offlineMode()
else
window.client = new Widlib.Client
fallback: "/widlib" # заменить на аякс
templates: JST
el: $('#widlib')
firstPage: ->
h=time().getHours()
if h>=10 && h<21
"start"
else
"sleep"
pages:
start:
onBind: ->
@app.loaded = true
sleep:
extends: "start"
main:
extends: "common"
section:
extends: "plusminus"
local: ["setSection"]
setSection: ->
@sectionID=@session.submits.main || @session.submits.start
@sectionName=@session.data.sections[@sectionID]
@currentSection=_(@session.data.products).where # почему здесь, а не вынесено?!!!
section: @sectionID
onEnter: ->
@extendsProducts()
@setSection()
true
cart:
extends: "plusminus"
local: ["cart"]
onEnter: ->
@sumtrigger = 0
@extendsProducts()
@cart()[0]
form:
extends: "common"
local: ["submitForm"]
remote: ["onSubmitServer"]
submitForm: ->
$("form[wl-submit]").submit()
onSubmit: (options)->
return options.to if options.to != "finish"
return false if !options.data.form.address || !options.data.form.phone
Q(@onSubmitServer(_(options.data.form).extend({products: @cart()}))) # имя страницы автоматом, ок
.then ->
options.to
finish:
extends: "common"
local: ['clear']
onLeave: ->
@clear()
true
clear: ->
_(@session.data.products).each (product) =>
product.quantity = 0
# плюс здесь еще invoke этого же метода
details:
extends: "common"
backStack: false
onEnter: ->
console.log ""
@product=_(@session.data.products).findWhere id: @session.submits.detailsShow
info:
extends: "common"
backStack: false
common:
local: ['sum', 'sumStr', 'cart']
onBind: ->
rivets.bind(@session.el,@)
if _(['section','cart','form','finish']).contains @name #ПЛОХО!
yaCounter23446726.reachGoal @name,
order_price: @sum()
currency: "RUR"
exchange_rate: 1
goods: @cart()
sum: (products=@session.data.products)->
_(products).reduce (sum, product) ->
sum + product.quantity*product.price
, 0
sumStr: ->
ret = @sum()
if ret > 0 then "#{ret} руб" else ""
cart: ->
_(@session.data.products).filter (product) ->
product.quantity
plusminus:
extends: "common"
local: ['extendsProducts']
extendsProducts: ->
@sumtrigger = 0
_(@session.data.products).each (product) =>
product.plus = (event) =>
# console.log ""
product.quantity++
event.preventDefault()
@sumtrigger++ # этот сумтриггер - принадлежит только этой странице!!!
product.minus = (evetn) =>
product.quantity-- if product.quantity
event.preventDefault()
@sumtrigger++
product.smallImage = -> "/images/35/#{product.id}.png"
product.bigImage = -> "/images/200-90/#{product.id}.png"
product.quantity ||= 0
onEnter: ->
@extendsProducts()
true
data:
sections:
pancakes: 'Блины'
rolls: 'Роллы'
salads: 'Салаты'
hot: 'Горячее'
desserts: 'Десерты'
beverages: 'Напитки'
products:
[
id: 'wo'
section: 'pancakes'
price: 35
name: 'Блины без начинки'
,
id: 'wquark'
section: 'pancakes'
price: 50
name: 'Блины с творогом'
,
id: 'wchicken'
section: 'pancakes'
price: 65
name: 'Блины с курицей'
,
id: 'wmeat'
section: 'pancakes'
price: 70
name: 'Блины с мясом'
,
id: 'california'
section: 'rolls'
price: 250
name: 'Калифорния'
,
id: 'canada'
section: 'rolls'
price: 270
name: 'Канада'
,
id: 'philadelphia'
section: 'rolls'
price: 250
name: 'Филадельфия'
,
id: 'kunsei'
section: 'rolls'
price: 200
name: 'Кунсей'
,
id: 'olivier'
section: 'salads'
price: 85
name: 'Оливье'
,
id: 'herring'
section: 'salads'
price: 70
name: 'Сельдь под шубой'
,
id: 'ceasar'
section: 'salads'
price: 140
name: 'Цезарь с курицей'
,
id: 'greek'
section: 'salads'
price: 120
name: 'Греческий'
,
id: 'pascarbonara'
section: 'hot'
price: 170
name: 'Паста Карбонара'
,
id: 'passalmon'
section: 'hot'
price: 195
name: 'Паста с лососем'
,
id: 'wokchicken'
section: 'hot'
price: 140
name: 'Лапша китайская с курицей'
,
id: 'wokveggie'
section: 'hot'
price: 110
name: 'Лапша китайская с овощами'
,
id: 'maminwhole'
section: 'desserts'
price: 550
name: 'Торт "Мамин" целиком'
,
id: 'maminpiece'
section: 'desserts'
price: 105
name: 'Торт "Мамин" кусочек'
,
id: 'honeywhole'
section: 'desserts'
price: 520
name: 'Торт "Медовый" целиком'
,
id: 'honeypiece'
section: 'desserts'
price: 80
name: 'Торт "Медовый" кусочек'
,
id: 'cowberry'
section: 'beverages'
price: 69
name: 'Брусничный морс 0,5л'
,
id: 'cranberry'
section: 'beverages'
price: 69
name: 'Клюквенный морс 0,5л'
,
id: 'cherry'
section: 'beverages'
price: 69
name: 'Вишневый морс 0,5л'
,
id: 'mojito'
section: 'beverages'
price: 69
name: 'Мохито (б/а) 0,33л'
]
| 172697 | $ ->
time = ->
d = new Date()
utc = d.getTime() + (d.getTimezoneOffset() * 60000)
new Date(utc + (3600000*6))
offlineMode = ->
el = document.getElementById("widlib")
el.innerHTML = '<a href="http://gurman-ufa.ru" target="_blank"><img src="/images/offline.jpg"></a>' if ltie? || !client.loaded
setTimeout ->
offlineMode()
, 1500
if ltie?
offlineMode()
else
window.client = new Widlib.Client
fallback: "/widlib" # заменить на аякс
templates: JST
el: $('#widlib')
firstPage: ->
h=time().getHours()
if h>=10 && h<21
"start"
else
"sleep"
pages:
start:
onBind: ->
@app.loaded = true
sleep:
extends: "start"
main:
extends: "common"
section:
extends: "plusminus"
local: ["setSection"]
setSection: ->
@sectionID=@session.submits.main || @session.submits.start
@sectionName=@session.data.sections[@sectionID]
@currentSection=_(@session.data.products).where # почему здесь, а не вынесено?!!!
section: @sectionID
onEnter: ->
@extendsProducts()
@setSection()
true
cart:
extends: "plusminus"
local: ["cart"]
onEnter: ->
@sumtrigger = 0
@extendsProducts()
@cart()[0]
form:
extends: "common"
local: ["submitForm"]
remote: ["onSubmitServer"]
submitForm: ->
$("form[wl-submit]").submit()
onSubmit: (options)->
return options.to if options.to != "finish"
return false if !options.data.form.address || !options.data.form.phone
Q(@onSubmitServer(_(options.data.form).extend({products: @cart()}))) # имя страницы автоматом, ок
.then ->
options.to
finish:
extends: "common"
local: ['clear']
onLeave: ->
@clear()
true
clear: ->
_(@session.data.products).each (product) =>
product.quantity = 0
# плюс здесь еще invoke этого же метода
details:
extends: "common"
backStack: false
onEnter: ->
console.log ""
@product=_(@session.data.products).findWhere id: @session.submits.detailsShow
info:
extends: "common"
backStack: false
common:
local: ['sum', 'sumStr', 'cart']
onBind: ->
rivets.bind(@session.el,@)
if _(['section','cart','form','finish']).contains @name #ПЛОХО!
yaCounter23446726.reachGoal @name,
order_price: @sum()
currency: "RUR"
exchange_rate: 1
goods: @cart()
sum: (products=@session.data.products)->
_(products).reduce (sum, product) ->
sum + product.quantity*product.price
, 0
sumStr: ->
ret = @sum()
if ret > 0 then "#{ret} руб" else ""
cart: ->
_(@session.data.products).filter (product) ->
product.quantity
plusminus:
extends: "common"
local: ['extendsProducts']
extendsProducts: ->
@sumtrigger = 0
_(@session.data.products).each (product) =>
product.plus = (event) =>
# console.log ""
product.quantity++
event.preventDefault()
@sumtrigger++ # этот сумтриггер - принадлежит только этой странице!!!
product.minus = (evetn) =>
product.quantity-- if product.quantity
event.preventDefault()
@sumtrigger++
product.smallImage = -> "/images/35/#{product.id}.png"
product.bigImage = -> "/images/200-90/#{product.id}.png"
product.quantity ||= 0
onEnter: ->
@extendsProducts()
true
data:
sections:
pancakes: 'Блины'
rolls: 'Роллы'
salads: 'Салаты'
hot: 'Горячее'
desserts: 'Десерты'
beverages: 'Напитки'
products:
[
id: 'wo'
section: 'pancakes'
price: 35
name: 'Блины без начинки'
,
id: 'wquark'
section: 'pancakes'
price: 50
name: 'Блины с творогом'
,
id: 'wchicken'
section: 'pancakes'
price: 65
name: 'Блины с курицей'
,
id: 'wmeat'
section: 'pancakes'
price: 70
name: 'Блины с мясом'
,
id: 'california'
section: 'rolls'
price: 250
name: '<NAME>'
,
id: 'canada'
section: 'rolls'
price: 270
name: '<NAME>'
,
id: 'philadelphia'
section: 'rolls'
price: 250
name: '<NAME>'
,
id: 'kunsei'
section: 'rolls'
price: 200
name: '<NAME>'
,
id: '<NAME>'
section: 'salads'
price: 85
name: '<NAME>'
,
id: 'herring'
section: 'salads'
price: 70
name: 'Сельдь под шубой'
,
id: 'ceasar'
section: 'salads'
price: 140
name: 'Цезарь с курицей'
,
id: 'greek'
section: 'salads'
price: 120
name: '<NAME>'
,
id: 'pascarbonara'
section: 'hot'
price: 170
name: '<NAME>'
,
id: 'passalmon'
section: 'hot'
price: 195
name: '<NAME> с лососем'
,
id: 'wokchicken'
section: 'hot'
price: 140
name: 'Лапша китайская с курицей'
,
id: 'wokveggie'
section: 'hot'
price: 110
name: 'Лапша китайская с овощами'
,
id: 'maminwhole'
section: 'desserts'
price: 550
name: 'Торт "Мамин" целиком'
,
id: 'maminpiece'
section: 'desserts'
price: 105
name: 'Торт "Мамин" кусочек'
,
id: 'honeywhole'
section: 'desserts'
price: 520
name: 'Торт "Медовый" целиком'
,
id: 'honeypiece'
section: 'desserts'
price: 80
name: 'Торт "Медовый" кусочек'
,
id: 'cowberry'
section: 'beverages'
price: 69
name: 'Брусничный морс 0,5л'
,
id: 'cranberry'
section: 'beverages'
price: 69
name: 'Клюквенный морс 0,5л'
,
id: 'cherry'
section: 'beverages'
price: 69
name: 'Вишневый морс 0,5л'
,
id: 'mojito'
section: 'beverages'
price: 69
name: 'Мохито (б/а) 0,33л'
]
| true | $ ->
time = ->
d = new Date()
utc = d.getTime() + (d.getTimezoneOffset() * 60000)
new Date(utc + (3600000*6))
offlineMode = ->
el = document.getElementById("widlib")
el.innerHTML = '<a href="http://gurman-ufa.ru" target="_blank"><img src="/images/offline.jpg"></a>' if ltie? || !client.loaded
setTimeout ->
offlineMode()
, 1500
if ltie?
offlineMode()
else
window.client = new Widlib.Client
fallback: "/widlib" # заменить на аякс
templates: JST
el: $('#widlib')
firstPage: ->
h=time().getHours()
if h>=10 && h<21
"start"
else
"sleep"
pages:
start:
onBind: ->
@app.loaded = true
sleep:
extends: "start"
main:
extends: "common"
section:
extends: "plusminus"
local: ["setSection"]
setSection: ->
@sectionID=@session.submits.main || @session.submits.start
@sectionName=@session.data.sections[@sectionID]
@currentSection=_(@session.data.products).where # почему здесь, а не вынесено?!!!
section: @sectionID
onEnter: ->
@extendsProducts()
@setSection()
true
cart:
extends: "plusminus"
local: ["cart"]
onEnter: ->
@sumtrigger = 0
@extendsProducts()
@cart()[0]
form:
extends: "common"
local: ["submitForm"]
remote: ["onSubmitServer"]
submitForm: ->
$("form[wl-submit]").submit()
onSubmit: (options)->
return options.to if options.to != "finish"
return false if !options.data.form.address || !options.data.form.phone
Q(@onSubmitServer(_(options.data.form).extend({products: @cart()}))) # имя страницы автоматом, ок
.then ->
options.to
finish:
extends: "common"
local: ['clear']
onLeave: ->
@clear()
true
clear: ->
_(@session.data.products).each (product) =>
product.quantity = 0
# плюс здесь еще invoke этого же метода
details:
extends: "common"
backStack: false
onEnter: ->
console.log ""
@product=_(@session.data.products).findWhere id: @session.submits.detailsShow
info:
extends: "common"
backStack: false
common:
local: ['sum', 'sumStr', 'cart']
onBind: ->
rivets.bind(@session.el,@)
if _(['section','cart','form','finish']).contains @name #ПЛОХО!
yaCounter23446726.reachGoal @name,
order_price: @sum()
currency: "RUR"
exchange_rate: 1
goods: @cart()
sum: (products=@session.data.products)->
_(products).reduce (sum, product) ->
sum + product.quantity*product.price
, 0
sumStr: ->
ret = @sum()
if ret > 0 then "#{ret} руб" else ""
cart: ->
_(@session.data.products).filter (product) ->
product.quantity
plusminus:
extends: "common"
local: ['extendsProducts']
extendsProducts: ->
@sumtrigger = 0
_(@session.data.products).each (product) =>
product.plus = (event) =>
# console.log ""
product.quantity++
event.preventDefault()
@sumtrigger++ # этот сумтриггер - принадлежит только этой странице!!!
product.minus = (evetn) =>
product.quantity-- if product.quantity
event.preventDefault()
@sumtrigger++
product.smallImage = -> "/images/35/#{product.id}.png"
product.bigImage = -> "/images/200-90/#{product.id}.png"
product.quantity ||= 0
onEnter: ->
@extendsProducts()
true
data:
sections:
pancakes: 'Блины'
rolls: 'Роллы'
salads: 'Салаты'
hot: 'Горячее'
desserts: 'Десерты'
beverages: 'Напитки'
products:
[
id: 'wo'
section: 'pancakes'
price: 35
name: 'Блины без начинки'
,
id: 'wquark'
section: 'pancakes'
price: 50
name: 'Блины с творогом'
,
id: 'wchicken'
section: 'pancakes'
price: 65
name: 'Блины с курицей'
,
id: 'wmeat'
section: 'pancakes'
price: 70
name: 'Блины с мясом'
,
id: 'california'
section: 'rolls'
price: 250
name: 'PI:NAME:<NAME>END_PI'
,
id: 'canada'
section: 'rolls'
price: 270
name: 'PI:NAME:<NAME>END_PI'
,
id: 'philadelphia'
section: 'rolls'
price: 250
name: 'PI:NAME:<NAME>END_PI'
,
id: 'kunsei'
section: 'rolls'
price: 200
name: 'PI:NAME:<NAME>END_PI'
,
id: 'PI:NAME:<NAME>END_PI'
section: 'salads'
price: 85
name: 'PI:NAME:<NAME>END_PI'
,
id: 'herring'
section: 'salads'
price: 70
name: 'Сельдь под шубой'
,
id: 'ceasar'
section: 'salads'
price: 140
name: 'Цезарь с курицей'
,
id: 'greek'
section: 'salads'
price: 120
name: 'PI:NAME:<NAME>END_PI'
,
id: 'pascarbonara'
section: 'hot'
price: 170
name: 'PI:NAME:<NAME>END_PI'
,
id: 'passalmon'
section: 'hot'
price: 195
name: 'PI:NAME:<NAME>END_PI с лососем'
,
id: 'wokchicken'
section: 'hot'
price: 140
name: 'Лапша китайская с курицей'
,
id: 'wokveggie'
section: 'hot'
price: 110
name: 'Лапша китайская с овощами'
,
id: 'maminwhole'
section: 'desserts'
price: 550
name: 'Торт "Мамин" целиком'
,
id: 'maminpiece'
section: 'desserts'
price: 105
name: 'Торт "Мамин" кусочек'
,
id: 'honeywhole'
section: 'desserts'
price: 520
name: 'Торт "Медовый" целиком'
,
id: 'honeypiece'
section: 'desserts'
price: 80
name: 'Торт "Медовый" кусочек'
,
id: 'cowberry'
section: 'beverages'
price: 69
name: 'Брусничный морс 0,5л'
,
id: 'cranberry'
section: 'beverages'
price: 69
name: 'Клюквенный морс 0,5л'
,
id: 'cherry'
section: 'beverages'
price: 69
name: 'Вишневый морс 0,5л'
,
id: 'mojito'
section: 'beverages'
price: 69
name: 'Мохито (б/а) 0,33л'
]
|
[
{
"context": "'scopeName': 'source.gfl-log'\n'name': 'GFL Log'\n\n'patterns': [\n {\n 'match': '^(.*)(:|:",
"end": 40,
"score": 0.6212658882141113,
"start": 39,
"tag": "NAME",
"value": "G"
},
{
"context": "'[-\\\\p{L}\\\\d ??]*\\\\(\\\\d*\\\\)'\n 'name': 'char-art'\n }\n {\n 'match': '(<",
"end": 229,
"score": 0.8987504839897156,
"start": 221,
"tag": "USERNAME",
"value": "char-art"
}
] | grammars/gfl-log.cson | JAK0723/language-gfl-log | 0 | 'scopeName': 'source.gfl-log'
'name': 'GFL Log'
'patterns': [
{
'match': '^(.*)(:|:)'
captures:
1:
'patterns': [
{
'match': '[-\\p{L}\\d ??]*\\(\\d*\\)'
'name': 'char-art'
}
{
'match': '(<Speaker>)(.*)(</Speaker>)'
captures:
1: name: 'meta'
2: name: 'speaker'
3: name: 'meta'
}
]
2: name: 'meta'
'name': 'meta'
}
]
| 150602 | 'scopeName': 'source.gfl-log'
'name': '<NAME>FL Log'
'patterns': [
{
'match': '^(.*)(:|:)'
captures:
1:
'patterns': [
{
'match': '[-\\p{L}\\d ??]*\\(\\d*\\)'
'name': 'char-art'
}
{
'match': '(<Speaker>)(.*)(</Speaker>)'
captures:
1: name: 'meta'
2: name: 'speaker'
3: name: 'meta'
}
]
2: name: 'meta'
'name': 'meta'
}
]
| true | 'scopeName': 'source.gfl-log'
'name': 'PI:NAME:<NAME>END_PIFL Log'
'patterns': [
{
'match': '^(.*)(:|:)'
captures:
1:
'patterns': [
{
'match': '[-\\p{L}\\d ??]*\\(\\d*\\)'
'name': 'char-art'
}
{
'match': '(<Speaker>)(.*)(</Speaker>)'
captures:
1: name: 'meta'
2: name: 'speaker'
3: name: 'meta'
}
]
2: name: 'meta'
'name': 'meta'
}
]
|
[
{
"context": "written. What do you thing?\"\n author: \"John Smith\"\n user : {name: 'johnsmith', user_id: ",
"end": 180,
"score": 0.9995837211608887,
"start": 170,
"tag": "NAME",
"value": "John Smith"
},
{
"context": " author: \"John Smith\"\n user : {name: 'johnsmith', user_id: 123456}\n slug: 'my-new-docu",
"end": 218,
"score": 0.9995467662811279,
"start": 209,
"tag": "USERNAME",
"value": "johnsmith"
},
{
"context": "content. What do you thing?\"\n author: \"Ann Smith\"\n user : {name: 'annsmith', user_id: 7",
"end": 420,
"score": 0.9989645481109619,
"start": 411,
"tag": "NAME",
"value": "Ann Smith"
},
{
"context": " author: \"Ann Smith\"\n user : {name: 'annsmith', user_id: 789123}\n slug: 'another-new",
"end": 457,
"score": 0.9996308088302612,
"start": 449,
"tag": "USERNAME",
"value": "annsmith"
}
] | src/helpers/testers/testDocs.coffee | SteveMcArthur/docpad-plugin-posteditor | 1 | getDocs = () ->
obj =
[
{
title: "My New Document"
content: "Some content I've written. What do you thing?"
author: "John Smith"
user : {name: 'johnsmith', user_id: 123456}
slug: 'my-new-document'
},{
title: "Another New Document"
content: "This is my content. What do you thing?"
author: "Ann Smith"
user : {name: 'annsmith', user_id: 789123}
slug: 'another-new-document'
}
]
return JSON.parse(JSON.stringify(obj))
module.exports = getDocs() | 72836 | getDocs = () ->
obj =
[
{
title: "My New Document"
content: "Some content I've written. What do you thing?"
author: "<NAME>"
user : {name: 'johnsmith', user_id: 123456}
slug: 'my-new-document'
},{
title: "Another New Document"
content: "This is my content. What do you thing?"
author: "<NAME>"
user : {name: 'annsmith', user_id: 789123}
slug: 'another-new-document'
}
]
return JSON.parse(JSON.stringify(obj))
module.exports = getDocs() | true | getDocs = () ->
obj =
[
{
title: "My New Document"
content: "Some content I've written. What do you thing?"
author: "PI:NAME:<NAME>END_PI"
user : {name: 'johnsmith', user_id: 123456}
slug: 'my-new-document'
},{
title: "Another New Document"
content: "This is my content. What do you thing?"
author: "PI:NAME:<NAME>END_PI"
user : {name: 'annsmith', user_id: 789123}
slug: 'another-new-document'
}
]
return JSON.parse(JSON.stringify(obj))
module.exports = getDocs() |
[
{
"context": "` custom wrapper tests\n#\n# Copyright (C) 2012-2013 Nikolay Nemshilov\n#\n{Test,should} = require('lovely')\n\ndescribe 'St",
"end": 84,
"score": 0.9998863935470581,
"start": 67,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | stl/dom/test/style_test.coffee | lovely-io/lovely.io-stl | 2 | #
# The `$.Style` custom wrapper tests
#
# Copyright (C) 2012-2013 Nikolay Nemshilov
#
{Test,should} = require('lovely')
describe 'Style', ->
$ = Element = Style = null
before Test.load (dom)->
$ = dom; Element = $.Element; Style = $.Style
it "should be registered as a dom-wrapper", ->
$.Wrapper.get('style').should.equal Style
it "should inherit the Element class", ->
Style.__super__.should.equal Element
style = new Style()
style.should.be.instanceOf Style
style.should.be.instanceOf Element
it "should assign the type='text/css' attribute automatically", ->
style = new Style()
style._.getAttribute('type').should.eql 'text/css'
it "should repurpose the 'html' option as the css text", ->
style = new Style(html: "div {color: blue}")
text = style._.firstChild
text.nodeType.should.eql 3
text.nodeValue.should.eql "div {color: blue}"
| 23247 | #
# The `$.Style` custom wrapper tests
#
# Copyright (C) 2012-2013 <NAME>
#
{Test,should} = require('lovely')
describe 'Style', ->
$ = Element = Style = null
before Test.load (dom)->
$ = dom; Element = $.Element; Style = $.Style
it "should be registered as a dom-wrapper", ->
$.Wrapper.get('style').should.equal Style
it "should inherit the Element class", ->
Style.__super__.should.equal Element
style = new Style()
style.should.be.instanceOf Style
style.should.be.instanceOf Element
it "should assign the type='text/css' attribute automatically", ->
style = new Style()
style._.getAttribute('type').should.eql 'text/css'
it "should repurpose the 'html' option as the css text", ->
style = new Style(html: "div {color: blue}")
text = style._.firstChild
text.nodeType.should.eql 3
text.nodeValue.should.eql "div {color: blue}"
| true | #
# The `$.Style` custom wrapper tests
#
# Copyright (C) 2012-2013 PI:NAME:<NAME>END_PI
#
{Test,should} = require('lovely')
describe 'Style', ->
$ = Element = Style = null
before Test.load (dom)->
$ = dom; Element = $.Element; Style = $.Style
it "should be registered as a dom-wrapper", ->
$.Wrapper.get('style').should.equal Style
it "should inherit the Element class", ->
Style.__super__.should.equal Element
style = new Style()
style.should.be.instanceOf Style
style.should.be.instanceOf Element
it "should assign the type='text/css' attribute automatically", ->
style = new Style()
style._.getAttribute('type').should.eql 'text/css'
it "should repurpose the 'html' option as the css text", ->
style = new Style(html: "div {color: blue}")
text = style._.firstChild
text.nodeType.should.eql 3
text.nodeValue.should.eql "div {color: blue}"
|
[
{
"context": " : $\n###\n\n\nclass NoteModel\n\n LOCALSTORAGE_KEY : \"scratchpad-note\"\n\n constructor : (options) ->\n _.extend(this,",
"end": 135,
"score": 0.9897778630256653,
"start": 120,
"tag": "KEY",
"value": "scratchpad-note"
}
] | app/scripts/models/note_model.coffee | scalableminds/fivepad | 1 | ### define
lodash : _
backbone : Backbone
diff : Diff
app : app
jquery : $
###
class NoteModel
LOCALSTORAGE_KEY : "scratchpad-note"
constructor : (options) ->
_.extend(this, Backbone.Events)
@id = options.id
@attributes = {
_syncedRevision : 0
_revision : 0
title : ""
contents : ""
}
@loaded = $.Deferred()
@load()
app.on("dropboxService:recordsChangedRemote", =>
console.debug(@id, "dropbox change")
@sync()
)
app.on("dropboxService:synced", =>
console.debug(@id, "dropbox synced", @pull()._revision)
@attributes._syncedRevision = @pull()._revision
@persist()
)
app.on("dropboxService:ready", =>
console.debug(@id, "dropbox ready")
@sync().then( => @trigger("reset"))
)
set : (key, value, options = {}) ->
if key of @attributes and @attributes[key] != value
@attributes[key] = value
@attributes._revision += 1
@persist()
if not options.silent
@trigger("change", this)
@trigger("change:#{key}", this, value)
@sync()
return
get : (key) ->
return @attributes[key]
sync : ->
@loaded.then( =>
if remote = @pull()
local = @attributes
if local._revision > local._syncedRevision and
remote._revision > local._syncedRevision and
not app.dropboxService.isTransient()
console.debug(@id, "merge conflict", app.dropboxService.isTransient())
if not confirm("Merge conflict in Panel '#{local.title}'. Do you wish to keep your local changes?")
@attributes.title = remote.title
@attributes.contents = remote.contents
@attributes._revision = Math.max(local._revision, remote._revision) + 1
@persist()
@push()
@trigger("reset")
else
@attributes._syncedRevision = remote._revision
@persist()
if local._revision > remote._revision
console.debug(@id, "merge local")
@push()
else if local._revision < remote._revision
console.debug(@id, "merge remote")
_.extend(@attributes, remote)
@trigger("reset")
@persist()
else
console.debug(@id, "merge equal")
else
@push()
return
)
toJSON : ->
return _.clone(@attributes)
push : ->
transferObj = _.omit(@attributes, "_syncedRevision")
app.dropboxService.updateNote(@id, transferObj)
return
pull : ->
return app.dropboxService.getNote(@id)
persist : ->
storedObj = _.pick(@attributes, ["_revision", "_syncedRevision", "title", "contents"])
if chrome?.storage?
obj = {}
obj["#{@LOCALSTORAGE_KEY}-#{@id}"] = storedObj
chrome.storage.local.set(obj)
else
window.localStorage.setItem("#{@LOCALSTORAGE_KEY}-#{@id}", JSON.stringify(storedObj))
return
load : ->
if chrome?.storage?
chrome.storage.local.get("#{@LOCALSTORAGE_KEY}-#{@id}", (item) =>
if item
_.extend(@attributes, item["#{@LOCALSTORAGE_KEY}-#{@id}"])
else
@attributes.title = app.options.defaultTitle[@id]
@loaded.resolve()
)
else
storedString = window.localStorage.getItem("#{@LOCALSTORAGE_KEY}-#{@id}")
if storedString
_.extend(@attributes, JSON.parse(storedString))
else
@attributes.title = app.options.defaultTitle[@id]
@loaded.resolve()
return
| 87872 | ### define
lodash : _
backbone : Backbone
diff : Diff
app : app
jquery : $
###
class NoteModel
LOCALSTORAGE_KEY : "<KEY>"
constructor : (options) ->
_.extend(this, Backbone.Events)
@id = options.id
@attributes = {
_syncedRevision : 0
_revision : 0
title : ""
contents : ""
}
@loaded = $.Deferred()
@load()
app.on("dropboxService:recordsChangedRemote", =>
console.debug(@id, "dropbox change")
@sync()
)
app.on("dropboxService:synced", =>
console.debug(@id, "dropbox synced", @pull()._revision)
@attributes._syncedRevision = @pull()._revision
@persist()
)
app.on("dropboxService:ready", =>
console.debug(@id, "dropbox ready")
@sync().then( => @trigger("reset"))
)
set : (key, value, options = {}) ->
if key of @attributes and @attributes[key] != value
@attributes[key] = value
@attributes._revision += 1
@persist()
if not options.silent
@trigger("change", this)
@trigger("change:#{key}", this, value)
@sync()
return
get : (key) ->
return @attributes[key]
sync : ->
@loaded.then( =>
if remote = @pull()
local = @attributes
if local._revision > local._syncedRevision and
remote._revision > local._syncedRevision and
not app.dropboxService.isTransient()
console.debug(@id, "merge conflict", app.dropboxService.isTransient())
if not confirm("Merge conflict in Panel '#{local.title}'. Do you wish to keep your local changes?")
@attributes.title = remote.title
@attributes.contents = remote.contents
@attributes._revision = Math.max(local._revision, remote._revision) + 1
@persist()
@push()
@trigger("reset")
else
@attributes._syncedRevision = remote._revision
@persist()
if local._revision > remote._revision
console.debug(@id, "merge local")
@push()
else if local._revision < remote._revision
console.debug(@id, "merge remote")
_.extend(@attributes, remote)
@trigger("reset")
@persist()
else
console.debug(@id, "merge equal")
else
@push()
return
)
toJSON : ->
return _.clone(@attributes)
push : ->
transferObj = _.omit(@attributes, "_syncedRevision")
app.dropboxService.updateNote(@id, transferObj)
return
pull : ->
return app.dropboxService.getNote(@id)
persist : ->
storedObj = _.pick(@attributes, ["_revision", "_syncedRevision", "title", "contents"])
if chrome?.storage?
obj = {}
obj["#{@LOCALSTORAGE_KEY}-#{@id}"] = storedObj
chrome.storage.local.set(obj)
else
window.localStorage.setItem("#{@LOCALSTORAGE_KEY}-#{@id}", JSON.stringify(storedObj))
return
load : ->
if chrome?.storage?
chrome.storage.local.get("#{@LOCALSTORAGE_KEY}-#{@id}", (item) =>
if item
_.extend(@attributes, item["#{@LOCALSTORAGE_KEY}-#{@id}"])
else
@attributes.title = app.options.defaultTitle[@id]
@loaded.resolve()
)
else
storedString = window.localStorage.getItem("#{@LOCALSTORAGE_KEY}-#{@id}")
if storedString
_.extend(@attributes, JSON.parse(storedString))
else
@attributes.title = app.options.defaultTitle[@id]
@loaded.resolve()
return
| true | ### define
lodash : _
backbone : Backbone
diff : Diff
app : app
jquery : $
###
class NoteModel
LOCALSTORAGE_KEY : "PI:KEY:<KEY>END_PI"
constructor : (options) ->
_.extend(this, Backbone.Events)
@id = options.id
@attributes = {
_syncedRevision : 0
_revision : 0
title : ""
contents : ""
}
@loaded = $.Deferred()
@load()
app.on("dropboxService:recordsChangedRemote", =>
console.debug(@id, "dropbox change")
@sync()
)
app.on("dropboxService:synced", =>
console.debug(@id, "dropbox synced", @pull()._revision)
@attributes._syncedRevision = @pull()._revision
@persist()
)
app.on("dropboxService:ready", =>
console.debug(@id, "dropbox ready")
@sync().then( => @trigger("reset"))
)
set : (key, value, options = {}) ->
if key of @attributes and @attributes[key] != value
@attributes[key] = value
@attributes._revision += 1
@persist()
if not options.silent
@trigger("change", this)
@trigger("change:#{key}", this, value)
@sync()
return
get : (key) ->
return @attributes[key]
sync : ->
@loaded.then( =>
if remote = @pull()
local = @attributes
if local._revision > local._syncedRevision and
remote._revision > local._syncedRevision and
not app.dropboxService.isTransient()
console.debug(@id, "merge conflict", app.dropboxService.isTransient())
if not confirm("Merge conflict in Panel '#{local.title}'. Do you wish to keep your local changes?")
@attributes.title = remote.title
@attributes.contents = remote.contents
@attributes._revision = Math.max(local._revision, remote._revision) + 1
@persist()
@push()
@trigger("reset")
else
@attributes._syncedRevision = remote._revision
@persist()
if local._revision > remote._revision
console.debug(@id, "merge local")
@push()
else if local._revision < remote._revision
console.debug(@id, "merge remote")
_.extend(@attributes, remote)
@trigger("reset")
@persist()
else
console.debug(@id, "merge equal")
else
@push()
return
)
toJSON : ->
return _.clone(@attributes)
push : ->
transferObj = _.omit(@attributes, "_syncedRevision")
app.dropboxService.updateNote(@id, transferObj)
return
pull : ->
return app.dropboxService.getNote(@id)
persist : ->
storedObj = _.pick(@attributes, ["_revision", "_syncedRevision", "title", "contents"])
if chrome?.storage?
obj = {}
obj["#{@LOCALSTORAGE_KEY}-#{@id}"] = storedObj
chrome.storage.local.set(obj)
else
window.localStorage.setItem("#{@LOCALSTORAGE_KEY}-#{@id}", JSON.stringify(storedObj))
return
load : ->
if chrome?.storage?
chrome.storage.local.get("#{@LOCALSTORAGE_KEY}-#{@id}", (item) =>
if item
_.extend(@attributes, item["#{@LOCALSTORAGE_KEY}-#{@id}"])
else
@attributes.title = app.options.defaultTitle[@id]
@loaded.resolve()
)
else
storedString = window.localStorage.getItem("#{@LOCALSTORAGE_KEY}-#{@id}")
if storedString
_.extend(@attributes, JSON.parse(storedString))
else
@attributes.title = app.options.defaultTitle[@id]
@loaded.resolve()
return
|
[
{
"context": "eturn all details for <user query>\n#\n# Author:\n# Angus Williams <angus@forest-technologies.co.uk>\n\n{filter} = req",
"end": 364,
"score": 0.9998503923416138,
"start": 350,
"tag": "NAME",
"value": "Angus Williams"
},
{
"context": " for <user query>\n#\n# Author:\n# Angus Williams <angus@forest-technologies.co.uk>\n\n{filter} = require 'fuzzaldrin'\n\n# Define a lis",
"end": 397,
"score": 0.9999368786811829,
"start": 366,
"tag": "EMAIL",
"value": "angus@forest-technologies.co.uk"
},
{
"context": "a list of users\ndirectory = [\n {\n firstName: \"John\",\n lastName: \"Lennon\",\n fullName: \"John Len",
"end": 496,
"score": 0.9997393488883972,
"start": 492,
"tag": "NAME",
"value": "John"
},
{
"context": "ory = [\n {\n firstName: \"John\",\n lastName: \"Lennon\",\n fullName: \"John Lennon\",\n email: \"johnl@",
"end": 520,
"score": 0.7884536385536194,
"start": 514,
"tag": "NAME",
"value": "Lennon"
},
{
"context": "e: \"John\",\n lastName: \"Lennon\",\n fullName: \"John Lennon\",\n email: \"johnl@example.com\",\n phone: \"+44",
"end": 549,
"score": 0.9997992515563965,
"start": 538,
"tag": "NAME",
"value": "John Lennon"
},
{
"context": "Lennon\",\n fullName: \"John Lennon\",\n email: \"johnl@example.com\",\n phone: \"+44 700 700 700\"\n },\n {\n first",
"end": 581,
"score": 0.9999327659606934,
"start": 564,
"tag": "EMAIL",
"value": "johnl@example.com"
},
{
"context": "phone: \"+44 700 700 700\"\n },\n {\n firstName: \"Paul\",\n lastName: \"McCartney\",\n fullName: \"Paul ",
"end": 642,
"score": 0.999737024307251,
"start": 638,
"tag": "NAME",
"value": "Paul"
},
{
"context": "0\"\n },\n {\n firstName: \"Paul\",\n lastName: \"McCartney\",\n fullName: \"Paul McCartney\",\n email: \"pau",
"end": 669,
"score": 0.9993727803230286,
"start": 660,
"tag": "NAME",
"value": "McCartney"
},
{
"context": "\"Paul\",\n lastName: \"McCartney\",\n fullName: \"Paul McCartney\",\n email: \"paulm@example.com\",\n phone: \"+44",
"end": 701,
"score": 0.9996959567070007,
"start": 687,
"tag": "NAME",
"value": "Paul McCartney"
},
{
"context": "ney\",\n fullName: \"Paul McCartney\",\n email: \"paulm@example.com\",\n phone: \"+44 700 700 701\"\n },\n {\n first",
"end": 733,
"score": 0.9999321103096008,
"start": 716,
"tag": "EMAIL",
"value": "paulm@example.com"
},
{
"context": "phone: \"+44 700 700 701\"\n },\n {\n firstName: \"George\",\n lastName: \"Harrison\",\n fullName: \"George",
"end": 796,
"score": 0.9997479915618896,
"start": 790,
"tag": "NAME",
"value": "George"
},
{
"context": "\n },\n {\n firstName: \"George\",\n lastName: \"Harrison\",\n fullName: \"George Harrison\",\n email: \"ge",
"end": 822,
"score": 0.9984213709831238,
"start": 814,
"tag": "NAME",
"value": "Harrison"
},
{
"context": "George\",\n lastName: \"Harrison\",\n fullName: \"George Harrison\",\n email: \"georgeh@example.com\",\n phone: \"+",
"end": 855,
"score": 0.9997812509536743,
"start": 840,
"tag": "NAME",
"value": "George Harrison"
},
{
"context": "on\",\n fullName: \"George Harrison\",\n email: \"georgeh@example.com\",\n phone: \"+44 700 700 703\"\n },\n {\n first",
"end": 889,
"score": 0.9999335408210754,
"start": 870,
"tag": "EMAIL",
"value": "georgeh@example.com"
},
{
"context": "phone: \"+44 700 700 703\"\n },\n {\n firstName: \"Ringo\",\n lastName: \"Starr\",\n fullName: \"Ringo Sta",
"end": 951,
"score": 0.999795138835907,
"start": 946,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\"\n },\n {\n firstName: \"Ringo\",\n lastName: \"Starr\",\n fullName: \"Ringo Starr\",\n email: \"ringos",
"end": 974,
"score": 0.999061644077301,
"start": 969,
"tag": "NAME",
"value": "Starr"
},
{
"context": "e: \"Ringo\",\n lastName: \"Starr\",\n fullName: \"Ringo Starr\",\n email: \"ringos@example.com\",\n phone: \"+4",
"end": 1003,
"score": 0.9998014569282532,
"start": 992,
"tag": "NAME",
"value": "Ringo Starr"
},
{
"context": "\"Starr\",\n fullName: \"Ringo Starr\",\n email: \"ringos@example.com\",\n phone: \"+44 700 700 704\"\n }\n]\n\nmodule.expo",
"end": 1036,
"score": 0.9999333024024963,
"start": 1018,
"tag": "EMAIL",
"value": "ringos@example.com"
},
{
"context": "uery\n results = filter(directory, query, key: 'fullName')\n\n # Reply with results\n res.send \"Found #",
"end": 1788,
"score": 0.9912710189819336,
"start": 1780,
"tag": "KEY",
"value": "fullName"
},
{
"context": "uery\n results = filter(directory, query, key: 'fullName')\n\n # Reply with results\n res.send \"Found #",
"end": 2221,
"score": 0.9926568269729614,
"start": 2213,
"tag": "KEY",
"value": "fullName"
}
] | scripts/company-directory.coffee | ForestTechnologiesLtd/chatops-example | 1 | # Description:
# Lookup user info from company directory
#
# Dependencies:
# "fuzzaldrin": "^2.1.0"
#
# Commands:
# hubot phone of <user query> - Return phone details for <user query>
# hubot email of <user query> - Return email details for <user query>
# hubot details of <user query> - Return all details for <user query>
#
# Author:
# Angus Williams <angus@forest-technologies.co.uk>
{filter} = require 'fuzzaldrin'
# Define a list of users
directory = [
{
firstName: "John",
lastName: "Lennon",
fullName: "John Lennon",
email: "johnl@example.com",
phone: "+44 700 700 700"
},
{
firstName: "Paul",
lastName: "McCartney",
fullName: "Paul McCartney",
email: "paulm@example.com",
phone: "+44 700 700 701"
},
{
firstName: "George",
lastName: "Harrison",
fullName: "George Harrison",
email: "georgeh@example.com",
phone: "+44 700 700 703"
},
{
firstName: "Ringo",
lastName: "Starr",
fullName: "Ringo Starr",
email: "ringos@example.com",
phone: "+44 700 700 704"
}
]
module.exports = (robot) ->
robot.respond /phone of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: 'fullName')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.phone}"
robot.respond /email of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: 'fullName')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.email}"
robot.respond /details of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: 'fullName')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.email}, #{person.phone}"
| 74052 | # Description:
# Lookup user info from company directory
#
# Dependencies:
# "fuzzaldrin": "^2.1.0"
#
# Commands:
# hubot phone of <user query> - Return phone details for <user query>
# hubot email of <user query> - Return email details for <user query>
# hubot details of <user query> - Return all details for <user query>
#
# Author:
# <NAME> <<EMAIL>>
{filter} = require 'fuzzaldrin'
# Define a list of users
directory = [
{
firstName: "<NAME>",
lastName: "<NAME>",
fullName: "<NAME>",
email: "<EMAIL>",
phone: "+44 700 700 700"
},
{
firstName: "<NAME>",
lastName: "<NAME>",
fullName: "<NAME>",
email: "<EMAIL>",
phone: "+44 700 700 701"
},
{
firstName: "<NAME>",
lastName: "<NAME>",
fullName: "<NAME>",
email: "<EMAIL>",
phone: "+44 700 700 703"
},
{
firstName: "<NAME>",
lastName: "<NAME>",
fullName: "<NAME>",
email: "<EMAIL>",
phone: "+44 700 700 704"
}
]
module.exports = (robot) ->
robot.respond /phone of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: 'fullName')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.phone}"
robot.respond /email of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: '<KEY>')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.email}"
robot.respond /details of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: '<KEY>')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.email}, #{person.phone}"
| true | # Description:
# Lookup user info from company directory
#
# Dependencies:
# "fuzzaldrin": "^2.1.0"
#
# Commands:
# hubot phone of <user query> - Return phone details for <user query>
# hubot email of <user query> - Return email details for <user query>
# hubot details of <user query> - Return all details for <user query>
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
{filter} = require 'fuzzaldrin'
# Define a list of users
directory = [
{
firstName: "PI:NAME:<NAME>END_PI",
lastName: "PI:NAME:<NAME>END_PI",
fullName: "PI:NAME:<NAME>END_PI",
email: "PI:EMAIL:<EMAIL>END_PI",
phone: "+44 700 700 700"
},
{
firstName: "PI:NAME:<NAME>END_PI",
lastName: "PI:NAME:<NAME>END_PI",
fullName: "PI:NAME:<NAME>END_PI",
email: "PI:EMAIL:<EMAIL>END_PI",
phone: "+44 700 700 701"
},
{
firstName: "PI:NAME:<NAME>END_PI",
lastName: "PI:NAME:<NAME>END_PI",
fullName: "PI:NAME:<NAME>END_PI",
email: "PI:EMAIL:<EMAIL>END_PI",
phone: "+44 700 700 703"
},
{
firstName: "PI:NAME:<NAME>END_PI",
lastName: "PI:NAME:<NAME>END_PI",
fullName: "PI:NAME:<NAME>END_PI",
email: "PI:EMAIL:<EMAIL>END_PI",
phone: "+44 700 700 704"
}
]
module.exports = (robot) ->
robot.respond /phone of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: 'fullName')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.phone}"
robot.respond /email of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: 'PI:KEY:<KEY>END_PI')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.email}"
robot.respond /details of ([\w .\-]+)\?*$/i, (res) ->
# Get user query from capture group and remove whitespace
query = res.match[1].trim()
# Fuzzy search the directory list for the query
results = filter(directory, query, key: 'PI:KEY:<KEY>END_PI')
# Reply with results
res.send "Found #{results.length} results for query '#{query}'"
for person in results
res.send "#{person.fullName}: #{person.email}, #{person.phone}"
|
[
{
"context": "Handler\", ->\n\n\tbeforeEach ->\n\t\t@user =\n\t\t\t_id:\"12390i\"\n\t\t\temail: \"bob@bob.com\"\n\t\t\tremove: sinon.stub()",
"end": 247,
"score": 0.5502157211303711,
"start": 245,
"tag": "USERNAME",
"value": "90"
},
{
"context": "eforeEach ->\n\t\t@user =\n\t\t\t_id:\"12390i\"\n\t\t\temail: \"bob@bob.com\"\n\t\t\tremove: sinon.stub().callsArgWith(0)\n\n\t\t@lice",
"end": 272,
"score": 0.9999103546142578,
"start": 261,
"tag": "EMAIL",
"value": "bob@bob.com"
},
{
"context": ">\n\t\t\t\t@NotificationsBuilder.groupPlan.calledWith(@user, @licence).should.equal true\n\t\t\t\tdone()\n\n\t\tdescri",
"end": 2396,
"score": 0.8936301469802856,
"start": 2392,
"tag": "USERNAME",
"value": "user"
}
] | test/unit/coffee/User/UserHandlerTests.coffee | davidmehren/web-sharelatex | 0 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
modulePath = "../../../../app/js/Features/User/UserHandler.js"
SandboxedModule = require('sandboxed-module')
describe "UserHandler", ->
beforeEach ->
@user =
_id:"12390i"
email: "bob@bob.com"
remove: sinon.stub().callsArgWith(0)
@licence =
subscription_id: 12323434
@SubscriptionDomainHandler =
getLicenceUserCanJoin: sinon.stub()
@SubscriptionGroupHandler =
isUserPartOfGroup:sinon.stub()
@createStub = sinon.stub().callsArgWith(0)
@NotificationsBuilder =
groupPlan:sinon.stub().returns({create:@createStub})
@TeamInvitesHandler =
createTeamInvitesForLegacyInvitedEmail: sinon.stub().yields()
@UserHandler = SandboxedModule.require modulePath, requires:
"logger-sharelatex": @logger = { log: sinon.stub() }
"../Notifications/NotificationsBuilder":@NotificationsBuilder
"../Subscription/SubscriptionDomainHandler":@SubscriptionDomainHandler
"../Subscription/SubscriptionGroupHandler":@SubscriptionGroupHandler
"../Subscription/TeamInvitesHandler": @TeamInvitesHandler
describe "populateTeamInvites", ->
beforeEach (done)->
@UserHandler.notifyDomainLicence = sinon.stub().yields()
@UserHandler.populateTeamInvites @user, done
it "notifies the user about domain licences zzzzz", ->
@UserHandler.notifyDomainLicence.calledWith(@user).should.eq true
it "notifies the user about legacy team invites", ->
@TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail
.calledWith(@user.email).should.eq true
describe "notifyDomainLicence", ->
describe "no licence", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns()
@UserHandler.populateTeamInvites @user, done
it "should not call NotificationsBuilder", (done)->
@NotificationsBuilder.groupPlan.called.should.equal false
done()
it "should not call isUserPartOfGroup", (done)->
@SubscriptionGroupHandler.isUserPartOfGroup.called.should.equal false
done()
describe "with matching licence user is not in", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns(@licence)
@SubscriptionGroupHandler.isUserPartOfGroup.callsArgWith(2, null, false)
@UserHandler.populateTeamInvites @user, done
it "should create notifcation", (done)->
@NotificationsBuilder.groupPlan.calledWith(@user, @licence).should.equal true
done()
describe "with matching licence user is already in", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns(@licence)
@SubscriptionGroupHandler.isUserPartOfGroup.callsArgWith(2, null, true)
@UserHandler.populateTeamInvites @user, done
it "should create notifcation", (done)->
@NotificationsBuilder.groupPlan.called.should.equal false
done()
| 99019 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
modulePath = "../../../../app/js/Features/User/UserHandler.js"
SandboxedModule = require('sandboxed-module')
describe "UserHandler", ->
beforeEach ->
@user =
_id:"12390i"
email: "<EMAIL>"
remove: sinon.stub().callsArgWith(0)
@licence =
subscription_id: 12323434
@SubscriptionDomainHandler =
getLicenceUserCanJoin: sinon.stub()
@SubscriptionGroupHandler =
isUserPartOfGroup:sinon.stub()
@createStub = sinon.stub().callsArgWith(0)
@NotificationsBuilder =
groupPlan:sinon.stub().returns({create:@createStub})
@TeamInvitesHandler =
createTeamInvitesForLegacyInvitedEmail: sinon.stub().yields()
@UserHandler = SandboxedModule.require modulePath, requires:
"logger-sharelatex": @logger = { log: sinon.stub() }
"../Notifications/NotificationsBuilder":@NotificationsBuilder
"../Subscription/SubscriptionDomainHandler":@SubscriptionDomainHandler
"../Subscription/SubscriptionGroupHandler":@SubscriptionGroupHandler
"../Subscription/TeamInvitesHandler": @TeamInvitesHandler
describe "populateTeamInvites", ->
beforeEach (done)->
@UserHandler.notifyDomainLicence = sinon.stub().yields()
@UserHandler.populateTeamInvites @user, done
it "notifies the user about domain licences zzzzz", ->
@UserHandler.notifyDomainLicence.calledWith(@user).should.eq true
it "notifies the user about legacy team invites", ->
@TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail
.calledWith(@user.email).should.eq true
describe "notifyDomainLicence", ->
describe "no licence", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns()
@UserHandler.populateTeamInvites @user, done
it "should not call NotificationsBuilder", (done)->
@NotificationsBuilder.groupPlan.called.should.equal false
done()
it "should not call isUserPartOfGroup", (done)->
@SubscriptionGroupHandler.isUserPartOfGroup.called.should.equal false
done()
describe "with matching licence user is not in", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns(@licence)
@SubscriptionGroupHandler.isUserPartOfGroup.callsArgWith(2, null, false)
@UserHandler.populateTeamInvites @user, done
it "should create notifcation", (done)->
@NotificationsBuilder.groupPlan.calledWith(@user, @licence).should.equal true
done()
describe "with matching licence user is already in", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns(@licence)
@SubscriptionGroupHandler.isUserPartOfGroup.callsArgWith(2, null, true)
@UserHandler.populateTeamInvites @user, done
it "should create notifcation", (done)->
@NotificationsBuilder.groupPlan.called.should.equal false
done()
| true | sinon = require('sinon')
chai = require('chai')
should = chai.should()
modulePath = "../../../../app/js/Features/User/UserHandler.js"
SandboxedModule = require('sandboxed-module')
describe "UserHandler", ->
beforeEach ->
@user =
_id:"12390i"
email: "PI:EMAIL:<EMAIL>END_PI"
remove: sinon.stub().callsArgWith(0)
@licence =
subscription_id: 12323434
@SubscriptionDomainHandler =
getLicenceUserCanJoin: sinon.stub()
@SubscriptionGroupHandler =
isUserPartOfGroup:sinon.stub()
@createStub = sinon.stub().callsArgWith(0)
@NotificationsBuilder =
groupPlan:sinon.stub().returns({create:@createStub})
@TeamInvitesHandler =
createTeamInvitesForLegacyInvitedEmail: sinon.stub().yields()
@UserHandler = SandboxedModule.require modulePath, requires:
"logger-sharelatex": @logger = { log: sinon.stub() }
"../Notifications/NotificationsBuilder":@NotificationsBuilder
"../Subscription/SubscriptionDomainHandler":@SubscriptionDomainHandler
"../Subscription/SubscriptionGroupHandler":@SubscriptionGroupHandler
"../Subscription/TeamInvitesHandler": @TeamInvitesHandler
describe "populateTeamInvites", ->
beforeEach (done)->
@UserHandler.notifyDomainLicence = sinon.stub().yields()
@UserHandler.populateTeamInvites @user, done
it "notifies the user about domain licences zzzzz", ->
@UserHandler.notifyDomainLicence.calledWith(@user).should.eq true
it "notifies the user about legacy team invites", ->
@TeamInvitesHandler.createTeamInvitesForLegacyInvitedEmail
.calledWith(@user.email).should.eq true
describe "notifyDomainLicence", ->
describe "no licence", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns()
@UserHandler.populateTeamInvites @user, done
it "should not call NotificationsBuilder", (done)->
@NotificationsBuilder.groupPlan.called.should.equal false
done()
it "should not call isUserPartOfGroup", (done)->
@SubscriptionGroupHandler.isUserPartOfGroup.called.should.equal false
done()
describe "with matching licence user is not in", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns(@licence)
@SubscriptionGroupHandler.isUserPartOfGroup.callsArgWith(2, null, false)
@UserHandler.populateTeamInvites @user, done
it "should create notifcation", (done)->
@NotificationsBuilder.groupPlan.calledWith(@user, @licence).should.equal true
done()
describe "with matching licence user is already in", ->
beforeEach (done)->
@SubscriptionDomainHandler.getLicenceUserCanJoin.returns(@licence)
@SubscriptionGroupHandler.isUserPartOfGroup.callsArgWith(2, null, true)
@UserHandler.populateTeamInvites @user, done
it "should create notifcation", (done)->
@NotificationsBuilder.groupPlan.called.should.equal false
done()
|
[
{
"context": "e Wistia Basics series is just what you need. Join Chris and \n Jeff as they take you through the key ",
"end": 1934,
"score": 0.9994539618492126,
"start": 1929,
"tag": "NAME",
"value": "Chris"
},
{
"context": "eries is just what you need. Join Chris and \n Jeff as they take you through the key features and wor",
"end": 1950,
"score": 0.9996830224990845,
"start": 1946,
"tag": "NAME",
"value": "Jeff"
}
] | _coffeescript/search.coffee | pra85/wistia-doc | 0 | class Search
constructor: ->
@query = @getQuery()
@getSearchResults @query, (data) =>
@resultHtml = ""
@resultsLength = data.results.length || 0
if @resultsLength > 0
for result in data.results
@resultHtml += @convertJsonToHtml result
else if @query?
@resultHtml = @noResultsStr(@query)
else
@resultHtml = @suggestedSearchesStr()
@header = @buildHeader()
@renderResults()
getQuery: ->
(window.location.href.split('?')[1] || "").split('=')[1]
getSearchResults: (query, callback) ->
$.getJSON "#{basepath}/search/#{query}?format=json&callback=?", callback
stringify: (str) ->
str.replace(/_/g, ' ')
noResultsStr: (query) ->
"""
<div class='no_result'>
<p>We couldn't find any results for your query, <span class='query'>#{@stringify query}</span>.
<p>Please try another search, or head back to the <a href='http://wistia.com/doc'>Documentation Main page</a>.</p>
</div>
"""
suggestedSearchesStr: ->
"""
<h2 class='suggested-title'>Here are some of our favorites:</h2>
<div class='result'>
<h2><a href='#{basepath}/media'>Guide to Using Media in Wistia</a></h2>
<p class='description'>From changing the title, to embedding it on your
website or blog, learn all the functionality for uploaded media here.</p>
</div>
<div class='result'>
<h2><a href='#{basepath}/projects'>Guide to Using Projects in Wistia</a></h2>
<p class='description'>Projects are where you store, organize, and access
media. Projects are the building blocks for Wistia organization.</p>
</div>
<div class='result'>
<h2><a href='#{basepath}/wistia-basics'>Wistia Basics Video Series</a></h2>
<p class='description'>If you are getting started, or just need a little
refresher, the Wistia Basics series is just what you need. Join Chris and
Jeff as they take you through the key features and workflows of Wistia,
to make sure you get the most out of your account.</p>
</div>
"""
convertJsonToHtml: (json) ->
"""
<div class='result'>
<h2><a href='#{basepath}#{json.url}'>#{json.title}</a></h2>
<p class='description'>#{json.description}</p>
</div>
"""
buildHeader: ->
html_start_str = "<div class='results_header'><h1>"
html_end_str = "</h1></div>"
resultHeaderText = if @query? and @query.length > 0
"#{@resultsLength} results found for #{@stringify @query}"
else
"Enter a search to begin"
return "#{html_start_str}#{resultHeaderText}#{html_end_str}"
renderResults: ->
$('#results').append(@header).append(@resultHtml)
$ ->
docSearch = new Search()
| 170304 | class Search
constructor: ->
@query = @getQuery()
@getSearchResults @query, (data) =>
@resultHtml = ""
@resultsLength = data.results.length || 0
if @resultsLength > 0
for result in data.results
@resultHtml += @convertJsonToHtml result
else if @query?
@resultHtml = @noResultsStr(@query)
else
@resultHtml = @suggestedSearchesStr()
@header = @buildHeader()
@renderResults()
getQuery: ->
(window.location.href.split('?')[1] || "").split('=')[1]
getSearchResults: (query, callback) ->
$.getJSON "#{basepath}/search/#{query}?format=json&callback=?", callback
stringify: (str) ->
str.replace(/_/g, ' ')
noResultsStr: (query) ->
"""
<div class='no_result'>
<p>We couldn't find any results for your query, <span class='query'>#{@stringify query}</span>.
<p>Please try another search, or head back to the <a href='http://wistia.com/doc'>Documentation Main page</a>.</p>
</div>
"""
suggestedSearchesStr: ->
"""
<h2 class='suggested-title'>Here are some of our favorites:</h2>
<div class='result'>
<h2><a href='#{basepath}/media'>Guide to Using Media in Wistia</a></h2>
<p class='description'>From changing the title, to embedding it on your
website or blog, learn all the functionality for uploaded media here.</p>
</div>
<div class='result'>
<h2><a href='#{basepath}/projects'>Guide to Using Projects in Wistia</a></h2>
<p class='description'>Projects are where you store, organize, and access
media. Projects are the building blocks for Wistia organization.</p>
</div>
<div class='result'>
<h2><a href='#{basepath}/wistia-basics'>Wistia Basics Video Series</a></h2>
<p class='description'>If you are getting started, or just need a little
refresher, the Wistia Basics series is just what you need. Join <NAME> and
<NAME> as they take you through the key features and workflows of Wistia,
to make sure you get the most out of your account.</p>
</div>
"""
convertJsonToHtml: (json) ->
"""
<div class='result'>
<h2><a href='#{basepath}#{json.url}'>#{json.title}</a></h2>
<p class='description'>#{json.description}</p>
</div>
"""
buildHeader: ->
html_start_str = "<div class='results_header'><h1>"
html_end_str = "</h1></div>"
resultHeaderText = if @query? and @query.length > 0
"#{@resultsLength} results found for #{@stringify @query}"
else
"Enter a search to begin"
return "#{html_start_str}#{resultHeaderText}#{html_end_str}"
renderResults: ->
$('#results').append(@header).append(@resultHtml)
$ ->
docSearch = new Search()
| true | class Search
constructor: ->
@query = @getQuery()
@getSearchResults @query, (data) =>
@resultHtml = ""
@resultsLength = data.results.length || 0
if @resultsLength > 0
for result in data.results
@resultHtml += @convertJsonToHtml result
else if @query?
@resultHtml = @noResultsStr(@query)
else
@resultHtml = @suggestedSearchesStr()
@header = @buildHeader()
@renderResults()
getQuery: ->
(window.location.href.split('?')[1] || "").split('=')[1]
getSearchResults: (query, callback) ->
$.getJSON "#{basepath}/search/#{query}?format=json&callback=?", callback
stringify: (str) ->
str.replace(/_/g, ' ')
noResultsStr: (query) ->
"""
<div class='no_result'>
<p>We couldn't find any results for your query, <span class='query'>#{@stringify query}</span>.
<p>Please try another search, or head back to the <a href='http://wistia.com/doc'>Documentation Main page</a>.</p>
</div>
"""
suggestedSearchesStr: ->
"""
<h2 class='suggested-title'>Here are some of our favorites:</h2>
<div class='result'>
<h2><a href='#{basepath}/media'>Guide to Using Media in Wistia</a></h2>
<p class='description'>From changing the title, to embedding it on your
website or blog, learn all the functionality for uploaded media here.</p>
</div>
<div class='result'>
<h2><a href='#{basepath}/projects'>Guide to Using Projects in Wistia</a></h2>
<p class='description'>Projects are where you store, organize, and access
media. Projects are the building blocks for Wistia organization.</p>
</div>
<div class='result'>
<h2><a href='#{basepath}/wistia-basics'>Wistia Basics Video Series</a></h2>
<p class='description'>If you are getting started, or just need a little
refresher, the Wistia Basics series is just what you need. Join PI:NAME:<NAME>END_PI and
PI:NAME:<NAME>END_PI as they take you through the key features and workflows of Wistia,
to make sure you get the most out of your account.</p>
</div>
"""
convertJsonToHtml: (json) ->
"""
<div class='result'>
<h2><a href='#{basepath}#{json.url}'>#{json.title}</a></h2>
<p class='description'>#{json.description}</p>
</div>
"""
buildHeader: ->
html_start_str = "<div class='results_header'><h1>"
html_end_str = "</h1></div>"
resultHeaderText = if @query? and @query.length > 0
"#{@resultsLength} results found for #{@stringify @query}"
else
"Enter a search to begin"
return "#{html_start_str}#{resultHeaderText}#{html_end_str}"
renderResults: ->
$('#results').append(@header).append(@resultHtml)
$ ->
docSearch = new Search()
|
[
{
"context": "overview Tests for no-multi-assign rule.\n# @author Stewart Rand\n###\n\n'use strict'\n\n#-----------------------------",
"end": 75,
"score": 0.9998127222061157,
"start": 63,
"tag": "NAME",
"value": "Stewart Rand"
}
] | src/tests/rules/no-multi-assign.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-multi-assign rule.
# @author Stewart Rand
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-multi-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Fixtures
#------------------------------------------------------------------------------
###*
# Returns an error object at the specified line and column
# @private
# @param {int} line - line number
# @param {int} column - column number
# @param {string} type - Type of node
# @returns {Oject} Error object
###
errorAt = (line, column, type) ->
{
message: 'Unexpected chained assignment.'
type
line
column
}
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-multi-assign', rule,
valid: [
'''
a = null
b = null
c = null
d = 0
'''
'''
a = 1
b = 2
c = 3
d = 0
'''
'a = 1 + (if b is 10 then 5 else 4)'
'a = 1; b = 2; c = 3'
]
invalid: [
code: 'a = b = c'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = c = d'
errors: [
errorAt 1, 5, 'AssignmentExpression'
errorAt 1, 9, 'AssignmentExpression'
]
,
code: 'foo = bar = cee = 100'
errors: [
errorAt 1, 7, 'AssignmentExpression'
errorAt 1, 13, 'AssignmentExpression'
]
,
code: 'a=b=c=d=e'
errors: [
errorAt 1, 3, 'AssignmentExpression'
errorAt 1, 5, 'AssignmentExpression'
errorAt 1, 7, 'AssignmentExpression'
]
,
code: 'a=b=c'
errors: [errorAt 1, 3, 'AssignmentExpression']
,
code: 'a = b = (((c)))'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = (c)'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = ( (c * 12) + 2)'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a =\nb =\n (c)'
errors: [errorAt 2, 1, 'AssignmentExpression']
,
code: "a = b = '=' + c + 'foo'"
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = 7 * 12 + 5'
errors: [errorAt 1, 5, 'AssignmentExpression']
]
| 116787 | ###*
# @fileoverview Tests for no-multi-assign rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-multi-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Fixtures
#------------------------------------------------------------------------------
###*
# Returns an error object at the specified line and column
# @private
# @param {int} line - line number
# @param {int} column - column number
# @param {string} type - Type of node
# @returns {Oject} Error object
###
errorAt = (line, column, type) ->
{
message: 'Unexpected chained assignment.'
type
line
column
}
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-multi-assign', rule,
valid: [
'''
a = null
b = null
c = null
d = 0
'''
'''
a = 1
b = 2
c = 3
d = 0
'''
'a = 1 + (if b is 10 then 5 else 4)'
'a = 1; b = 2; c = 3'
]
invalid: [
code: 'a = b = c'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = c = d'
errors: [
errorAt 1, 5, 'AssignmentExpression'
errorAt 1, 9, 'AssignmentExpression'
]
,
code: 'foo = bar = cee = 100'
errors: [
errorAt 1, 7, 'AssignmentExpression'
errorAt 1, 13, 'AssignmentExpression'
]
,
code: 'a=b=c=d=e'
errors: [
errorAt 1, 3, 'AssignmentExpression'
errorAt 1, 5, 'AssignmentExpression'
errorAt 1, 7, 'AssignmentExpression'
]
,
code: 'a=b=c'
errors: [errorAt 1, 3, 'AssignmentExpression']
,
code: 'a = b = (((c)))'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = (c)'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = ( (c * 12) + 2)'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a =\nb =\n (c)'
errors: [errorAt 2, 1, 'AssignmentExpression']
,
code: "a = b = '=' + c + 'foo'"
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = 7 * 12 + 5'
errors: [errorAt 1, 5, 'AssignmentExpression']
]
| true | ###*
# @fileoverview Tests for no-multi-assign rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-multi-assign'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Fixtures
#------------------------------------------------------------------------------
###*
# Returns an error object at the specified line and column
# @private
# @param {int} line - line number
# @param {int} column - column number
# @param {string} type - Type of node
# @returns {Oject} Error object
###
errorAt = (line, column, type) ->
{
message: 'Unexpected chained assignment.'
type
line
column
}
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-multi-assign', rule,
valid: [
'''
a = null
b = null
c = null
d = 0
'''
'''
a = 1
b = 2
c = 3
d = 0
'''
'a = 1 + (if b is 10 then 5 else 4)'
'a = 1; b = 2; c = 3'
]
invalid: [
code: 'a = b = c'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = c = d'
errors: [
errorAt 1, 5, 'AssignmentExpression'
errorAt 1, 9, 'AssignmentExpression'
]
,
code: 'foo = bar = cee = 100'
errors: [
errorAt 1, 7, 'AssignmentExpression'
errorAt 1, 13, 'AssignmentExpression'
]
,
code: 'a=b=c=d=e'
errors: [
errorAt 1, 3, 'AssignmentExpression'
errorAt 1, 5, 'AssignmentExpression'
errorAt 1, 7, 'AssignmentExpression'
]
,
code: 'a=b=c'
errors: [errorAt 1, 3, 'AssignmentExpression']
,
code: 'a = b = (((c)))'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = (c)'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = ( (c * 12) + 2)'
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a =\nb =\n (c)'
errors: [errorAt 2, 1, 'AssignmentExpression']
,
code: "a = b = '=' + c + 'foo'"
errors: [errorAt 1, 5, 'AssignmentExpression']
,
code: 'a = b = 7 * 12 + 5'
errors: [errorAt 1, 5, 'AssignmentExpression']
]
|
[
{
"context": " String\n string_redirect: (oref,cls) ->\n key = \"#{cls}::#{oref}\"\n cdata = @class_lookup(c2t(cls))\n unless @s",
"end": 2109,
"score": 0.9946381449699402,
"start": 2092,
"tag": "KEY",
"value": "\"#{cls}::#{oref}\""
}
] | src/runtime.coffee | Jivings/doppio | 1 | # Things assigned to root will be available outside this module.
root = exports ? this.runtime = {}
util ?= require './util'
types ?= require './types'
ClassFile ?= require './class_file'
{log,debug,error,java_throw} = util
{c2t} = types
trace = (msg) -> log 9, msg
initial_value = (type_str) ->
if type_str is 'J' then gLong.ZERO
else if type_str[0] in ['[','L'] then null
else 0
class root.StackFrame
constructor: (@method,@locals,@stack) ->
@pc = 0
# Contains all the mutable state of the Java program.
class root.RuntimeState
constructor: (@print, @async_input, @read_classfile) ->
@classes = {}
@high_oref = 1
@string_pool = {}
@string_redirector = {}
@zip_descriptors = [null]
# Init the first class, and put the command-line args on the stack for use by
# its main method.
initialize: (class_name, initial_args) ->
# initialize thread objects
@meta_stack = [new root.StackFrame null,[],[]]
@push (group = @init_object 'java/lang/ThreadGroup')
@method_lookup({class: 'java/lang/ThreadGroup', sig: '<init>()V'}).run(this)
@main_thread = @init_object 'java/lang/Thread',
name: @init_carr 'main'
priority: 1
group: group
threadLocals: null
@push gLong.ZERO, null # set up for static_put
@static_put {class:'java/lang/Thread', name:'threadSeqNumber'}
args = @set_obj(c2t('[Ljava/lang/String;'),(@init_string(a) for a in initial_args))
# prepare meta_stack for main(String[] args)
@meta_stack = [new root.StackFrame(null,[],[args])]
@class_lookup c2t class_name
# Convert a Java String object into an equivalent JS one.
jvm2js_str: (jvm_str) ->
@jvm_carr2js_str(jvm_str.fields.value, jvm_str.fields.offset, jvm_str.fields.count)
# Convert :count chars starting from :offset in a Java character array into a
# JS string
jvm_carr2js_str: (jvm_arr, offset, count) ->
carr = jvm_arr.array
(util.bytes2str carr).substr(offset ? 0, count)
# Convert references to strings in the constant pool to an interned String
string_redirect: (oref,cls) ->
key = "#{cls}::#{oref}"
cdata = @class_lookup(c2t(cls))
unless @string_redirector[key]
cstr = cdata.constant_pool.get(oref)
throw new Error "can't redirect const string at #{oref}" unless cstr and cstr.type is 'Asciz'
@string_redirector[key] = @init_string(cstr.value,true)
trace "heapifying #{oref} -> #{@string_redirector[key].ref} : '#{cstr.value}'"
trace "redirecting #{oref} -> #{@string_redirector[key].ref}"
return @string_redirector[key]
# Used by ZipFile to return unique zip file descriptor IDs.
set_zip_descriptor: (zd_obj) ->
@zip_descriptors.push zd_obj
gLong.fromInt(@zip_descriptors.length - 1)
get_zip_descriptor: (zd_long) ->
@zip_descriptors[zd_long.toInt()]
free_zip_descriptor: (zd_long) ->
#delete @zip_descriptors[zd_long.toInt()]
curr_frame: () ->
if @resuming_stack? then @meta_stack[@resuming_stack]
else _.last(@meta_stack)
cl: (idx) -> @curr_frame().locals[idx]
put_cl: (idx,val) -> @curr_frame().locals[idx] = val
# Category 2 values (longs, doubles) take two slots in Java. Since we only
# need one slot to represent a double in JS, we pad it with a null.
put_cl2: (idx,val) -> @put_cl(idx,val); @put_cl(idx+1,null)
push: (args...) ->
cs = @curr_frame().stack
Array::push.apply cs, args
pop: () -> @curr_frame().stack.pop()
pop2: () -> @pop(); @pop() # For category 2 values.
# Program counter manipulation.
curr_pc: () -> @curr_frame().pc
goto_pc: (pc) -> @curr_frame().pc = pc
inc_pc: (n) -> @curr_frame().pc += n
# Heap manipulation.
check_null: (obj) ->
java_throw @, 'java/lang/NullPointerException', '' unless obj?
obj
set_obj: (type, obj={}) ->
if type instanceof types.ArrayType
{type: type, array: obj, ref: @high_oref++}
else
{type: type, fields: obj, ref: @high_oref++}
heap_newarray: (type,len) ->
if type == 'J'
@set_obj(c2t("[J"),(gLong.ZERO for i in [0...len] by 1))
else if type[0] == 'L' # array of object
@set_obj(c2t("[#{type}"),(null for i in [0...len] by 1))
else # numeric array
@set_obj(c2t("[#{type}"),(0 for i in [0...len] by 1))
heap_put: (field_spec) ->
val = if field_spec.type in ['J','D'] then @pop2() else @pop()
obj = @pop()
trace "setting #{field_spec.name} = #{val} on obj of type #{obj.type.toClassString()}"
obj.fields[field_spec.name] = val
heap_get: (field_spec, obj) ->
name = field_spec.name
obj.fields[name] ?= initial_value field_spec.type
trace "getting #{name} from obj of type #{obj.type.toClassString()}: #{obj.fields[name]}"
@push obj.fields[name]
@push null if field_spec.type in ['J','D']
# static stuff
static_get: (field_spec) ->
f = @field_lookup(field_spec)
obj = @class_lookup(f.class_type, true)
val = obj.fields[f.name]
val ?= initial_value f.type.toString()
trace "getting #{field_spec.name} from class #{field_spec.class}: #{val}"
val
static_put: (field_spec) ->
val = if field_spec.type in ['J','D'] then @pop2() else @pop()
f = @field_lookup(field_spec)
obj = @class_lookup(f.class_type, true)
obj.fields[f.name] = val
trace "setting #{field_spec.name} = #{val} on class #{field_spec.class}"
# heap object initialization
init_object: (cls, obj) ->
type = c2t(cls)
@class_lookup type
@set_obj type, obj
init_string: (str,intern=false) ->
# this is a bit of a kludge: if the string we want to intern is __proto__ or a function name,
# we fail to intern it.
return @string_pool[str] if intern and @string_pool[str]?.type?.toClassString?() is 'java/lang/String'
carr = @init_carr str
jvm_str = @set_obj c2t('java/lang/String'), {'value':carr, 'count':str.length}
@string_pool[str] = jvm_str if intern
return jvm_str
init_carr: (str) -> @set_obj c2t('[C'), (str.charCodeAt(i) for i in [0...str.length])
# Tries to obtain the class of type :type. Called by the bootstrap class loader.
# Throws a NoClassDefFoundError on failure.
class_lookup: (type,get_obj=false) ->
c = @_class_lookup type
unless c
cls = (type.toClassString?() ? type.toString())
java_throw @, 'java/lang/NoClassDefFoundError', cls
if get_obj then c.obj else c.file
# Tries to obtain the class of type :type. Called by reflective methods, e.g.
# `Class.forName`, `ClassLoader.findSystemClass`, and `ClassLoader.loadClass`.
# Throws a ClassNotFoundException on failure.
dyn_class_lookup: (type, get_obj=false) ->
c = @_class_lookup type
unless c
cls = (type.toClassString?() ? type.toString())
java_throw @, 'java/lang/ClassNotFoundException', cls
if get_obj then c.obj else c.file
# Fetch the relevant class file. Returns `undefined` if it cannot be found.
# Results are cached in `@classes`.
_class_lookup: (type) ->
throw new Error "class_lookup needs a type object, got #{typeof type}: #{type}" unless type instanceof types.Type
cls = type.toClassString?() ? type.toString()
unless @classes[cls]?
trace "loading new class: #{cls}"
if type instanceof types.ArrayType
class_file = ClassFile.for_array_type type
@classes[cls] =
file: class_file
obj: @set_obj(c2t('java/lang/Class'), { $type: type })
component = type.component_type
if component instanceof types.ArrayType or component instanceof types.ClassType
@_class_lookup component
else if type instanceof types.PrimitiveType
@classes[type] = {file: '<primitive>', obj: @set_obj(c2t('java/lang/Class'), { $type: type })}
else
class_file = @read_classfile cls
return unless class_file?
@classes[cls] =
file: class_file
obj: @set_obj(c2t('java/lang/Class'), { $type: type })
# Run class initialization code. Superclasses get init'ed first. We
# don't want to call this more than once per class, so don't do dynamic
# lookup. See spec [2.17.4][1].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/Concepts.doc.html#19075
if class_file.super_class
@_class_lookup class_file.super_class
class_file.methods['<clinit>()V']?.run(this)
if cls is 'java/lang/System' # zomg hardcode
class_file.methods['initializeSystemClass()V'].run(this)
@classes[cls]
# Spec [5.4.3.3][1], [5.4.3.4][2].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#79473
# [2]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#78621
method_lookup: (method_spec) ->
type = c2t method_spec.class
t = type
while t
cls = @class_lookup(t)
method = cls.methods[method_spec.sig]
return method if method?
t = cls.super_class
cls = @class_lookup(type)
ifaces = (c2t(cls.constant_pool.get(i).deref()) for i in cls.interfaces)
while ifaces.length > 0
iface_name = ifaces.shift()
ifc = @class_lookup iface_name
method = ifc.methods[method_spec.sig]
return method if method?
Array::push.apply ifaces,
(c2t(ifc.constant_pool.get(i).deref()) for i in ifc.interfaces)
java_throw @, 'java/lang/NoSuchMethodError',
"No such method found in #{method_spec.class}: #{method_spec.sig}"
# Spec [5.4.3.2][1].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#77678
field_lookup: (field_spec) ->
filter_field = (c) -> _.find(c.fields, (f)-> f.name is field_spec.name)
field = @_field_lookup field_spec.class, filter_field
return field if field?
java_throw @, 'java/lang/NoSuchFieldError',
"No such field found in #{field_spec.class}: #{field_spec.name}"
_field_lookup: (class_name, filter_fn) ->
t = c2t class_name
while t
cls = @class_lookup(t)
field = filter_fn cls
return field if field?
ifaces = (cls.constant_pool.get(i).deref() for i in cls.interfaces)
for ifc in ifaces
field = @_field_lookup ifc, filter_fn
return field if field?
t = cls.super_class
null
| 134573 | # Things assigned to root will be available outside this module.
root = exports ? this.runtime = {}
util ?= require './util'
types ?= require './types'
ClassFile ?= require './class_file'
{log,debug,error,java_throw} = util
{c2t} = types
trace = (msg) -> log 9, msg
initial_value = (type_str) ->
if type_str is 'J' then gLong.ZERO
else if type_str[0] in ['[','L'] then null
else 0
class root.StackFrame
constructor: (@method,@locals,@stack) ->
@pc = 0
# Contains all the mutable state of the Java program.
class root.RuntimeState
constructor: (@print, @async_input, @read_classfile) ->
@classes = {}
@high_oref = 1
@string_pool = {}
@string_redirector = {}
@zip_descriptors = [null]
# Init the first class, and put the command-line args on the stack for use by
# its main method.
initialize: (class_name, initial_args) ->
# initialize thread objects
@meta_stack = [new root.StackFrame null,[],[]]
@push (group = @init_object 'java/lang/ThreadGroup')
@method_lookup({class: 'java/lang/ThreadGroup', sig: '<init>()V'}).run(this)
@main_thread = @init_object 'java/lang/Thread',
name: @init_carr 'main'
priority: 1
group: group
threadLocals: null
@push gLong.ZERO, null # set up for static_put
@static_put {class:'java/lang/Thread', name:'threadSeqNumber'}
args = @set_obj(c2t('[Ljava/lang/String;'),(@init_string(a) for a in initial_args))
# prepare meta_stack for main(String[] args)
@meta_stack = [new root.StackFrame(null,[],[args])]
@class_lookup c2t class_name
# Convert a Java String object into an equivalent JS one.
jvm2js_str: (jvm_str) ->
@jvm_carr2js_str(jvm_str.fields.value, jvm_str.fields.offset, jvm_str.fields.count)
# Convert :count chars starting from :offset in a Java character array into a
# JS string
jvm_carr2js_str: (jvm_arr, offset, count) ->
carr = jvm_arr.array
(util.bytes2str carr).substr(offset ? 0, count)
# Convert references to strings in the constant pool to an interned String
string_redirect: (oref,cls) ->
key = <KEY>
cdata = @class_lookup(c2t(cls))
unless @string_redirector[key]
cstr = cdata.constant_pool.get(oref)
throw new Error "can't redirect const string at #{oref}" unless cstr and cstr.type is 'Asciz'
@string_redirector[key] = @init_string(cstr.value,true)
trace "heapifying #{oref} -> #{@string_redirector[key].ref} : '#{cstr.value}'"
trace "redirecting #{oref} -> #{@string_redirector[key].ref}"
return @string_redirector[key]
# Used by ZipFile to return unique zip file descriptor IDs.
set_zip_descriptor: (zd_obj) ->
@zip_descriptors.push zd_obj
gLong.fromInt(@zip_descriptors.length - 1)
get_zip_descriptor: (zd_long) ->
@zip_descriptors[zd_long.toInt()]
free_zip_descriptor: (zd_long) ->
#delete @zip_descriptors[zd_long.toInt()]
curr_frame: () ->
if @resuming_stack? then @meta_stack[@resuming_stack]
else _.last(@meta_stack)
cl: (idx) -> @curr_frame().locals[idx]
put_cl: (idx,val) -> @curr_frame().locals[idx] = val
# Category 2 values (longs, doubles) take two slots in Java. Since we only
# need one slot to represent a double in JS, we pad it with a null.
put_cl2: (idx,val) -> @put_cl(idx,val); @put_cl(idx+1,null)
push: (args...) ->
cs = @curr_frame().stack
Array::push.apply cs, args
pop: () -> @curr_frame().stack.pop()
pop2: () -> @pop(); @pop() # For category 2 values.
# Program counter manipulation.
curr_pc: () -> @curr_frame().pc
goto_pc: (pc) -> @curr_frame().pc = pc
inc_pc: (n) -> @curr_frame().pc += n
# Heap manipulation.
check_null: (obj) ->
java_throw @, 'java/lang/NullPointerException', '' unless obj?
obj
set_obj: (type, obj={}) ->
if type instanceof types.ArrayType
{type: type, array: obj, ref: @high_oref++}
else
{type: type, fields: obj, ref: @high_oref++}
heap_newarray: (type,len) ->
if type == 'J'
@set_obj(c2t("[J"),(gLong.ZERO for i in [0...len] by 1))
else if type[0] == 'L' # array of object
@set_obj(c2t("[#{type}"),(null for i in [0...len] by 1))
else # numeric array
@set_obj(c2t("[#{type}"),(0 for i in [0...len] by 1))
heap_put: (field_spec) ->
val = if field_spec.type in ['J','D'] then @pop2() else @pop()
obj = @pop()
trace "setting #{field_spec.name} = #{val} on obj of type #{obj.type.toClassString()}"
obj.fields[field_spec.name] = val
heap_get: (field_spec, obj) ->
name = field_spec.name
obj.fields[name] ?= initial_value field_spec.type
trace "getting #{name} from obj of type #{obj.type.toClassString()}: #{obj.fields[name]}"
@push obj.fields[name]
@push null if field_spec.type in ['J','D']
# static stuff
static_get: (field_spec) ->
f = @field_lookup(field_spec)
obj = @class_lookup(f.class_type, true)
val = obj.fields[f.name]
val ?= initial_value f.type.toString()
trace "getting #{field_spec.name} from class #{field_spec.class}: #{val}"
val
static_put: (field_spec) ->
val = if field_spec.type in ['J','D'] then @pop2() else @pop()
f = @field_lookup(field_spec)
obj = @class_lookup(f.class_type, true)
obj.fields[f.name] = val
trace "setting #{field_spec.name} = #{val} on class #{field_spec.class}"
# heap object initialization
init_object: (cls, obj) ->
type = c2t(cls)
@class_lookup type
@set_obj type, obj
init_string: (str,intern=false) ->
# this is a bit of a kludge: if the string we want to intern is __proto__ or a function name,
# we fail to intern it.
return @string_pool[str] if intern and @string_pool[str]?.type?.toClassString?() is 'java/lang/String'
carr = @init_carr str
jvm_str = @set_obj c2t('java/lang/String'), {'value':carr, 'count':str.length}
@string_pool[str] = jvm_str if intern
return jvm_str
init_carr: (str) -> @set_obj c2t('[C'), (str.charCodeAt(i) for i in [0...str.length])
# Tries to obtain the class of type :type. Called by the bootstrap class loader.
# Throws a NoClassDefFoundError on failure.
class_lookup: (type,get_obj=false) ->
c = @_class_lookup type
unless c
cls = (type.toClassString?() ? type.toString())
java_throw @, 'java/lang/NoClassDefFoundError', cls
if get_obj then c.obj else c.file
# Tries to obtain the class of type :type. Called by reflective methods, e.g.
# `Class.forName`, `ClassLoader.findSystemClass`, and `ClassLoader.loadClass`.
# Throws a ClassNotFoundException on failure.
dyn_class_lookup: (type, get_obj=false) ->
c = @_class_lookup type
unless c
cls = (type.toClassString?() ? type.toString())
java_throw @, 'java/lang/ClassNotFoundException', cls
if get_obj then c.obj else c.file
# Fetch the relevant class file. Returns `undefined` if it cannot be found.
# Results are cached in `@classes`.
_class_lookup: (type) ->
throw new Error "class_lookup needs a type object, got #{typeof type}: #{type}" unless type instanceof types.Type
cls = type.toClassString?() ? type.toString()
unless @classes[cls]?
trace "loading new class: #{cls}"
if type instanceof types.ArrayType
class_file = ClassFile.for_array_type type
@classes[cls] =
file: class_file
obj: @set_obj(c2t('java/lang/Class'), { $type: type })
component = type.component_type
if component instanceof types.ArrayType or component instanceof types.ClassType
@_class_lookup component
else if type instanceof types.PrimitiveType
@classes[type] = {file: '<primitive>', obj: @set_obj(c2t('java/lang/Class'), { $type: type })}
else
class_file = @read_classfile cls
return unless class_file?
@classes[cls] =
file: class_file
obj: @set_obj(c2t('java/lang/Class'), { $type: type })
# Run class initialization code. Superclasses get init'ed first. We
# don't want to call this more than once per class, so don't do dynamic
# lookup. See spec [2.17.4][1].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/Concepts.doc.html#19075
if class_file.super_class
@_class_lookup class_file.super_class
class_file.methods['<clinit>()V']?.run(this)
if cls is 'java/lang/System' # zomg hardcode
class_file.methods['initializeSystemClass()V'].run(this)
@classes[cls]
# Spec [5.4.3.3][1], [5.4.3.4][2].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#79473
# [2]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#78621
method_lookup: (method_spec) ->
type = c2t method_spec.class
t = type
while t
cls = @class_lookup(t)
method = cls.methods[method_spec.sig]
return method if method?
t = cls.super_class
cls = @class_lookup(type)
ifaces = (c2t(cls.constant_pool.get(i).deref()) for i in cls.interfaces)
while ifaces.length > 0
iface_name = ifaces.shift()
ifc = @class_lookup iface_name
method = ifc.methods[method_spec.sig]
return method if method?
Array::push.apply ifaces,
(c2t(ifc.constant_pool.get(i).deref()) for i in ifc.interfaces)
java_throw @, 'java/lang/NoSuchMethodError',
"No such method found in #{method_spec.class}: #{method_spec.sig}"
# Spec [5.4.3.2][1].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#77678
field_lookup: (field_spec) ->
filter_field = (c) -> _.find(c.fields, (f)-> f.name is field_spec.name)
field = @_field_lookup field_spec.class, filter_field
return field if field?
java_throw @, 'java/lang/NoSuchFieldError',
"No such field found in #{field_spec.class}: #{field_spec.name}"
_field_lookup: (class_name, filter_fn) ->
t = c2t class_name
while t
cls = @class_lookup(t)
field = filter_fn cls
return field if field?
ifaces = (cls.constant_pool.get(i).deref() for i in cls.interfaces)
for ifc in ifaces
field = @_field_lookup ifc, filter_fn
return field if field?
t = cls.super_class
null
| true | # Things assigned to root will be available outside this module.
root = exports ? this.runtime = {}
util ?= require './util'
types ?= require './types'
ClassFile ?= require './class_file'
{log,debug,error,java_throw} = util
{c2t} = types
trace = (msg) -> log 9, msg
initial_value = (type_str) ->
if type_str is 'J' then gLong.ZERO
else if type_str[0] in ['[','L'] then null
else 0
class root.StackFrame
constructor: (@method,@locals,@stack) ->
@pc = 0
# Contains all the mutable state of the Java program.
class root.RuntimeState
constructor: (@print, @async_input, @read_classfile) ->
@classes = {}
@high_oref = 1
@string_pool = {}
@string_redirector = {}
@zip_descriptors = [null]
# Init the first class, and put the command-line args on the stack for use by
# its main method.
initialize: (class_name, initial_args) ->
# initialize thread objects
@meta_stack = [new root.StackFrame null,[],[]]
@push (group = @init_object 'java/lang/ThreadGroup')
@method_lookup({class: 'java/lang/ThreadGroup', sig: '<init>()V'}).run(this)
@main_thread = @init_object 'java/lang/Thread',
name: @init_carr 'main'
priority: 1
group: group
threadLocals: null
@push gLong.ZERO, null # set up for static_put
@static_put {class:'java/lang/Thread', name:'threadSeqNumber'}
args = @set_obj(c2t('[Ljava/lang/String;'),(@init_string(a) for a in initial_args))
# prepare meta_stack for main(String[] args)
@meta_stack = [new root.StackFrame(null,[],[args])]
@class_lookup c2t class_name
# Convert a Java String object into an equivalent JS one.
jvm2js_str: (jvm_str) ->
@jvm_carr2js_str(jvm_str.fields.value, jvm_str.fields.offset, jvm_str.fields.count)
# Convert :count chars starting from :offset in a Java character array into a
# JS string
jvm_carr2js_str: (jvm_arr, offset, count) ->
carr = jvm_arr.array
(util.bytes2str carr).substr(offset ? 0, count)
# Convert references to strings in the constant pool to an interned String
string_redirect: (oref,cls) ->
key = PI:KEY:<KEY>END_PI
cdata = @class_lookup(c2t(cls))
unless @string_redirector[key]
cstr = cdata.constant_pool.get(oref)
throw new Error "can't redirect const string at #{oref}" unless cstr and cstr.type is 'Asciz'
@string_redirector[key] = @init_string(cstr.value,true)
trace "heapifying #{oref} -> #{@string_redirector[key].ref} : '#{cstr.value}'"
trace "redirecting #{oref} -> #{@string_redirector[key].ref}"
return @string_redirector[key]
# Used by ZipFile to return unique zip file descriptor IDs.
set_zip_descriptor: (zd_obj) ->
@zip_descriptors.push zd_obj
gLong.fromInt(@zip_descriptors.length - 1)
get_zip_descriptor: (zd_long) ->
@zip_descriptors[zd_long.toInt()]
free_zip_descriptor: (zd_long) ->
#delete @zip_descriptors[zd_long.toInt()]
curr_frame: () ->
if @resuming_stack? then @meta_stack[@resuming_stack]
else _.last(@meta_stack)
cl: (idx) -> @curr_frame().locals[idx]
put_cl: (idx,val) -> @curr_frame().locals[idx] = val
# Category 2 values (longs, doubles) take two slots in Java. Since we only
# need one slot to represent a double in JS, we pad it with a null.
put_cl2: (idx,val) -> @put_cl(idx,val); @put_cl(idx+1,null)
push: (args...) ->
cs = @curr_frame().stack
Array::push.apply cs, args
pop: () -> @curr_frame().stack.pop()
pop2: () -> @pop(); @pop() # For category 2 values.
# Program counter manipulation.
curr_pc: () -> @curr_frame().pc
goto_pc: (pc) -> @curr_frame().pc = pc
inc_pc: (n) -> @curr_frame().pc += n
# Heap manipulation.
check_null: (obj) ->
java_throw @, 'java/lang/NullPointerException', '' unless obj?
obj
set_obj: (type, obj={}) ->
if type instanceof types.ArrayType
{type: type, array: obj, ref: @high_oref++}
else
{type: type, fields: obj, ref: @high_oref++}
heap_newarray: (type,len) ->
if type == 'J'
@set_obj(c2t("[J"),(gLong.ZERO for i in [0...len] by 1))
else if type[0] == 'L' # array of object
@set_obj(c2t("[#{type}"),(null for i in [0...len] by 1))
else # numeric array
@set_obj(c2t("[#{type}"),(0 for i in [0...len] by 1))
heap_put: (field_spec) ->
val = if field_spec.type in ['J','D'] then @pop2() else @pop()
obj = @pop()
trace "setting #{field_spec.name} = #{val} on obj of type #{obj.type.toClassString()}"
obj.fields[field_spec.name] = val
heap_get: (field_spec, obj) ->
name = field_spec.name
obj.fields[name] ?= initial_value field_spec.type
trace "getting #{name} from obj of type #{obj.type.toClassString()}: #{obj.fields[name]}"
@push obj.fields[name]
@push null if field_spec.type in ['J','D']
# static stuff
static_get: (field_spec) ->
f = @field_lookup(field_spec)
obj = @class_lookup(f.class_type, true)
val = obj.fields[f.name]
val ?= initial_value f.type.toString()
trace "getting #{field_spec.name} from class #{field_spec.class}: #{val}"
val
static_put: (field_spec) ->
val = if field_spec.type in ['J','D'] then @pop2() else @pop()
f = @field_lookup(field_spec)
obj = @class_lookup(f.class_type, true)
obj.fields[f.name] = val
trace "setting #{field_spec.name} = #{val} on class #{field_spec.class}"
# heap object initialization
init_object: (cls, obj) ->
type = c2t(cls)
@class_lookup type
@set_obj type, obj
init_string: (str,intern=false) ->
# this is a bit of a kludge: if the string we want to intern is __proto__ or a function name,
# we fail to intern it.
return @string_pool[str] if intern and @string_pool[str]?.type?.toClassString?() is 'java/lang/String'
carr = @init_carr str
jvm_str = @set_obj c2t('java/lang/String'), {'value':carr, 'count':str.length}
@string_pool[str] = jvm_str if intern
return jvm_str
init_carr: (str) -> @set_obj c2t('[C'), (str.charCodeAt(i) for i in [0...str.length])
# Tries to obtain the class of type :type. Called by the bootstrap class loader.
# Throws a NoClassDefFoundError on failure.
class_lookup: (type,get_obj=false) ->
c = @_class_lookup type
unless c
cls = (type.toClassString?() ? type.toString())
java_throw @, 'java/lang/NoClassDefFoundError', cls
if get_obj then c.obj else c.file
# Tries to obtain the class of type :type. Called by reflective methods, e.g.
# `Class.forName`, `ClassLoader.findSystemClass`, and `ClassLoader.loadClass`.
# Throws a ClassNotFoundException on failure.
dyn_class_lookup: (type, get_obj=false) ->
c = @_class_lookup type
unless c
cls = (type.toClassString?() ? type.toString())
java_throw @, 'java/lang/ClassNotFoundException', cls
if get_obj then c.obj else c.file
# Fetch the relevant class file. Returns `undefined` if it cannot be found.
# Results are cached in `@classes`.
_class_lookup: (type) ->
throw new Error "class_lookup needs a type object, got #{typeof type}: #{type}" unless type instanceof types.Type
cls = type.toClassString?() ? type.toString()
unless @classes[cls]?
trace "loading new class: #{cls}"
if type instanceof types.ArrayType
class_file = ClassFile.for_array_type type
@classes[cls] =
file: class_file
obj: @set_obj(c2t('java/lang/Class'), { $type: type })
component = type.component_type
if component instanceof types.ArrayType or component instanceof types.ClassType
@_class_lookup component
else if type instanceof types.PrimitiveType
@classes[type] = {file: '<primitive>', obj: @set_obj(c2t('java/lang/Class'), { $type: type })}
else
class_file = @read_classfile cls
return unless class_file?
@classes[cls] =
file: class_file
obj: @set_obj(c2t('java/lang/Class'), { $type: type })
# Run class initialization code. Superclasses get init'ed first. We
# don't want to call this more than once per class, so don't do dynamic
# lookup. See spec [2.17.4][1].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/Concepts.doc.html#19075
if class_file.super_class
@_class_lookup class_file.super_class
class_file.methods['<clinit>()V']?.run(this)
if cls is 'java/lang/System' # zomg hardcode
class_file.methods['initializeSystemClass()V'].run(this)
@classes[cls]
# Spec [5.4.3.3][1], [5.4.3.4][2].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#79473
# [2]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#78621
method_lookup: (method_spec) ->
type = c2t method_spec.class
t = type
while t
cls = @class_lookup(t)
method = cls.methods[method_spec.sig]
return method if method?
t = cls.super_class
cls = @class_lookup(type)
ifaces = (c2t(cls.constant_pool.get(i).deref()) for i in cls.interfaces)
while ifaces.length > 0
iface_name = ifaces.shift()
ifc = @class_lookup iface_name
method = ifc.methods[method_spec.sig]
return method if method?
Array::push.apply ifaces,
(c2t(ifc.constant_pool.get(i).deref()) for i in ifc.interfaces)
java_throw @, 'java/lang/NoSuchMethodError',
"No such method found in #{method_spec.class}: #{method_spec.sig}"
# Spec [5.4.3.2][1].
# [1]: http://docs.oracle.com/javase/specs/jvms/se5.0/html/ConstantPool.doc.html#77678
field_lookup: (field_spec) ->
filter_field = (c) -> _.find(c.fields, (f)-> f.name is field_spec.name)
field = @_field_lookup field_spec.class, filter_field
return field if field?
java_throw @, 'java/lang/NoSuchFieldError',
"No such field found in #{field_spec.class}: #{field_spec.name}"
_field_lookup: (class_name, filter_fn) ->
t = c2t class_name
while t
cls = @class_lookup(t)
field = filter_fn cls
return field if field?
ifaces = (cls.constant_pool.get(i).deref() for i in cls.interfaces)
for ifc in ifaces
field = @_field_lookup ifc, filter_fn
return field if field?
t = cls.super_class
null
|
[
{
"context": "n\n username: options.username\n password: options.password\n host: options.host\n port: options.port",
"end": 600,
"score": 0.9983014464378357,
"start": 584,
"tag": "PASSWORD",
"value": "options.password"
}
] | agent/node_modules/mail-listener/src/mail.listener.coffee | awidarto/ecmv1 | 0 | util = require "util"
{EventEmitter} = require "events"
{MailParser} = require "mailparser"
{ImapConnection} = require "imap"
# MailListener class. Can `emit` events in `node.js` fashion.
class MailListener extends EventEmitter
constructor: (options) ->
# set this option to `true` if you want to fetch unread emial immediately on lib start.
@fetchUnreadOnStart = options.fetchUnreadOnStart
@markSeen = options.markSeen
# TODO add validation for required parameters
@imap = new ImapConnection
username: options.username
password: options.password
host: options.host
port: options.port
secure: options.secure
@mailbox = options.mailbox || "INBOX"
# start listener
start: =>
# 1. connect to imap server
@imap.connect (err) =>
if err
util.log "connect to mail server: error #{err}"
@emit "error", err
else
util.log "connect to mail server: success"
@emit "server:connected"
# 2. open mailbox
@imap.openBox @mailbox, false, (err) =>
if err
util.log "open mail box '#{@mailbox}': error #{err}"
@emit "error", err
else
if @fetchUnreadOnStart
@_parseUnreadEmails()
util.log "open mail box '#{@mailbox}': success"
# 3. listen for new emails in the inbox
@imap.on "mail", (id) =>
util.log "new mail arrived with id #{id}"
@emit "mail:arrived", id
# 4. find all unseen emails
@_parseUnreadEmails()
# stop listener
stop: =>
@imap.logout =>
@emit "server:disconnected"
_parseUnreadEmails: =>
@imap.search ["UNSEEN"], (err, searchResults) =>
if err
util.log "error searching unseen emails #{err}"
@emit "error", err
else
util.log "found #{searchResults.length} emails"
if Array.isArray(searchResults) and searchResults.length == 0
util.log "no email were found"
return
# 5. fetch emails
params = {}
if @markSeen
params.markSeen = true
@imap.fetch searchResults, params,
headers:
parse: false
body: true
cb: (fetch) =>
# 6. email was fetched. Parse it!
fetch.on "message", (msg) =>
parser = new MailParser
parser.on "end", (mail) =>
util.log "parsed mail" + util.inspect mail, false, 5
mail.uid = msg.uid
@emit "mail:parsed", mail
msg.on "data", (data) -> parser.write data.toString()
msg.on "end", ->
util.log "fetched message: " + util.inspect(msg, false, 5)
parser.end()
# imap
imap = @imap
module.exports = MailListener | 107755 | util = require "util"
{EventEmitter} = require "events"
{MailParser} = require "mailparser"
{ImapConnection} = require "imap"
# MailListener class. Can `emit` events in `node.js` fashion.
class MailListener extends EventEmitter
constructor: (options) ->
# set this option to `true` if you want to fetch unread emial immediately on lib start.
@fetchUnreadOnStart = options.fetchUnreadOnStart
@markSeen = options.markSeen
# TODO add validation for required parameters
@imap = new ImapConnection
username: options.username
password: <PASSWORD>
host: options.host
port: options.port
secure: options.secure
@mailbox = options.mailbox || "INBOX"
# start listener
start: =>
# 1. connect to imap server
@imap.connect (err) =>
if err
util.log "connect to mail server: error #{err}"
@emit "error", err
else
util.log "connect to mail server: success"
@emit "server:connected"
# 2. open mailbox
@imap.openBox @mailbox, false, (err) =>
if err
util.log "open mail box '#{@mailbox}': error #{err}"
@emit "error", err
else
if @fetchUnreadOnStart
@_parseUnreadEmails()
util.log "open mail box '#{@mailbox}': success"
# 3. listen for new emails in the inbox
@imap.on "mail", (id) =>
util.log "new mail arrived with id #{id}"
@emit "mail:arrived", id
# 4. find all unseen emails
@_parseUnreadEmails()
# stop listener
stop: =>
@imap.logout =>
@emit "server:disconnected"
_parseUnreadEmails: =>
@imap.search ["UNSEEN"], (err, searchResults) =>
if err
util.log "error searching unseen emails #{err}"
@emit "error", err
else
util.log "found #{searchResults.length} emails"
if Array.isArray(searchResults) and searchResults.length == 0
util.log "no email were found"
return
# 5. fetch emails
params = {}
if @markSeen
params.markSeen = true
@imap.fetch searchResults, params,
headers:
parse: false
body: true
cb: (fetch) =>
# 6. email was fetched. Parse it!
fetch.on "message", (msg) =>
parser = new MailParser
parser.on "end", (mail) =>
util.log "parsed mail" + util.inspect mail, false, 5
mail.uid = msg.uid
@emit "mail:parsed", mail
msg.on "data", (data) -> parser.write data.toString()
msg.on "end", ->
util.log "fetched message: " + util.inspect(msg, false, 5)
parser.end()
# imap
imap = @imap
module.exports = MailListener | true | util = require "util"
{EventEmitter} = require "events"
{MailParser} = require "mailparser"
{ImapConnection} = require "imap"
# MailListener class. Can `emit` events in `node.js` fashion.
class MailListener extends EventEmitter
constructor: (options) ->
# set this option to `true` if you want to fetch unread emial immediately on lib start.
@fetchUnreadOnStart = options.fetchUnreadOnStart
@markSeen = options.markSeen
# TODO add validation for required parameters
@imap = new ImapConnection
username: options.username
password: PI:PASSWORD:<PASSWORD>END_PI
host: options.host
port: options.port
secure: options.secure
@mailbox = options.mailbox || "INBOX"
# start listener
start: =>
# 1. connect to imap server
@imap.connect (err) =>
if err
util.log "connect to mail server: error #{err}"
@emit "error", err
else
util.log "connect to mail server: success"
@emit "server:connected"
# 2. open mailbox
@imap.openBox @mailbox, false, (err) =>
if err
util.log "open mail box '#{@mailbox}': error #{err}"
@emit "error", err
else
if @fetchUnreadOnStart
@_parseUnreadEmails()
util.log "open mail box '#{@mailbox}': success"
# 3. listen for new emails in the inbox
@imap.on "mail", (id) =>
util.log "new mail arrived with id #{id}"
@emit "mail:arrived", id
# 4. find all unseen emails
@_parseUnreadEmails()
# stop listener
stop: =>
@imap.logout =>
@emit "server:disconnected"
_parseUnreadEmails: =>
@imap.search ["UNSEEN"], (err, searchResults) =>
if err
util.log "error searching unseen emails #{err}"
@emit "error", err
else
util.log "found #{searchResults.length} emails"
if Array.isArray(searchResults) and searchResults.length == 0
util.log "no email were found"
return
# 5. fetch emails
params = {}
if @markSeen
params.markSeen = true
@imap.fetch searchResults, params,
headers:
parse: false
body: true
cb: (fetch) =>
# 6. email was fetched. Parse it!
fetch.on "message", (msg) =>
parser = new MailParser
parser.on "end", (mail) =>
util.log "parsed mail" + util.inspect mail, false, 5
mail.uid = msg.uid
@emit "mail:parsed", mail
msg.on "data", (data) -> parser.write data.toString()
msg.on "end", ->
util.log "fetched message: " + util.inspect(msg, false, 5)
parser.end()
# imap
imap = @imap
module.exports = MailListener |
[
{
"context": "allback auth: false\n\n vk.getAccessToken \"12345\", ->\n if vk.accessToken is null\n ",
"end": 3346,
"score": 0.4881227910518646,
"start": 3345,
"tag": "PASSWORD",
"value": "5"
},
{
"context": " callback fakeData\n\n vk.getAccessToken \"12345\"\n .then ( accessToken ) ->\n vk.access",
"end": 3566,
"score": 0.5263032913208008,
"start": 3564,
"tag": "PASSWORD",
"value": "45"
},
{
"context": ">\n vk.request = ->\n vk.getAccessToken \"12345\"\n\n expect( vk.appId ).to.equal \"12345\"\n\n\n ",
"end": 3808,
"score": 0.7553502321243286,
"start": 3804,
"tag": "PASSWORD",
"value": "2345"
},
{
"context": "ethod\"\n\n beforeEach ->\n vk.accessToken = \"fake-token\"\n vk.version = \"fake-version\"\n\n it \"shoul",
"end": 7451,
"score": 0.8218563199043274,
"start": 7441,
"tag": "KEY",
"value": "fake-token"
},
{
"context": "ual\n foo: \"bar\"\n access_token: \"fake-token\"\n v: \"fake-version\"\n\n callback fa",
"end": 7862,
"score": 0.9320952296257019,
"start": 7852,
"tag": "KEY",
"value": "fake-token"
},
{
"context": "params.should.deep.equal\n access_token: \"fake-token\"\n v: \"fake-version\"\n\n callback re",
"end": 8691,
"score": 0.8168242573738098,
"start": 8681,
"tag": "KEY",
"value": "fake-token"
}
] | test/vk.coffee | vk-x/vk-api | 4 | describe "vk", ->
vk = null
cleanVk = require "inject!../src/vk"
beforeEach ->
delete window.VK
vk = cleanVk {}
describe "getAuthUrl", ->
it "should use passed app id, permissions and options", ->
url = vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "5.10"
windowStyle: "popup"
redirectUrl: "close.html"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=audio,photos&" +
"redirect_uri=close.html&display=popup&v=5.10&response_type=token"
it "should use correct redirect url for standalone apps", ->
url = vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "5.10"
windowStyle: "popup"
redirectUrl: "https://oauth.vk.com/blank.html"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=audio,photos&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.10&response_type=token"
it "should use sensible defaults", ->
url = vk.getAuthUrl "12345"
expect( vk.version ).to.equal "5.53"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.53&response_type=token"
it "should set vk.version", ->
vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "4.4"
expect( vk.version ).to.equal "4.4"
it "should default to vk.version when version is not specified", ->
vk.version = "1.2.3"
url = vk.getAuthUrl "12345"
expect( vk.version ).to.equal "1.2.3"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=1.2.3&response_type=token"
it "should set vk.appId", ->
vk.getAuthUrl "12345"
expect( vk.appId ).to.equal "12345"
it "should default to vk.appId when appId is not specified", ->
vk.appId = "12345"
url = vk.getAuthUrl()
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.53&response_type=token"
it "vk.version should be initially set to default", ->
expect( vk.version ).to.equal "5.53"
describe "getAccessToken", ->
fakeData =
auth: true
access_token: "fake-token"
it "should get the access token from login.vk.com", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
method.should.equal "GET"
url.should.equal "https://login.vk.com/"
params.should.deep.equal
act: "openapi"
oauth: 1
new: 1
aid: "12345"
location: window.document.location.hostname
callback fakeData
vk.getAccessToken "12345", ( accessToken ) ->
if accessToken is "fake-token"
done()
it "should set vk.accessToken", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback fakeData
vk.getAccessToken "12345", ->
if vk.accessToken is "fake-token"
done()
it "should return null if app is not authenticated", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback auth: false
vk.getAccessToken "12345", ->
if vk.accessToken is null
done()
it "should support promises", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback fakeData
vk.getAccessToken "12345"
.then ( accessToken ) ->
vk.accessToken
if ( vk.accessToken is "fake-token" ) and ( accessToken is "fake-token" )
done()
it "should set vk.appId", ->
vk.request = ->
vk.getAccessToken "12345"
expect( vk.appId ).to.equal "12345"
it "should default to vk.appId when appId is not specified", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
params.aid.should.equal "12345"
callback fakeData
vk.appId = "12345"
vk.getAccessToken().then ( accessToken ) ->
if accessToken is "fake-token"
done()
describe "authWebsite", ->
afterEach ->
window.open.restore()
it "should open a popup, wait for it to close, get access token", ( done ) ->
vk.getAuthUrl = ( appId, permissions, options ) ->
appId.should.equal "12345"
permissions.should.deep.equal [ "foo", "bar" ]
options.should.deep.equal
windowStyle: "popup"
redirectUrl: "close.html"
"fake-url"
sinon.stub window, "open", ( url ) ->
url.should.equal "fake-url"
fakeWindow =
closed: false
setTimeout ->
fakeWindow.closed = true
, 300
fakeWindow
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite "12345", [ "foo", "bar" ], null, ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should pass windowStyle to vk.getAuthUrl()", ( done ) ->
vk.getAuthUrl = ( appId, permissions, options ) ->
options.should.deep.equal
windowStyle: "page"
redirectUrl: "close.html"
"fake-url"
sinon.stub window, "open", ->
closed: true
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite "12345", [ "foo", "bar" ], "page", ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should support promises", ( done ) ->
vk.getAuthUrl = ->
"fake-url"
sinon.stub window, "open", ->
closed: true
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite().then ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should try to get access token first and only login if no luck", ( done ) ->
vk.getAuthUrl = ->
done new Error "tried to log in!"
sinon.stub window, "open", ->
done new Error "tried to open a window!"
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite().then ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
describe "authFrame", ->
it "should use VK.init", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onSuccess()
vk.authFrame ( error ) ->
expect( error ).to.not.be.ok
done()
it "should pass error to callback when onFail is called", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onFail()
vk.authFrame ( error ) ->
expect( error ).to.be.instanceof Error
done()
it "should support promises", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onSuccess()
vk.authFrame().then ->
done()
, ->
done new Error "rejected!"
it "should reject when window.VK is undefined", ( done ) ->
vk.authFrame().then ->
done new Error "resolved!"
, ->
done()
describe "method", ->
fakeMethod = "fake-method"
fakeUrl = "https://api.vk.com/method/fake-method"
beforeEach ->
vk.accessToken = "fake-token"
vk.version = "fake-version"
it "should call @request and then callback(error, data)", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
vk.request = ({ method, url, params, callback }) ->
method.should.equal "POST"
url.should.equal fakeUrl
params.should.deep.equal
foo: "bar"
access_token: "fake-token"
v: "fake-version"
callback fakeData
vk.method fakeMethod, foo: "bar", ( error, response ) ->
expect( error ).to.equal fakeData.error
response.should.equal fakeData.response
done()
it "should support promises", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback response: "foo"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
response.should.equal "foo"
done()
, ( error ) ->
done new Error "rejected!"
it "should default to {} when no params specified", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
vk.request = ({ method, url, params, callback }) ->
params.should.deep.equal
access_token: "fake-token"
v: "fake-version"
callback response: "foo"
vk.method fakeMethod
.then ( response ) ->
response.should.equal "foo"
done()
, ( error ) ->
done new Error "rejected!"
it "should reject promise when data.error exists", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback response: "foo", error: "exists"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
done new Error "resolved!"
, ( error ) ->
expect( error ).to.equal "exists"
done()
it "should auto-retry on 'too many requests' error", ( done ) ->
clock = sinon.useFakeTimers()
ERROR_TOO_MANY_REQUESTS = 6
calls = 0
vk.request = ({ method, url, params, callback }) ->
calls += 1
if calls < 3
callback error: error_code: ERROR_TOO_MANY_REQUESTS
clock.tick 310
else
callback response: "success"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
clock.restore()
response.should.equal "success"
done()
, ( error ) ->
clock.restore()
done new Error "rejected!"
it "should proxy calls to VK.api when possible", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
window.VK =
api: ( method, params, callback ) ->
method.should.equal fakeMethod
params.should.deep.equal
foo: "bar"
callback fakeData
vk.request = ->
done new Error "called vk.request!"
vk.method fakeMethod, foo: "bar", ( error, response ) ->
expect( error ).to.equal fakeData.error
response.should.equal fakeData.response
done()
describe "request", ->
fakeUrl = "https://api.vk.com/method/fake-method"
fakeXhr = null
fakeParams =
foo: "foo 2"
bar: "bar/2"
fakeData =
error: "fake error"
response:
foo: "bar"
beforeEach ->
fakeXhr = sinon.useFakeXMLHttpRequest()
fakeXhr.requests = []
fakeXhr.onCreate = ( xhr ) ->
fakeXhr.requests.push xhr
afterEach ->
fakeXhr.restore()
it "should make a get xhr and call back with parsed json", ( done ) ->
vk.request
method: "GET"
url: fakeUrl
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "GET"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal false
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl + "?foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
it "should make a post xhr and call back with parsed json", ( done ) ->
vk.request
method: "POST"
url: fakeUrl
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "POST"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal false
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl
expect( fakeXhr.requests[ 0 ].requestHeaders ).to.have.property "Content-Type"
expect( fakeXhr.requests[ 0 ].requestHeaders[ "Content-Type"] ).to.contain "application/x-www-form-urlencoded"
expect( fakeXhr.requests[ 0 ].requestBody ).to.equal "foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
it "should use credentials when specified", ( done ) ->
vk.request
method: "GET"
url: fakeUrl
withCredentials: true
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "GET"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal true
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl + "?foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
describe "clientMethod", ->
it "should proxy calls to VK.callMethod", ->
window.VK =
callMethod: ( method, one, two ) ->
method.should.equal "fake-method"
one.should.equal 1
two.should.equal 2
"fake-result"
result = vk.clientMethod "fake-method", 1, 2
result.should.equal "fake-result"
describe "on", ->
it "should proxy calls to VK.addCallback", ( done ) ->
window.VK =
addCallback: ( event, listener ) ->
event.should.equal "onApplicationAdded"
listener "foo", "bar"
vk.on "onApplicationAdded", ( foo, bar ) ->
foo.should.equal "foo"
bar.should.equal "bar"
done()
describe "off", ->
it "should proxy calls to VK.removeCallback", ( done ) ->
fakeListener = ->
window.VK =
removeCallback: ( event, listener ) ->
event.should.equal "onApplicationAdded"
listener.should.equal fakeListener
done()
vk.off "onApplicationAdded", fakeListener
| 16378 | describe "vk", ->
vk = null
cleanVk = require "inject!../src/vk"
beforeEach ->
delete window.VK
vk = cleanVk {}
describe "getAuthUrl", ->
it "should use passed app id, permissions and options", ->
url = vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "5.10"
windowStyle: "popup"
redirectUrl: "close.html"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=audio,photos&" +
"redirect_uri=close.html&display=popup&v=5.10&response_type=token"
it "should use correct redirect url for standalone apps", ->
url = vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "5.10"
windowStyle: "popup"
redirectUrl: "https://oauth.vk.com/blank.html"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=audio,photos&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.10&response_type=token"
it "should use sensible defaults", ->
url = vk.getAuthUrl "12345"
expect( vk.version ).to.equal "5.53"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.53&response_type=token"
it "should set vk.version", ->
vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "4.4"
expect( vk.version ).to.equal "4.4"
it "should default to vk.version when version is not specified", ->
vk.version = "1.2.3"
url = vk.getAuthUrl "12345"
expect( vk.version ).to.equal "1.2.3"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=1.2.3&response_type=token"
it "should set vk.appId", ->
vk.getAuthUrl "12345"
expect( vk.appId ).to.equal "12345"
it "should default to vk.appId when appId is not specified", ->
vk.appId = "12345"
url = vk.getAuthUrl()
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.53&response_type=token"
it "vk.version should be initially set to default", ->
expect( vk.version ).to.equal "5.53"
describe "getAccessToken", ->
fakeData =
auth: true
access_token: "fake-token"
it "should get the access token from login.vk.com", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
method.should.equal "GET"
url.should.equal "https://login.vk.com/"
params.should.deep.equal
act: "openapi"
oauth: 1
new: 1
aid: "12345"
location: window.document.location.hostname
callback fakeData
vk.getAccessToken "12345", ( accessToken ) ->
if accessToken is "fake-token"
done()
it "should set vk.accessToken", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback fakeData
vk.getAccessToken "12345", ->
if vk.accessToken is "fake-token"
done()
it "should return null if app is not authenticated", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback auth: false
vk.getAccessToken "1234<PASSWORD>", ->
if vk.accessToken is null
done()
it "should support promises", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback fakeData
vk.getAccessToken "123<PASSWORD>"
.then ( accessToken ) ->
vk.accessToken
if ( vk.accessToken is "fake-token" ) and ( accessToken is "fake-token" )
done()
it "should set vk.appId", ->
vk.request = ->
vk.getAccessToken "1<PASSWORD>"
expect( vk.appId ).to.equal "12345"
it "should default to vk.appId when appId is not specified", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
params.aid.should.equal "12345"
callback fakeData
vk.appId = "12345"
vk.getAccessToken().then ( accessToken ) ->
if accessToken is "fake-token"
done()
describe "authWebsite", ->
afterEach ->
window.open.restore()
it "should open a popup, wait for it to close, get access token", ( done ) ->
vk.getAuthUrl = ( appId, permissions, options ) ->
appId.should.equal "12345"
permissions.should.deep.equal [ "foo", "bar" ]
options.should.deep.equal
windowStyle: "popup"
redirectUrl: "close.html"
"fake-url"
sinon.stub window, "open", ( url ) ->
url.should.equal "fake-url"
fakeWindow =
closed: false
setTimeout ->
fakeWindow.closed = true
, 300
fakeWindow
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite "12345", [ "foo", "bar" ], null, ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should pass windowStyle to vk.getAuthUrl()", ( done ) ->
vk.getAuthUrl = ( appId, permissions, options ) ->
options.should.deep.equal
windowStyle: "page"
redirectUrl: "close.html"
"fake-url"
sinon.stub window, "open", ->
closed: true
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite "12345", [ "foo", "bar" ], "page", ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should support promises", ( done ) ->
vk.getAuthUrl = ->
"fake-url"
sinon.stub window, "open", ->
closed: true
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite().then ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should try to get access token first and only login if no luck", ( done ) ->
vk.getAuthUrl = ->
done new Error "tried to log in!"
sinon.stub window, "open", ->
done new Error "tried to open a window!"
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite().then ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
describe "authFrame", ->
it "should use VK.init", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onSuccess()
vk.authFrame ( error ) ->
expect( error ).to.not.be.ok
done()
it "should pass error to callback when onFail is called", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onFail()
vk.authFrame ( error ) ->
expect( error ).to.be.instanceof Error
done()
it "should support promises", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onSuccess()
vk.authFrame().then ->
done()
, ->
done new Error "rejected!"
it "should reject when window.VK is undefined", ( done ) ->
vk.authFrame().then ->
done new Error "resolved!"
, ->
done()
describe "method", ->
fakeMethod = "fake-method"
fakeUrl = "https://api.vk.com/method/fake-method"
beforeEach ->
vk.accessToken = "<KEY>"
vk.version = "fake-version"
it "should call @request and then callback(error, data)", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
vk.request = ({ method, url, params, callback }) ->
method.should.equal "POST"
url.should.equal fakeUrl
params.should.deep.equal
foo: "bar"
access_token: "<KEY>"
v: "fake-version"
callback fakeData
vk.method fakeMethod, foo: "bar", ( error, response ) ->
expect( error ).to.equal fakeData.error
response.should.equal fakeData.response
done()
it "should support promises", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback response: "foo"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
response.should.equal "foo"
done()
, ( error ) ->
done new Error "rejected!"
it "should default to {} when no params specified", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
vk.request = ({ method, url, params, callback }) ->
params.should.deep.equal
access_token: "<KEY>"
v: "fake-version"
callback response: "foo"
vk.method fakeMethod
.then ( response ) ->
response.should.equal "foo"
done()
, ( error ) ->
done new Error "rejected!"
it "should reject promise when data.error exists", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback response: "foo", error: "exists"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
done new Error "resolved!"
, ( error ) ->
expect( error ).to.equal "exists"
done()
it "should auto-retry on 'too many requests' error", ( done ) ->
clock = sinon.useFakeTimers()
ERROR_TOO_MANY_REQUESTS = 6
calls = 0
vk.request = ({ method, url, params, callback }) ->
calls += 1
if calls < 3
callback error: error_code: ERROR_TOO_MANY_REQUESTS
clock.tick 310
else
callback response: "success"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
clock.restore()
response.should.equal "success"
done()
, ( error ) ->
clock.restore()
done new Error "rejected!"
it "should proxy calls to VK.api when possible", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
window.VK =
api: ( method, params, callback ) ->
method.should.equal fakeMethod
params.should.deep.equal
foo: "bar"
callback fakeData
vk.request = ->
done new Error "called vk.request!"
vk.method fakeMethod, foo: "bar", ( error, response ) ->
expect( error ).to.equal fakeData.error
response.should.equal fakeData.response
done()
describe "request", ->
fakeUrl = "https://api.vk.com/method/fake-method"
fakeXhr = null
fakeParams =
foo: "foo 2"
bar: "bar/2"
fakeData =
error: "fake error"
response:
foo: "bar"
beforeEach ->
fakeXhr = sinon.useFakeXMLHttpRequest()
fakeXhr.requests = []
fakeXhr.onCreate = ( xhr ) ->
fakeXhr.requests.push xhr
afterEach ->
fakeXhr.restore()
it "should make a get xhr and call back with parsed json", ( done ) ->
vk.request
method: "GET"
url: fakeUrl
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "GET"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal false
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl + "?foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
it "should make a post xhr and call back with parsed json", ( done ) ->
vk.request
method: "POST"
url: fakeUrl
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "POST"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal false
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl
expect( fakeXhr.requests[ 0 ].requestHeaders ).to.have.property "Content-Type"
expect( fakeXhr.requests[ 0 ].requestHeaders[ "Content-Type"] ).to.contain "application/x-www-form-urlencoded"
expect( fakeXhr.requests[ 0 ].requestBody ).to.equal "foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
it "should use credentials when specified", ( done ) ->
vk.request
method: "GET"
url: fakeUrl
withCredentials: true
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "GET"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal true
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl + "?foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
describe "clientMethod", ->
it "should proxy calls to VK.callMethod", ->
window.VK =
callMethod: ( method, one, two ) ->
method.should.equal "fake-method"
one.should.equal 1
two.should.equal 2
"fake-result"
result = vk.clientMethod "fake-method", 1, 2
result.should.equal "fake-result"
describe "on", ->
it "should proxy calls to VK.addCallback", ( done ) ->
window.VK =
addCallback: ( event, listener ) ->
event.should.equal "onApplicationAdded"
listener "foo", "bar"
vk.on "onApplicationAdded", ( foo, bar ) ->
foo.should.equal "foo"
bar.should.equal "bar"
done()
describe "off", ->
it "should proxy calls to VK.removeCallback", ( done ) ->
fakeListener = ->
window.VK =
removeCallback: ( event, listener ) ->
event.should.equal "onApplicationAdded"
listener.should.equal fakeListener
done()
vk.off "onApplicationAdded", fakeListener
| true | describe "vk", ->
vk = null
cleanVk = require "inject!../src/vk"
beforeEach ->
delete window.VK
vk = cleanVk {}
describe "getAuthUrl", ->
it "should use passed app id, permissions and options", ->
url = vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "5.10"
windowStyle: "popup"
redirectUrl: "close.html"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=audio,photos&" +
"redirect_uri=close.html&display=popup&v=5.10&response_type=token"
it "should use correct redirect url for standalone apps", ->
url = vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "5.10"
windowStyle: "popup"
redirectUrl: "https://oauth.vk.com/blank.html"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=audio,photos&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.10&response_type=token"
it "should use sensible defaults", ->
url = vk.getAuthUrl "12345"
expect( vk.version ).to.equal "5.53"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.53&response_type=token"
it "should set vk.version", ->
vk.getAuthUrl "12345", [ "audio", "photos" ],
version: "4.4"
expect( vk.version ).to.equal "4.4"
it "should default to vk.version when version is not specified", ->
vk.version = "1.2.3"
url = vk.getAuthUrl "12345"
expect( vk.version ).to.equal "1.2.3"
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=1.2.3&response_type=token"
it "should set vk.appId", ->
vk.getAuthUrl "12345"
expect( vk.appId ).to.equal "12345"
it "should default to vk.appId when appId is not specified", ->
vk.appId = "12345"
url = vk.getAuthUrl()
url.should.equal "https://oauth.vk.com/authorize?client_id=12345&scope=&" +
"redirect_uri=https%3A%2F%2Foauth.vk.com%2Fblank.html&display=popup&v=5.53&response_type=token"
it "vk.version should be initially set to default", ->
expect( vk.version ).to.equal "5.53"
describe "getAccessToken", ->
fakeData =
auth: true
access_token: "fake-token"
it "should get the access token from login.vk.com", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
method.should.equal "GET"
url.should.equal "https://login.vk.com/"
params.should.deep.equal
act: "openapi"
oauth: 1
new: 1
aid: "12345"
location: window.document.location.hostname
callback fakeData
vk.getAccessToken "12345", ( accessToken ) ->
if accessToken is "fake-token"
done()
it "should set vk.accessToken", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback fakeData
vk.getAccessToken "12345", ->
if vk.accessToken is "fake-token"
done()
it "should return null if app is not authenticated", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback auth: false
vk.getAccessToken "1234PI:PASSWORD:<PASSWORD>END_PI", ->
if vk.accessToken is null
done()
it "should support promises", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback fakeData
vk.getAccessToken "123PI:PASSWORD:<PASSWORD>END_PI"
.then ( accessToken ) ->
vk.accessToken
if ( vk.accessToken is "fake-token" ) and ( accessToken is "fake-token" )
done()
it "should set vk.appId", ->
vk.request = ->
vk.getAccessToken "1PI:PASSWORD:<PASSWORD>END_PI"
expect( vk.appId ).to.equal "12345"
it "should default to vk.appId when appId is not specified", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
params.aid.should.equal "12345"
callback fakeData
vk.appId = "12345"
vk.getAccessToken().then ( accessToken ) ->
if accessToken is "fake-token"
done()
describe "authWebsite", ->
afterEach ->
window.open.restore()
it "should open a popup, wait for it to close, get access token", ( done ) ->
vk.getAuthUrl = ( appId, permissions, options ) ->
appId.should.equal "12345"
permissions.should.deep.equal [ "foo", "bar" ]
options.should.deep.equal
windowStyle: "popup"
redirectUrl: "close.html"
"fake-url"
sinon.stub window, "open", ( url ) ->
url.should.equal "fake-url"
fakeWindow =
closed: false
setTimeout ->
fakeWindow.closed = true
, 300
fakeWindow
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite "12345", [ "foo", "bar" ], null, ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should pass windowStyle to vk.getAuthUrl()", ( done ) ->
vk.getAuthUrl = ( appId, permissions, options ) ->
options.should.deep.equal
windowStyle: "page"
redirectUrl: "close.html"
"fake-url"
sinon.stub window, "open", ->
closed: true
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite "12345", [ "foo", "bar" ], "page", ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should support promises", ( done ) ->
vk.getAuthUrl = ->
"fake-url"
sinon.stub window, "open", ->
closed: true
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite().then ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
it "should try to get access token first and only login if no luck", ( done ) ->
vk.getAuthUrl = ->
done new Error "tried to log in!"
sinon.stub window, "open", ->
done new Error "tried to open a window!"
vk.getAccessToken = ->
Promise.resolve "fake-token"
vk.authWebsite().then ( accessToken ) ->
accessToken.should.equal "fake-token"
done()
describe "authFrame", ->
it "should use VK.init", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onSuccess()
vk.authFrame ( error ) ->
expect( error ).to.not.be.ok
done()
it "should pass error to callback when onFail is called", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onFail()
vk.authFrame ( error ) ->
expect( error ).to.be.instanceof Error
done()
it "should support promises", ( done ) ->
window.VK =
init: ( onSuccess, onFail, version ) ->
version.should.equal "5.53"
onSuccess()
vk.authFrame().then ->
done()
, ->
done new Error "rejected!"
it "should reject when window.VK is undefined", ( done ) ->
vk.authFrame().then ->
done new Error "resolved!"
, ->
done()
describe "method", ->
fakeMethod = "fake-method"
fakeUrl = "https://api.vk.com/method/fake-method"
beforeEach ->
vk.accessToken = "PI:KEY:<KEY>END_PI"
vk.version = "fake-version"
it "should call @request and then callback(error, data)", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
vk.request = ({ method, url, params, callback }) ->
method.should.equal "POST"
url.should.equal fakeUrl
params.should.deep.equal
foo: "bar"
access_token: "PI:KEY:<KEY>END_PI"
v: "fake-version"
callback fakeData
vk.method fakeMethod, foo: "bar", ( error, response ) ->
expect( error ).to.equal fakeData.error
response.should.equal fakeData.response
done()
it "should support promises", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback response: "foo"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
response.should.equal "foo"
done()
, ( error ) ->
done new Error "rejected!"
it "should default to {} when no params specified", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
vk.request = ({ method, url, params, callback }) ->
params.should.deep.equal
access_token: "PI:KEY:<KEY>END_PI"
v: "fake-version"
callback response: "foo"
vk.method fakeMethod
.then ( response ) ->
response.should.equal "foo"
done()
, ( error ) ->
done new Error "rejected!"
it "should reject promise when data.error exists", ( done ) ->
vk.request = ({ method, url, params, callback }) ->
callback response: "foo", error: "exists"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
done new Error "resolved!"
, ( error ) ->
expect( error ).to.equal "exists"
done()
it "should auto-retry on 'too many requests' error", ( done ) ->
clock = sinon.useFakeTimers()
ERROR_TOO_MANY_REQUESTS = 6
calls = 0
vk.request = ({ method, url, params, callback }) ->
calls += 1
if calls < 3
callback error: error_code: ERROR_TOO_MANY_REQUESTS
clock.tick 310
else
callback response: "success"
vk.method fakeMethod, foo: "bar"
.then ( response ) ->
clock.restore()
response.should.equal "success"
done()
, ( error ) ->
clock.restore()
done new Error "rejected!"
it "should proxy calls to VK.api when possible", ( done ) ->
fakeData =
error: "fake error"
response:
foo: "bar"
window.VK =
api: ( method, params, callback ) ->
method.should.equal fakeMethod
params.should.deep.equal
foo: "bar"
callback fakeData
vk.request = ->
done new Error "called vk.request!"
vk.method fakeMethod, foo: "bar", ( error, response ) ->
expect( error ).to.equal fakeData.error
response.should.equal fakeData.response
done()
describe "request", ->
fakeUrl = "https://api.vk.com/method/fake-method"
fakeXhr = null
fakeParams =
foo: "foo 2"
bar: "bar/2"
fakeData =
error: "fake error"
response:
foo: "bar"
beforeEach ->
fakeXhr = sinon.useFakeXMLHttpRequest()
fakeXhr.requests = []
fakeXhr.onCreate = ( xhr ) ->
fakeXhr.requests.push xhr
afterEach ->
fakeXhr.restore()
it "should make a get xhr and call back with parsed json", ( done ) ->
vk.request
method: "GET"
url: fakeUrl
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "GET"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal false
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl + "?foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
it "should make a post xhr and call back with parsed json", ( done ) ->
vk.request
method: "POST"
url: fakeUrl
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "POST"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal false
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl
expect( fakeXhr.requests[ 0 ].requestHeaders ).to.have.property "Content-Type"
expect( fakeXhr.requests[ 0 ].requestHeaders[ "Content-Type"] ).to.contain "application/x-www-form-urlencoded"
expect( fakeXhr.requests[ 0 ].requestBody ).to.equal "foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
it "should use credentials when specified", ( done ) ->
vk.request
method: "GET"
url: fakeUrl
withCredentials: true
params: fakeParams
callback: ( data ) ->
data.should.deep.equal fakeData
done()
fakeXhr.requests.length.should.equal 1
expect( fakeXhr.requests[ 0 ].method ).to.equal "GET"
expect( fakeXhr.requests[ 0 ].withCredentials ).to.equal true
expect( fakeXhr.requests[ 0 ].url ).to.equal fakeUrl + "?foo=foo%202&bar=bar%2F2"
fakeXhr.requests[ 0 ].respond 200, {}, JSON.stringify fakeData
describe "clientMethod", ->
it "should proxy calls to VK.callMethod", ->
window.VK =
callMethod: ( method, one, two ) ->
method.should.equal "fake-method"
one.should.equal 1
two.should.equal 2
"fake-result"
result = vk.clientMethod "fake-method", 1, 2
result.should.equal "fake-result"
describe "on", ->
it "should proxy calls to VK.addCallback", ( done ) ->
window.VK =
addCallback: ( event, listener ) ->
event.should.equal "onApplicationAdded"
listener "foo", "bar"
vk.on "onApplicationAdded", ( foo, bar ) ->
foo.should.equal "foo"
bar.should.equal "bar"
done()
describe "off", ->
it "should proxy calls to VK.removeCallback", ( done ) ->
fakeListener = ->
window.VK =
removeCallback: ( event, listener ) ->
event.should.equal "onApplicationAdded"
listener.should.equal fakeListener
done()
vk.off "onApplicationAdded", fakeListener
|
[
{
"context": "sOfQuantumNeutrinoFields\n professor: \"Professor Hubert Farnsworth\"\n books: [\":shrug:\"]\n\n drop: ->\n con",
"end": 337,
"score": 0.9998712539672852,
"start": 320,
"tag": "NAME",
"value": "Hubert Farnsworth"
},
{
"context": "ports.InlineClass = class InternalName\n name: \"Phillip J. Fry\"\n\nModuleName.Reexport = require(\"./simple-module\"",
"end": 669,
"score": 0.9998614192008972,
"start": 655,
"tag": "NAME",
"value": "Phillip J. Fry"
}
] | test/resources/exports/module-exports-alias.coffee | hulu/splitshot | 13 | ModuleName = module.exports
ModuleName.Foo = "Some string"
ModuleName.Bar = {
someObjectLiteral: true
}
ModuleName.function = "fnucotin" # tests reserved word exports
ModuleName.getStuff = (anArgument) ->
return ["stuff", "and more stuff"]
class TheMathematicsOfQuantumNeutrinoFields
professor: "Professor Hubert Farnsworth"
books: [":shrug:"]
drop: ->
console.log("Good riddence")
@register: ->
console.log("Good luck")
ModuleName.MQNF = TheMathematicsOfQuantumNeutrinoFields
ModuleName.ClassInSession = new TheMathematicsOfQuantumNeutrinoFields()
module.exports.InlineClass = class InternalName
name: "Phillip J. Fry"
ModuleName.Reexport = require("./simple-module")
| 65691 | ModuleName = module.exports
ModuleName.Foo = "Some string"
ModuleName.Bar = {
someObjectLiteral: true
}
ModuleName.function = "fnucotin" # tests reserved word exports
ModuleName.getStuff = (anArgument) ->
return ["stuff", "and more stuff"]
class TheMathematicsOfQuantumNeutrinoFields
professor: "Professor <NAME>"
books: [":shrug:"]
drop: ->
console.log("Good riddence")
@register: ->
console.log("Good luck")
ModuleName.MQNF = TheMathematicsOfQuantumNeutrinoFields
ModuleName.ClassInSession = new TheMathematicsOfQuantumNeutrinoFields()
module.exports.InlineClass = class InternalName
name: "<NAME>"
ModuleName.Reexport = require("./simple-module")
| true | ModuleName = module.exports
ModuleName.Foo = "Some string"
ModuleName.Bar = {
someObjectLiteral: true
}
ModuleName.function = "fnucotin" # tests reserved word exports
ModuleName.getStuff = (anArgument) ->
return ["stuff", "and more stuff"]
class TheMathematicsOfQuantumNeutrinoFields
professor: "Professor PI:NAME:<NAME>END_PI"
books: [":shrug:"]
drop: ->
console.log("Good riddence")
@register: ->
console.log("Good luck")
ModuleName.MQNF = TheMathematicsOfQuantumNeutrinoFields
ModuleName.ClassInSession = new TheMathematicsOfQuantumNeutrinoFields()
module.exports.InlineClass = class InternalName
name: "PI:NAME:<NAME>END_PI"
ModuleName.Reexport = require("./simple-module")
|
[
{
"context": "-test', ->\n beforeEach (done) ->\n refKey = MongoKey.escape '$ref'\n record =\n uuid: 'pet-r",
"end": 688,
"score": 0.5765731334686279,
"start": 680,
"tag": "KEY",
"value": "MongoKey"
},
{
"context": "\n beforeEach (done) ->\n refKey = MongoKey.escape '$ref'\n record =\n uuid: 'pet-rock'\n ",
"end": 695,
"score": 0.8798843622207642,
"start": 689,
"tag": "KEY",
"value": "escape"
},
{
"context": "eforeEach (done) ->\n refKey = MongoKey.escape '$ref'\n record =\n uuid: 'pet-rock'\n ",
"end": 701,
"score": 0.8265330195426941,
"start": 696,
"tag": "KEY",
"value": "'$ref"
}
] | test/find-one-spec.coffee | octoblu/meshblu-core-manager-device | 0 | mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
MongoKey = require '../src/mongo-key'
UUID = require 'uuid'
DeviceManager = require '..'
describe 'Find Device', ->
beforeEach (done) ->
database = mongojs 'device-manager-test', ['devices']
@datastore = new Datastore
database: database
collection: 'devices'
database.devices.remove done
beforeEach ->
@uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid)
@sut = new DeviceManager {@datastore, @uuidAliasResolver}
describe 'when called with a subscriberUuid and has devices-test', ->
beforeEach (done) ->
refKey = MongoKey.escape '$ref'
record =
uuid: 'pet-rock'
something: {}
record.something[refKey] = 'oh-no'
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid:'pet-rock'}, (error, @device) => done error
it 'should have a device', ->
expect(@device.uuid).to.equal 'pet-rock'
expect(@device.something['$ref']).to.equal 'oh-no'
describe 'with a projection', ->
beforeEach (done) ->
record =
uuid: 'pet-rock'
blah: 'blargh'
hi: 'low'
@datastore.insert record, done
beforeEach (done) ->
uuid = 'pet-rock'
projection = hi: false
@sut.findOne {uuid, projection}, (error, @device) => done error
it 'should have a device with projection', ->
expect(@device).to.deep.equal uuid: 'pet-rock', blah: 'blargh'
describe 'with a device with the first value being falsy', ->
beforeEach (done) ->
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have a device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
}
describe 'with a device with a collection', ->
beforeEach (done) ->
collectionItem = {}
collectionItem[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
collectionItem
]
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
{ $foo: 'bar' }
]
}
describe 'with a device with a none string collection', ->
beforeEach (done) ->
collectionItem = {}
collectionItem[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
collectionItem
]
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
{ $foo: 'bar' }
]
}
describe 'with a device with a nested object', ->
beforeEach (done) ->
item = {}
item[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
nested: { item }
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
nested:
item: { $foo: 'bar' }
}
| 127461 | mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
MongoKey = require '../src/mongo-key'
UUID = require 'uuid'
DeviceManager = require '..'
describe 'Find Device', ->
beforeEach (done) ->
database = mongojs 'device-manager-test', ['devices']
@datastore = new Datastore
database: database
collection: 'devices'
database.devices.remove done
beforeEach ->
@uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid)
@sut = new DeviceManager {@datastore, @uuidAliasResolver}
describe 'when called with a subscriberUuid and has devices-test', ->
beforeEach (done) ->
refKey = <KEY>.<KEY> <KEY>'
record =
uuid: 'pet-rock'
something: {}
record.something[refKey] = 'oh-no'
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid:'pet-rock'}, (error, @device) => done error
it 'should have a device', ->
expect(@device.uuid).to.equal 'pet-rock'
expect(@device.something['$ref']).to.equal 'oh-no'
describe 'with a projection', ->
beforeEach (done) ->
record =
uuid: 'pet-rock'
blah: 'blargh'
hi: 'low'
@datastore.insert record, done
beforeEach (done) ->
uuid = 'pet-rock'
projection = hi: false
@sut.findOne {uuid, projection}, (error, @device) => done error
it 'should have a device with projection', ->
expect(@device).to.deep.equal uuid: 'pet-rock', blah: 'blargh'
describe 'with a device with the first value being falsy', ->
beforeEach (done) ->
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have a device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
}
describe 'with a device with a collection', ->
beforeEach (done) ->
collectionItem = {}
collectionItem[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
collectionItem
]
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
{ $foo: 'bar' }
]
}
describe 'with a device with a none string collection', ->
beforeEach (done) ->
collectionItem = {}
collectionItem[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
collectionItem
]
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
{ $foo: 'bar' }
]
}
describe 'with a device with a nested object', ->
beforeEach (done) ->
item = {}
item[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
nested: { item }
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
nested:
item: { $foo: 'bar' }
}
| true | mongojs = require 'mongojs'
Datastore = require 'meshblu-core-datastore'
MongoKey = require '../src/mongo-key'
UUID = require 'uuid'
DeviceManager = require '..'
describe 'Find Device', ->
beforeEach (done) ->
database = mongojs 'device-manager-test', ['devices']
@datastore = new Datastore
database: database
collection: 'devices'
database.devices.remove done
beforeEach ->
@uuidAliasResolver = resolve: (uuid, callback) => callback(null, uuid)
@sut = new DeviceManager {@datastore, @uuidAliasResolver}
describe 'when called with a subscriberUuid and has devices-test', ->
beforeEach (done) ->
refKey = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI'
record =
uuid: 'pet-rock'
something: {}
record.something[refKey] = 'oh-no'
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid:'pet-rock'}, (error, @device) => done error
it 'should have a device', ->
expect(@device.uuid).to.equal 'pet-rock'
expect(@device.something['$ref']).to.equal 'oh-no'
describe 'with a projection', ->
beforeEach (done) ->
record =
uuid: 'pet-rock'
blah: 'blargh'
hi: 'low'
@datastore.insert record, done
beforeEach (done) ->
uuid = 'pet-rock'
projection = hi: false
@sut.findOne {uuid, projection}, (error, @device) => done error
it 'should have a device with projection', ->
expect(@device).to.deep.equal uuid: 'pet-rock', blah: 'blargh'
describe 'with a device with the first value being falsy', ->
beforeEach (done) ->
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have a device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
}
describe 'with a device with a collection', ->
beforeEach (done) ->
collectionItem = {}
collectionItem[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
collectionItem
]
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
{ $foo: 'bar' }
]
}
describe 'with a device with a none string collection', ->
beforeEach (done) ->
collectionItem = {}
collectionItem[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
collectionItem
]
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
collection: [
{ $foo: 'bar' }
]
}
describe 'with a device with a nested object', ->
beforeEach (done) ->
item = {}
item[MongoKey.escape('$foo')] = 'bar'
record =
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
nested: { item }
@datastore.insert record, done
beforeEach (done) ->
@sut.findOne {uuid: 'pet-rocky'}, (error, @device) => done error
it 'should have the full device', ->
expect(@device).to.deep.equal {
online: false
uuid: 'pet-rocky'
blah: 'blargh'
hi: 'low'
super: 'duper'
nested:
item: { $foo: 'bar' }
}
|
[
{
"context": " getClientsForMap = ->\n smallimap.addMapIcon('Sebastian Helzle IT-Consulting, Karlsruhe', 'Hey, this is where I ",
"end": 546,
"score": 0.9998542666435242,
"start": 530,
"tag": "NAME",
"value": "Sebastian Helzle"
}
] | public/template/vendor/dotted-map/coffee/demo.coffee | hafizhhadi/Fashionista | 2 |
(($) ->
debugMode = true
testIntervalId = -1
markerPath = 'images/marker.png'
siLogoPath = 'images/si.png'
myLogoPath = 'images/sh-it.png'
mapOptions =
dotRadius: 3
width: 920
height: 460
colors:
lights: ["#fdf6e3", "#fafafa", "#dddddd", "#cccccc", "#bbbbbb"]
darks: ["#777777", "#888888", "#999999", "#aaaaaa"]
log = (message) ->
window.console?.log message if debugMode
# Query clients from the server and show them on the map
getClientsForMap = ->
smallimap.addMapIcon('Sebastian Helzle IT-Consulting, Karlsruhe', 'Hey, this is where I live!', markerPath, myLogoPath, 8.38, 49)
smallimap.addMapIcon('Small Improvements, Berlin', 'Easy performance review software online.', markerPath, siLogoPath, 13.40185, 52.52564)
smallimap.addMapIcon('Sample Company, Rio', 'Somewhere in brazil', markerPath, siLogoPath, -43.173, -22.925)
# Test function for the map which creates random events all over the world
window.runSmallimapTest = ->
testIntervalId = setInterval ->
event = new $.si.smallimap.events.BlipEvent smallimap,
latitude: Math.random() * 180 - 90
longitude: Math.random() * 360 - 180
color: '#ff3333'
eventRadius: 5
duration: 3000
weight: 0.6
smallimap.enqueueEvent event
, 512
"""
lastX = 0
lastY = 0
pxToX = (px) -> Math.floor(px / smallimap.dotDiameter)
pyToY = (py) -> Math.floor(py / smallimap.dotDiameter)
$('#smallimap').mousemove(function (event) {
var px = event.pageX - $(this).offset().left,// - smallimap.width,
py = event.pageY - $(this).offset().top,
x = pxToX(px),
y = pyToY(py);
if(x != lastX || y != lastY) {
var inEvent = new $.si.smallimap.events.LensEvent(smallimap, {
longitude: smallimap.xToLong(x),
latitude: smallimap.yToLat(y),
eventRadius: 0,
duration: 128,
fade: "in"
});
smallimap.enqueueEvent(inEvent);
var outEvent = new $.si.smallimap.events.LensEvent(smallimap, {
longitude: smallimap.xToLong(lastX),
latitude: smallimap.yToLat(lastY),
eventRadius: 0,
delay: 128,
duration: 256,
fade: "out"
});
smallimap.enqueueEvent(outEvent);
lastX = x
lastY = y
}
});
"""
window.stopSmallimapTest = ->
clearInterval testIntervalId
# Init smallipops
$('.smallipop').smallipop
theme: 'black'
cssAnimations:
enabled: true
show: 'animated flipInX'
hide: 'animated flipOutX'
# Init map
window.smallimap = $('#smallimap').smallimap(mapOptions).data('api')
# Init metrics client
smallimap.run()
# Get list of clients
getClientsForMap()
$('#startDemoButton').click (e) ->
e.preventDefault()
$('.smallipopTour').smallipop 'tour'
stopSmallimapTest() if testIntervalId
runSmallimapTest()
)(jQuery)
| 70834 |
(($) ->
debugMode = true
testIntervalId = -1
markerPath = 'images/marker.png'
siLogoPath = 'images/si.png'
myLogoPath = 'images/sh-it.png'
mapOptions =
dotRadius: 3
width: 920
height: 460
colors:
lights: ["#fdf6e3", "#fafafa", "#dddddd", "#cccccc", "#bbbbbb"]
darks: ["#777777", "#888888", "#999999", "#aaaaaa"]
log = (message) ->
window.console?.log message if debugMode
# Query clients from the server and show them on the map
getClientsForMap = ->
smallimap.addMapIcon('<NAME> IT-Consulting, Karlsruhe', 'Hey, this is where I live!', markerPath, myLogoPath, 8.38, 49)
smallimap.addMapIcon('Small Improvements, Berlin', 'Easy performance review software online.', markerPath, siLogoPath, 13.40185, 52.52564)
smallimap.addMapIcon('Sample Company, Rio', 'Somewhere in brazil', markerPath, siLogoPath, -43.173, -22.925)
# Test function for the map which creates random events all over the world
window.runSmallimapTest = ->
testIntervalId = setInterval ->
event = new $.si.smallimap.events.BlipEvent smallimap,
latitude: Math.random() * 180 - 90
longitude: Math.random() * 360 - 180
color: '#ff3333'
eventRadius: 5
duration: 3000
weight: 0.6
smallimap.enqueueEvent event
, 512
"""
lastX = 0
lastY = 0
pxToX = (px) -> Math.floor(px / smallimap.dotDiameter)
pyToY = (py) -> Math.floor(py / smallimap.dotDiameter)
$('#smallimap').mousemove(function (event) {
var px = event.pageX - $(this).offset().left,// - smallimap.width,
py = event.pageY - $(this).offset().top,
x = pxToX(px),
y = pyToY(py);
if(x != lastX || y != lastY) {
var inEvent = new $.si.smallimap.events.LensEvent(smallimap, {
longitude: smallimap.xToLong(x),
latitude: smallimap.yToLat(y),
eventRadius: 0,
duration: 128,
fade: "in"
});
smallimap.enqueueEvent(inEvent);
var outEvent = new $.si.smallimap.events.LensEvent(smallimap, {
longitude: smallimap.xToLong(lastX),
latitude: smallimap.yToLat(lastY),
eventRadius: 0,
delay: 128,
duration: 256,
fade: "out"
});
smallimap.enqueueEvent(outEvent);
lastX = x
lastY = y
}
});
"""
window.stopSmallimapTest = ->
clearInterval testIntervalId
# Init smallipops
$('.smallipop').smallipop
theme: 'black'
cssAnimations:
enabled: true
show: 'animated flipInX'
hide: 'animated flipOutX'
# Init map
window.smallimap = $('#smallimap').smallimap(mapOptions).data('api')
# Init metrics client
smallimap.run()
# Get list of clients
getClientsForMap()
$('#startDemoButton').click (e) ->
e.preventDefault()
$('.smallipopTour').smallipop 'tour'
stopSmallimapTest() if testIntervalId
runSmallimapTest()
)(jQuery)
| true |
(($) ->
debugMode = true
testIntervalId = -1
markerPath = 'images/marker.png'
siLogoPath = 'images/si.png'
myLogoPath = 'images/sh-it.png'
mapOptions =
dotRadius: 3
width: 920
height: 460
colors:
lights: ["#fdf6e3", "#fafafa", "#dddddd", "#cccccc", "#bbbbbb"]
darks: ["#777777", "#888888", "#999999", "#aaaaaa"]
log = (message) ->
window.console?.log message if debugMode
# Query clients from the server and show them on the map
getClientsForMap = ->
smallimap.addMapIcon('PI:NAME:<NAME>END_PI IT-Consulting, Karlsruhe', 'Hey, this is where I live!', markerPath, myLogoPath, 8.38, 49)
smallimap.addMapIcon('Small Improvements, Berlin', 'Easy performance review software online.', markerPath, siLogoPath, 13.40185, 52.52564)
smallimap.addMapIcon('Sample Company, Rio', 'Somewhere in brazil', markerPath, siLogoPath, -43.173, -22.925)
# Test function for the map which creates random events all over the world
window.runSmallimapTest = ->
testIntervalId = setInterval ->
event = new $.si.smallimap.events.BlipEvent smallimap,
latitude: Math.random() * 180 - 90
longitude: Math.random() * 360 - 180
color: '#ff3333'
eventRadius: 5
duration: 3000
weight: 0.6
smallimap.enqueueEvent event
, 512
"""
lastX = 0
lastY = 0
pxToX = (px) -> Math.floor(px / smallimap.dotDiameter)
pyToY = (py) -> Math.floor(py / smallimap.dotDiameter)
$('#smallimap').mousemove(function (event) {
var px = event.pageX - $(this).offset().left,// - smallimap.width,
py = event.pageY - $(this).offset().top,
x = pxToX(px),
y = pyToY(py);
if(x != lastX || y != lastY) {
var inEvent = new $.si.smallimap.events.LensEvent(smallimap, {
longitude: smallimap.xToLong(x),
latitude: smallimap.yToLat(y),
eventRadius: 0,
duration: 128,
fade: "in"
});
smallimap.enqueueEvent(inEvent);
var outEvent = new $.si.smallimap.events.LensEvent(smallimap, {
longitude: smallimap.xToLong(lastX),
latitude: smallimap.yToLat(lastY),
eventRadius: 0,
delay: 128,
duration: 256,
fade: "out"
});
smallimap.enqueueEvent(outEvent);
lastX = x
lastY = y
}
});
"""
window.stopSmallimapTest = ->
clearInterval testIntervalId
# Init smallipops
$('.smallipop').smallipop
theme: 'black'
cssAnimations:
enabled: true
show: 'animated flipInX'
hide: 'animated flipOutX'
# Init map
window.smallimap = $('#smallimap').smallimap(mapOptions).data('api')
# Init metrics client
smallimap.run()
# Get list of clients
getClientsForMap()
$('#startDemoButton').click (e) ->
e.preventDefault()
$('.smallipopTour').smallipop 'tour'
stopSmallimapTest() if testIntervalId
runSmallimapTest()
)(jQuery)
|
[
{
"context": "inue to experience issues, please <a href=\"mailto:support@altheahealth.com?subject=Support request for creating user payment",
"end": 4465,
"score": 0.9999274015426636,
"start": 4441,
"tag": "EMAIL",
"value": "support@altheahealth.com"
},
{
"context": "inue to experience issues, please <a href=\"mailto:support@altheahealth.com?subject=Unable to create user payment\">click here",
"end": 4770,
"score": 0.9999256730079651,
"start": 4746,
"tag": "EMAIL",
"value": "support@altheahealth.com"
},
{
"context": "inue to experience issues, please <a href=\"mailto:support@altheahealth.com?subject=Support request for a payment issue&body=",
"end": 7175,
"score": 0.9997624158859253,
"start": 7151,
"tag": "EMAIL",
"value": "support@altheahealth.com"
}
] | app/assets/javascripts/campaigns.js.coffee | sateeshkumardamera/AltheaHealth | 0 | Crowdhoster.campaigns =
init: ->
_this = this
this.timeCheck('#days')
$(document).ready ->
$('.payment_radio').click (event) ->
$('.payment_text#amount_other').attr('disabled', true);
$('.payment_text#amount_other').val("");
$(document).ready ->
$('.payment_radio').click (event) ->
$('#amount_other').attr('disabled', true);
$('#amount_other').val("");
$(document).ready ->
$('.payment_radio_other').click (event) ->
$('.payment_text#amount_other').attr('disabled', false);
$('.payment_text#amount_other').val("");
$("#anonymous").on "change" , ->
if($(this).prop('checked'))
$("#additional_info").attr('value', 'anonymous')
else
$("#additional_info").attr('value', '')
$(".faq_anchor").on "click", ->
$('.faq_content').attr('src', $(this).attr('value'));
$("#video_image").on "click", ->
$("#player").removeClass("hidden")
$("#player").css('display', 'block')
$(this).hide()
# Checkout section functions:
#if($('#checkout').length)
#$('html,body').animate({scrollTop: $('#header')[0].scrollHeight})
$('#quantity').on "change", (e) ->
quantity = $(this).val()
$amount = $('#amount')
new_amount = parseFloat($amount.attr('data-original')) * quantity
$amount.val(new_amount)
$('#total').html(new_amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");)
$('#amount').on "keyup", (e) ->
$(this).addClass('edited')
$('#amount').removeClass('error')
$('.error').hide()
$('.reward_option.active').on "click", (e) ->
$this = $(this)
if(!$(e.target).hasClass('reward_edit'))
$amount = $('#amount')
$this.find('input').prop('checked', true)
$('.reward_option').removeClass('selected').hide()
$this.addClass('selected').show()
$('.reward_edit').show()
$('html,body').animate({scrollTop: $('#checkout').offset().top});
if(!$amount.hasClass('edited'))
$amount.val($this.attr('data-price'))
$('.reward_edit').on "click", (e) ->
e.preventDefault()
$('.reward_edit').hide()
$('.reward_option').removeClass('selected').show()
$('input').prop('checked', false)
$('#amount').removeClass('error')
$('.error').hide()
submitAmountForm: (form) ->
$reward = $('.reward_option.selected')
$amount = $('#amount')
if($reward && $amount.val().length == 0)
$amount.val($reward.attr('data-price'))
this.submit()
else if($reward && (parseFloat($reward.attr('data-price')) > parseFloat($amount.val())))
$amount.addClass('error')
$('.error').html('Amount must be at least $' + $reward.attr('data-price') + ' to select that ' + $('#reward_select').attr('data-reference') + '.').show()
else
this.submit()
submitPaymentForm: (form) ->
$('#refresh-msg').show()
$('#errors').hide()
$('#errors').html('')
$('button[type="submit"]').attr('disabled', true).html('Processing, please wait...')
$('#card_number').removeAttr('name')
$('#security_code').removeAttr('name')
if($("#anonymous").hasClass('checked'))
$("#additional_info").attr('value', 'anonymous')
$form = $(form)
cardData =
number: $form.find('#card_number').val().replace(/\s/g, "")
expiration_month: $form.find('#expiration_month').val()
expiration_year: $form.find('#expiration_year').val()
security_code: $form.find('#security_code').val()
postal_code: $form.find('#billing_postal_code').val()
errors = crowdtilt.card.validate(cardData)
if !$.isEmptyObject(errors)
$.each errors, (index, value) ->
$('#errors').append('<p>' + value + '</p>')
Crowdhoster.campaigns.resetPaymentForm()
else
$.post($form.attr('data-user-create-action'), { email: $(document.getElementById('email')).val() })
.done((user_id) ->
$('#ct_user_id').val(user_id)
crowdtilt.card.create(user_id, cardData, Crowdhoster.campaigns.cardResponseHandler)
)
.fail((jqXHR, textStatus) ->
Crowdhoster.campaigns.resetPaymentForm()
if jqXHR.status == 400
$('#errors').append('<p>Sorry, we weren\'t able to process your contribution. Please try again.</p><br><p>If you continue to experience issues, please <a href="mailto:support@altheahealth.com?subject=Support request for creating user payment">click here</a> to email support.</p>')
else
$('#errors').append('<p>Sorry, we weren\'t able to process your contribution. Please try again.</p><br><p>If you continue to experience issues, please <a href="mailto:support@altheahealth.com?subject=Unable to create user payment">click here</a> to email support.</p>')
)
resetPaymentForm: (with_errors = true) ->
$('#refresh-msg').hide()
$('#errors').show() if with_errors
$('.loader').hide()
$button = $('button[type="submit"]')
$button.attr('disabled', false).html('Confirm payment of $' + $button.attr('data-total'))
$('#card_number').attr('name', 'card_number')
$('#security_code').attr('name', 'security_code')
timeCheck: (element) ->
expiration = $(element).attr("date-element")
date_moment = moment.unix(expiration)
expired = moment().diff(date_moment, "seconds") > 0
if expired
$(element).html "No <span>days left!</span>"
return
months = date_moment.diff(moment(), "months")
days = date_moment.diff(moment(), "days")
refDate = "months"
refDiff = months
if days < 120
hours = date_moment.diff(moment(), "hours")
if hours > 72
refDiff = days
refDate = "days"
else
if hours >= 2
refDiff = hours
refDate = "hours"
else
refDiff = date_moment.diff(moment(), "minutes")
refDate = "minutes"
$(element).html refDiff + "<span style=\"width:100px\">" + refDate + " left</span>"
cardResponseHandler: (response) ->
form = document.getElementById('payment_form')
request_id_token = response.request_id
# store our new request_id
previous_token_elem = $("input[name='ct_tokenize_request_id']")
if (previous_token_elem.length > 0)
previous_token_elem.attr('value', request_id_token)
else
request_input = $('<input name="ct_tokenize_request_id" value="' + request_id_token + '" type="hidden" />');
form.appendChild(request_input[0])
$('#client_timestamp').val((new Date()).getTime())
switch response.status
when 201
card_token = response.card.id
card_input = $('<input name="ct_card_id" value="' + card_token + '" type="hidden" />');
form.appendChild(card_input[0])
form.submit()
else
# show an error, re-enable the form submit button, save a record of errored payment
$('#refresh-msg').hide()
$('#errors').append('<p>An error occurred. Please check your credit card details and try again.</p><br><p>If you continue to experience issues, please <a href="mailto:support@altheahealth.com?subject=Support request for a payment issue&body=PLEASE DESCRIBE YOUR PAYMENT ISSUES HERE">click here</a> to contact support.</p>')
$('#errors').show()
$('.loader').hide()
$button = $('button[type="submit"]')
$button.attr('disabled', false).html('Confirm payment of $' + $button.attr('data-total') )
data = $(form).serializeObject()
data.ct_tokenize_request_error_id = response.error_id
# make sure we don't have sensitive info
delete data.card_number
delete data.security_code
error_path = form.getAttribute('data-error-action')
$.post(error_path, data)
| 174488 | Crowdhoster.campaigns =
init: ->
_this = this
this.timeCheck('#days')
$(document).ready ->
$('.payment_radio').click (event) ->
$('.payment_text#amount_other').attr('disabled', true);
$('.payment_text#amount_other').val("");
$(document).ready ->
$('.payment_radio').click (event) ->
$('#amount_other').attr('disabled', true);
$('#amount_other').val("");
$(document).ready ->
$('.payment_radio_other').click (event) ->
$('.payment_text#amount_other').attr('disabled', false);
$('.payment_text#amount_other').val("");
$("#anonymous").on "change" , ->
if($(this).prop('checked'))
$("#additional_info").attr('value', 'anonymous')
else
$("#additional_info").attr('value', '')
$(".faq_anchor").on "click", ->
$('.faq_content').attr('src', $(this).attr('value'));
$("#video_image").on "click", ->
$("#player").removeClass("hidden")
$("#player").css('display', 'block')
$(this).hide()
# Checkout section functions:
#if($('#checkout').length)
#$('html,body').animate({scrollTop: $('#header')[0].scrollHeight})
$('#quantity').on "change", (e) ->
quantity = $(this).val()
$amount = $('#amount')
new_amount = parseFloat($amount.attr('data-original')) * quantity
$amount.val(new_amount)
$('#total').html(new_amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");)
$('#amount').on "keyup", (e) ->
$(this).addClass('edited')
$('#amount').removeClass('error')
$('.error').hide()
$('.reward_option.active').on "click", (e) ->
$this = $(this)
if(!$(e.target).hasClass('reward_edit'))
$amount = $('#amount')
$this.find('input').prop('checked', true)
$('.reward_option').removeClass('selected').hide()
$this.addClass('selected').show()
$('.reward_edit').show()
$('html,body').animate({scrollTop: $('#checkout').offset().top});
if(!$amount.hasClass('edited'))
$amount.val($this.attr('data-price'))
$('.reward_edit').on "click", (e) ->
e.preventDefault()
$('.reward_edit').hide()
$('.reward_option').removeClass('selected').show()
$('input').prop('checked', false)
$('#amount').removeClass('error')
$('.error').hide()
submitAmountForm: (form) ->
$reward = $('.reward_option.selected')
$amount = $('#amount')
if($reward && $amount.val().length == 0)
$amount.val($reward.attr('data-price'))
this.submit()
else if($reward && (parseFloat($reward.attr('data-price')) > parseFloat($amount.val())))
$amount.addClass('error')
$('.error').html('Amount must be at least $' + $reward.attr('data-price') + ' to select that ' + $('#reward_select').attr('data-reference') + '.').show()
else
this.submit()
submitPaymentForm: (form) ->
$('#refresh-msg').show()
$('#errors').hide()
$('#errors').html('')
$('button[type="submit"]').attr('disabled', true).html('Processing, please wait...')
$('#card_number').removeAttr('name')
$('#security_code').removeAttr('name')
if($("#anonymous").hasClass('checked'))
$("#additional_info").attr('value', 'anonymous')
$form = $(form)
cardData =
number: $form.find('#card_number').val().replace(/\s/g, "")
expiration_month: $form.find('#expiration_month').val()
expiration_year: $form.find('#expiration_year').val()
security_code: $form.find('#security_code').val()
postal_code: $form.find('#billing_postal_code').val()
errors = crowdtilt.card.validate(cardData)
if !$.isEmptyObject(errors)
$.each errors, (index, value) ->
$('#errors').append('<p>' + value + '</p>')
Crowdhoster.campaigns.resetPaymentForm()
else
$.post($form.attr('data-user-create-action'), { email: $(document.getElementById('email')).val() })
.done((user_id) ->
$('#ct_user_id').val(user_id)
crowdtilt.card.create(user_id, cardData, Crowdhoster.campaigns.cardResponseHandler)
)
.fail((jqXHR, textStatus) ->
Crowdhoster.campaigns.resetPaymentForm()
if jqXHR.status == 400
$('#errors').append('<p>Sorry, we weren\'t able to process your contribution. Please try again.</p><br><p>If you continue to experience issues, please <a href="mailto:<EMAIL>?subject=Support request for creating user payment">click here</a> to email support.</p>')
else
$('#errors').append('<p>Sorry, we weren\'t able to process your contribution. Please try again.</p><br><p>If you continue to experience issues, please <a href="mailto:<EMAIL>?subject=Unable to create user payment">click here</a> to email support.</p>')
)
resetPaymentForm: (with_errors = true) ->
$('#refresh-msg').hide()
$('#errors').show() if with_errors
$('.loader').hide()
$button = $('button[type="submit"]')
$button.attr('disabled', false).html('Confirm payment of $' + $button.attr('data-total'))
$('#card_number').attr('name', 'card_number')
$('#security_code').attr('name', 'security_code')
timeCheck: (element) ->
expiration = $(element).attr("date-element")
date_moment = moment.unix(expiration)
expired = moment().diff(date_moment, "seconds") > 0
if expired
$(element).html "No <span>days left!</span>"
return
months = date_moment.diff(moment(), "months")
days = date_moment.diff(moment(), "days")
refDate = "months"
refDiff = months
if days < 120
hours = date_moment.diff(moment(), "hours")
if hours > 72
refDiff = days
refDate = "days"
else
if hours >= 2
refDiff = hours
refDate = "hours"
else
refDiff = date_moment.diff(moment(), "minutes")
refDate = "minutes"
$(element).html refDiff + "<span style=\"width:100px\">" + refDate + " left</span>"
cardResponseHandler: (response) ->
form = document.getElementById('payment_form')
request_id_token = response.request_id
# store our new request_id
previous_token_elem = $("input[name='ct_tokenize_request_id']")
if (previous_token_elem.length > 0)
previous_token_elem.attr('value', request_id_token)
else
request_input = $('<input name="ct_tokenize_request_id" value="' + request_id_token + '" type="hidden" />');
form.appendChild(request_input[0])
$('#client_timestamp').val((new Date()).getTime())
switch response.status
when 201
card_token = response.card.id
card_input = $('<input name="ct_card_id" value="' + card_token + '" type="hidden" />');
form.appendChild(card_input[0])
form.submit()
else
# show an error, re-enable the form submit button, save a record of errored payment
$('#refresh-msg').hide()
$('#errors').append('<p>An error occurred. Please check your credit card details and try again.</p><br><p>If you continue to experience issues, please <a href="mailto:<EMAIL>?subject=Support request for a payment issue&body=PLEASE DESCRIBE YOUR PAYMENT ISSUES HERE">click here</a> to contact support.</p>')
$('#errors').show()
$('.loader').hide()
$button = $('button[type="submit"]')
$button.attr('disabled', false).html('Confirm payment of $' + $button.attr('data-total') )
data = $(form).serializeObject()
data.ct_tokenize_request_error_id = response.error_id
# make sure we don't have sensitive info
delete data.card_number
delete data.security_code
error_path = form.getAttribute('data-error-action')
$.post(error_path, data)
| true | Crowdhoster.campaigns =
init: ->
_this = this
this.timeCheck('#days')
$(document).ready ->
$('.payment_radio').click (event) ->
$('.payment_text#amount_other').attr('disabled', true);
$('.payment_text#amount_other').val("");
$(document).ready ->
$('.payment_radio').click (event) ->
$('#amount_other').attr('disabled', true);
$('#amount_other').val("");
$(document).ready ->
$('.payment_radio_other').click (event) ->
$('.payment_text#amount_other').attr('disabled', false);
$('.payment_text#amount_other').val("");
$("#anonymous").on "change" , ->
if($(this).prop('checked'))
$("#additional_info").attr('value', 'anonymous')
else
$("#additional_info").attr('value', '')
$(".faq_anchor").on "click", ->
$('.faq_content').attr('src', $(this).attr('value'));
$("#video_image").on "click", ->
$("#player").removeClass("hidden")
$("#player").css('display', 'block')
$(this).hide()
# Checkout section functions:
#if($('#checkout').length)
#$('html,body').animate({scrollTop: $('#header')[0].scrollHeight})
$('#quantity').on "change", (e) ->
quantity = $(this).val()
$amount = $('#amount')
new_amount = parseFloat($amount.attr('data-original')) * quantity
$amount.val(new_amount)
$('#total').html(new_amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");)
$('#amount').on "keyup", (e) ->
$(this).addClass('edited')
$('#amount').removeClass('error')
$('.error').hide()
$('.reward_option.active').on "click", (e) ->
$this = $(this)
if(!$(e.target).hasClass('reward_edit'))
$amount = $('#amount')
$this.find('input').prop('checked', true)
$('.reward_option').removeClass('selected').hide()
$this.addClass('selected').show()
$('.reward_edit').show()
$('html,body').animate({scrollTop: $('#checkout').offset().top});
if(!$amount.hasClass('edited'))
$amount.val($this.attr('data-price'))
$('.reward_edit').on "click", (e) ->
e.preventDefault()
$('.reward_edit').hide()
$('.reward_option').removeClass('selected').show()
$('input').prop('checked', false)
$('#amount').removeClass('error')
$('.error').hide()
submitAmountForm: (form) ->
$reward = $('.reward_option.selected')
$amount = $('#amount')
if($reward && $amount.val().length == 0)
$amount.val($reward.attr('data-price'))
this.submit()
else if($reward && (parseFloat($reward.attr('data-price')) > parseFloat($amount.val())))
$amount.addClass('error')
$('.error').html('Amount must be at least $' + $reward.attr('data-price') + ' to select that ' + $('#reward_select').attr('data-reference') + '.').show()
else
this.submit()
submitPaymentForm: (form) ->
$('#refresh-msg').show()
$('#errors').hide()
$('#errors').html('')
$('button[type="submit"]').attr('disabled', true).html('Processing, please wait...')
$('#card_number').removeAttr('name')
$('#security_code').removeAttr('name')
if($("#anonymous").hasClass('checked'))
$("#additional_info").attr('value', 'anonymous')
$form = $(form)
cardData =
number: $form.find('#card_number').val().replace(/\s/g, "")
expiration_month: $form.find('#expiration_month').val()
expiration_year: $form.find('#expiration_year').val()
security_code: $form.find('#security_code').val()
postal_code: $form.find('#billing_postal_code').val()
errors = crowdtilt.card.validate(cardData)
if !$.isEmptyObject(errors)
$.each errors, (index, value) ->
$('#errors').append('<p>' + value + '</p>')
Crowdhoster.campaigns.resetPaymentForm()
else
$.post($form.attr('data-user-create-action'), { email: $(document.getElementById('email')).val() })
.done((user_id) ->
$('#ct_user_id').val(user_id)
crowdtilt.card.create(user_id, cardData, Crowdhoster.campaigns.cardResponseHandler)
)
.fail((jqXHR, textStatus) ->
Crowdhoster.campaigns.resetPaymentForm()
if jqXHR.status == 400
$('#errors').append('<p>Sorry, we weren\'t able to process your contribution. Please try again.</p><br><p>If you continue to experience issues, please <a href="mailto:PI:EMAIL:<EMAIL>END_PI?subject=Support request for creating user payment">click here</a> to email support.</p>')
else
$('#errors').append('<p>Sorry, we weren\'t able to process your contribution. Please try again.</p><br><p>If you continue to experience issues, please <a href="mailto:PI:EMAIL:<EMAIL>END_PI?subject=Unable to create user payment">click here</a> to email support.</p>')
)
resetPaymentForm: (with_errors = true) ->
$('#refresh-msg').hide()
$('#errors').show() if with_errors
$('.loader').hide()
$button = $('button[type="submit"]')
$button.attr('disabled', false).html('Confirm payment of $' + $button.attr('data-total'))
$('#card_number').attr('name', 'card_number')
$('#security_code').attr('name', 'security_code')
timeCheck: (element) ->
expiration = $(element).attr("date-element")
date_moment = moment.unix(expiration)
expired = moment().diff(date_moment, "seconds") > 0
if expired
$(element).html "No <span>days left!</span>"
return
months = date_moment.diff(moment(), "months")
days = date_moment.diff(moment(), "days")
refDate = "months"
refDiff = months
if days < 120
hours = date_moment.diff(moment(), "hours")
if hours > 72
refDiff = days
refDate = "days"
else
if hours >= 2
refDiff = hours
refDate = "hours"
else
refDiff = date_moment.diff(moment(), "minutes")
refDate = "minutes"
$(element).html refDiff + "<span style=\"width:100px\">" + refDate + " left</span>"
cardResponseHandler: (response) ->
form = document.getElementById('payment_form')
request_id_token = response.request_id
# store our new request_id
previous_token_elem = $("input[name='ct_tokenize_request_id']")
if (previous_token_elem.length > 0)
previous_token_elem.attr('value', request_id_token)
else
request_input = $('<input name="ct_tokenize_request_id" value="' + request_id_token + '" type="hidden" />');
form.appendChild(request_input[0])
$('#client_timestamp').val((new Date()).getTime())
switch response.status
when 201
card_token = response.card.id
card_input = $('<input name="ct_card_id" value="' + card_token + '" type="hidden" />');
form.appendChild(card_input[0])
form.submit()
else
# show an error, re-enable the form submit button, save a record of errored payment
$('#refresh-msg').hide()
$('#errors').append('<p>An error occurred. Please check your credit card details and try again.</p><br><p>If you continue to experience issues, please <a href="mailto:PI:EMAIL:<EMAIL>END_PI?subject=Support request for a payment issue&body=PLEASE DESCRIBE YOUR PAYMENT ISSUES HERE">click here</a> to contact support.</p>')
$('#errors').show()
$('.loader').hide()
$button = $('button[type="submit"]')
$button.attr('disabled', false).html('Confirm payment of $' + $button.attr('data-total') )
data = $(form).serializeObject()
data.ct_tokenize_request_error_id = response.error_id
# make sure we don't have sensitive info
delete data.card_number
delete data.security_code
error_path = form.getAttribute('data-error-action')
$.post(error_path, data)
|
[
{
"context": "_user=process.env.HUBOT_JENKINS_USER\njenkins_pass=process.env.HUBOT_JENKINS_PASSWORD\njenkins_api=process.env.HU",
"end": 1572,
"score": 0.7655249238014221,
"start": 1561,
"tag": "PASSWORD",
"value": "process.env"
},
{
"context": "s.env.HUBOT_JENKINS_USER\njenkins_pass=process.env.HUBOT_JENKINS_PASSWORD\njenkins_api=process.env.HUBOT_JE",
"end": 1578,
"score": 0.7388663291931152,
"start": 1573,
"tag": "PASSWORD",
"value": "HUBOT"
},
{
"context": "UBOT_JENKINS_USER\njenkins_pass=process.env.HUBOT_JENKINS_PASSWORD\njenkins_api=process.env.HUBOT_JENKIN",
"end": 1582,
"score": 0.5058309435844421,
"start": 1580,
"tag": "PASSWORD",
"value": "EN"
},
{
"context": "\t\t\toptions = {\n\t\t\turl: url,\n\t\t\tauth: {\n\t\t\t\t'user': jenkins_user,\n\t\t\t\t'pass': jenkins_pass\n\t\t\t},\n\t\t\tmethod: 'GET',",
"end": 2258,
"score": 0.8409110903739929,
"start": 2246,
"tag": "USERNAME",
"value": "jenkins_user"
},
{
"context": ",\n\t\t\tauth: {\n\t\t\t\t'user': jenkins_user,\n\t\t\t\t'pass': jenkins_pass\n\t\t\t},\n\t\t\tmethod: 'GET',\n\t\t\theaders: {\"Content-Typ",
"end": 2284,
"score": 0.9978528618812561,
"start": 2272,
"tag": "PASSWORD",
"value": "jenkins_pass"
},
{
"context": "Jenkins-Crumb\"]=crumbvalue\n\t\t\t\toptions.auth.pass = jenkins_api\n\t\t\trequest.get options, (error, response, body) -",
"end": 2464,
"score": 0.9772788882255554,
"start": 2453,
"tag": "PASSWORD",
"value": "jenkins_api"
},
{
"context": "ions = {\n\t\t\t\t\turl: url,\n\t\t\t\t\tauth: {\n\t\t\t\t\t\t'user': jenkins_user,\n\t\t\t\t\t\t'pass': jenkins_pass\n\t\t\t\t\t},\n\t\t\t\t\tmethod: ",
"end": 3383,
"score": 0.9964520931243896,
"start": 3371,
"tag": "USERNAME",
"value": "jenkins_user"
},
{
"context": "\tauth: {\n\t\t\t\t\t\t'user': jenkins_user,\n\t\t\t\t\t\t'pass': jenkins_pass\n\t\t\t\t\t},\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\theaders: {\"Cont",
"end": 3411,
"score": 0.9991227984428406,
"start": 3399,
"tag": "PASSWORD",
"value": "jenkins_pass"
},
{
"context": "nkins-Crumb\"]=crumbvalue\n\t\t\t\t\t\toptions.auth.pass = jenkins_api\n\t\t\t\t\trequest.post(options, (error, response, body",
"end": 3624,
"score": 0.9989244937896729,
"start": 3613,
"tag": "PASSWORD",
"value": "jenkins_api"
}
] | scripts/jenkins/scripts-mattermost/addParams.coffee | akash1233/OnBot_Demo | 4 | #-------------------------------------------------------------------------------
# Copyright 2018 Cognizant Technology Solutions
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#-------------------------------------------------------------------------------
#Description:
# Adds a new param by downloading the config.xml file of a jenkins job,
# modifying the config.xml and uploading it
#
#Configuration:
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
#give <jobname> config -> downloads the config.xml file and saves it as <jobname>_config.xml inside 'scripts' folder
#upload <jobname> config -> uploads <jobname>_config.xml from scripts folder as config.xml for <jobname>
#
#Dependencies:
# "elasticSearch": "^0.9.2"
# "request": "2.81.0"
request = require('request')
fs=require('fs')
index = require('./index')
crumb = require('./jenkinscrumb.js')
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=process.env.HUBOT_JENKINS_PASSWORD
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
crumbvalue = ''
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
console.log stdout
if(stdout)
crumbvalue=stdout
module.exports = (robot) ->
cmd_give_config=new RegExp('@' + process.env.HUBOT_NAME + ' give (.*) config')
robot.listen(
(message) ->
return unless message.text
message.text.match cmd_give_config
(msg) ->
console.log "inside addParams"
jobname=msg.match[1]
filepath="scripts/"+jobname+"_config.xml"
url=jenkins_url+"/job/"+jobname+"/config.xml"
options = {
url: url,
auth: {
'user': jenkins_user,
'pass': jenkins_pass
},
method: 'GET',
headers: {"Content-Type":"text/xml"} };
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = jenkins_api
request.get options, (error, response, body) ->
fs.writeFile filepath, body, (err) ->
if(err)
dt="Could not get config for "+jobname
msg.send dt
setTimeout (->index.passData dt),1000
console.log err
else
dt="Config file retreived successfully as "+jobname+"_config.xml"
msg.send dt
setTimeout (->index.passData dt),1000
)
cmd_upload_config=new RegExp('@' + process.env.HUBOT_NAME + ' upload (.*) config')
robot.listen(
(message) ->
return unless message.text
message.text.match cmd_upload_config
(msg) ->
jobname=msg.match[1]
url=jenkins_url+"/job/"+jobname+"/config.xml"
fs.readFile './scripts/'+jobname+'_config.xml', 'utf8', (err, fileData) ->
if(err)
dt="Error in reading XML: " +err
msg.send dt
setTimeout (->index.passData dt),1000
else
options = {
url: url,
auth: {
'user': jenkins_user,
'pass': jenkins_pass
},
method: 'POST',
headers: {"Content-Type":"text/xml"},
body: fileData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = jenkins_api
request.post(options, (error, response, body) ->
if response.statusCode==200
dt="config modified successfully"
msg.send dt
setTimeout (->index.passData dt),1000
else
dt="Could not upload file: Response Status:"+response.statusCode
msg.send dt
setTimeout (->index.passData dt),1000)
)
| 3954 | #-------------------------------------------------------------------------------
# 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.
#-------------------------------------------------------------------------------
#Description:
# Adds a new param by downloading the config.xml file of a jenkins job,
# modifying the config.xml and uploading it
#
#Configuration:
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
#give <jobname> config -> downloads the config.xml file and saves it as <jobname>_config.xml inside 'scripts' folder
#upload <jobname> config -> uploads <jobname>_config.xml from scripts folder as config.xml for <jobname>
#
#Dependencies:
# "elasticSearch": "^0.9.2"
# "request": "2.81.0"
request = require('request')
fs=require('fs')
index = require('./index')
crumb = require('./jenkinscrumb.js')
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=<PASSWORD>.<PASSWORD>_J<PASSWORD>KINS_PASSWORD
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
crumbvalue = ''
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
console.log stdout
if(stdout)
crumbvalue=stdout
module.exports = (robot) ->
cmd_give_config=new RegExp('@' + process.env.HUBOT_NAME + ' give (.*) config')
robot.listen(
(message) ->
return unless message.text
message.text.match cmd_give_config
(msg) ->
console.log "inside addParams"
jobname=msg.match[1]
filepath="scripts/"+jobname+"_config.xml"
url=jenkins_url+"/job/"+jobname+"/config.xml"
options = {
url: url,
auth: {
'user': jenkins_user,
'pass': <PASSWORD>
},
method: 'GET',
headers: {"Content-Type":"text/xml"} };
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = <PASSWORD>
request.get options, (error, response, body) ->
fs.writeFile filepath, body, (err) ->
if(err)
dt="Could not get config for "+jobname
msg.send dt
setTimeout (->index.passData dt),1000
console.log err
else
dt="Config file retreived successfully as "+jobname+"_config.xml"
msg.send dt
setTimeout (->index.passData dt),1000
)
cmd_upload_config=new RegExp('@' + process.env.HUBOT_NAME + ' upload (.*) config')
robot.listen(
(message) ->
return unless message.text
message.text.match cmd_upload_config
(msg) ->
jobname=msg.match[1]
url=jenkins_url+"/job/"+jobname+"/config.xml"
fs.readFile './scripts/'+jobname+'_config.xml', 'utf8', (err, fileData) ->
if(err)
dt="Error in reading XML: " +err
msg.send dt
setTimeout (->index.passData dt),1000
else
options = {
url: url,
auth: {
'user': jenkins_user,
'pass': <PASSWORD>
},
method: 'POST',
headers: {"Content-Type":"text/xml"},
body: fileData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = <PASSWORD>
request.post(options, (error, response, body) ->
if response.statusCode==200
dt="config modified successfully"
msg.send dt
setTimeout (->index.passData dt),1000
else
dt="Could not upload file: Response Status:"+response.statusCode
msg.send dt
setTimeout (->index.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.
#-------------------------------------------------------------------------------
#Description:
# Adds a new param by downloading the config.xml file of a jenkins job,
# modifying the config.xml and uploading it
#
#Configuration:
# HUBOT_JENKINS_URL
# HUBOT_JENKINS_USER
# HUBOT_JENKINS_PASSWORD
# HUBOT_JENKINS_API_TOKEN
# HUBOT_JENKINS_VERSION
#
#COMMANDS:
#give <jobname> config -> downloads the config.xml file and saves it as <jobname>_config.xml inside 'scripts' folder
#upload <jobname> config -> uploads <jobname>_config.xml from scripts folder as config.xml for <jobname>
#
#Dependencies:
# "elasticSearch": "^0.9.2"
# "request": "2.81.0"
request = require('request')
fs=require('fs')
index = require('./index')
crumb = require('./jenkinscrumb.js')
jenkins_url=process.env.HUBOT_JENKINS_URL
jenkins_user=process.env.HUBOT_JENKINS_USER
jenkins_pass=PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI_JPI:PASSWORD:<PASSWORD>END_PIKINS_PASSWORD
jenkins_api=process.env.HUBOT_JENKINS_API_TOKEN
jenkins_version=process.env.HUBOT_JENKINS_VERSION
crumbvalue = ''
if jenkins_version >= 2.0
crumb.crumb (stderr, stdout) ->
console.log stdout
if(stdout)
crumbvalue=stdout
module.exports = (robot) ->
cmd_give_config=new RegExp('@' + process.env.HUBOT_NAME + ' give (.*) config')
robot.listen(
(message) ->
return unless message.text
message.text.match cmd_give_config
(msg) ->
console.log "inside addParams"
jobname=msg.match[1]
filepath="scripts/"+jobname+"_config.xml"
url=jenkins_url+"/job/"+jobname+"/config.xml"
options = {
url: url,
auth: {
'user': jenkins_user,
'pass': PI:PASSWORD:<PASSWORD>END_PI
},
method: 'GET',
headers: {"Content-Type":"text/xml"} };
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = PI:PASSWORD:<PASSWORD>END_PI
request.get options, (error, response, body) ->
fs.writeFile filepath, body, (err) ->
if(err)
dt="Could not get config for "+jobname
msg.send dt
setTimeout (->index.passData dt),1000
console.log err
else
dt="Config file retreived successfully as "+jobname+"_config.xml"
msg.send dt
setTimeout (->index.passData dt),1000
)
cmd_upload_config=new RegExp('@' + process.env.HUBOT_NAME + ' upload (.*) config')
robot.listen(
(message) ->
return unless message.text
message.text.match cmd_upload_config
(msg) ->
jobname=msg.match[1]
url=jenkins_url+"/job/"+jobname+"/config.xml"
fs.readFile './scripts/'+jobname+'_config.xml', 'utf8', (err, fileData) ->
if(err)
dt="Error in reading XML: " +err
msg.send dt
setTimeout (->index.passData dt),1000
else
options = {
url: url,
auth: {
'user': jenkins_user,
'pass': PI:PASSWORD:<PASSWORD>END_PI
},
method: 'POST',
headers: {"Content-Type":"text/xml"},
body: fileData};
if jenkins_version >= 2.0
options.headers["Jenkins-Crumb"]=crumbvalue
options.auth.pass = PI:PASSWORD:<PASSWORD>END_PI
request.post(options, (error, response, body) ->
if response.statusCode==200
dt="config modified successfully"
msg.send dt
setTimeout (->index.passData dt),1000
else
dt="Could not upload file: Response Status:"+response.statusCode
msg.send dt
setTimeout (->index.passData dt),1000)
)
|
[
{
"context": "pplication/json\"}, JSON.stringify [{id: 1, text: 'Aaron'}]\n ]\n\nfillInDropdown = (object) ->\n keyEvent",
"end": 254,
"score": 0.9994394779205322,
"start": 249,
"tag": "NAME",
"value": "Aaron"
},
{
"context": " 'keydown')\n fillIn('.select2-container input', 'Aaron')\n keyEvent('.select2-container input', 'keyup')",
"end": 2526,
"score": 0.9985587000846863,
"start": 2521,
"tag": "NAME",
"value": "Aaron"
}
] | test/javascripts/components/select2_test.js.coffee | johan--/tahi | 1 | moduleForComponent 'select2', 'Unit: components/select2',
teardown: -> ETahi.reset()
setup: ->
setupApp()
server.respondWith 'GET', /filtered_objects.*/, [
200, {"Content-Type": "application/json"}, JSON.stringify [{id: 1, text: 'Aaron'}]
]
fillInDropdown = (object) ->
keyEvent('.select2-container input', 'keydown')
fillIn('.select2-container input', object)
keyEvent('.select2-container input', 'keyup')
selectObjectFromDropdown = (object) ->
fillInDropdown(object)
click('.select2-result-selectable', 'body')
appendBasicComponent = (context) ->
Ember.run =>
context.component = context.subject()
context.component.setProperties
multiSelect: true
source: [{id: 1, text: '1'}
{id: 2, text: '2'}
{id: 3, text: '3'}]
context.append()
test "User can make a selection from the dropdown", ->
appendBasicComponent(this)
selectObjectFromDropdown('1')
andThen ->
ok $('.select2-container').select2('val').contains("1")
test "User can remove a selection from the dropdown", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 1, text: '1'}]
ok $('.select2-container').select2('val').contains("1")
click('.select2-search-choice-close')
ok !$('.select2-container').select2('val').contains("1")
test "Making a selection should trigger a callback to add the object", ->
appendBasicComponent(this)
targetObject =
externalAction: (choice) ->
equal choice.id, '1'
@component.set 'selectionSelected', 'externalAction'
@component.set 'targetObject', targetObject
selectObjectFromDropdown('1')
test "Removing a selection should trigger a callback to remove the object", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 1, text: '1'}]
targetObject =
externalAction: (choice) ->
equal choice.id, '1'
@component.set('selectionRemoved', 'externalAction')
@component.set('targetObject', targetObject)
click('.select2-search-choice-close')
test "Typing more than 3 letters with a remote url should make a call to said remote url", ->
Ember.run =>
@component = @subject()
@component.setProperties
multiSelect: true
source: []
remoteSource:
url: "filtered_objects"
dataType: "json"
data: (term) ->
query: term
results: (data) ->
results: data
@append()
keyEvent('.select2-container input', 'keydown')
fillIn('.select2-container input', 'Aaron')
keyEvent('.select2-container input', 'keyup')
waitForElement('.select2-result-selectable')
andThen ->
ok find('.select2-result-selectable', 'body').length
test "Event stream object added should add the object to the selected objects in the dropdown", ->
Ember.run =>
@component = @subject()
@component.setProperties
multiSelect: true
source: [{id: 1, text: '1'}, {id: 2, text: '2'}, {id: 3, text: '3'}]
@append()
ok !$('.select2-container').select2('val').contains("4")
# event stream will update this property when a user is added
@component.setProperties
selectedData: [{id: 4, text: '4'}]
ok $('.select2-container').select2('val').contains("4")
test "Event stream object removed should remove the object from the selected objects in the dropdown", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 4, text: '4'}]
ok $('.select2-container').select2('val').contains("4")
@component.setProperties
selectedData: []
ok !$('.select2-container').select2('val').contains("4")
| 206374 | moduleForComponent 'select2', 'Unit: components/select2',
teardown: -> ETahi.reset()
setup: ->
setupApp()
server.respondWith 'GET', /filtered_objects.*/, [
200, {"Content-Type": "application/json"}, JSON.stringify [{id: 1, text: '<NAME>'}]
]
fillInDropdown = (object) ->
keyEvent('.select2-container input', 'keydown')
fillIn('.select2-container input', object)
keyEvent('.select2-container input', 'keyup')
selectObjectFromDropdown = (object) ->
fillInDropdown(object)
click('.select2-result-selectable', 'body')
appendBasicComponent = (context) ->
Ember.run =>
context.component = context.subject()
context.component.setProperties
multiSelect: true
source: [{id: 1, text: '1'}
{id: 2, text: '2'}
{id: 3, text: '3'}]
context.append()
test "User can make a selection from the dropdown", ->
appendBasicComponent(this)
selectObjectFromDropdown('1')
andThen ->
ok $('.select2-container').select2('val').contains("1")
test "User can remove a selection from the dropdown", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 1, text: '1'}]
ok $('.select2-container').select2('val').contains("1")
click('.select2-search-choice-close')
ok !$('.select2-container').select2('val').contains("1")
test "Making a selection should trigger a callback to add the object", ->
appendBasicComponent(this)
targetObject =
externalAction: (choice) ->
equal choice.id, '1'
@component.set 'selectionSelected', 'externalAction'
@component.set 'targetObject', targetObject
selectObjectFromDropdown('1')
test "Removing a selection should trigger a callback to remove the object", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 1, text: '1'}]
targetObject =
externalAction: (choice) ->
equal choice.id, '1'
@component.set('selectionRemoved', 'externalAction')
@component.set('targetObject', targetObject)
click('.select2-search-choice-close')
test "Typing more than 3 letters with a remote url should make a call to said remote url", ->
Ember.run =>
@component = @subject()
@component.setProperties
multiSelect: true
source: []
remoteSource:
url: "filtered_objects"
dataType: "json"
data: (term) ->
query: term
results: (data) ->
results: data
@append()
keyEvent('.select2-container input', 'keydown')
fillIn('.select2-container input', '<NAME>')
keyEvent('.select2-container input', 'keyup')
waitForElement('.select2-result-selectable')
andThen ->
ok find('.select2-result-selectable', 'body').length
test "Event stream object added should add the object to the selected objects in the dropdown", ->
Ember.run =>
@component = @subject()
@component.setProperties
multiSelect: true
source: [{id: 1, text: '1'}, {id: 2, text: '2'}, {id: 3, text: '3'}]
@append()
ok !$('.select2-container').select2('val').contains("4")
# event stream will update this property when a user is added
@component.setProperties
selectedData: [{id: 4, text: '4'}]
ok $('.select2-container').select2('val').contains("4")
test "Event stream object removed should remove the object from the selected objects in the dropdown", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 4, text: '4'}]
ok $('.select2-container').select2('val').contains("4")
@component.setProperties
selectedData: []
ok !$('.select2-container').select2('val').contains("4")
| true | moduleForComponent 'select2', 'Unit: components/select2',
teardown: -> ETahi.reset()
setup: ->
setupApp()
server.respondWith 'GET', /filtered_objects.*/, [
200, {"Content-Type": "application/json"}, JSON.stringify [{id: 1, text: 'PI:NAME:<NAME>END_PI'}]
]
fillInDropdown = (object) ->
keyEvent('.select2-container input', 'keydown')
fillIn('.select2-container input', object)
keyEvent('.select2-container input', 'keyup')
selectObjectFromDropdown = (object) ->
fillInDropdown(object)
click('.select2-result-selectable', 'body')
appendBasicComponent = (context) ->
Ember.run =>
context.component = context.subject()
context.component.setProperties
multiSelect: true
source: [{id: 1, text: '1'}
{id: 2, text: '2'}
{id: 3, text: '3'}]
context.append()
test "User can make a selection from the dropdown", ->
appendBasicComponent(this)
selectObjectFromDropdown('1')
andThen ->
ok $('.select2-container').select2('val').contains("1")
test "User can remove a selection from the dropdown", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 1, text: '1'}]
ok $('.select2-container').select2('val').contains("1")
click('.select2-search-choice-close')
ok !$('.select2-container').select2('val').contains("1")
test "Making a selection should trigger a callback to add the object", ->
appendBasicComponent(this)
targetObject =
externalAction: (choice) ->
equal choice.id, '1'
@component.set 'selectionSelected', 'externalAction'
@component.set 'targetObject', targetObject
selectObjectFromDropdown('1')
test "Removing a selection should trigger a callback to remove the object", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 1, text: '1'}]
targetObject =
externalAction: (choice) ->
equal choice.id, '1'
@component.set('selectionRemoved', 'externalAction')
@component.set('targetObject', targetObject)
click('.select2-search-choice-close')
test "Typing more than 3 letters with a remote url should make a call to said remote url", ->
Ember.run =>
@component = @subject()
@component.setProperties
multiSelect: true
source: []
remoteSource:
url: "filtered_objects"
dataType: "json"
data: (term) ->
query: term
results: (data) ->
results: data
@append()
keyEvent('.select2-container input', 'keydown')
fillIn('.select2-container input', 'PI:NAME:<NAME>END_PI')
keyEvent('.select2-container input', 'keyup')
waitForElement('.select2-result-selectable')
andThen ->
ok find('.select2-result-selectable', 'body').length
test "Event stream object added should add the object to the selected objects in the dropdown", ->
Ember.run =>
@component = @subject()
@component.setProperties
multiSelect: true
source: [{id: 1, text: '1'}, {id: 2, text: '2'}, {id: 3, text: '3'}]
@append()
ok !$('.select2-container').select2('val').contains("4")
# event stream will update this property when a user is added
@component.setProperties
selectedData: [{id: 4, text: '4'}]
ok $('.select2-container').select2('val').contains("4")
test "Event stream object removed should remove the object from the selected objects in the dropdown", ->
appendBasicComponent(this)
@component.setProperties
selectedData: [{id: 4, text: '4'}]
ok $('.select2-container').select2('val').contains("4")
@component.setProperties
selectedData: []
ok !$('.select2-container').select2('val').contains("4")
|
[
{
"context": ".variations]\n picks = []\n\n testSayKey = 9999 + repetition * variations + count\n\n # get su",
"end": 579,
"score": 0.9865741729736328,
"start": 575,
"tag": "KEY",
"value": "9999"
}
] | tests/data/say-randomization/litexa/main.coffee | Symbitic/litexa | 34 | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
testSay = (context) ->
# test the algorithm directly for a range of variation counts
totalDeviations = {}
repetitionCount = 100.0
testRepetitions = 10
variations = 12
for repetition in [0...repetitionCount]
for count in [2..variations]
picks = []
testSayKey = 9999 + repetition * variations + count
# get successive variations, testing each against the last
lastPick = null
testLength = count * testRepetitions
for i in [0...testLength]
idx = pickSayString context, testSayKey, count
picks.push idx
if idx == lastPick
console.error "picks: #{JSON.stringify picks}"
throw "count #{count} picked the same choice back to back #{idx} == #{lastPick}"
lastPick = idx
# run test to visually inspect the output patterns
density = {}
for i in picks
density[i] = density[i] ? 0
density[i] += 1
deviation = ( Math.abs(testRepetitions - v) for k, v of density )
average = 0
average += d for d in deviation
average /= count
average = average.toFixed(2)
totalDeviations[count] = totalDeviations[count] ? 0
totalDeviations[count] += average / repetitionCount
if repetition < 3
if picks.length > 16
picks = "#{picks[0...16].join(',')}..."
else
picks = picks.join '.'
if count < 10
count = " #{count}"
console.log "count #{count}, deviation #{average} picked #{picks}"
console.log "totalDeviations, #{(k + ':' + v.toFixed(2) for k, v of totalDeviations).join ', '} "
| 75550 | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
testSay = (context) ->
# test the algorithm directly for a range of variation counts
totalDeviations = {}
repetitionCount = 100.0
testRepetitions = 10
variations = 12
for repetition in [0...repetitionCount]
for count in [2..variations]
picks = []
testSayKey = <KEY> + repetition * variations + count
# get successive variations, testing each against the last
lastPick = null
testLength = count * testRepetitions
for i in [0...testLength]
idx = pickSayString context, testSayKey, count
picks.push idx
if idx == lastPick
console.error "picks: #{JSON.stringify picks}"
throw "count #{count} picked the same choice back to back #{idx} == #{lastPick}"
lastPick = idx
# run test to visually inspect the output patterns
density = {}
for i in picks
density[i] = density[i] ? 0
density[i] += 1
deviation = ( Math.abs(testRepetitions - v) for k, v of density )
average = 0
average += d for d in deviation
average /= count
average = average.toFixed(2)
totalDeviations[count] = totalDeviations[count] ? 0
totalDeviations[count] += average / repetitionCount
if repetition < 3
if picks.length > 16
picks = "#{picks[0...16].join(',')}..."
else
picks = picks.join '.'
if count < 10
count = " #{count}"
console.log "count #{count}, deviation #{average} picked #{picks}"
console.log "totalDeviations, #{(k + ':' + v.toFixed(2) for k, v of totalDeviations).join ', '} "
| true | ###
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
###
testSay = (context) ->
# test the algorithm directly for a range of variation counts
totalDeviations = {}
repetitionCount = 100.0
testRepetitions = 10
variations = 12
for repetition in [0...repetitionCount]
for count in [2..variations]
picks = []
testSayKey = PI:KEY:<KEY>END_PI + repetition * variations + count
# get successive variations, testing each against the last
lastPick = null
testLength = count * testRepetitions
for i in [0...testLength]
idx = pickSayString context, testSayKey, count
picks.push idx
if idx == lastPick
console.error "picks: #{JSON.stringify picks}"
throw "count #{count} picked the same choice back to back #{idx} == #{lastPick}"
lastPick = idx
# run test to visually inspect the output patterns
density = {}
for i in picks
density[i] = density[i] ? 0
density[i] += 1
deviation = ( Math.abs(testRepetitions - v) for k, v of density )
average = 0
average += d for d in deviation
average /= count
average = average.toFixed(2)
totalDeviations[count] = totalDeviations[count] ? 0
totalDeviations[count] += average / repetitionCount
if repetition < 3
if picks.length > 16
picks = "#{picks[0...16].join(',')}..."
else
picks = picks.join '.'
if count < 10
count = " #{count}"
console.log "count #{count}, deviation #{average} picked #{picks}"
console.log "totalDeviations, #{(k + ':' + v.toFixed(2) for k, v of totalDeviations).join ', '} "
|
[
{
"context": "# jquery.herounit\n# https://github.com/zamiang/jquery.herounit\n#\n# Copyright (c) 2013 Brennan Mo",
"end": 46,
"score": 0.9993904232978821,
"start": 39,
"tag": "USERNAME",
"value": "zamiang"
},
{
"context": "com/zamiang/jquery.herounit\n#\n# Copyright (c) 2013 Brennan Moore, Artsy\n# Licensed under the MIT license.\n\n(($, wi",
"end": 99,
"score": 0.9998844265937805,
"start": 86,
"tag": "NAME",
"value": "Brennan Moore"
},
{
"context": ".herounit\n#\n# Copyright (c) 2013 Brennan Moore, Artsy\n# Licensed under the MIT license.\n\n(($, window, ",
"end": 105,
"score": 0.7236246466636658,
"start": 103,
"tag": "NAME",
"value": "ts"
}
] | src/jquery.herounit.coffee | zamiang/jquery.herounit | 1 | # jquery.herounit
# https://github.com/zamiang/jquery.herounit
#
# Copyright (c) 2013 Brennan Moore, Artsy
# Licensed under the MIT license.
(($, window, document) ->
pluginName = "heroUnit"
class HeroUnit
requires: ['height', '$img']
optional: ['afterImageLoadcont']
constructor: ($el, settings) ->
for require in @requires
throw "You must pass #{require}" unless settings[require]?
throw "Herounit must be called on an element" unless $el.length > 0
@$el = $el
@settings = settings
@$img = @settings.$img
@detectPhone()
@$img.load (=> @render() )
@onLoad()
@$el.height @settings.height
render: ->
@neutralizeImageSize()
@setImageAttrs()
@centerImage()
@$img.show()
@settings.afterImageLoadcont?()
neutralizeImageSize: ->
@$img.css
height: 'auto'
width: 'auto'
# background image must be sized auto
# sizes image
setImageAttrs: ->
@naturalImageHeight = @$img.height()
@naturalImageWidth = @$img.width()
@imageRatio = @naturalImageWidth / @naturalImageHeight
@minWidth = Math.floor(@settings.height * @imageRatio)
@height = @settings.height or @$el.height()
@width = @$el.width()
# vertically centers image
centerImage: ->
if @IS_PHONE
@$img.width 'auto'
else
if @width < @minWidth
left = - Math.floor((@minWidth - @width) /2)
@$img.width @minWidth
else
left = 0
@$img.width @width
if @height >= @$img.height()
top = 0
else
top = - Math.abs(Math.floor((@height - @$img.height()) /2))
@$img.css
'margin-top' : "#{top}px"
'margin-left': "#{left}px"
onLoad: ->
unless @IS_PHONE
$(window).on "resize.#{pluginName}", @debounce =>
@render()
, 100
##
## Helpers
# from underscore.js
debounce: (func, wait) ->
timeout = 0
return ->
args = arguments
throttler = =>
timeout = null
func args
clearTimeout timeout
timeout = setTimeout(throttler, wait)
# do not bind resize events for 2 reasons
# - iOS resize event fires when document height or width change (such as when items are added to the dom)
# - phones don't exactly 'resize' like browsers do (todo: bind on rotate)
detectPhone: ->
@uagent = navigator.userAgent.toLowerCase()
@IS_PHONE =
@uagent.search('iphone') > -1 or
@uagent.search('ipod') > -1 or
(@uagent.search('android') > -1 and @uagent.search('mobile') > -1)
destroy: ->
$(window).off ".#{pluginName}"
@$img.fadeOut()
$.removeData @$el, "plugin_#{pluginName}"
$.fn[pluginName] = (options) ->
if !$.data(@, "plugin_#{pluginName}")
throw "You must pass settings" unless options?
$.data(@, "plugin_#{pluginName}", new HeroUnit(@, options))
else if $.data(@, "plugin_#{pluginName}")[options]?
$.data(@, "plugin_#{pluginName}")[options] Array::slice.call(arguments, 1)[0], Array::slice.call(arguments, 1)[1]
else
throw "Method '#{options}' does not exist on jQuery.#{pluginName}"
)(jQuery, window, document)
| 47647 | # jquery.herounit
# https://github.com/zamiang/jquery.herounit
#
# Copyright (c) 2013 <NAME>, Ar<NAME>y
# Licensed under the MIT license.
(($, window, document) ->
pluginName = "heroUnit"
class HeroUnit
requires: ['height', '$img']
optional: ['afterImageLoadcont']
constructor: ($el, settings) ->
for require in @requires
throw "You must pass #{require}" unless settings[require]?
throw "Herounit must be called on an element" unless $el.length > 0
@$el = $el
@settings = settings
@$img = @settings.$img
@detectPhone()
@$img.load (=> @render() )
@onLoad()
@$el.height @settings.height
render: ->
@neutralizeImageSize()
@setImageAttrs()
@centerImage()
@$img.show()
@settings.afterImageLoadcont?()
neutralizeImageSize: ->
@$img.css
height: 'auto'
width: 'auto'
# background image must be sized auto
# sizes image
setImageAttrs: ->
@naturalImageHeight = @$img.height()
@naturalImageWidth = @$img.width()
@imageRatio = @naturalImageWidth / @naturalImageHeight
@minWidth = Math.floor(@settings.height * @imageRatio)
@height = @settings.height or @$el.height()
@width = @$el.width()
# vertically centers image
centerImage: ->
if @IS_PHONE
@$img.width 'auto'
else
if @width < @minWidth
left = - Math.floor((@minWidth - @width) /2)
@$img.width @minWidth
else
left = 0
@$img.width @width
if @height >= @$img.height()
top = 0
else
top = - Math.abs(Math.floor((@height - @$img.height()) /2))
@$img.css
'margin-top' : "#{top}px"
'margin-left': "#{left}px"
onLoad: ->
unless @IS_PHONE
$(window).on "resize.#{pluginName}", @debounce =>
@render()
, 100
##
## Helpers
# from underscore.js
debounce: (func, wait) ->
timeout = 0
return ->
args = arguments
throttler = =>
timeout = null
func args
clearTimeout timeout
timeout = setTimeout(throttler, wait)
# do not bind resize events for 2 reasons
# - iOS resize event fires when document height or width change (such as when items are added to the dom)
# - phones don't exactly 'resize' like browsers do (todo: bind on rotate)
detectPhone: ->
@uagent = navigator.userAgent.toLowerCase()
@IS_PHONE =
@uagent.search('iphone') > -1 or
@uagent.search('ipod') > -1 or
(@uagent.search('android') > -1 and @uagent.search('mobile') > -1)
destroy: ->
$(window).off ".#{pluginName}"
@$img.fadeOut()
$.removeData @$el, "plugin_#{pluginName}"
$.fn[pluginName] = (options) ->
if !$.data(@, "plugin_#{pluginName}")
throw "You must pass settings" unless options?
$.data(@, "plugin_#{pluginName}", new HeroUnit(@, options))
else if $.data(@, "plugin_#{pluginName}")[options]?
$.data(@, "plugin_#{pluginName}")[options] Array::slice.call(arguments, 1)[0], Array::slice.call(arguments, 1)[1]
else
throw "Method '#{options}' does not exist on jQuery.#{pluginName}"
)(jQuery, window, document)
| true | # jquery.herounit
# https://github.com/zamiang/jquery.herounit
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI, ArPI:NAME:<NAME>END_PIy
# Licensed under the MIT license.
(($, window, document) ->
pluginName = "heroUnit"
class HeroUnit
requires: ['height', '$img']
optional: ['afterImageLoadcont']
constructor: ($el, settings) ->
for require in @requires
throw "You must pass #{require}" unless settings[require]?
throw "Herounit must be called on an element" unless $el.length > 0
@$el = $el
@settings = settings
@$img = @settings.$img
@detectPhone()
@$img.load (=> @render() )
@onLoad()
@$el.height @settings.height
render: ->
@neutralizeImageSize()
@setImageAttrs()
@centerImage()
@$img.show()
@settings.afterImageLoadcont?()
neutralizeImageSize: ->
@$img.css
height: 'auto'
width: 'auto'
# background image must be sized auto
# sizes image
setImageAttrs: ->
@naturalImageHeight = @$img.height()
@naturalImageWidth = @$img.width()
@imageRatio = @naturalImageWidth / @naturalImageHeight
@minWidth = Math.floor(@settings.height * @imageRatio)
@height = @settings.height or @$el.height()
@width = @$el.width()
# vertically centers image
centerImage: ->
if @IS_PHONE
@$img.width 'auto'
else
if @width < @minWidth
left = - Math.floor((@minWidth - @width) /2)
@$img.width @minWidth
else
left = 0
@$img.width @width
if @height >= @$img.height()
top = 0
else
top = - Math.abs(Math.floor((@height - @$img.height()) /2))
@$img.css
'margin-top' : "#{top}px"
'margin-left': "#{left}px"
onLoad: ->
unless @IS_PHONE
$(window).on "resize.#{pluginName}", @debounce =>
@render()
, 100
##
## Helpers
# from underscore.js
debounce: (func, wait) ->
timeout = 0
return ->
args = arguments
throttler = =>
timeout = null
func args
clearTimeout timeout
timeout = setTimeout(throttler, wait)
# do not bind resize events for 2 reasons
# - iOS resize event fires when document height or width change (such as when items are added to the dom)
# - phones don't exactly 'resize' like browsers do (todo: bind on rotate)
detectPhone: ->
@uagent = navigator.userAgent.toLowerCase()
@IS_PHONE =
@uagent.search('iphone') > -1 or
@uagent.search('ipod') > -1 or
(@uagent.search('android') > -1 and @uagent.search('mobile') > -1)
destroy: ->
$(window).off ".#{pluginName}"
@$img.fadeOut()
$.removeData @$el, "plugin_#{pluginName}"
$.fn[pluginName] = (options) ->
if !$.data(@, "plugin_#{pluginName}")
throw "You must pass settings" unless options?
$.data(@, "plugin_#{pluginName}", new HeroUnit(@, options))
else if $.data(@, "plugin_#{pluginName}")[options]?
$.data(@, "plugin_#{pluginName}")[options] Array::slice.call(arguments, 1)[0], Array::slice.call(arguments, 1)[1]
else
throw "Method '#{options}' does not exist on jQuery.#{pluginName}"
)(jQuery, window, document)
|
[
{
"context": ": new ExpressRedisStore redis_config\n secret: 'rock zappa rock'\n resave: true\n saveUninitialized: true\n\n ",
"end": 205,
"score": 0.9466297626495361,
"start": 190,
"tag": "KEY",
"value": "rock zappa rock"
}
] | examples/redis_setup.coffee | zappajs/zappajs | 50 | @include = ->
redis_config = require './redis_config'
ExpressRedisStore = (require 'connect-redis') @session
@use session:
store: new ExpressRedisStore redis_config
secret: 'rock zappa rock'
resave: true
saveUninitialized: true
###
# Optional: use this to allow broadcast across multiple Socket.IO instances.
SocketIORedisStore = require 'socket.io-redis'
@io.adapter SocketIORedisStore redis_config
###
| 217142 | @include = ->
redis_config = require './redis_config'
ExpressRedisStore = (require 'connect-redis') @session
@use session:
store: new ExpressRedisStore redis_config
secret: '<KEY>'
resave: true
saveUninitialized: true
###
# Optional: use this to allow broadcast across multiple Socket.IO instances.
SocketIORedisStore = require 'socket.io-redis'
@io.adapter SocketIORedisStore redis_config
###
| true | @include = ->
redis_config = require './redis_config'
ExpressRedisStore = (require 'connect-redis') @session
@use session:
store: new ExpressRedisStore redis_config
secret: 'PI:KEY:<KEY>END_PI'
resave: true
saveUninitialized: true
###
# Optional: use this to allow broadcast across multiple Socket.IO instances.
SocketIORedisStore = require 'socket.io-redis'
@io.adapter SocketIORedisStore redis_config
###
|
[
{
"context": "erview A class of the code path segment.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------",
"end": 79,
"score": 0.9998570084571838,
"start": 65,
"tag": "NAME",
"value": "Toru Nagashima"
}
] | src/code-path-analysis/code-path-segment.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview A class of the code path segment.
# @author Toru Nagashima
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
debug = require '../eslint-code-path-analysis-debug-helpers'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Checks whether or not a given segment is reachable.
#
# @param {CodePathSegment} segment - A segment to check.
# @returns {boolean} `true` if the segment is reachable.
###
isReachable = (segment) -> segment.reachable
#------------------------------------------------------------------------------
# Public Interface
#------------------------------------------------------------------------------
###*
# A code path segment.
###
class CodePathSegment
###*
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# This array includes unreachable segments.
# @param {boolean} reachable - A flag which shows this is reachable.
###
constructor: (
###*
# The identifier of this code path.
# Rules use it to store additional information of each rule.
# @type {string}
###
@id
###*
# An array of the previous segments.
# This array includes unreachable segments.
# @type {CodePathSegment[]}
###
@allPrevSegments
###*
# A flag which shows this is reachable.
# @type {boolean}
###
@reachable
) ->
###*
# An array of the next segments.
# @type {CodePathSegment[]}
###
@nextSegments = []
###*
# An array of the previous segments.
# @type {CodePathSegment[]}
###
@prevSegments = @allPrevSegments.filter isReachable
###*
# An array of the next segments.
# This array includes unreachable segments.
# @type {CodePathSegment[]}
###
@allNextSegments = []
# Internal data.
Object.defineProperty @, 'internal',
value:
used: no
loopedPrevSegments: []
### istanbul ignore if ###
if debug.enabled
@internal.nodes = []
@internal.exitNodes = []
###*
# Checks a given previous segment is coming from the end of a loop.
#
# @param {CodePathSegment} segment - A previous segment to check.
# @returns {boolean} `true` if the segment is coming from the end of a loop.
###
isLoopedPrevSegment: (segment) ->
@internal.loopedPrevSegments.indexOf(segment) isnt -1
###*
# Creates the root segment.
#
# @param {string} id - An identifier.
# @returns {CodePathSegment} The created segment.
###
@newRoot: (id) -> new CodePathSegment id, [], yes
###*
# Creates a segment that follows given segments.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newNext: (id, allPrevSegments) ->
new CodePathSegment(
id
CodePathSegment.flattenUnusedSegments allPrevSegments
allPrevSegments.some isReachable
)
###*
# Creates an unreachable segment that follows given segments.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newUnreachable: (id, allPrevSegments) ->
segment = new CodePathSegment(
id
CodePathSegment.flattenUnusedSegments allPrevSegments
no
)
###
# In `if (a) return a; foo();` case, the unreachable segment preceded by
# the return statement is not used but must not be remove.
###
CodePathSegment.markUsed segment
segment
###*
# Creates a segment that follows given segments.
# This factory method does not connect with `allPrevSegments`.
# But this inherits `reachable` flag.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newDisconnected: (id, allPrevSegments) ->
new CodePathSegment id, [], allPrevSegments.some isReachable
###*
# Makes a given segment being used.
#
# And this function registers the segment into the previous segments as a next.
#
# @param {CodePathSegment} segment - A segment to mark.
# @returns {void}
###
@markUsed: (segment) ->
return if segment.internal.used
segment.internal.used = yes
if segment.reachable
for prevSegment in segment.allPrevSegments
prevSegment.allNextSegments.push segment
prevSegment.nextSegments.push segment
else
for prevSegment in segment.allPrevSegments
prevSegment.allNextSegments.push segment
###*
# Marks a previous segment as looped.
#
# @param {CodePathSegment} segment - A segment.
# @param {CodePathSegment} prevSegment - A previous segment to mark.
# @returns {void}
###
@markPrevSegmentAsLooped: (segment, prevSegment) ->
segment.internal.loopedPrevSegments.push prevSegment
###*
# Replaces unused segments with the previous segments of each unused segment.
#
# @param {CodePathSegment[]} segments - An array of segments to replace.
# @returns {CodePathSegment[]} The replaced array.
###
@flattenUnusedSegments: (segments) ->
done = Object.create null
retv = []
for segment in segments
# Ignores duplicated.
continue if done[segment.id]
# Use previous segments if unused.
unless segment.internal.used
for prevSegment in segment.allPrevSegments
unless done[prevSegment.id]
done[prevSegment.id] = yes
retv.push prevSegment
else
done[segment.id] = yes
retv.push segment
retv
module.exports = CodePathSegment
| 57720 | ###*
# @fileoverview A class of the code path segment.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
debug = require '../eslint-code-path-analysis-debug-helpers'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Checks whether or not a given segment is reachable.
#
# @param {CodePathSegment} segment - A segment to check.
# @returns {boolean} `true` if the segment is reachable.
###
isReachable = (segment) -> segment.reachable
#------------------------------------------------------------------------------
# Public Interface
#------------------------------------------------------------------------------
###*
# A code path segment.
###
class CodePathSegment
###*
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# This array includes unreachable segments.
# @param {boolean} reachable - A flag which shows this is reachable.
###
constructor: (
###*
# The identifier of this code path.
# Rules use it to store additional information of each rule.
# @type {string}
###
@id
###*
# An array of the previous segments.
# This array includes unreachable segments.
# @type {CodePathSegment[]}
###
@allPrevSegments
###*
# A flag which shows this is reachable.
# @type {boolean}
###
@reachable
) ->
###*
# An array of the next segments.
# @type {CodePathSegment[]}
###
@nextSegments = []
###*
# An array of the previous segments.
# @type {CodePathSegment[]}
###
@prevSegments = @allPrevSegments.filter isReachable
###*
# An array of the next segments.
# This array includes unreachable segments.
# @type {CodePathSegment[]}
###
@allNextSegments = []
# Internal data.
Object.defineProperty @, 'internal',
value:
used: no
loopedPrevSegments: []
### istanbul ignore if ###
if debug.enabled
@internal.nodes = []
@internal.exitNodes = []
###*
# Checks a given previous segment is coming from the end of a loop.
#
# @param {CodePathSegment} segment - A previous segment to check.
# @returns {boolean} `true` if the segment is coming from the end of a loop.
###
isLoopedPrevSegment: (segment) ->
@internal.loopedPrevSegments.indexOf(segment) isnt -1
###*
# Creates the root segment.
#
# @param {string} id - An identifier.
# @returns {CodePathSegment} The created segment.
###
@newRoot: (id) -> new CodePathSegment id, [], yes
###*
# Creates a segment that follows given segments.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newNext: (id, allPrevSegments) ->
new CodePathSegment(
id
CodePathSegment.flattenUnusedSegments allPrevSegments
allPrevSegments.some isReachable
)
###*
# Creates an unreachable segment that follows given segments.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newUnreachable: (id, allPrevSegments) ->
segment = new CodePathSegment(
id
CodePathSegment.flattenUnusedSegments allPrevSegments
no
)
###
# In `if (a) return a; foo();` case, the unreachable segment preceded by
# the return statement is not used but must not be remove.
###
CodePathSegment.markUsed segment
segment
###*
# Creates a segment that follows given segments.
# This factory method does not connect with `allPrevSegments`.
# But this inherits `reachable` flag.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newDisconnected: (id, allPrevSegments) ->
new CodePathSegment id, [], allPrevSegments.some isReachable
###*
# Makes a given segment being used.
#
# And this function registers the segment into the previous segments as a next.
#
# @param {CodePathSegment} segment - A segment to mark.
# @returns {void}
###
@markUsed: (segment) ->
return if segment.internal.used
segment.internal.used = yes
if segment.reachable
for prevSegment in segment.allPrevSegments
prevSegment.allNextSegments.push segment
prevSegment.nextSegments.push segment
else
for prevSegment in segment.allPrevSegments
prevSegment.allNextSegments.push segment
###*
# Marks a previous segment as looped.
#
# @param {CodePathSegment} segment - A segment.
# @param {CodePathSegment} prevSegment - A previous segment to mark.
# @returns {void}
###
@markPrevSegmentAsLooped: (segment, prevSegment) ->
segment.internal.loopedPrevSegments.push prevSegment
###*
# Replaces unused segments with the previous segments of each unused segment.
#
# @param {CodePathSegment[]} segments - An array of segments to replace.
# @returns {CodePathSegment[]} The replaced array.
###
@flattenUnusedSegments: (segments) ->
done = Object.create null
retv = []
for segment in segments
# Ignores duplicated.
continue if done[segment.id]
# Use previous segments if unused.
unless segment.internal.used
for prevSegment in segment.allPrevSegments
unless done[prevSegment.id]
done[prevSegment.id] = yes
retv.push prevSegment
else
done[segment.id] = yes
retv.push segment
retv
module.exports = CodePathSegment
| true | ###*
# @fileoverview A class of the code path segment.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
debug = require '../eslint-code-path-analysis-debug-helpers'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Checks whether or not a given segment is reachable.
#
# @param {CodePathSegment} segment - A segment to check.
# @returns {boolean} `true` if the segment is reachable.
###
isReachable = (segment) -> segment.reachable
#------------------------------------------------------------------------------
# Public Interface
#------------------------------------------------------------------------------
###*
# A code path segment.
###
class CodePathSegment
###*
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# This array includes unreachable segments.
# @param {boolean} reachable - A flag which shows this is reachable.
###
constructor: (
###*
# The identifier of this code path.
# Rules use it to store additional information of each rule.
# @type {string}
###
@id
###*
# An array of the previous segments.
# This array includes unreachable segments.
# @type {CodePathSegment[]}
###
@allPrevSegments
###*
# A flag which shows this is reachable.
# @type {boolean}
###
@reachable
) ->
###*
# An array of the next segments.
# @type {CodePathSegment[]}
###
@nextSegments = []
###*
# An array of the previous segments.
# @type {CodePathSegment[]}
###
@prevSegments = @allPrevSegments.filter isReachable
###*
# An array of the next segments.
# This array includes unreachable segments.
# @type {CodePathSegment[]}
###
@allNextSegments = []
# Internal data.
Object.defineProperty @, 'internal',
value:
used: no
loopedPrevSegments: []
### istanbul ignore if ###
if debug.enabled
@internal.nodes = []
@internal.exitNodes = []
###*
# Checks a given previous segment is coming from the end of a loop.
#
# @param {CodePathSegment} segment - A previous segment to check.
# @returns {boolean} `true` if the segment is coming from the end of a loop.
###
isLoopedPrevSegment: (segment) ->
@internal.loopedPrevSegments.indexOf(segment) isnt -1
###*
# Creates the root segment.
#
# @param {string} id - An identifier.
# @returns {CodePathSegment} The created segment.
###
@newRoot: (id) -> new CodePathSegment id, [], yes
###*
# Creates a segment that follows given segments.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newNext: (id, allPrevSegments) ->
new CodePathSegment(
id
CodePathSegment.flattenUnusedSegments allPrevSegments
allPrevSegments.some isReachable
)
###*
# Creates an unreachable segment that follows given segments.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newUnreachable: (id, allPrevSegments) ->
segment = new CodePathSegment(
id
CodePathSegment.flattenUnusedSegments allPrevSegments
no
)
###
# In `if (a) return a; foo();` case, the unreachable segment preceded by
# the return statement is not used but must not be remove.
###
CodePathSegment.markUsed segment
segment
###*
# Creates a segment that follows given segments.
# This factory method does not connect with `allPrevSegments`.
# But this inherits `reachable` flag.
#
# @param {string} id - An identifier.
# @param {CodePathSegment[]} allPrevSegments - An array of the previous segments.
# @returns {CodePathSegment} The created segment.
###
@newDisconnected: (id, allPrevSegments) ->
new CodePathSegment id, [], allPrevSegments.some isReachable
###*
# Makes a given segment being used.
#
# And this function registers the segment into the previous segments as a next.
#
# @param {CodePathSegment} segment - A segment to mark.
# @returns {void}
###
@markUsed: (segment) ->
return if segment.internal.used
segment.internal.used = yes
if segment.reachable
for prevSegment in segment.allPrevSegments
prevSegment.allNextSegments.push segment
prevSegment.nextSegments.push segment
else
for prevSegment in segment.allPrevSegments
prevSegment.allNextSegments.push segment
###*
# Marks a previous segment as looped.
#
# @param {CodePathSegment} segment - A segment.
# @param {CodePathSegment} prevSegment - A previous segment to mark.
# @returns {void}
###
@markPrevSegmentAsLooped: (segment, prevSegment) ->
segment.internal.loopedPrevSegments.push prevSegment
###*
# Replaces unused segments with the previous segments of each unused segment.
#
# @param {CodePathSegment[]} segments - An array of segments to replace.
# @returns {CodePathSegment[]} The replaced array.
###
@flattenUnusedSegments: (segments) ->
done = Object.create null
retv = []
for segment in segments
# Ignores duplicated.
continue if done[segment.id]
# Use previous segments if unused.
unless segment.internal.used
for prevSegment in segment.allPrevSegments
unless done[prevSegment.id]
done[prevSegment.id] = yes
retv.push prevSegment
else
done[segment.id] = yes
retv.push segment
retv
module.exports = CodePathSegment
|
[
{
"context": "# Leisure (C) 2016 Bill Burdick and TEAM CTHULHU\n\n# Many thanks to webBoxio for w",
"end": 31,
"score": 0.9998183846473694,
"start": 19,
"tag": "NAME",
"value": "Bill Burdick"
},
{
"context": "ill Burdick and TEAM CTHULHU\n\n# Many thanks to webBoxio for writing atom-html-preview: https://github.com",
"end": 75,
"score": 0.6885625123977661,
"start": 70,
"tag": "USERNAME",
"value": "Boxio"
},
{
"context": "for writing atom-html-preview: https://github.com/webBoxio/atom-html-preview\n\n{CompositeDisposable, Disposab",
"end": 134,
"score": 0.9918379187583923,
"start": 126,
"tag": "USERNAME",
"value": "webBoxio"
},
{
"context": " = document.createElement('iframe')\n # Fix from @kwaak (https://github.com/webBoxio/atom-html-preview/is",
"end": 2354,
"score": 0.9992125630378723,
"start": 2348,
"tag": "USERNAME",
"value": "@kwaak"
},
{
"context": "frame')\n # Fix from @kwaak (https://github.com/webBoxio/atom-html-preview/issues/1/#issuecomment-49639162",
"end": 2383,
"score": 0.9989373087882996,
"start": 2375,
"tag": "USERNAME",
"value": "webBoxio"
}
] | atom-support/leisure/lib/leisure-view.coffee | zot/Leisure | 58 | # Leisure (C) 2016 Bill Burdick and TEAM CTHULHU
# Many thanks to webBoxio for writing atom-html-preview: https://github.com/webBoxio/atom-html-preview
{CompositeDisposable, Disposable} = require 'atom'
{$, $$$, ScrollView} = require 'atom-space-pen-views'
module.exports =
class LeisureView extends ScrollView
atom.deserializers.add(this)
@deserialize: (state)-> new LeisureView(state)
@content: -> @div class: 'leisure-view native-key-bindings', tabindex: -1
editorSub: null
onDidChangeTitle: -> new Disposable()
onDidChangeModified: -> new Disposable()
constructor: (@editorId) ->
super
if @editorId?
@resolveEditor @editorId
@leisureURL = "#{atom.config.get('leisure.leisureURL')}?connect=atom://#{@editorId}"
console.log 'Leisure view', this
else if atom.workspace? then @subscribeToFilePath filePath
else atom.packages.onDidActivatePackage =>
@subscribeToFilePath filePath
serialize: ->
deserializer: 'LeisureView'
filePath: @getPath()
editorId: @editorId
destroy: -> @editorSub.dispose()
subscribeToFilePath: (filePath) ->
@trigger 'title-changed'
@handleEvents()
@renderHTML()
resolveEditor: (editorId) ->
resolve = =>
@editor = @editorForId(editorId)
if @editor?
@trigger 'title-changed' if @editor?
@handleEvents()
else
# The editor this Leisure view was created for has been closed so close
# this Leisure view since a Leisure view cannot be rendered without an editor
atom.workspace?.paneForItem(this)?.destroyItem(this)
if atom.workspace? then resolve()
else atom.packages.onDidActivatePackage =>
resolve()
@renderHTML()
editorForId: (editorId) ->
for editor in atom.workspace.getTextEditors()
return editor if editor.id?.toString() is editorId.toString()
null
handleEvents: =>
@editorSub = new CompositeDisposable
if @editor?
@editorSub.add @editor.onDidChange (e)=>
@leisureWindow.atomSupport?.handleAtomTextChanged e
renderHTML: ->
@showLoading()
if @editor? then @renderHTMLCode()
save: (callback) ->
renderHTMLCode: (text) ->
# if not atom.config.get("atom-html-preview.triggerOnSave") and @editor.getPath()? then @save () =>
@iframe = document.createElement('iframe')
# Fix from @kwaak (https://github.com/webBoxio/atom-html-preview/issues/1/#issuecomment-49639162)
# Allows for the use of relative resources (scripts, styles)
@iframe.setAttribute 'sandbox', 'allow-scripts allow-same-origin'
@iframe.src = @leisureURL
@iframe.view = this
console.log 'set src of', @iframe, "to #{@leisureURL}"
@children().remove()
@glass = $ '<div name="glass"></div>'
@append @iframe
@append @glass
@leisureWindow = @iframe.contentWindow
@leisureWindow.atomView = this
atom.commands.dispatch 'leisure', 'html-changed'
getTitle: ->
if @editor? then "Leisure: #{@editor.getTitle()}"
else 'Leisure'
getURI: -> "leisure://editor/#{@editorId}"
getPath: -> if @editor? then @editor.getPath()
showError: (result) ->
failureMessage = result?.message
@html $$$ ->
@h2 'Leisure view failed'
@h3 failureMessage if failureMessage?
showLoading: -> @html $$$ -> @div class: 'atom-html-spinner', 'Loading Leisure\u2026'
| 37240 | # Leisure (C) 2016 <NAME> and TEAM CTHULHU
# Many thanks to webBoxio for writing atom-html-preview: https://github.com/webBoxio/atom-html-preview
{CompositeDisposable, Disposable} = require 'atom'
{$, $$$, ScrollView} = require 'atom-space-pen-views'
module.exports =
class LeisureView extends ScrollView
atom.deserializers.add(this)
@deserialize: (state)-> new LeisureView(state)
@content: -> @div class: 'leisure-view native-key-bindings', tabindex: -1
editorSub: null
onDidChangeTitle: -> new Disposable()
onDidChangeModified: -> new Disposable()
constructor: (@editorId) ->
super
if @editorId?
@resolveEditor @editorId
@leisureURL = "#{atom.config.get('leisure.leisureURL')}?connect=atom://#{@editorId}"
console.log 'Leisure view', this
else if atom.workspace? then @subscribeToFilePath filePath
else atom.packages.onDidActivatePackage =>
@subscribeToFilePath filePath
serialize: ->
deserializer: 'LeisureView'
filePath: @getPath()
editorId: @editorId
destroy: -> @editorSub.dispose()
subscribeToFilePath: (filePath) ->
@trigger 'title-changed'
@handleEvents()
@renderHTML()
resolveEditor: (editorId) ->
resolve = =>
@editor = @editorForId(editorId)
if @editor?
@trigger 'title-changed' if @editor?
@handleEvents()
else
# The editor this Leisure view was created for has been closed so close
# this Leisure view since a Leisure view cannot be rendered without an editor
atom.workspace?.paneForItem(this)?.destroyItem(this)
if atom.workspace? then resolve()
else atom.packages.onDidActivatePackage =>
resolve()
@renderHTML()
editorForId: (editorId) ->
for editor in atom.workspace.getTextEditors()
return editor if editor.id?.toString() is editorId.toString()
null
handleEvents: =>
@editorSub = new CompositeDisposable
if @editor?
@editorSub.add @editor.onDidChange (e)=>
@leisureWindow.atomSupport?.handleAtomTextChanged e
renderHTML: ->
@showLoading()
if @editor? then @renderHTMLCode()
save: (callback) ->
renderHTMLCode: (text) ->
# if not atom.config.get("atom-html-preview.triggerOnSave") and @editor.getPath()? then @save () =>
@iframe = document.createElement('iframe')
# Fix from @kwaak (https://github.com/webBoxio/atom-html-preview/issues/1/#issuecomment-49639162)
# Allows for the use of relative resources (scripts, styles)
@iframe.setAttribute 'sandbox', 'allow-scripts allow-same-origin'
@iframe.src = @leisureURL
@iframe.view = this
console.log 'set src of', @iframe, "to #{@leisureURL}"
@children().remove()
@glass = $ '<div name="glass"></div>'
@append @iframe
@append @glass
@leisureWindow = @iframe.contentWindow
@leisureWindow.atomView = this
atom.commands.dispatch 'leisure', 'html-changed'
getTitle: ->
if @editor? then "Leisure: #{@editor.getTitle()}"
else 'Leisure'
getURI: -> "leisure://editor/#{@editorId}"
getPath: -> if @editor? then @editor.getPath()
showError: (result) ->
failureMessage = result?.message
@html $$$ ->
@h2 'Leisure view failed'
@h3 failureMessage if failureMessage?
showLoading: -> @html $$$ -> @div class: 'atom-html-spinner', 'Loading Leisure\u2026'
| true | # Leisure (C) 2016 PI:NAME:<NAME>END_PI and TEAM CTHULHU
# Many thanks to webBoxio for writing atom-html-preview: https://github.com/webBoxio/atom-html-preview
{CompositeDisposable, Disposable} = require 'atom'
{$, $$$, ScrollView} = require 'atom-space-pen-views'
module.exports =
class LeisureView extends ScrollView
atom.deserializers.add(this)
@deserialize: (state)-> new LeisureView(state)
@content: -> @div class: 'leisure-view native-key-bindings', tabindex: -1
editorSub: null
onDidChangeTitle: -> new Disposable()
onDidChangeModified: -> new Disposable()
constructor: (@editorId) ->
super
if @editorId?
@resolveEditor @editorId
@leisureURL = "#{atom.config.get('leisure.leisureURL')}?connect=atom://#{@editorId}"
console.log 'Leisure view', this
else if atom.workspace? then @subscribeToFilePath filePath
else atom.packages.onDidActivatePackage =>
@subscribeToFilePath filePath
serialize: ->
deserializer: 'LeisureView'
filePath: @getPath()
editorId: @editorId
destroy: -> @editorSub.dispose()
subscribeToFilePath: (filePath) ->
@trigger 'title-changed'
@handleEvents()
@renderHTML()
resolveEditor: (editorId) ->
resolve = =>
@editor = @editorForId(editorId)
if @editor?
@trigger 'title-changed' if @editor?
@handleEvents()
else
# The editor this Leisure view was created for has been closed so close
# this Leisure view since a Leisure view cannot be rendered without an editor
atom.workspace?.paneForItem(this)?.destroyItem(this)
if atom.workspace? then resolve()
else atom.packages.onDidActivatePackage =>
resolve()
@renderHTML()
editorForId: (editorId) ->
for editor in atom.workspace.getTextEditors()
return editor if editor.id?.toString() is editorId.toString()
null
handleEvents: =>
@editorSub = new CompositeDisposable
if @editor?
@editorSub.add @editor.onDidChange (e)=>
@leisureWindow.atomSupport?.handleAtomTextChanged e
renderHTML: ->
@showLoading()
if @editor? then @renderHTMLCode()
save: (callback) ->
renderHTMLCode: (text) ->
# if not atom.config.get("atom-html-preview.triggerOnSave") and @editor.getPath()? then @save () =>
@iframe = document.createElement('iframe')
# Fix from @kwaak (https://github.com/webBoxio/atom-html-preview/issues/1/#issuecomment-49639162)
# Allows for the use of relative resources (scripts, styles)
@iframe.setAttribute 'sandbox', 'allow-scripts allow-same-origin'
@iframe.src = @leisureURL
@iframe.view = this
console.log 'set src of', @iframe, "to #{@leisureURL}"
@children().remove()
@glass = $ '<div name="glass"></div>'
@append @iframe
@append @glass
@leisureWindow = @iframe.contentWindow
@leisureWindow.atomView = this
atom.commands.dispatch 'leisure', 'html-changed'
getTitle: ->
if @editor? then "Leisure: #{@editor.getTitle()}"
else 'Leisure'
getURI: -> "leisure://editor/#{@editorId}"
getPath: -> if @editor? then @editor.getPath()
showError: (result) ->
failureMessage = result?.message
@html $$$ ->
@h2 'Leisure view failed'
@h3 failureMessage if failureMessage?
showLoading: -> @html $$$ -> @div class: 'atom-html-spinner', 'Loading Leisure\u2026'
|
[
{
"context": " consentCode: 'PAYPAL_CONSENT_CODE'\n token: \"PAYPAL_ACCOUNT_#{randomId()}\"\n generateNonceForNewPaymentMethod nonceParams,",
"end": 5674,
"score": 0.8749251961708069,
"start": 5647,
"tag": "KEY",
"value": "PAYPAL_ACCOUNT_#{randomId()"
}
] | spec/spec_helper.coffee | StreamCo/braintree_node | 0 | try
require('source-map-support').install()
catch err
http = require('http')
{TransactionAmounts} = require('../lib/braintree/test/transaction_amounts')
{Util} = require('../lib/braintree/util')
{Config} = require('../lib/braintree/config')
querystring = require('../vendor/querystring.node.js.511d6a2/querystring')
chai = require("chai")
{Buffer} = require('buffer')
xml2js = require('xml2js')
chai.Assertion.includeStack = true
GLOBAL.assert = chai.assert
GLOBAL.assert.isEmptyArray = (array) ->
assert.isArray(array)
assert.equal(array.length, 0)
GLOBAL.inspect = (object) ->
console.dir(object)
braintree = require('./../lib/braintree.js')
defaultConfig = {
environment: braintree.Environment.Development
merchantId: 'integration_merchant_id'
publicKey: 'integration_public_key'
privateKey: 'integration_private_key'
}
defaultGateway = braintree.connect(defaultConfig)
multiplyString = (string, times) ->
(new Array(times+1)).join(string)
plans = {
trialless: { id: 'integration_trialless_plan', price: '12.34' }
addonDiscountPlan: {
id: 'integration_plan_with_add_ons_and_discounts',
price: '9.99'
}
}
addOns = {
increase10: 'increase_10'
increase20: 'increase_20'
}
escrowTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/escrow",
null,
callback
)
makePastDue = (subscription, callback) ->
defaultGateway.http.put(
"/subscriptions/#{subscription.id}/make_past_due?days_past_due=1",
null,
callback
)
settleTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settle",
null,
callback
)
declineSettlingTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settlement_decline",
null,
callback
)
pendSettlingTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settlement_pending",
null,
callback
)
settlePayPalTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settle",
null,
callback
)
create3DSVerification = (merchantAccountId, params, callback) ->
responseCallback = (err, response) ->
threeDSecureToken = response.threeDSecureVerification.threeDSecureToken
callback(threeDSecureToken)
defaultGateway.http.post(
"/three_d_secure/create_verification/#{merchantAccountId}",
{three_d_secure_verification: params},
responseCallback
)
simulateTrFormPost = (url, trData, inputFormData, callback) ->
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'localhost'
}
formData = Util.convertObjectKeysToUnderscores(inputFormData)
formData.tr_data = trData
requestBody = querystring.stringify(formData)
headers['Content-Length'] = requestBody.length.toString()
options = {
port: specHelper.defaultGateway.config.environment.port
host: specHelper.defaultGateway.config.environment.server
method: 'POST'
headers: headers
path: url
}
if specHelper.defaultGateway.config.environment.ssl
request = https.request(options, ->)
else
request = http.request(options, ->)
request.on('response', (response) ->
callback(null, response.headers.location.split('?', 2)[1])
)
request.write(requestBody)
request.end()
dateToMdy = (date) ->
year = date.getFullYear().toString()
month = (date.getMonth() + 1).toString()
day = date.getDate().toString()
if month.length == 1
month = "0" + month
if day.length == 1
day = "0" + day
formattedDate = year + '-' + month + '-' + day
return formattedDate
nowInEastern = ->
now = new Date
eastern = now.getTime() - (5*60*60*1000)
return new Date(eastern)
randomId = ->
Math.floor(Math.random() * Math.pow(36,8)).toString(36)
doesNotInclude = (array, value) ->
assert.isTrue(array.indexOf(value) is -1)
generateNonceForNewPaymentMethod = (paymentMethodParams, customerId, callback) ->
myHttp = new ClientApiHttp(new Config(specHelper.defaultConfig))
clientTokenOptions = {}
clientTokenOptions.customerId = customerId if customerId
specHelper.defaultGateway.clientToken.generate(clientTokenOptions, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
params = { authorizationFingerprint: clientToken.authorizationFingerprint }
if paymentMethodParams["paypalAccount"]?
params["paypalAccount"] = paymentMethodParams["paypalAccount"]
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
callback(nonce)
)
else
params["creditCard"] = paymentMethodParams["creditCard"]
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode, body) ->
nonce = JSON.parse(body).creditCards[0].nonce
callback(nonce)
)
)
createTransactionToRefund = (callback) ->
transactionParams =
amount: '5.00'
creditCard:
number: '5105105105105100'
expirationDate: '05/2012'
options:
submitForSettlement: true
specHelper.defaultGateway.transaction.sale transactionParams, (err, result) ->
specHelper.settleTransaction result.transaction.id, (err, settleResult) ->
specHelper.defaultGateway.transaction.find result.transaction.id, (err, transaction) ->
callback(transaction)
createPayPalTransactionToRefund = (callback) ->
nonceParams =
paypalAccount:
consentCode: 'PAYPAL_CONSENT_CODE'
token: "PAYPAL_ACCOUNT_#{randomId()}"
generateNonceForNewPaymentMethod nonceParams, null, (nonce) ->
transactionParams =
amount: TransactionAmounts.Authorize
paymentMethodNonce: nonce
options:
submitForSettlement: true
defaultGateway.transaction.sale transactionParams, (err, response) ->
transactionId = response.transaction.id
specHelper.settlePayPalTransaction transactionId, (err, settleResult) ->
defaultGateway.transaction.find transactionId, (err, transaction) ->
callback(transaction)
createEscrowedTransaction = (callback) ->
transactionParams =
merchantAccountId: specHelper.nonDefaultSubMerchantAccountId
amount: '5.00'
serviceFeeAmount: '1.00'
creditCard:
number: '5105105105105100'
expirationDate: '05/2012'
options:
holdInEscrow: true
specHelper.defaultGateway.transaction.sale transactionParams, (err, result) ->
specHelper.escrowTransaction result.transaction.id, (err, settleResult) ->
specHelper.defaultGateway.transaction.find result.transaction.id, (err, transaction) ->
callback(transaction)
decodeClientToken = (encodedClientToken) ->
decodedClientToken = new Buffer(encodedClientToken, "base64").toString("utf8")
unescapedClientToken = decodedClientToken.replace("\\u0026", "&")
unescapedClientToken
createPlanForTests = (attributes, callback) ->
specHelper.defaultGateway.http.post '/plans/create_plan_for_tests', {plan: attributes}, (err, resp) ->
callback()
createModificationForTests = (attributes, callback) ->
specHelper.defaultGateway.http.post '/modifications/create_modification_for_tests', {modification: attributes}, (err, resp) ->
callback()
class ClientApiHttp
timeout: 60000
constructor: (@config) ->
@parser = new xml2js.Parser
explicitRoot: true
get: (url, params, callback) ->
if params
url += '?'
for key, value of params
url += "#{encodeURIComponent(key)}=#{encodeURIComponent(value)}&"
url = url.slice(0, -1)
@request('GET', url, null, callback)
post: (url, body, callback) ->
@request('POST', url, body, callback)
checkHttpStatus: (status) ->
switch status.toString()
when '200', '201', '422' then null
else status.toString()
request: (method, url, body, callback) ->
client = http
options = {
host: @config.environment.server,
port: @config.environment.port,
method: method,
path: "/merchants/" + @config.merchantId + url,
headers: {
'X-ApiVersion': @config.apiVersion,
'Accept': 'application/xml',
'Content-Type': 'application/json',
'User-Agent': 'Braintree Node ' + braintree.version
}
}
if body
requestBody = JSON.stringify(Util.convertObjectKeysToUnderscores(body))
options.headers['Content-Length'] = Buffer.byteLength(requestBody).toString()
theRequest = client.request(options, (response) =>
body = ''
response.on('data', (responseBody) -> body += responseBody )
response.on('end', => callback(response.statusCode, body))
response.on('error', (err) -> callback("Unexpected response error: #{err}"))
)
theRequest.setTimeout(@timeout, -> callback("timeout"))
theRequest.on('error', (err) -> callback("Unexpected request error: #{err}"))
theRequest.write(requestBody) if body
theRequest.end()
GLOBAL.specHelper =
addOns: addOns
braintree: braintree
create3DSVerification: create3DSVerification
dateToMdy: dateToMdy
defaultConfig: defaultConfig
defaultGateway: defaultGateway
defaultConfig: defaultConfig
defaultGateway: defaultGateway
doesNotInclude: doesNotInclude
escrowTransaction: escrowTransaction
makePastDue: makePastDue
multiplyString: multiplyString
nowInEastern: nowInEastern
plans: plans
randomId: randomId
settleTransaction: settleTransaction
declineSettlingTransaction: declineSettlingTransaction
pendSettlingTransaction: pendSettlingTransaction
settlePayPalTransaction: settlePayPalTransaction
simulateTrFormPost: simulateTrFormPost
defaultMerchantAccountId: "sandbox_credit_card"
nonDefaultMerchantAccountId: "sandbox_credit_card_non_default"
nonDefaultSubMerchantAccountId: "sandbox_sub_merchant_account"
threeDSecureMerchantAccountId: "three_d_secure_merchant_account"
clientApiHttp: ClientApiHttp
decodeClientToken: decodeClientToken
createTransactionToRefund: createTransactionToRefund
createPayPalTransactionToRefund: createPayPalTransactionToRefund
createEscrowedTransaction: createEscrowedTransaction
generateNonceForNewPaymentMethod: generateNonceForNewPaymentMethod
createPlanForTests: createPlanForTests
createModificationForTests: createModificationForTests
| 222209 | try
require('source-map-support').install()
catch err
http = require('http')
{TransactionAmounts} = require('../lib/braintree/test/transaction_amounts')
{Util} = require('../lib/braintree/util')
{Config} = require('../lib/braintree/config')
querystring = require('../vendor/querystring.node.js.511d6a2/querystring')
chai = require("chai")
{Buffer} = require('buffer')
xml2js = require('xml2js')
chai.Assertion.includeStack = true
GLOBAL.assert = chai.assert
GLOBAL.assert.isEmptyArray = (array) ->
assert.isArray(array)
assert.equal(array.length, 0)
GLOBAL.inspect = (object) ->
console.dir(object)
braintree = require('./../lib/braintree.js')
defaultConfig = {
environment: braintree.Environment.Development
merchantId: 'integration_merchant_id'
publicKey: 'integration_public_key'
privateKey: 'integration_private_key'
}
defaultGateway = braintree.connect(defaultConfig)
multiplyString = (string, times) ->
(new Array(times+1)).join(string)
plans = {
trialless: { id: 'integration_trialless_plan', price: '12.34' }
addonDiscountPlan: {
id: 'integration_plan_with_add_ons_and_discounts',
price: '9.99'
}
}
addOns = {
increase10: 'increase_10'
increase20: 'increase_20'
}
escrowTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/escrow",
null,
callback
)
makePastDue = (subscription, callback) ->
defaultGateway.http.put(
"/subscriptions/#{subscription.id}/make_past_due?days_past_due=1",
null,
callback
)
settleTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settle",
null,
callback
)
declineSettlingTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settlement_decline",
null,
callback
)
pendSettlingTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settlement_pending",
null,
callback
)
settlePayPalTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settle",
null,
callback
)
create3DSVerification = (merchantAccountId, params, callback) ->
responseCallback = (err, response) ->
threeDSecureToken = response.threeDSecureVerification.threeDSecureToken
callback(threeDSecureToken)
defaultGateway.http.post(
"/three_d_secure/create_verification/#{merchantAccountId}",
{three_d_secure_verification: params},
responseCallback
)
simulateTrFormPost = (url, trData, inputFormData, callback) ->
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'localhost'
}
formData = Util.convertObjectKeysToUnderscores(inputFormData)
formData.tr_data = trData
requestBody = querystring.stringify(formData)
headers['Content-Length'] = requestBody.length.toString()
options = {
port: specHelper.defaultGateway.config.environment.port
host: specHelper.defaultGateway.config.environment.server
method: 'POST'
headers: headers
path: url
}
if specHelper.defaultGateway.config.environment.ssl
request = https.request(options, ->)
else
request = http.request(options, ->)
request.on('response', (response) ->
callback(null, response.headers.location.split('?', 2)[1])
)
request.write(requestBody)
request.end()
dateToMdy = (date) ->
year = date.getFullYear().toString()
month = (date.getMonth() + 1).toString()
day = date.getDate().toString()
if month.length == 1
month = "0" + month
if day.length == 1
day = "0" + day
formattedDate = year + '-' + month + '-' + day
return formattedDate
nowInEastern = ->
now = new Date
eastern = now.getTime() - (5*60*60*1000)
return new Date(eastern)
randomId = ->
Math.floor(Math.random() * Math.pow(36,8)).toString(36)
doesNotInclude = (array, value) ->
assert.isTrue(array.indexOf(value) is -1)
generateNonceForNewPaymentMethod = (paymentMethodParams, customerId, callback) ->
myHttp = new ClientApiHttp(new Config(specHelper.defaultConfig))
clientTokenOptions = {}
clientTokenOptions.customerId = customerId if customerId
specHelper.defaultGateway.clientToken.generate(clientTokenOptions, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
params = { authorizationFingerprint: clientToken.authorizationFingerprint }
if paymentMethodParams["paypalAccount"]?
params["paypalAccount"] = paymentMethodParams["paypalAccount"]
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
callback(nonce)
)
else
params["creditCard"] = paymentMethodParams["creditCard"]
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode, body) ->
nonce = JSON.parse(body).creditCards[0].nonce
callback(nonce)
)
)
createTransactionToRefund = (callback) ->
transactionParams =
amount: '5.00'
creditCard:
number: '5105105105105100'
expirationDate: '05/2012'
options:
submitForSettlement: true
specHelper.defaultGateway.transaction.sale transactionParams, (err, result) ->
specHelper.settleTransaction result.transaction.id, (err, settleResult) ->
specHelper.defaultGateway.transaction.find result.transaction.id, (err, transaction) ->
callback(transaction)
createPayPalTransactionToRefund = (callback) ->
nonceParams =
paypalAccount:
consentCode: 'PAYPAL_CONSENT_CODE'
token: "<KEY>}"
generateNonceForNewPaymentMethod nonceParams, null, (nonce) ->
transactionParams =
amount: TransactionAmounts.Authorize
paymentMethodNonce: nonce
options:
submitForSettlement: true
defaultGateway.transaction.sale transactionParams, (err, response) ->
transactionId = response.transaction.id
specHelper.settlePayPalTransaction transactionId, (err, settleResult) ->
defaultGateway.transaction.find transactionId, (err, transaction) ->
callback(transaction)
createEscrowedTransaction = (callback) ->
transactionParams =
merchantAccountId: specHelper.nonDefaultSubMerchantAccountId
amount: '5.00'
serviceFeeAmount: '1.00'
creditCard:
number: '5105105105105100'
expirationDate: '05/2012'
options:
holdInEscrow: true
specHelper.defaultGateway.transaction.sale transactionParams, (err, result) ->
specHelper.escrowTransaction result.transaction.id, (err, settleResult) ->
specHelper.defaultGateway.transaction.find result.transaction.id, (err, transaction) ->
callback(transaction)
decodeClientToken = (encodedClientToken) ->
decodedClientToken = new Buffer(encodedClientToken, "base64").toString("utf8")
unescapedClientToken = decodedClientToken.replace("\\u0026", "&")
unescapedClientToken
createPlanForTests = (attributes, callback) ->
specHelper.defaultGateway.http.post '/plans/create_plan_for_tests', {plan: attributes}, (err, resp) ->
callback()
createModificationForTests = (attributes, callback) ->
specHelper.defaultGateway.http.post '/modifications/create_modification_for_tests', {modification: attributes}, (err, resp) ->
callback()
class ClientApiHttp
timeout: 60000
constructor: (@config) ->
@parser = new xml2js.Parser
explicitRoot: true
get: (url, params, callback) ->
if params
url += '?'
for key, value of params
url += "#{encodeURIComponent(key)}=#{encodeURIComponent(value)}&"
url = url.slice(0, -1)
@request('GET', url, null, callback)
post: (url, body, callback) ->
@request('POST', url, body, callback)
checkHttpStatus: (status) ->
switch status.toString()
when '200', '201', '422' then null
else status.toString()
request: (method, url, body, callback) ->
client = http
options = {
host: @config.environment.server,
port: @config.environment.port,
method: method,
path: "/merchants/" + @config.merchantId + url,
headers: {
'X-ApiVersion': @config.apiVersion,
'Accept': 'application/xml',
'Content-Type': 'application/json',
'User-Agent': 'Braintree Node ' + braintree.version
}
}
if body
requestBody = JSON.stringify(Util.convertObjectKeysToUnderscores(body))
options.headers['Content-Length'] = Buffer.byteLength(requestBody).toString()
theRequest = client.request(options, (response) =>
body = ''
response.on('data', (responseBody) -> body += responseBody )
response.on('end', => callback(response.statusCode, body))
response.on('error', (err) -> callback("Unexpected response error: #{err}"))
)
theRequest.setTimeout(@timeout, -> callback("timeout"))
theRequest.on('error', (err) -> callback("Unexpected request error: #{err}"))
theRequest.write(requestBody) if body
theRequest.end()
GLOBAL.specHelper =
addOns: addOns
braintree: braintree
create3DSVerification: create3DSVerification
dateToMdy: dateToMdy
defaultConfig: defaultConfig
defaultGateway: defaultGateway
defaultConfig: defaultConfig
defaultGateway: defaultGateway
doesNotInclude: doesNotInclude
escrowTransaction: escrowTransaction
makePastDue: makePastDue
multiplyString: multiplyString
nowInEastern: nowInEastern
plans: plans
randomId: randomId
settleTransaction: settleTransaction
declineSettlingTransaction: declineSettlingTransaction
pendSettlingTransaction: pendSettlingTransaction
settlePayPalTransaction: settlePayPalTransaction
simulateTrFormPost: simulateTrFormPost
defaultMerchantAccountId: "sandbox_credit_card"
nonDefaultMerchantAccountId: "sandbox_credit_card_non_default"
nonDefaultSubMerchantAccountId: "sandbox_sub_merchant_account"
threeDSecureMerchantAccountId: "three_d_secure_merchant_account"
clientApiHttp: ClientApiHttp
decodeClientToken: decodeClientToken
createTransactionToRefund: createTransactionToRefund
createPayPalTransactionToRefund: createPayPalTransactionToRefund
createEscrowedTransaction: createEscrowedTransaction
generateNonceForNewPaymentMethod: generateNonceForNewPaymentMethod
createPlanForTests: createPlanForTests
createModificationForTests: createModificationForTests
| true | try
require('source-map-support').install()
catch err
http = require('http')
{TransactionAmounts} = require('../lib/braintree/test/transaction_amounts')
{Util} = require('../lib/braintree/util')
{Config} = require('../lib/braintree/config')
querystring = require('../vendor/querystring.node.js.511d6a2/querystring')
chai = require("chai")
{Buffer} = require('buffer')
xml2js = require('xml2js')
chai.Assertion.includeStack = true
GLOBAL.assert = chai.assert
GLOBAL.assert.isEmptyArray = (array) ->
assert.isArray(array)
assert.equal(array.length, 0)
GLOBAL.inspect = (object) ->
console.dir(object)
braintree = require('./../lib/braintree.js')
defaultConfig = {
environment: braintree.Environment.Development
merchantId: 'integration_merchant_id'
publicKey: 'integration_public_key'
privateKey: 'integration_private_key'
}
defaultGateway = braintree.connect(defaultConfig)
multiplyString = (string, times) ->
(new Array(times+1)).join(string)
plans = {
trialless: { id: 'integration_trialless_plan', price: '12.34' }
addonDiscountPlan: {
id: 'integration_plan_with_add_ons_and_discounts',
price: '9.99'
}
}
addOns = {
increase10: 'increase_10'
increase20: 'increase_20'
}
escrowTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/escrow",
null,
callback
)
makePastDue = (subscription, callback) ->
defaultGateway.http.put(
"/subscriptions/#{subscription.id}/make_past_due?days_past_due=1",
null,
callback
)
settleTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settle",
null,
callback
)
declineSettlingTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settlement_decline",
null,
callback
)
pendSettlingTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settlement_pending",
null,
callback
)
settlePayPalTransaction = (transactionId, callback) ->
defaultGateway.http.put(
"/transactions/#{transactionId}/settle",
null,
callback
)
create3DSVerification = (merchantAccountId, params, callback) ->
responseCallback = (err, response) ->
threeDSecureToken = response.threeDSecureVerification.threeDSecureToken
callback(threeDSecureToken)
defaultGateway.http.post(
"/three_d_secure/create_verification/#{merchantAccountId}",
{three_d_secure_verification: params},
responseCallback
)
simulateTrFormPost = (url, trData, inputFormData, callback) ->
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'localhost'
}
formData = Util.convertObjectKeysToUnderscores(inputFormData)
formData.tr_data = trData
requestBody = querystring.stringify(formData)
headers['Content-Length'] = requestBody.length.toString()
options = {
port: specHelper.defaultGateway.config.environment.port
host: specHelper.defaultGateway.config.environment.server
method: 'POST'
headers: headers
path: url
}
if specHelper.defaultGateway.config.environment.ssl
request = https.request(options, ->)
else
request = http.request(options, ->)
request.on('response', (response) ->
callback(null, response.headers.location.split('?', 2)[1])
)
request.write(requestBody)
request.end()
dateToMdy = (date) ->
year = date.getFullYear().toString()
month = (date.getMonth() + 1).toString()
day = date.getDate().toString()
if month.length == 1
month = "0" + month
if day.length == 1
day = "0" + day
formattedDate = year + '-' + month + '-' + day
return formattedDate
nowInEastern = ->
now = new Date
eastern = now.getTime() - (5*60*60*1000)
return new Date(eastern)
randomId = ->
Math.floor(Math.random() * Math.pow(36,8)).toString(36)
doesNotInclude = (array, value) ->
assert.isTrue(array.indexOf(value) is -1)
generateNonceForNewPaymentMethod = (paymentMethodParams, customerId, callback) ->
myHttp = new ClientApiHttp(new Config(specHelper.defaultConfig))
clientTokenOptions = {}
clientTokenOptions.customerId = customerId if customerId
specHelper.defaultGateway.clientToken.generate(clientTokenOptions, (err, result) ->
clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken))
params = { authorizationFingerprint: clientToken.authorizationFingerprint }
if paymentMethodParams["paypalAccount"]?
params["paypalAccount"] = paymentMethodParams["paypalAccount"]
myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) ->
nonce = JSON.parse(body).paypalAccounts[0].nonce
callback(nonce)
)
else
params["creditCard"] = paymentMethodParams["creditCard"]
myHttp.post("/client_api/v1/payment_methods/credit_cards.json", params, (statusCode, body) ->
nonce = JSON.parse(body).creditCards[0].nonce
callback(nonce)
)
)
createTransactionToRefund = (callback) ->
transactionParams =
amount: '5.00'
creditCard:
number: '5105105105105100'
expirationDate: '05/2012'
options:
submitForSettlement: true
specHelper.defaultGateway.transaction.sale transactionParams, (err, result) ->
specHelper.settleTransaction result.transaction.id, (err, settleResult) ->
specHelper.defaultGateway.transaction.find result.transaction.id, (err, transaction) ->
callback(transaction)
createPayPalTransactionToRefund = (callback) ->
nonceParams =
paypalAccount:
consentCode: 'PAYPAL_CONSENT_CODE'
token: "PI:KEY:<KEY>END_PI}"
generateNonceForNewPaymentMethod nonceParams, null, (nonce) ->
transactionParams =
amount: TransactionAmounts.Authorize
paymentMethodNonce: nonce
options:
submitForSettlement: true
defaultGateway.transaction.sale transactionParams, (err, response) ->
transactionId = response.transaction.id
specHelper.settlePayPalTransaction transactionId, (err, settleResult) ->
defaultGateway.transaction.find transactionId, (err, transaction) ->
callback(transaction)
createEscrowedTransaction = (callback) ->
transactionParams =
merchantAccountId: specHelper.nonDefaultSubMerchantAccountId
amount: '5.00'
serviceFeeAmount: '1.00'
creditCard:
number: '5105105105105100'
expirationDate: '05/2012'
options:
holdInEscrow: true
specHelper.defaultGateway.transaction.sale transactionParams, (err, result) ->
specHelper.escrowTransaction result.transaction.id, (err, settleResult) ->
specHelper.defaultGateway.transaction.find result.transaction.id, (err, transaction) ->
callback(transaction)
decodeClientToken = (encodedClientToken) ->
decodedClientToken = new Buffer(encodedClientToken, "base64").toString("utf8")
unescapedClientToken = decodedClientToken.replace("\\u0026", "&")
unescapedClientToken
createPlanForTests = (attributes, callback) ->
specHelper.defaultGateway.http.post '/plans/create_plan_for_tests', {plan: attributes}, (err, resp) ->
callback()
createModificationForTests = (attributes, callback) ->
specHelper.defaultGateway.http.post '/modifications/create_modification_for_tests', {modification: attributes}, (err, resp) ->
callback()
class ClientApiHttp
timeout: 60000
constructor: (@config) ->
@parser = new xml2js.Parser
explicitRoot: true
get: (url, params, callback) ->
if params
url += '?'
for key, value of params
url += "#{encodeURIComponent(key)}=#{encodeURIComponent(value)}&"
url = url.slice(0, -1)
@request('GET', url, null, callback)
post: (url, body, callback) ->
@request('POST', url, body, callback)
checkHttpStatus: (status) ->
switch status.toString()
when '200', '201', '422' then null
else status.toString()
request: (method, url, body, callback) ->
client = http
options = {
host: @config.environment.server,
port: @config.environment.port,
method: method,
path: "/merchants/" + @config.merchantId + url,
headers: {
'X-ApiVersion': @config.apiVersion,
'Accept': 'application/xml',
'Content-Type': 'application/json',
'User-Agent': 'Braintree Node ' + braintree.version
}
}
if body
requestBody = JSON.stringify(Util.convertObjectKeysToUnderscores(body))
options.headers['Content-Length'] = Buffer.byteLength(requestBody).toString()
theRequest = client.request(options, (response) =>
body = ''
response.on('data', (responseBody) -> body += responseBody )
response.on('end', => callback(response.statusCode, body))
response.on('error', (err) -> callback("Unexpected response error: #{err}"))
)
theRequest.setTimeout(@timeout, -> callback("timeout"))
theRequest.on('error', (err) -> callback("Unexpected request error: #{err}"))
theRequest.write(requestBody) if body
theRequest.end()
GLOBAL.specHelper =
addOns: addOns
braintree: braintree
create3DSVerification: create3DSVerification
dateToMdy: dateToMdy
defaultConfig: defaultConfig
defaultGateway: defaultGateway
defaultConfig: defaultConfig
defaultGateway: defaultGateway
doesNotInclude: doesNotInclude
escrowTransaction: escrowTransaction
makePastDue: makePastDue
multiplyString: multiplyString
nowInEastern: nowInEastern
plans: plans
randomId: randomId
settleTransaction: settleTransaction
declineSettlingTransaction: declineSettlingTransaction
pendSettlingTransaction: pendSettlingTransaction
settlePayPalTransaction: settlePayPalTransaction
simulateTrFormPost: simulateTrFormPost
defaultMerchantAccountId: "sandbox_credit_card"
nonDefaultMerchantAccountId: "sandbox_credit_card_non_default"
nonDefaultSubMerchantAccountId: "sandbox_sub_merchant_account"
threeDSecureMerchantAccountId: "three_d_secure_merchant_account"
clientApiHttp: ClientApiHttp
decodeClientToken: decodeClientToken
createTransactionToRefund: createTransactionToRefund
createPayPalTransactionToRefund: createPayPalTransactionToRefund
createEscrowedTransaction: createEscrowedTransaction
generateNonceForNewPaymentMethod: generateNonceForNewPaymentMethod
createPlanForTests: createPlanForTests
createModificationForTests: createModificationForTests
|
[
{
"context": "id-123\"\n\t\t@project_history_id = 987\n\t\t@user_id = \"user-id-456\"\n\t\t@brand_variation_id = 789\n\t\t@title = \"title\"\n\t",
"end": 864,
"score": 0.8260274529457092,
"start": 853,
"tag": "USERNAME",
"value": "user-id-456"
},
{
"context": "itle\"\n\t\t@description = \"description\"\n\t\t@author = \"author\"\n\t\t@license = \"other\"\n\t\t@show_source = true\n\t\t@ex",
"end": 963,
"score": 0.3969930410385132,
"start": 957,
"tag": "USERNAME",
"value": "author"
},
{
"context": "le: @title\n\t\t\tdescription: @description\n\t\t\tauthor: @author\n\t\t\tlicense: @license\n\t\t\tshow_source: @show_source",
"end": 1186,
"score": 0.8728880286216736,
"start": 1179,
"tag": "USERNAME",
"value": "@author"
},
{
"context": "y_id\n\t\t\t@user =\n\t\t\t\tid: @user_id\n\t\t\t\tfirst_name: 'Arthur'\n\t\t\t\tlast_name: 'Author'\n\t\t\t\temail: 'arthur.autho",
"end": 3400,
"score": 0.9995932579040527,
"start": 3394,
"tag": "NAME",
"value": "Arthur"
},
{
"context": "@user_id\n\t\t\t\tfirst_name: 'Arthur'\n\t\t\t\tlast_name: 'Author'\n\t\t\t\temail: 'arthur.author@arthurauthoring.org'\n\t",
"end": 3424,
"score": 0.9967960119247437,
"start": 3418,
"tag": "NAME",
"value": "Author"
},
{
"context": "ame: 'Arthur'\n\t\t\t\tlast_name: 'Author'\n\t\t\t\temail: 'arthur.author@arthurauthoring.org'\n\t\t\t\toverleaf:\n\t\t\t\t\tid: 876\n\t\t\t@rootDocPath = 'ma",
"end": 3471,
"score": 0.9999265074729919,
"start": 3438,
"tag": "EMAIL",
"value": "arthur.author@arthurauthoring.org"
},
{
"context": "le\n\t\t\t\t\t\t\tdescription: @description\n\t\t\t\t\t\t\tauthor: @author\n\t\t\t\t\t\t\tlicense: @license\n\t\t\t\t\t\t\tshowSource: @show",
"end": 4880,
"score": 0.9377094507217407,
"start": 4873,
"tag": "USERNAME",
"value": "@author"
},
{
"context": "\t\t\tbeforeEach (done) ->\n\t\t\t\t@custom_first_name = \"FIRST\"\n\t\t\t\t@custom_last_name = \"LAST\"\n\t\t\t\t@export_param",
"end": 5398,
"score": 0.9433093070983887,
"start": 5393,
"tag": "NAME",
"value": "FIRST"
},
{
"context": "tom_first_name = \"FIRST\"\n\t\t\t\t@custom_last_name = \"LAST\"\n\t\t\t\t@export_params.first_name = @custom_first_na",
"end": 5429,
"score": 0.9552266001701355,
"start": 5425,
"tag": "NAME",
"value": "LAST"
},
{
"context": "\n\t\t\t\t\t\t\tdescription: @description\n\t\t\t\t\t\t\tauthor: @author\n\t\t\t\t\t\t\tlicense: @license\n\t\t\t\t\t\t\tshowSource: @show",
"end": 6070,
"score": 0.6594592332839966,
"start": 6064,
"tag": "USERNAME",
"value": "author"
},
{
"context": "\t\t\t\t\tshowSource: @show_source\n\t\t\t\t\tuser:\n\t\t\t\t\t\tid: @user_id\n\t\t\t\t\t\tfirstName: @custom_first_name\n\t\t\t\t\t\tlastNam",
"end": 6157,
"score": 0.9613877534866333,
"start": 6149,
"tag": "USERNAME",
"value": "@user_id"
},
{
"context": "rce\n\t\t\t\t\tuser:\n\t\t\t\t\t\tid: @user_id\n\t\t\t\t\t\tfirstName: @custom_first_name\n\t\t\t\t\t\tlastName: @custom_last_name\n\t\t\t\t\t\temail: @u",
"end": 6193,
"score": 0.9978435635566711,
"start": 6175,
"tag": "USERNAME",
"value": "@custom_first_name"
},
{
"context": "\t\t\t\t\tfirstName: @custom_first_name\n\t\t\t\t\t\tlastName: @custom_last_name\n\t\t\t\t\t\temail: @user.email\n\t\t\t\t\t\torcidId: null\n\t\t\t\t",
"end": 6227,
"score": 0.9983095526695251,
"start": 6210,
"tag": "USERNAME",
"value": "@custom_last_name"
},
{
"context": "ame\n\t\t\t\t\t\tlastName: @custom_last_name\n\t\t\t\t\t\temail: @user.email\n\t\t\t\t\t\torcidId: null\n\t\t\t\t\t\tv1UserId: 876\n\t\t\t\t\tdest",
"end": 6252,
"score": 0.8971151113510132,
"start": 6241,
"tag": "USERNAME",
"value": "@user.email"
},
{
"context": "\t\t\t\t\t\t\tdescription: @description\n\t\t\t\t\t\t\t\tauthor: @author\n\t\t\t\t\t\t\t\tlicense: @license\n\t\t\t\t\t\t\t\tshowSource: @sh",
"end": 7764,
"score": 0.6043281555175781,
"start": 7758,
"tag": "USERNAME",
"value": "author"
},
{
"context": "\t\t\tshowSource: @show_source\n\t\t\t\t\t\tuser:\n\t\t\t\t\t\t\tid: @user_id\n\t\t\t\t\t\t\tfirstName: @user.first_name\n\t\t\t\t\t\t\t",
"end": 7846,
"score": 0.6967921257019043,
"start": 7846,
"tag": "USERNAME",
"value": ""
},
{
"context": "wSource: @show_source\n\t\t\t\t\t\tuser:\n\t\t\t\t\t\t\tid: @user_id\n\t\t\t\t\t\t\tfirstName: @user.first_name\n\t\t\t\t\t\t\tlastNam",
"end": 7855,
"score": 0.6266770362854004,
"start": 7853,
"tag": "USERNAME",
"value": "id"
},
{
"context": "\n\t\t\t\t\t\tuser:\n\t\t\t\t\t\t\tid: @user_id\n\t\t\t\t\t\t\tfirstName: @user.first_name\n\t\t\t\t\t\t\tlastName: @user.last_name\n\t\t\t\t\t\t\temail: @u",
"end": 7890,
"score": 0.9578379988670349,
"start": 7874,
"tag": "USERNAME",
"value": "@user.first_name"
},
{
"context": "\t\t\t\t\t\tfirstName: @user.first_name\n\t\t\t\t\t\t\tlastName: @user.last_name\n\t\t\t\t\t\t\temail: @user.email\n\t\t\t\t\t\t\torcidId: null\n\t\t",
"end": 7923,
"score": 0.9902560114860535,
"start": 7908,
"tag": "USERNAME",
"value": "@user.last_name"
},
{
"context": "\n\t\t\t\t\t\t\t\tdescription: @description\n\t\t\t\t\t\t\t\tauthor: @author\n\t\t\t\t\t\t\t\tlicense: @license\n\t\t\t\t\t\t\t\tshowSource: @sh",
"end": 9153,
"score": 0.9929708242416382,
"start": 9146,
"tag": "USERNAME",
"value": "@author"
},
{
"context": "\t\t\tshowSource: @show_source\n\t\t\t\t\t\tuser:\n\t\t\t\t\t\t\tid: @user_id\n\t\t\t\t\t\t\tfirstName: @user.first_name\n\t\t\t\t\t\t\tlastNam",
"end": 9244,
"score": 0.9585914015769958,
"start": 9236,
"tag": "USERNAME",
"value": "@user_id"
},
{
"context": "\n\t\t\t\t\t\tuser:\n\t\t\t\t\t\t\tid: @user_id\n\t\t\t\t\t\t\tfirstName: @user.first_name\n\t\t\t\t\t\t\tlastName: @user.last_name\n\t\t\t\t\t\t\temail: @u",
"end": 9279,
"score": 0.9609308242797852,
"start": 9263,
"tag": "USERNAME",
"value": "@user.first_name"
},
{
"context": "\t\t\t\t\t\tfirstName: @user.first_name\n\t\t\t\t\t\t\tlastName: @user.last_name\n\t\t\t\t\t\t\temail: @user.email\n\t\t\t\t\t\t\tor",
"end": 9296,
"score": 0.5592325925827026,
"start": 9296,
"tag": "NAME",
"value": ""
},
{
"context": "\t\t\t\tfirstName: @user.first_name\n\t\t\t\t\t\t\tlastName: @user.last_name\n\t\t\t\t\t\t\temail: @user.email\n\t\t\t\t\t\t\torcidId: null\n\t\t",
"end": 9312,
"score": 0.9187979698181152,
"start": 9298,
"tag": "USERNAME",
"value": "user.last_name"
},
{
"context": "ame\n\t\t\t\t\t\t\tlastName: @user.last_name\n\t\t\t\t\t\t\temail: @user.email\n\t\t\t\t\t\t\torcidId: null\n\t\t\t\t\t\t\tv1UserId: 876\n\t\t\t\t\t\td",
"end": 9338,
"score": 0.987572431564331,
"start": 9327,
"tag": "USERNAME",
"value": "@user.email"
},
{
"context": "v1:\n\t\t\t\t\turl: 'http://localhost:5000'\n\t\t\t\t\tuser: 'overleaf'\n\t\t\t\t\tpass: 'pass'\n\t\t\t@export_data = {iAmAnExport",
"end": 10846,
"score": 0.9933749437332153,
"start": 10838,
"tag": "USERNAME",
"value": "overleaf"
},
{
"context": "localhost:5000'\n\t\t\t\t\tuser: 'overleaf'\n\t\t\t\t\tpass: 'pass'\n\t\t\t@export_data = {iAmAnExport: true}\n\t\t\t@export",
"end": 10864,
"score": 0.9993517398834229,
"start": 10860,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "v1:\n\t\t\t\t\turl: 'http://localhost:5000'\n\t\t\t\t\tuser: 'overleaf'\n\t\t\t\t\tpass: 'pass'\n\t\t\t@export_id = 897\n\t\t\t@body =",
"end": 12696,
"score": 0.9878032207489014,
"start": 12688,
"tag": "USERNAME",
"value": "overleaf"
},
{
"context": "localhost:5000'\n\t\t\t\t\tuser: 'overleaf'\n\t\t\t\t\tpass: 'pass'\n\t\t\t@export_id = 897\n\t\t\t@body = \"{\\\"id\\\":897, \\\"s",
"end": 12714,
"score": 0.9993350505828857,
"start": 12710,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "v1:\n\t\t\t\t\turl: 'http://localhost:5000'\n\t\t\t\t\tuser: 'overleaf'\n\t\t\t\t\tpass: 'pass'\n\t\t\t@export_id = 897\n\t\t\t@body =",
"end": 13577,
"score": 0.9974599480628967,
"start": 13569,
"tag": "USERNAME",
"value": "overleaf"
},
{
"context": "localhost:5000'\n\t\t\t\t\tuser: 'overleaf'\n\t\t\t\t\tpass: 'pass'\n\t\t\t@export_id = 897\n\t\t\t@body = \"https://writelat",
"end": 13595,
"score": 0.9989675283432007,
"start": 13591,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": "X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJDGDIJFGLNVGZH6A/20180730/us-east-1/s3/aws4_request&X-Amz-SignedHeaders=host",
"end": 13876,
"score": 0.953742265701294,
"start": 13846,
"tag": "KEY",
"value": "AKIAJDGDIJFGLNVGZH6A/20180730/"
},
{
"context": "&X-Amz-Credential=AKIAJDGDIJFGLNVGZH6A/20180730/us-east-1/s3/aws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=dec99033",
"end": 13901,
"score": 0.7036676406860352,
"start": 13879,
"tag": "KEY",
"value": "east-1/s3/aws4_request"
}
] | test/unit/coffee/Exports/ExportsHandlerTests.coffee | shyoshyo/web-sharelatex | 1 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = '../../../../app/js/Features/Exports/ExportsHandler.js'
SandboxedModule = require('sandboxed-module')
describe 'ExportsHandler', ->
beforeEach ->
@stubRequest = {}
@request = defaults: => return @stubRequest
@ExportsHandler = SandboxedModule.require modulePath, requires:
'logger-sharelatex':
log: ->
err: ->
'../Project/ProjectGetter': @ProjectGetter = {}
'../Project/ProjectHistoryHandler': @ProjectHistoryHandler = {}
'../Project/ProjectLocator': @ProjectLocator = {}
'../Project/ProjectRootDocManager': @ProjectRootDocManager = {}
'../User/UserGetter': @UserGetter = {}
'settings-sharelatex': @settings = {}
'request': @request
@project_id = "project-id-123"
@project_history_id = 987
@user_id = "user-id-456"
@brand_variation_id = 789
@title = "title"
@description = "description"
@author = "author"
@license = "other"
@show_source = true
@export_params = {
project_id: @project_id,
brand_variation_id: @brand_variation_id,
user_id: @user_id
title: @title
description: @description
author: @author
license: @license
show_source: @show_source
}
@callback = sinon.stub()
describe 'exportProject', ->
beforeEach ->
@export_data = {iAmAnExport: true}
@response_body = {iAmAResponseBody: true}
@ExportsHandler._buildExport = sinon.stub().yields(null, @export_data)
@ExportsHandler._requestExport = sinon.stub().yields(null, @response_body)
describe "when all goes well", ->
beforeEach (done) ->
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should build the export", ->
@ExportsHandler._buildExport
.calledWith(@export_params)
.should.equal true
it "should request the export", ->
@ExportsHandler._requestExport
.calledWith(@export_data)
.should.equal true
it "should return the export", ->
@callback
.calledWith(null, @export_data)
.should.equal true
describe "when request can't be built", ->
beforeEach (done) ->
@ExportsHandler._buildExport = sinon.stub().yields(new Error("cannot export project without root doc"))
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when export request returns an error to forward to the user", ->
beforeEach (done) ->
@error_json = { status: 422, message: 'nope' }
@ExportsHandler._requestExport = sinon.stub().yields(null, forwardResponse: @error_json)
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return success and the response to forward", ->
(@callback.args[0][0] instanceof Error)
.should.equal false
@callback.calledWith(null, {forwardResponse: @error_json})
describe '_buildExport', ->
beforeEach (done) ->
@project =
id: @project_id
rootDoc_id: 'doc1_id'
compiler: 'pdflatex'
imageName: 'mock-image-name'
overleaf:
id: @project_history_id # for projects imported from v1
history:
id: @project_history_id
@user =
id: @user_id
first_name: 'Arthur'
last_name: 'Author'
email: 'arthur.author@arthurauthoring.org'
overleaf:
id: 876
@rootDocPath = 'main.tex'
@historyVersion = 777
@ProjectGetter.getProject = sinon.stub().yields(null, @project)
@ProjectHistoryHandler.ensureHistoryExistsForProject = sinon.stub().yields(null)
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'main.tex'}])
@ProjectRootDocManager.ensureRootDocumentIsValid = sinon.stub().callsArgWith(1, null)
@UserGetter.getUser = sinon.stub().yields(null, @user)
@ExportsHandler._requestVersion = sinon.stub().yields(null, @historyVersion)
done()
describe "when all goes well", ->
beforeEach (done) ->
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should ensure the project has history", ->
@ProjectHistoryHandler.ensureHistoryExistsForProject.called
.should.equal true
it "should request the project history version", ->
@ExportsHandler._requestVersion.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: @rootDocPath
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName: @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when we send replacement user first and last name", ->
beforeEach (done) ->
@custom_first_name = "FIRST"
@custom_last_name = "LAST"
@export_params.first_name = @custom_first_name
@export_params.last_name = @custom_last_name
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should send the data from the user input", ->
expected_export_data =
project:
id: @project_id
rootDocPath: @rootDocPath
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @custom_first_name
lastName: @custom_last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when project is not found", ->
beforeEach (done) ->
@ProjectGetter.getProject = sinon.stub().yields(new Error("project not found"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when project has no root doc", ->
describe "when a root doc can be set automatically", ->
beforeEach (done) ->
@project.rootDoc_id = null
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'other.tex'}])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should set a root doc", ->
@ProjectRootDocManager.ensureRootDocumentIsValid.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: 'other.tex'
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName: @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when project has an invalid root doc", ->
describe "when a new root doc can be set automatically", ->
beforeEach (done) ->
@fakeDoc_id = '1a2b3c4d5e6f'
@project.rootDoc_id = @fakeDoc_id
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'other.tex'}])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should set a valid root doc", ->
@ProjectRootDocManager.ensureRootDocumentIsValid.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: 'other.tex'
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName: @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when no root doc can be identified", ->
beforeEach (done) ->
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, null])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when user is not found", ->
beforeEach (done) ->
@UserGetter.getUser = sinon.stub().yields(new Error("user not found"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when project history request fails", ->
beforeEach (done) ->
@ExportsHandler._requestVersion = sinon.stub().yields(new Error("project history call failed"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe '_requestExport', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: 'pass'
@export_data = {iAmAnExport: true}
@export_id = 4096
@stubPost = sinon.stub().yields(null, {statusCode: 200}, { exportId: @export_id })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.post = @stubPost
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it 'should issue the request', ->
expect(@stubPost.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports'
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
json: @export_data
it 'should return the v1 export id', ->
@callback.calledWith(null, @export_id)
.should.equal true
describe "when the request fails", ->
beforeEach (done) ->
@stubRequest.post = sinon.stub().yields(new Error("export request failed"))
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when the request returns an error response to forward", ->
beforeEach (done) ->
@error_code = 422
@error_json = { status: @error_code, message: 'nope' }
@stubRequest.post = sinon.stub().yields(null, {statusCode: @error_code}, @error_json)
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it "should return success and the response to forward", ->
(@callback.args[0][0] instanceof Error)
.should.equal false
@callback.calledWith(null, {forwardResponse: @error_json})
describe 'fetchExport', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: 'pass'
@export_id = 897
@body = "{\"id\":897, \"status_summary\":\"completed\"}"
@stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.get = @stubGet
@ExportsHandler.fetchExport @export_id, (error, body) =>
@callback(error, body)
done()
it 'should issue the request', ->
expect(@stubGet.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
it 'should return the v1 export id', ->
@callback.calledWith(null, { body: @body })
.should.equal true
describe 'fetchDownload', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: 'pass'
@export_id = 897
@body = "https://writelatex-conversions-dev.s3.amazonaws.com/exports/ieee_latexqc/tnb/2912/xggmprcrpfwbsnqzqqmvktddnrbqkqkr.zip?X-Amz-Expires=14400&X-Amz-Date=20180730T181003Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJDGDIJFGLNVGZH6A/20180730/us-east-1/s3/aws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature=dec990336913cef9933f0e269afe99722d7ab2830ebf2c618a75673ee7159fee"
@stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.get = @stubGet
@ExportsHandler.fetchDownload @export_id, 'zip', (error, body) =>
@callback(error, body)
done()
it 'should issue the request', ->
expect(@stubGet.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id + '/zip_url'
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
it 'should return the v1 export id', ->
@callback.calledWith(null, { body: @body })
.should.equal true
| 191273 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = '../../../../app/js/Features/Exports/ExportsHandler.js'
SandboxedModule = require('sandboxed-module')
describe 'ExportsHandler', ->
beforeEach ->
@stubRequest = {}
@request = defaults: => return @stubRequest
@ExportsHandler = SandboxedModule.require modulePath, requires:
'logger-sharelatex':
log: ->
err: ->
'../Project/ProjectGetter': @ProjectGetter = {}
'../Project/ProjectHistoryHandler': @ProjectHistoryHandler = {}
'../Project/ProjectLocator': @ProjectLocator = {}
'../Project/ProjectRootDocManager': @ProjectRootDocManager = {}
'../User/UserGetter': @UserGetter = {}
'settings-sharelatex': @settings = {}
'request': @request
@project_id = "project-id-123"
@project_history_id = 987
@user_id = "user-id-456"
@brand_variation_id = 789
@title = "title"
@description = "description"
@author = "author"
@license = "other"
@show_source = true
@export_params = {
project_id: @project_id,
brand_variation_id: @brand_variation_id,
user_id: @user_id
title: @title
description: @description
author: @author
license: @license
show_source: @show_source
}
@callback = sinon.stub()
describe 'exportProject', ->
beforeEach ->
@export_data = {iAmAnExport: true}
@response_body = {iAmAResponseBody: true}
@ExportsHandler._buildExport = sinon.stub().yields(null, @export_data)
@ExportsHandler._requestExport = sinon.stub().yields(null, @response_body)
describe "when all goes well", ->
beforeEach (done) ->
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should build the export", ->
@ExportsHandler._buildExport
.calledWith(@export_params)
.should.equal true
it "should request the export", ->
@ExportsHandler._requestExport
.calledWith(@export_data)
.should.equal true
it "should return the export", ->
@callback
.calledWith(null, @export_data)
.should.equal true
describe "when request can't be built", ->
beforeEach (done) ->
@ExportsHandler._buildExport = sinon.stub().yields(new Error("cannot export project without root doc"))
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when export request returns an error to forward to the user", ->
beforeEach (done) ->
@error_json = { status: 422, message: 'nope' }
@ExportsHandler._requestExport = sinon.stub().yields(null, forwardResponse: @error_json)
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return success and the response to forward", ->
(@callback.args[0][0] instanceof Error)
.should.equal false
@callback.calledWith(null, {forwardResponse: @error_json})
describe '_buildExport', ->
beforeEach (done) ->
@project =
id: @project_id
rootDoc_id: 'doc1_id'
compiler: 'pdflatex'
imageName: 'mock-image-name'
overleaf:
id: @project_history_id # for projects imported from v1
history:
id: @project_history_id
@user =
id: @user_id
first_name: '<NAME>'
last_name: '<NAME>'
email: '<EMAIL>'
overleaf:
id: 876
@rootDocPath = 'main.tex'
@historyVersion = 777
@ProjectGetter.getProject = sinon.stub().yields(null, @project)
@ProjectHistoryHandler.ensureHistoryExistsForProject = sinon.stub().yields(null)
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'main.tex'}])
@ProjectRootDocManager.ensureRootDocumentIsValid = sinon.stub().callsArgWith(1, null)
@UserGetter.getUser = sinon.stub().yields(null, @user)
@ExportsHandler._requestVersion = sinon.stub().yields(null, @historyVersion)
done()
describe "when all goes well", ->
beforeEach (done) ->
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should ensure the project has history", ->
@ProjectHistoryHandler.ensureHistoryExistsForProject.called
.should.equal true
it "should request the project history version", ->
@ExportsHandler._requestVersion.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: @rootDocPath
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName: @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when we send replacement user first and last name", ->
beforeEach (done) ->
@custom_first_name = "<NAME>"
@custom_last_name = "<NAME>"
@export_params.first_name = @custom_first_name
@export_params.last_name = @custom_last_name
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should send the data from the user input", ->
expected_export_data =
project:
id: @project_id
rootDocPath: @rootDocPath
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @custom_first_name
lastName: @custom_last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when project is not found", ->
beforeEach (done) ->
@ProjectGetter.getProject = sinon.stub().yields(new Error("project not found"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when project has no root doc", ->
describe "when a root doc can be set automatically", ->
beforeEach (done) ->
@project.rootDoc_id = null
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'other.tex'}])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should set a root doc", ->
@ProjectRootDocManager.ensureRootDocumentIsValid.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: 'other.tex'
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName: @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when project has an invalid root doc", ->
describe "when a new root doc can be set automatically", ->
beforeEach (done) ->
@fakeDoc_id = '1a2b3c4d5e6f'
@project.rootDoc_id = @fakeDoc_id
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'other.tex'}])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should set a valid root doc", ->
@ProjectRootDocManager.ensureRootDocumentIsValid.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: 'other.tex'
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName:<NAME> @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when no root doc can be identified", ->
beforeEach (done) ->
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, null])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when user is not found", ->
beforeEach (done) ->
@UserGetter.getUser = sinon.stub().yields(new Error("user not found"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when project history request fails", ->
beforeEach (done) ->
@ExportsHandler._requestVersion = sinon.stub().yields(new Error("project history call failed"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe '_requestExport', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: '<PASSWORD>'
@export_data = {iAmAnExport: true}
@export_id = 4096
@stubPost = sinon.stub().yields(null, {statusCode: 200}, { exportId: @export_id })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.post = @stubPost
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it 'should issue the request', ->
expect(@stubPost.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports'
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
json: @export_data
it 'should return the v1 export id', ->
@callback.calledWith(null, @export_id)
.should.equal true
describe "when the request fails", ->
beforeEach (done) ->
@stubRequest.post = sinon.stub().yields(new Error("export request failed"))
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when the request returns an error response to forward", ->
beforeEach (done) ->
@error_code = 422
@error_json = { status: @error_code, message: 'nope' }
@stubRequest.post = sinon.stub().yields(null, {statusCode: @error_code}, @error_json)
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it "should return success and the response to forward", ->
(@callback.args[0][0] instanceof Error)
.should.equal false
@callback.calledWith(null, {forwardResponse: @error_json})
describe 'fetchExport', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: '<PASSWORD>'
@export_id = 897
@body = "{\"id\":897, \"status_summary\":\"completed\"}"
@stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.get = @stubGet
@ExportsHandler.fetchExport @export_id, (error, body) =>
@callback(error, body)
done()
it 'should issue the request', ->
expect(@stubGet.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
it 'should return the v1 export id', ->
@callback.calledWith(null, { body: @body })
.should.equal true
describe 'fetchDownload', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: '<PASSWORD>'
@export_id = 897
@body = "https://writelatex-conversions-dev.s3.amazonaws.com/exports/ieee_latexqc/tnb/2912/xggmprcrpfwbsnqzqqmvktddnrbqkqkr.zip?X-Amz-Expires=14400&X-Amz-Date=20180730T181003Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<KEY>us-<KEY>&X-Amz-SignedHeaders=host&X-Amz-Signature=dec990336913cef9933f0e269afe99722d7ab2830ebf2c618a75673ee7159fee"
@stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.get = @stubGet
@ExportsHandler.fetchDownload @export_id, 'zip', (error, body) =>
@callback(error, body)
done()
it 'should issue the request', ->
expect(@stubGet.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id + '/zip_url'
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
it 'should return the v1 export id', ->
@callback.calledWith(null, { body: @body })
.should.equal true
| true | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = '../../../../app/js/Features/Exports/ExportsHandler.js'
SandboxedModule = require('sandboxed-module')
describe 'ExportsHandler', ->
beforeEach ->
@stubRequest = {}
@request = defaults: => return @stubRequest
@ExportsHandler = SandboxedModule.require modulePath, requires:
'logger-sharelatex':
log: ->
err: ->
'../Project/ProjectGetter': @ProjectGetter = {}
'../Project/ProjectHistoryHandler': @ProjectHistoryHandler = {}
'../Project/ProjectLocator': @ProjectLocator = {}
'../Project/ProjectRootDocManager': @ProjectRootDocManager = {}
'../User/UserGetter': @UserGetter = {}
'settings-sharelatex': @settings = {}
'request': @request
@project_id = "project-id-123"
@project_history_id = 987
@user_id = "user-id-456"
@brand_variation_id = 789
@title = "title"
@description = "description"
@author = "author"
@license = "other"
@show_source = true
@export_params = {
project_id: @project_id,
brand_variation_id: @brand_variation_id,
user_id: @user_id
title: @title
description: @description
author: @author
license: @license
show_source: @show_source
}
@callback = sinon.stub()
describe 'exportProject', ->
beforeEach ->
@export_data = {iAmAnExport: true}
@response_body = {iAmAResponseBody: true}
@ExportsHandler._buildExport = sinon.stub().yields(null, @export_data)
@ExportsHandler._requestExport = sinon.stub().yields(null, @response_body)
describe "when all goes well", ->
beforeEach (done) ->
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should build the export", ->
@ExportsHandler._buildExport
.calledWith(@export_params)
.should.equal true
it "should request the export", ->
@ExportsHandler._requestExport
.calledWith(@export_data)
.should.equal true
it "should return the export", ->
@callback
.calledWith(null, @export_data)
.should.equal true
describe "when request can't be built", ->
beforeEach (done) ->
@ExportsHandler._buildExport = sinon.stub().yields(new Error("cannot export project without root doc"))
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when export request returns an error to forward to the user", ->
beforeEach (done) ->
@error_json = { status: 422, message: 'nope' }
@ExportsHandler._requestExport = sinon.stub().yields(null, forwardResponse: @error_json)
@ExportsHandler.exportProject @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return success and the response to forward", ->
(@callback.args[0][0] instanceof Error)
.should.equal false
@callback.calledWith(null, {forwardResponse: @error_json})
describe '_buildExport', ->
beforeEach (done) ->
@project =
id: @project_id
rootDoc_id: 'doc1_id'
compiler: 'pdflatex'
imageName: 'mock-image-name'
overleaf:
id: @project_history_id # for projects imported from v1
history:
id: @project_history_id
@user =
id: @user_id
first_name: 'PI:NAME:<NAME>END_PI'
last_name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
overleaf:
id: 876
@rootDocPath = 'main.tex'
@historyVersion = 777
@ProjectGetter.getProject = sinon.stub().yields(null, @project)
@ProjectHistoryHandler.ensureHistoryExistsForProject = sinon.stub().yields(null)
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'main.tex'}])
@ProjectRootDocManager.ensureRootDocumentIsValid = sinon.stub().callsArgWith(1, null)
@UserGetter.getUser = sinon.stub().yields(null, @user)
@ExportsHandler._requestVersion = sinon.stub().yields(null, @historyVersion)
done()
describe "when all goes well", ->
beforeEach (done) ->
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should ensure the project has history", ->
@ProjectHistoryHandler.ensureHistoryExistsForProject.called
.should.equal true
it "should request the project history version", ->
@ExportsHandler._requestVersion.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: @rootDocPath
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName: @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when we send replacement user first and last name", ->
beforeEach (done) ->
@custom_first_name = "PI:NAME:<NAME>END_PI"
@custom_last_name = "PI:NAME:<NAME>END_PI"
@export_params.first_name = @custom_first_name
@export_params.last_name = @custom_last_name
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should send the data from the user input", ->
expected_export_data =
project:
id: @project_id
rootDocPath: @rootDocPath
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @custom_first_name
lastName: @custom_last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when project is not found", ->
beforeEach (done) ->
@ProjectGetter.getProject = sinon.stub().yields(new Error("project not found"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when project has no root doc", ->
describe "when a root doc can be set automatically", ->
beforeEach (done) ->
@project.rootDoc_id = null
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'other.tex'}])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should set a root doc", ->
@ProjectRootDocManager.ensureRootDocumentIsValid.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: 'other.tex'
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName: @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when project has an invalid root doc", ->
describe "when a new root doc can be set automatically", ->
beforeEach (done) ->
@fakeDoc_id = '1a2b3c4d5e6f'
@project.rootDoc_id = @fakeDoc_id
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, {fileSystem: 'other.tex'}])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should set a valid root doc", ->
@ProjectRootDocManager.ensureRootDocumentIsValid.called
.should.equal true
it "should return export data", ->
expected_export_data =
project:
id: @project_id
rootDocPath: 'other.tex'
historyId: @project_history_id
historyVersion: @historyVersion
v1ProjectId: @project_history_id
metadata:
compiler: 'pdflatex'
imageName: 'mock-image-name'
title: @title
description: @description
author: @author
license: @license
showSource: @show_source
user:
id: @user_id
firstName: @user.first_name
lastName:PI:NAME:<NAME>END_PI @user.last_name
email: @user.email
orcidId: null
v1UserId: 876
destination:
brandVariationId: @brand_variation_id
options:
callbackUrl: null
@callback.calledWith(null, expected_export_data)
.should.equal true
describe "when no root doc can be identified", ->
beforeEach (done) ->
@ProjectLocator.findRootDoc = sinon.stub().yields(null, [null, null])
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when user is not found", ->
beforeEach (done) ->
@UserGetter.getUser = sinon.stub().yields(new Error("user not found"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when project history request fails", ->
beforeEach (done) ->
@ExportsHandler._requestVersion = sinon.stub().yields(new Error("project history call failed"))
@ExportsHandler._buildExport @export_params, (error, export_data) =>
@callback(error, export_data)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe '_requestExport', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: 'PI:PASSWORD:<PASSWORD>END_PI'
@export_data = {iAmAnExport: true}
@export_id = 4096
@stubPost = sinon.stub().yields(null, {statusCode: 200}, { exportId: @export_id })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.post = @stubPost
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it 'should issue the request', ->
expect(@stubPost.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports'
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
json: @export_data
it 'should return the v1 export id', ->
@callback.calledWith(null, @export_id)
.should.equal true
describe "when the request fails", ->
beforeEach (done) ->
@stubRequest.post = sinon.stub().yields(new Error("export request failed"))
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it "should return an error", ->
(@callback.args[0][0] instanceof Error)
.should.equal true
describe "when the request returns an error response to forward", ->
beforeEach (done) ->
@error_code = 422
@error_json = { status: @error_code, message: 'nope' }
@stubRequest.post = sinon.stub().yields(null, {statusCode: @error_code}, @error_json)
@ExportsHandler._requestExport @export_data, (error, export_v1_id) =>
@callback(error, export_v1_id)
done()
it "should return success and the response to forward", ->
(@callback.args[0][0] instanceof Error)
.should.equal false
@callback.calledWith(null, {forwardResponse: @error_json})
describe 'fetchExport', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: 'PI:PASSWORD:<PASSWORD>END_PI'
@export_id = 897
@body = "{\"id\":897, \"status_summary\":\"completed\"}"
@stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.get = @stubGet
@ExportsHandler.fetchExport @export_id, (error, body) =>
@callback(error, body)
done()
it 'should issue the request', ->
expect(@stubGet.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
it 'should return the v1 export id', ->
@callback.calledWith(null, { body: @body })
.should.equal true
describe 'fetchDownload', ->
beforeEach (done) ->
@settings.apis =
v1:
url: 'http://localhost:5000'
user: 'overleaf'
pass: 'PI:PASSWORD:<PASSWORD>END_PI'
@export_id = 897
@body = "https://writelatex-conversions-dev.s3.amazonaws.com/exports/ieee_latexqc/tnb/2912/xggmprcrpfwbsnqzqqmvktddnrbqkqkr.zip?X-Amz-Expires=14400&X-Amz-Date=20180730T181003Z&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=PI:KEY:<KEY>END_PIus-PI:KEY:<KEY>END_PI&X-Amz-SignedHeaders=host&X-Amz-Signature=dec990336913cef9933f0e269afe99722d7ab2830ebf2c618a75673ee7159fee"
@stubGet = sinon.stub().yields(null, {statusCode: 200}, { body: @body })
done()
describe "when all goes well", ->
beforeEach (done) ->
@stubRequest.get = @stubGet
@ExportsHandler.fetchDownload @export_id, 'zip', (error, body) =>
@callback(error, body)
done()
it 'should issue the request', ->
expect(@stubGet.getCall(0).args[0]).to.deep.equal
url: @settings.apis.v1.url + '/api/v1/sharelatex/exports/' + @export_id + '/zip_url'
auth:
user: @settings.apis.v1.user
pass: @settings.apis.v1.pass
it 'should return the v1 export id', ->
@callback.calledWith(null, { body: @body })
.should.equal true
|
[
{
"context": "\ttriggerChangeFields.forEach (key)->\n\t\t\t\tif key == '_my_approve_read_dates'\n\t\t\t\t\ttriggerChangeFieldsValues[key] = getMyappro",
"end": 1823,
"score": 0.738890528678894,
"start": 1800,
"tag": "KEY",
"value": "'_my_approve_read_dates"
},
{
"context": ".findOne({ space: instance.space, key: \"show_modal_traces_list\" }, { fields: { values: 1 } })?.values",
"end": 2157,
"score": 0.5382764339447021,
"start": 2157,
"tag": "KEY",
"value": ""
},
{
"context": "e({ space: instance.space, key: \"show_modal_traces_list\" }, { fields: { values: 1 } })?.values || fal",
"end": 2164,
"score": 0.5382226705551147,
"start": 2164,
"tag": "KEY",
"value": ""
},
{
"context": "hangeFields, (key)->\n\t\t\t\t_key = key\n\n\t\t\t\tif key == '_my_approve_read_dates'\n\t\t\t\t\t_key = 'traces'\n\n\t\t\t\tif _.has(changeFields,",
"end": 2863,
"score": 0.900240957736969,
"start": 2840,
"tag": "KEY",
"value": "'_my_approve_read_dates"
},
{
"context": "\t\tif key == '_my_approve_read_dates'\n\t\t\t\t\t_key = 'traces'\n\n\t\t\t\tif _.has(changeFields, _key)\n\n\t\t\t\t\tif key =",
"end": 2884,
"score": 0.8485298156738281,
"start": 2878,
"tag": "KEY",
"value": "traces"
},
{
"context": "\n\n\t\t\t\tif _.has(changeFields, _key)\n\n\t\t\t\t\tif key == '_my_approve_read_dates'\n\n\t\t\t\t\t\t_my_approve_modifieds = getMyapproveModif",
"end": 2959,
"score": 0.9378775358200073,
"start": 2936,
"tag": "KEY",
"value": "'_my_approve_read_dates"
}
] | creator/packages/steedos-workflow/server/publications/instance_data.coffee | baozhoutao/steedos-platform | 10 | Meteor.publish 'instance_data', (instanceId, box)->
unless this.userId
return this.ready()
unless (instanceId && db.instances.find({_id: instanceId}).count())
return this.ready()
self = this;
miniApproveFields = ['_id', 'is_finished', 'user', 'handler', 'handler_name', 'type', 'start_date', 'description',
'is_read', 'judge', 'finish_date', 'from_user_name', 'from_user', 'cc_description', 'auto_submitted']
triggerChangeFields = ['form_version', 'flow_version', 'related_instances', '_my_approve_read_dates', 'values']
triggerChangeFieldsValues = {}
instance_fields_0 = {
"record_synced": 0,
# "traces.approves.handler_organization_fullname": 0,
"traces.approves.handler_organization_name": 0,
"traces.approves.handler_organization": 0,
"traces.approves.cost_time": 0,
# "traces.approves.read_date": 0,
"traces.approves.is_error": 0,
# "traces.approves.user_name": 0,
"traces.approves.deadline": 0,
"traces.approves.remind_date": 0,
"traces.approves.reminded_count": 0,
"traces.approves.modified_by": 0,
"traces.approves.modified": 0,
"traces.approves.geolocation": 0,
"traces.approves.cc_users": 0,
"traces.approves.from_approve_id": 0,
"traces.approves.values_history": 0
}
getMyapproveModified = (traces)->
myApproveModifieds = new Array()
traces?.forEach (trace)->
trace?.approves?.forEach (approve)->
if (approve.user == self.userId || approve.handler == self.userId)
# && !approve.is_finished
# console.log("approve", approve._id, approve.read_date)
myApproveModifieds.push(approve.read_date)
return myApproveModifieds
getMiniInstance = (_instanceId)->
instance = db.instances.findOne({_id: _instanceId}, {fields: instance_fields_0})
if instance
triggerChangeFields.forEach (key)->
if key == '_my_approve_read_dates'
triggerChangeFieldsValues[key] = getMyapproveModified(instance.traces)
else
triggerChangeFieldsValues[key] = instance[key]
# hasOpinionField = InstanceSignText.includesOpinionField(instance.form, instance.form_version)
show_modal_traces_list = db.space_settings.findOne({ space: instance.space, key: "show_modal_traces_list" }, { fields: { values: 1 } })?.values || false
if show_modal_traces_list
traces = new Array();
instance?.traces?.forEach (trace)->
_trace = _.clone(trace)
approves = new Array()
trace?.approves?.forEach (approve)->
if approve.type != 'cc' || approve.user == self.userId || approve.handler == self.userId || (!_.isEmpty(approve.sign_field_code))
approves.push(approve)
_trace.approves = approves
traces.push(_trace)
instance.traces = traces;
return instance
needChange = (changeFields)->
if changeFields
_change = false
_rev = _.find triggerChangeFields, (key)->
_key = key
if key == '_my_approve_read_dates'
_key = 'traces'
if _.has(changeFields, _key)
if key == '_my_approve_read_dates'
_my_approve_modifieds = getMyapproveModified(changeFields.traces)
# console.log(triggerChangeFieldsValues[key], _my_approve_modifieds)
return !_.isEqual(triggerChangeFieldsValues[key], _my_approve_modifieds)
else
return !_.isEqual(triggerChangeFieldsValues[key], changeFields[key])
if _rev
_change = true
# console.log(_rev, _change)
return _change
return true
#此处不能添加fields限制,否则会导致数据不实时
handle = db.instances.find({_id: instanceId}).observeChanges {
changed: (id, fields)->
if(box != 'inbox' || needChange(fields))
self.changed("instances", id, getMiniInstance(id));
removed: (id)->
self.removed("instances", id);
}
instance = getMiniInstance(instanceId)
self.added("instances", instance?._id, instance);
self.ready();
self.onStop ()->
handle.stop()
Meteor.publish 'instance_traces', (instanceId)->
unless this.userId
return this.ready()
unless instanceId
return this.ready()
self = this
getInstanceTraces = (_insId)->
return db.instances.findOne({_id: _insId}, {fields: {_id: 1, traces: 1}})
handle = db.instances.find({_id: instanceId}).observeChanges {
changed: (id)->
self.changed("instance_traces", instanceId, getInstanceTraces(instanceId));
}
self.added("instance_traces", instanceId, getInstanceTraces(instanceId));
self.ready();
self.onStop ()->
handle.stop() | 41035 | Meteor.publish 'instance_data', (instanceId, box)->
unless this.userId
return this.ready()
unless (instanceId && db.instances.find({_id: instanceId}).count())
return this.ready()
self = this;
miniApproveFields = ['_id', 'is_finished', 'user', 'handler', 'handler_name', 'type', 'start_date', 'description',
'is_read', 'judge', 'finish_date', 'from_user_name', 'from_user', 'cc_description', 'auto_submitted']
triggerChangeFields = ['form_version', 'flow_version', 'related_instances', '_my_approve_read_dates', 'values']
triggerChangeFieldsValues = {}
instance_fields_0 = {
"record_synced": 0,
# "traces.approves.handler_organization_fullname": 0,
"traces.approves.handler_organization_name": 0,
"traces.approves.handler_organization": 0,
"traces.approves.cost_time": 0,
# "traces.approves.read_date": 0,
"traces.approves.is_error": 0,
# "traces.approves.user_name": 0,
"traces.approves.deadline": 0,
"traces.approves.remind_date": 0,
"traces.approves.reminded_count": 0,
"traces.approves.modified_by": 0,
"traces.approves.modified": 0,
"traces.approves.geolocation": 0,
"traces.approves.cc_users": 0,
"traces.approves.from_approve_id": 0,
"traces.approves.values_history": 0
}
getMyapproveModified = (traces)->
myApproveModifieds = new Array()
traces?.forEach (trace)->
trace?.approves?.forEach (approve)->
if (approve.user == self.userId || approve.handler == self.userId)
# && !approve.is_finished
# console.log("approve", approve._id, approve.read_date)
myApproveModifieds.push(approve.read_date)
return myApproveModifieds
getMiniInstance = (_instanceId)->
instance = db.instances.findOne({_id: _instanceId}, {fields: instance_fields_0})
if instance
triggerChangeFields.forEach (key)->
if key == <KEY>'
triggerChangeFieldsValues[key] = getMyapproveModified(instance.traces)
else
triggerChangeFieldsValues[key] = instance[key]
# hasOpinionField = InstanceSignText.includesOpinionField(instance.form, instance.form_version)
show_modal_traces_list = db.space_settings.findOne({ space: instance.space, key: "show_modal<KEY>_traces<KEY>_list" }, { fields: { values: 1 } })?.values || false
if show_modal_traces_list
traces = new Array();
instance?.traces?.forEach (trace)->
_trace = _.clone(trace)
approves = new Array()
trace?.approves?.forEach (approve)->
if approve.type != 'cc' || approve.user == self.userId || approve.handler == self.userId || (!_.isEmpty(approve.sign_field_code))
approves.push(approve)
_trace.approves = approves
traces.push(_trace)
instance.traces = traces;
return instance
needChange = (changeFields)->
if changeFields
_change = false
_rev = _.find triggerChangeFields, (key)->
_key = key
if key == <KEY>'
_key = '<KEY>'
if _.has(changeFields, _key)
if key == <KEY>'
_my_approve_modifieds = getMyapproveModified(changeFields.traces)
# console.log(triggerChangeFieldsValues[key], _my_approve_modifieds)
return !_.isEqual(triggerChangeFieldsValues[key], _my_approve_modifieds)
else
return !_.isEqual(triggerChangeFieldsValues[key], changeFields[key])
if _rev
_change = true
# console.log(_rev, _change)
return _change
return true
#此处不能添加fields限制,否则会导致数据不实时
handle = db.instances.find({_id: instanceId}).observeChanges {
changed: (id, fields)->
if(box != 'inbox' || needChange(fields))
self.changed("instances", id, getMiniInstance(id));
removed: (id)->
self.removed("instances", id);
}
instance = getMiniInstance(instanceId)
self.added("instances", instance?._id, instance);
self.ready();
self.onStop ()->
handle.stop()
Meteor.publish 'instance_traces', (instanceId)->
unless this.userId
return this.ready()
unless instanceId
return this.ready()
self = this
getInstanceTraces = (_insId)->
return db.instances.findOne({_id: _insId}, {fields: {_id: 1, traces: 1}})
handle = db.instances.find({_id: instanceId}).observeChanges {
changed: (id)->
self.changed("instance_traces", instanceId, getInstanceTraces(instanceId));
}
self.added("instance_traces", instanceId, getInstanceTraces(instanceId));
self.ready();
self.onStop ()->
handle.stop() | true | Meteor.publish 'instance_data', (instanceId, box)->
unless this.userId
return this.ready()
unless (instanceId && db.instances.find({_id: instanceId}).count())
return this.ready()
self = this;
miniApproveFields = ['_id', 'is_finished', 'user', 'handler', 'handler_name', 'type', 'start_date', 'description',
'is_read', 'judge', 'finish_date', 'from_user_name', 'from_user', 'cc_description', 'auto_submitted']
triggerChangeFields = ['form_version', 'flow_version', 'related_instances', '_my_approve_read_dates', 'values']
triggerChangeFieldsValues = {}
instance_fields_0 = {
"record_synced": 0,
# "traces.approves.handler_organization_fullname": 0,
"traces.approves.handler_organization_name": 0,
"traces.approves.handler_organization": 0,
"traces.approves.cost_time": 0,
# "traces.approves.read_date": 0,
"traces.approves.is_error": 0,
# "traces.approves.user_name": 0,
"traces.approves.deadline": 0,
"traces.approves.remind_date": 0,
"traces.approves.reminded_count": 0,
"traces.approves.modified_by": 0,
"traces.approves.modified": 0,
"traces.approves.geolocation": 0,
"traces.approves.cc_users": 0,
"traces.approves.from_approve_id": 0,
"traces.approves.values_history": 0
}
getMyapproveModified = (traces)->
myApproveModifieds = new Array()
traces?.forEach (trace)->
trace?.approves?.forEach (approve)->
if (approve.user == self.userId || approve.handler == self.userId)
# && !approve.is_finished
# console.log("approve", approve._id, approve.read_date)
myApproveModifieds.push(approve.read_date)
return myApproveModifieds
getMiniInstance = (_instanceId)->
instance = db.instances.findOne({_id: _instanceId}, {fields: instance_fields_0})
if instance
triggerChangeFields.forEach (key)->
if key == PI:KEY:<KEY>END_PI'
triggerChangeFieldsValues[key] = getMyapproveModified(instance.traces)
else
triggerChangeFieldsValues[key] = instance[key]
# hasOpinionField = InstanceSignText.includesOpinionField(instance.form, instance.form_version)
show_modal_traces_list = db.space_settings.findOne({ space: instance.space, key: "show_modalPI:KEY:<KEY>END_PI_tracesPI:KEY:<KEY>END_PI_list" }, { fields: { values: 1 } })?.values || false
if show_modal_traces_list
traces = new Array();
instance?.traces?.forEach (trace)->
_trace = _.clone(trace)
approves = new Array()
trace?.approves?.forEach (approve)->
if approve.type != 'cc' || approve.user == self.userId || approve.handler == self.userId || (!_.isEmpty(approve.sign_field_code))
approves.push(approve)
_trace.approves = approves
traces.push(_trace)
instance.traces = traces;
return instance
needChange = (changeFields)->
if changeFields
_change = false
_rev = _.find triggerChangeFields, (key)->
_key = key
if key == PI:KEY:<KEY>END_PI'
_key = 'PI:KEY:<KEY>END_PI'
if _.has(changeFields, _key)
if key == PI:KEY:<KEY>END_PI'
_my_approve_modifieds = getMyapproveModified(changeFields.traces)
# console.log(triggerChangeFieldsValues[key], _my_approve_modifieds)
return !_.isEqual(triggerChangeFieldsValues[key], _my_approve_modifieds)
else
return !_.isEqual(triggerChangeFieldsValues[key], changeFields[key])
if _rev
_change = true
# console.log(_rev, _change)
return _change
return true
#此处不能添加fields限制,否则会导致数据不实时
handle = db.instances.find({_id: instanceId}).observeChanges {
changed: (id, fields)->
if(box != 'inbox' || needChange(fields))
self.changed("instances", id, getMiniInstance(id));
removed: (id)->
self.removed("instances", id);
}
instance = getMiniInstance(instanceId)
self.added("instances", instance?._id, instance);
self.ready();
self.onStop ()->
handle.stop()
Meteor.publish 'instance_traces', (instanceId)->
unless this.userId
return this.ready()
unless instanceId
return this.ready()
self = this
getInstanceTraces = (_insId)->
return db.instances.findOne({_id: _insId}, {fields: {_id: 1, traces: 1}})
handle = db.instances.find({_id: instanceId}).observeChanges {
changed: (id)->
self.changed("instance_traces", instanceId, getInstanceTraces(instanceId));
}
self.added("instance_traces", instanceId, getInstanceTraces(instanceId));
self.ready();
self.onStop ()->
handle.stop() |
[
{
"context": "hbluServer\n\n beforeEach (done) ->\n @redisKey = UUID.v1()\n meshbluConfig =\n server: 'localhost'\n ",
"end": 420,
"score": 0.9939724802970886,
"start": 411,
"tag": "KEY",
"value": "UUID.v1()"
},
{
"context": "tp://localhost:20000'\n auth: {username: 'governator-uuid', password: 'governator-token'}\n json:\n ",
"end": 1701,
"score": 0.9738052487373352,
"start": 1686,
"tag": "USERNAME",
"value": "governator-uuid"
},
{
"context": " auth: {username: 'governator-uuid', password: 'governator-token'}\n json:\n etcdDir: '/somedir/",
"end": 1731,
"score": 0.9994614720344543,
"start": 1715,
"tag": "PASSWORD",
"value": "governator-token"
},
{
"context": "ate the sorted set', (done) ->\n keyName = 'governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1'\n @client.zscore 'governator:deploys', key",
"end": 2232,
"score": 0.9972941875457764,
"start": 2164,
"tag": "KEY",
"value": "governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1"
},
{
"context": "tp://localhost:20000'\n auth: {username: 'governator-uuid', password: 'governator-token'}\n json:\n ",
"end": 2973,
"score": 0.9996458888053894,
"start": 2958,
"tag": "USERNAME",
"value": "governator-uuid"
},
{
"context": " auth: {username: 'governator-uuid', password: 'governator-token'}\n json:\n etcdDir: '/somedir/",
"end": 3003,
"score": 0.9992839097976685,
"start": 2987,
"tag": "PASSWORD",
"value": "governator-token"
},
{
"context": "tp://localhost:20000'\n auth: {username: 'wrong-uuid', password: 'wrong-token'}\n\n request.post ",
"end": 3738,
"score": 0.9989780783653259,
"start": 3728,
"tag": "USERNAME",
"value": "wrong-uuid"
},
{
"context": " auth: {username: 'wrong-uuid', password: 'wrong-token'}\n\n request.post options, (error, response",
"end": 3763,
"score": 0.9993503093719482,
"start": 3752,
"tag": "PASSWORD",
"value": "wrong-token"
},
{
"context": "tp://localhost:20000'\n auth: {username: 'wrong-uuid', password: 'wrong-token'}\n\n request.post ",
"end": 4424,
"score": 0.9988706111907959,
"start": 4414,
"tag": "USERNAME",
"value": "wrong-uuid"
},
{
"context": " auth: {username: 'wrong-uuid', password: 'wrong-token'}\n\n request.post options, (error, response",
"end": 4449,
"score": 0.999342143535614,
"start": 4438,
"tag": "PASSWORD",
"value": "wrong-token"
}
] | test/integration/create-schedule-spec.coffee | octoblu/governator-service | 0 | UUID = require 'uuid'
shmock = require 'shmock'
request = require 'request'
RedisNs = require '@octoblu/redis-ns'
redis = require 'ioredis'
enableDestroy = require 'server-destroy'
Server = require '../../server'
describe 'Create Schedule', ->
beforeEach ->
@meshbluServer = shmock 30000
enableDestroy @meshbluServer
beforeEach (done) ->
@redisKey = UUID.v1()
meshbluConfig =
server: 'localhost'
port: '30000'
uuid: 'governator-uuid'
token: 'governator-token'
@client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true
@logFn = sinon.spy()
@sut = new Server {
meshbluConfig: meshbluConfig
port: 20000
disableLogging: true
deployDelay: 1
redisUri: 'redis://localhost:6379'
namespace: @redisKey
maxConnections: 2,
requiredClusters: ['minor']
cluster: 'super'
deployStateUri: 'http://localhost'
@logFn
}
@sut.run done
afterEach ->
@sut.destroy()
@meshbluServer.destroy()
describe 'POST /schedules', ->
describe 'when exists', ->
beforeEach (done) ->
@client.set 'governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1', '', done
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: 'governator-token'}
json:
etcdDir: '/somedir/my-governed-deploy'
dockerUrl: 'octoblu/my-governed-deploy:v1'
deployAt: 550959
request.post options, (error, @response, @body) =>
return done error if error?
done()
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should update the sorted set', (done) ->
keyName = 'governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1'
@client.zscore 'governator:deploys', keyName, (error, rank) =>
return done error if error?
expect(rank).to.equal '550959'
done()
describe 'when does not exist', ->
beforeEach (done) ->
@client.del 'governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1', done
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: 'governator-token'}
json:
etcdDir: '/somedir/my-governed-deploy'
dockerUrl: 'octoblu/my-governed-deploy:v1'
deployAt: 550959
request.post options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, @body
describe 'when called with invalid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 403
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: 'wrong-token'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
describe 'when called the wrong valid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 200, uuid: 'wrong-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: 'wrong-token'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
| 224726 | UUID = require 'uuid'
shmock = require 'shmock'
request = require 'request'
RedisNs = require '@octoblu/redis-ns'
redis = require 'ioredis'
enableDestroy = require 'server-destroy'
Server = require '../../server'
describe 'Create Schedule', ->
beforeEach ->
@meshbluServer = shmock 30000
enableDestroy @meshbluServer
beforeEach (done) ->
@redisKey = <KEY>
meshbluConfig =
server: 'localhost'
port: '30000'
uuid: 'governator-uuid'
token: 'governator-token'
@client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true
@logFn = sinon.spy()
@sut = new Server {
meshbluConfig: meshbluConfig
port: 20000
disableLogging: true
deployDelay: 1
redisUri: 'redis://localhost:6379'
namespace: @redisKey
maxConnections: 2,
requiredClusters: ['minor']
cluster: 'super'
deployStateUri: 'http://localhost'
@logFn
}
@sut.run done
afterEach ->
@sut.destroy()
@meshbluServer.destroy()
describe 'POST /schedules', ->
describe 'when exists', ->
beforeEach (done) ->
@client.set 'governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1', '', done
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: '<PASSWORD>'}
json:
etcdDir: '/somedir/my-governed-deploy'
dockerUrl: 'octoblu/my-governed-deploy:v1'
deployAt: 550959
request.post options, (error, @response, @body) =>
return done error if error?
done()
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should update the sorted set', (done) ->
keyName = '<KEY>'
@client.zscore 'governator:deploys', keyName, (error, rank) =>
return done error if error?
expect(rank).to.equal '550959'
done()
describe 'when does not exist', ->
beforeEach (done) ->
@client.del 'governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1', done
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: '<PASSWORD>'}
json:
etcdDir: '/somedir/my-governed-deploy'
dockerUrl: 'octoblu/my-governed-deploy:v1'
deployAt: 550959
request.post options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, @body
describe 'when called with invalid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 403
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: '<PASSWORD>'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
describe 'when called the wrong valid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 200, uuid: 'wrong-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: '<PASSWORD>'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
| true | UUID = require 'uuid'
shmock = require 'shmock'
request = require 'request'
RedisNs = require '@octoblu/redis-ns'
redis = require 'ioredis'
enableDestroy = require 'server-destroy'
Server = require '../../server'
describe 'Create Schedule', ->
beforeEach ->
@meshbluServer = shmock 30000
enableDestroy @meshbluServer
beforeEach (done) ->
@redisKey = PI:KEY:<KEY>END_PI
meshbluConfig =
server: 'localhost'
port: '30000'
uuid: 'governator-uuid'
token: 'governator-token'
@client = new RedisNs @redisKey, redis.createClient 'redis://localhost:6379', dropBufferSupport: true
@logFn = sinon.spy()
@sut = new Server {
meshbluConfig: meshbluConfig
port: 20000
disableLogging: true
deployDelay: 1
redisUri: 'redis://localhost:6379'
namespace: @redisKey
maxConnections: 2,
requiredClusters: ['minor']
cluster: 'super'
deployStateUri: 'http://localhost'
@logFn
}
@sut.run done
afterEach ->
@sut.destroy()
@meshbluServer.destroy()
describe 'POST /schedules', ->
describe 'when exists', ->
beforeEach (done) ->
@client.set 'governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1', '', done
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
json:
etcdDir: '/somedir/my-governed-deploy'
dockerUrl: 'octoblu/my-governed-deploy:v1'
deployAt: 550959
request.post options, (error, @response, @body) =>
return done error if error?
done()
it 'should return a 201', ->
expect(@response.statusCode).to.equal 201, @body
it 'should update the sorted set', (done) ->
keyName = 'PI:KEY:<KEY>END_PI'
@client.zscore 'governator:deploys', keyName, (error, rank) =>
return done error if error?
expect(rank).to.equal '550959'
done()
describe 'when does not exist', ->
beforeEach (done) ->
@client.del 'governator:/somedir/my-governed-deploy:octoblu/my-governed-deploy:v1', done
beforeEach (done) ->
governatorAuth = new Buffer('governator-uuid:governator-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{governatorAuth}"
.reply 200, uuid: 'governator-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'governator-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
json:
etcdDir: '/somedir/my-governed-deploy'
dockerUrl: 'octoblu/my-governed-deploy:v1'
deployAt: 550959
request.post options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, @body
describe 'when called with invalid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 403
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
describe 'when called the wrong valid auth', ->
beforeEach (done) ->
wrongAuth = new Buffer('wrong-uuid:wrong-token').toString 'base64'
@meshbluServer
.get '/v2/whoami'
.set 'Authorization', "Basic #{wrongAuth}"
.reply 200, uuid: 'wrong-uuid'
options =
uri: '/schedules'
baseUrl: 'http://localhost:20000'
auth: {username: 'wrong-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'}
request.post options, (error, response) =>
return done error if error?
@statusCode = response.statusCode
done()
it 'should return a 403', ->
expect(@statusCode).to.equal 403
|
[
{
"context": ")\"\n params =\n email: email\n password: password\n @post \"session\", params, (data) -> fn data if",
"end": 631,
"score": 0.9983367919921875,
"start": 623,
"tag": "PASSWORD",
"value": "password"
}
] | src/Models/Users.coffee | baidao/node-gitlab | 0 | BaseModel = require '../BaseModel'
class Users extends BaseModel
all: (fn = null) =>
@debug "Users::all()"
@get "users", (data) => fn data if fn
current: (fn = null) =>
@debug "Users::current()"
@get "user", (data) -> fn data if fn
show: (userId, fn = null) =>
@debug "Users::show()"
@get "users/#{parseInt userId}", (data) => fn data if fn
create: (params = {}, fn = null) =>
@debug "Users::create()", params
@post "users", params, (data) -> fn data if fn
session: (email, password, fn = null) =>
@debug "Users::session()"
params =
email: email
password: password
@post "session", params, (data) -> fn data if fn
module.exports = (client) -> new Users client
| 107806 | BaseModel = require '../BaseModel'
class Users extends BaseModel
all: (fn = null) =>
@debug "Users::all()"
@get "users", (data) => fn data if fn
current: (fn = null) =>
@debug "Users::current()"
@get "user", (data) -> fn data if fn
show: (userId, fn = null) =>
@debug "Users::show()"
@get "users/#{parseInt userId}", (data) => fn data if fn
create: (params = {}, fn = null) =>
@debug "Users::create()", params
@post "users", params, (data) -> fn data if fn
session: (email, password, fn = null) =>
@debug "Users::session()"
params =
email: email
password: <PASSWORD>
@post "session", params, (data) -> fn data if fn
module.exports = (client) -> new Users client
| true | BaseModel = require '../BaseModel'
class Users extends BaseModel
all: (fn = null) =>
@debug "Users::all()"
@get "users", (data) => fn data if fn
current: (fn = null) =>
@debug "Users::current()"
@get "user", (data) -> fn data if fn
show: (userId, fn = null) =>
@debug "Users::show()"
@get "users/#{parseInt userId}", (data) => fn data if fn
create: (params = {}, fn = null) =>
@debug "Users::create()", params
@post "users", params, (data) -> fn data if fn
session: (email, password, fn = null) =>
@debug "Users::session()"
params =
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
@post "session", params, (data) -> fn data if fn
module.exports = (client) -> new Users client
|
[
{
"context": "ppid=dc1ff3c5007c4abd9a824b0dd5948515&accesskeyid=e137fdc716b94abd80306f596ad67604_5870727701_1387234472742_ChooChee&ratetableid=a171ef84826a467593f8be",
"end": 1480,
"score": 0.9983999133110046,
"start": 1429,
"tag": "KEY",
"value": "e137fdc716b94abd80306f596ad67604_5870727701_1387234"
},
{
"context": "716b94abd80306f596ad67604_5870727701_1387234472742_ChooChee&ratetableid=a171ef84826a467593f8bed15bfb9",
"end": 1486,
"score": 0.9300719499588013,
"start": 1486,
"tag": "KEY",
"value": ""
}
] | pages/account/index/account_index.coffee | signonsridhar/sridhar_hbs | 0 | define([
'bases/page'
'modules/left_nav/left_nav',
'modules/tab/tab_header',
'models/account/account',
'models/credit_card/credit_card',
'models/tenant/tenant',
'models/auth/auth',
'modules/notification/notification',
'_',
'css! pages/account/index/account_index'
], (BasePage,LeftNav,TabHeader,Account,CreditCard,Tenant,Auth,Notification,_)->
BasePage.extend({
init:($elem, options)->
this.render('account/index/account_index')
this.header = new TabHeader(this.find('.tab_header_container'))
#display status
this.status_msg = new Notification(this.find('.status_container_js'))
this.left_nav = new LeftNav(this.find('.left_nav_container_js'),{
tabs:{
css:'account'
map:{
account_info:'Your Plan',
payment_method: 'Payment Method',
billing_history: 'Billing History',
rates: 'Rates'
}
change:(key, item)->
can.route.attr({main: 'account', sub: key }, true)
renderer:(key, value)->
"<span>#{value}</span>"
}
})
#/bss/commerce/ratetable?action=getabbreviatedrates&appid=dc1ff3c5007c4abd9a824b0dd5948515&accesskeyid=e137fdc716b94abd80306f596ad67604_5870727701_1387234472742_ChooChee&ratetableid=a171ef84826a467593f8bed15bfb9310&filter=country%3DUnited%20States&start_offset=0&count=20&_=1387234763056
account_id = options.account_id = Auth.get_auth().attr('account_id')
options.models = models = {}
models.credit_card = new CreditCard()
models.credit_card.set_mode(CreditCard.MODE.ARIA)
models.credit_card.set_validated_attrs(_.keys(models.credit_card.validations[CreditCard.MODE.ARIA]) )
this.account = options.account = models.account = new Account()
this.account.set_promise(Account.get_account_details(account_id))
this.on()
###'{can.route} change':(e)->
this.left_nav.left_tab.set_active(can.route.attr('sub'))###
get_sub:()->
sub = can.route.attr('sub')
if sub == 'index' then 'account_info' else sub
switch_sub: (sub)->
sub = 'account_info' if sub == 'index'
require(["pages/account/#{sub}/#{sub}_page"], (PageStep)=>
$account_cont = $("<div class='account_container'></div>")
this.account_page = new PageStep($account_cont, {
models: this.options.models,
rightnav: this.find('.right_nav_container_js')
})
this.left_nav.set_content(this.account_page)
this.left_nav.set_active(this.get_sub())
this.on()
)
'{account} account_id':_.debounce(()->
if( this.options.models.account.attr('account_address_street1') &&
this.options.models.account.attr('account_address_city') &&
this.options.models.account.attr('account_address_state') &&
this.options.models.account.attr('account_address_zip') )
this.options.models.account.attr('tenant_id',Auth.get_auth().attr('tenant_id'))
this.options.models.tenant = new Tenant({
primary_address_street1: this.options.models.account.attr('account_address_street1'),
primary_address_city: this.options.models.account.attr('account_address_city'),
primary_address_state: this.options.models.account.attr('account_address_state'),
primary_address_zip: this.options.models.account.attr('account_address_zip'),
primary_address_country: this.options.models.account.attr('account_address_country'),
name: this.options.models.account.attr('name')
account_id: this.options.models.account.attr('account_id'),
tenant_id: Auth.get_auth().attr('tenant_id')
})
this.switch_sub(can.route.attr('sub'))
, 100 )
})
) | 97687 | define([
'bases/page'
'modules/left_nav/left_nav',
'modules/tab/tab_header',
'models/account/account',
'models/credit_card/credit_card',
'models/tenant/tenant',
'models/auth/auth',
'modules/notification/notification',
'_',
'css! pages/account/index/account_index'
], (BasePage,LeftNav,TabHeader,Account,CreditCard,Tenant,Auth,Notification,_)->
BasePage.extend({
init:($elem, options)->
this.render('account/index/account_index')
this.header = new TabHeader(this.find('.tab_header_container'))
#display status
this.status_msg = new Notification(this.find('.status_container_js'))
this.left_nav = new LeftNav(this.find('.left_nav_container_js'),{
tabs:{
css:'account'
map:{
account_info:'Your Plan',
payment_method: 'Payment Method',
billing_history: 'Billing History',
rates: 'Rates'
}
change:(key, item)->
can.route.attr({main: 'account', sub: key }, true)
renderer:(key, value)->
"<span>#{value}</span>"
}
})
#/bss/commerce/ratetable?action=getabbreviatedrates&appid=dc1ff3c5007c4abd9a824b0dd5948515&accesskeyid=<KEY>472742<KEY>_ChooChee&ratetableid=a171ef84826a467593f8bed15bfb9310&filter=country%3DUnited%20States&start_offset=0&count=20&_=1387234763056
account_id = options.account_id = Auth.get_auth().attr('account_id')
options.models = models = {}
models.credit_card = new CreditCard()
models.credit_card.set_mode(CreditCard.MODE.ARIA)
models.credit_card.set_validated_attrs(_.keys(models.credit_card.validations[CreditCard.MODE.ARIA]) )
this.account = options.account = models.account = new Account()
this.account.set_promise(Account.get_account_details(account_id))
this.on()
###'{can.route} change':(e)->
this.left_nav.left_tab.set_active(can.route.attr('sub'))###
get_sub:()->
sub = can.route.attr('sub')
if sub == 'index' then 'account_info' else sub
switch_sub: (sub)->
sub = 'account_info' if sub == 'index'
require(["pages/account/#{sub}/#{sub}_page"], (PageStep)=>
$account_cont = $("<div class='account_container'></div>")
this.account_page = new PageStep($account_cont, {
models: this.options.models,
rightnav: this.find('.right_nav_container_js')
})
this.left_nav.set_content(this.account_page)
this.left_nav.set_active(this.get_sub())
this.on()
)
'{account} account_id':_.debounce(()->
if( this.options.models.account.attr('account_address_street1') &&
this.options.models.account.attr('account_address_city') &&
this.options.models.account.attr('account_address_state') &&
this.options.models.account.attr('account_address_zip') )
this.options.models.account.attr('tenant_id',Auth.get_auth().attr('tenant_id'))
this.options.models.tenant = new Tenant({
primary_address_street1: this.options.models.account.attr('account_address_street1'),
primary_address_city: this.options.models.account.attr('account_address_city'),
primary_address_state: this.options.models.account.attr('account_address_state'),
primary_address_zip: this.options.models.account.attr('account_address_zip'),
primary_address_country: this.options.models.account.attr('account_address_country'),
name: this.options.models.account.attr('name')
account_id: this.options.models.account.attr('account_id'),
tenant_id: Auth.get_auth().attr('tenant_id')
})
this.switch_sub(can.route.attr('sub'))
, 100 )
})
) | true | define([
'bases/page'
'modules/left_nav/left_nav',
'modules/tab/tab_header',
'models/account/account',
'models/credit_card/credit_card',
'models/tenant/tenant',
'models/auth/auth',
'modules/notification/notification',
'_',
'css! pages/account/index/account_index'
], (BasePage,LeftNav,TabHeader,Account,CreditCard,Tenant,Auth,Notification,_)->
BasePage.extend({
init:($elem, options)->
this.render('account/index/account_index')
this.header = new TabHeader(this.find('.tab_header_container'))
#display status
this.status_msg = new Notification(this.find('.status_container_js'))
this.left_nav = new LeftNav(this.find('.left_nav_container_js'),{
tabs:{
css:'account'
map:{
account_info:'Your Plan',
payment_method: 'Payment Method',
billing_history: 'Billing History',
rates: 'Rates'
}
change:(key, item)->
can.route.attr({main: 'account', sub: key }, true)
renderer:(key, value)->
"<span>#{value}</span>"
}
})
#/bss/commerce/ratetable?action=getabbreviatedrates&appid=dc1ff3c5007c4abd9a824b0dd5948515&accesskeyid=PI:KEY:<KEY>END_PI472742PI:KEY:<KEY>END_PI_ChooChee&ratetableid=a171ef84826a467593f8bed15bfb9310&filter=country%3DUnited%20States&start_offset=0&count=20&_=1387234763056
account_id = options.account_id = Auth.get_auth().attr('account_id')
options.models = models = {}
models.credit_card = new CreditCard()
models.credit_card.set_mode(CreditCard.MODE.ARIA)
models.credit_card.set_validated_attrs(_.keys(models.credit_card.validations[CreditCard.MODE.ARIA]) )
this.account = options.account = models.account = new Account()
this.account.set_promise(Account.get_account_details(account_id))
this.on()
###'{can.route} change':(e)->
this.left_nav.left_tab.set_active(can.route.attr('sub'))###
get_sub:()->
sub = can.route.attr('sub')
if sub == 'index' then 'account_info' else sub
switch_sub: (sub)->
sub = 'account_info' if sub == 'index'
require(["pages/account/#{sub}/#{sub}_page"], (PageStep)=>
$account_cont = $("<div class='account_container'></div>")
this.account_page = new PageStep($account_cont, {
models: this.options.models,
rightnav: this.find('.right_nav_container_js')
})
this.left_nav.set_content(this.account_page)
this.left_nav.set_active(this.get_sub())
this.on()
)
'{account} account_id':_.debounce(()->
if( this.options.models.account.attr('account_address_street1') &&
this.options.models.account.attr('account_address_city') &&
this.options.models.account.attr('account_address_state') &&
this.options.models.account.attr('account_address_zip') )
this.options.models.account.attr('tenant_id',Auth.get_auth().attr('tenant_id'))
this.options.models.tenant = new Tenant({
primary_address_street1: this.options.models.account.attr('account_address_street1'),
primary_address_city: this.options.models.account.attr('account_address_city'),
primary_address_state: this.options.models.account.attr('account_address_state'),
primary_address_zip: this.options.models.account.attr('account_address_zip'),
primary_address_country: this.options.models.account.attr('account_address_country'),
name: this.options.models.account.attr('name')
account_id: this.options.models.account.attr('account_id'),
tenant_id: Auth.get_auth().attr('tenant_id')
})
this.switch_sub(can.route.attr('sub'))
, 100 )
})
) |
[
{
"context": "\n # pace.start()\n\n swal.setDefaults\n title: \"Framesia\"\n text: \"Framesia\"\n html: true\n showCa",
"end": 232,
"score": 0.9061342477798462,
"start": 226,
"tag": "NAME",
"value": "Frames"
},
{
"context": "swal.setDefaults\n title: \"Framesia\"\n text: \"Framesia\"\n html: true\n showCancelButton: false\n ",
"end": 253,
"score": 0.9541922211647034,
"start": 247,
"tag": "NAME",
"value": "Frames"
}
] | asset/frms/js/main.coffee | damaera/framesia-code | 1 | ( documentReady = () ->
swal = require 'sweetalert'
request = require 'superagent'
{ $, $$ } = require './helper/selector.coffee'
# pace = require './vendor/pace.js'
# pace.start()
swal.setDefaults
title: "Framesia"
text: "Framesia"
html: true
showCancelButton: false
showConfirmButton: false
animation: "slide-from-top"
allowOutsideClick: true
closeOnConfirm: true
love = require './include/love.coffee'
repost = require './include/repost.coffee'
repostLink = require './include/repostLink.coffee'
article = require './include/article.coffee'
csrf = require './include/csrf.coffee'
repost()
repostLink()
love.article()
love.comment()
article.delete()
article.publish()
csrf()
require './include/headerFix.coffee'
require './include/drop.coffee'
require './include/firstTime.coffee'
require './include/tag.coffee'
require './include/feedRight.coffee'
require './include/notif.coffee'
require './include/comment.coffee'
require './include/follow.coffee'
require './include/checkRead.coffee'
require './include/checkUsername.coffee'
require './include/saveArticle.coffee'
require './include/getArticle.coffee'
require './include/autocompleteUser.coffee'
require './include/collection.coffee'
require './include/collectionPeople.coffee'
require './include/collectionArticle.coffee'
require './include/addCollection.coffee'
require './include/getComment.coffee'
# require './include/getFeedHome.coffee'
# require './include/getFeedProfile.coffee'
require './include/getLovedArticles.coffee'
require './include/getArticles2.coffee'
require './include/getArticles.coffee'
require './include/report.coffee'
require './include/makeTableOfContent.coffee'
require './include/comment2.coffee'
$$loginButton = $$ '.js-login-button'
for $loginButton in $$loginButton
$loginButton.onclick = (e) ->
swal
title: "Sign in to Framesia"
text: """
<p>Welcome to Framesia</p>
<a href='/a/facebook'>
<button class='i-button i-button--green'>Sign in with Facebook</button>
</a>
<br>
<a href='/a/google'>
<button class='i-button i-button--red'>Sign in with Google</button>
</a>
"""
html: true
showCancelButton: false
showConfirmButton: false
$$imgCoverFull = $$ ('.is-cover-full img')
for $imgCoverFull in $$imgCoverFull
$container = $imgCoverFull.parentNode
imgUrl = $imgCoverFull.getAttribute 'src'
$imgCoverFull.classList.add 'is-hidden'
$container.style.backgroundImage = "url('#{imgUrl}')"
$container.style.backgroundSize = "cover"
$$imgCoverSlide = $$ ('.is-cover-slide img')
for $imgCoverSlide in $$imgCoverSlide
$container = $imgCoverSlide.parentNode
imgUrl = $imgCoverSlide.getAttribute 'src'
$imgCoverSlide.classList.add 'is-hidden'
$container.style.backgroundImage = "url('#{imgUrl}')"
$container.style.backgroundSize = "cover"
if $('.b-article__cover.is-cover-not-full')
$('.b-article__cover.is-cover-not-full').parentNode.style.background = '#fff'
if ($ '.js-editable')
for $figure in ($$ 'figure')
$figure.editable = false
for $figcaption in ($$ 'figcaption')
$figcaption.editable = true
require './editor/main.coffee'
if not window.location.hash or ( window.location.hash isnt '#_=_' )
return
if window.history and window.history.replaceState
return window.history.replaceState "", document.title, window.location.pathname
scroll =
top: document.body.scrollTop
left: document.body.scrollLeft
window.location.hash = ""
document.body.scrollTop = scroll.top
document.body.scrollLeft = scroll.left
)()
| 214472 | ( documentReady = () ->
swal = require 'sweetalert'
request = require 'superagent'
{ $, $$ } = require './helper/selector.coffee'
# pace = require './vendor/pace.js'
# pace.start()
swal.setDefaults
title: "<NAME>ia"
text: "<NAME>ia"
html: true
showCancelButton: false
showConfirmButton: false
animation: "slide-from-top"
allowOutsideClick: true
closeOnConfirm: true
love = require './include/love.coffee'
repost = require './include/repost.coffee'
repostLink = require './include/repostLink.coffee'
article = require './include/article.coffee'
csrf = require './include/csrf.coffee'
repost()
repostLink()
love.article()
love.comment()
article.delete()
article.publish()
csrf()
require './include/headerFix.coffee'
require './include/drop.coffee'
require './include/firstTime.coffee'
require './include/tag.coffee'
require './include/feedRight.coffee'
require './include/notif.coffee'
require './include/comment.coffee'
require './include/follow.coffee'
require './include/checkRead.coffee'
require './include/checkUsername.coffee'
require './include/saveArticle.coffee'
require './include/getArticle.coffee'
require './include/autocompleteUser.coffee'
require './include/collection.coffee'
require './include/collectionPeople.coffee'
require './include/collectionArticle.coffee'
require './include/addCollection.coffee'
require './include/getComment.coffee'
# require './include/getFeedHome.coffee'
# require './include/getFeedProfile.coffee'
require './include/getLovedArticles.coffee'
require './include/getArticles2.coffee'
require './include/getArticles.coffee'
require './include/report.coffee'
require './include/makeTableOfContent.coffee'
require './include/comment2.coffee'
$$loginButton = $$ '.js-login-button'
for $loginButton in $$loginButton
$loginButton.onclick = (e) ->
swal
title: "Sign in to Framesia"
text: """
<p>Welcome to Framesia</p>
<a href='/a/facebook'>
<button class='i-button i-button--green'>Sign in with Facebook</button>
</a>
<br>
<a href='/a/google'>
<button class='i-button i-button--red'>Sign in with Google</button>
</a>
"""
html: true
showCancelButton: false
showConfirmButton: false
$$imgCoverFull = $$ ('.is-cover-full img')
for $imgCoverFull in $$imgCoverFull
$container = $imgCoverFull.parentNode
imgUrl = $imgCoverFull.getAttribute 'src'
$imgCoverFull.classList.add 'is-hidden'
$container.style.backgroundImage = "url('#{imgUrl}')"
$container.style.backgroundSize = "cover"
$$imgCoverSlide = $$ ('.is-cover-slide img')
for $imgCoverSlide in $$imgCoverSlide
$container = $imgCoverSlide.parentNode
imgUrl = $imgCoverSlide.getAttribute 'src'
$imgCoverSlide.classList.add 'is-hidden'
$container.style.backgroundImage = "url('#{imgUrl}')"
$container.style.backgroundSize = "cover"
if $('.b-article__cover.is-cover-not-full')
$('.b-article__cover.is-cover-not-full').parentNode.style.background = '#fff'
if ($ '.js-editable')
for $figure in ($$ 'figure')
$figure.editable = false
for $figcaption in ($$ 'figcaption')
$figcaption.editable = true
require './editor/main.coffee'
if not window.location.hash or ( window.location.hash isnt '#_=_' )
return
if window.history and window.history.replaceState
return window.history.replaceState "", document.title, window.location.pathname
scroll =
top: document.body.scrollTop
left: document.body.scrollLeft
window.location.hash = ""
document.body.scrollTop = scroll.top
document.body.scrollLeft = scroll.left
)()
| true | ( documentReady = () ->
swal = require 'sweetalert'
request = require 'superagent'
{ $, $$ } = require './helper/selector.coffee'
# pace = require './vendor/pace.js'
# pace.start()
swal.setDefaults
title: "PI:NAME:<NAME>END_PIia"
text: "PI:NAME:<NAME>END_PIia"
html: true
showCancelButton: false
showConfirmButton: false
animation: "slide-from-top"
allowOutsideClick: true
closeOnConfirm: true
love = require './include/love.coffee'
repost = require './include/repost.coffee'
repostLink = require './include/repostLink.coffee'
article = require './include/article.coffee'
csrf = require './include/csrf.coffee'
repost()
repostLink()
love.article()
love.comment()
article.delete()
article.publish()
csrf()
require './include/headerFix.coffee'
require './include/drop.coffee'
require './include/firstTime.coffee'
require './include/tag.coffee'
require './include/feedRight.coffee'
require './include/notif.coffee'
require './include/comment.coffee'
require './include/follow.coffee'
require './include/checkRead.coffee'
require './include/checkUsername.coffee'
require './include/saveArticle.coffee'
require './include/getArticle.coffee'
require './include/autocompleteUser.coffee'
require './include/collection.coffee'
require './include/collectionPeople.coffee'
require './include/collectionArticle.coffee'
require './include/addCollection.coffee'
require './include/getComment.coffee'
# require './include/getFeedHome.coffee'
# require './include/getFeedProfile.coffee'
require './include/getLovedArticles.coffee'
require './include/getArticles2.coffee'
require './include/getArticles.coffee'
require './include/report.coffee'
require './include/makeTableOfContent.coffee'
require './include/comment2.coffee'
$$loginButton = $$ '.js-login-button'
for $loginButton in $$loginButton
$loginButton.onclick = (e) ->
swal
title: "Sign in to Framesia"
text: """
<p>Welcome to Framesia</p>
<a href='/a/facebook'>
<button class='i-button i-button--green'>Sign in with Facebook</button>
</a>
<br>
<a href='/a/google'>
<button class='i-button i-button--red'>Sign in with Google</button>
</a>
"""
html: true
showCancelButton: false
showConfirmButton: false
$$imgCoverFull = $$ ('.is-cover-full img')
for $imgCoverFull in $$imgCoverFull
$container = $imgCoverFull.parentNode
imgUrl = $imgCoverFull.getAttribute 'src'
$imgCoverFull.classList.add 'is-hidden'
$container.style.backgroundImage = "url('#{imgUrl}')"
$container.style.backgroundSize = "cover"
$$imgCoverSlide = $$ ('.is-cover-slide img')
for $imgCoverSlide in $$imgCoverSlide
$container = $imgCoverSlide.parentNode
imgUrl = $imgCoverSlide.getAttribute 'src'
$imgCoverSlide.classList.add 'is-hidden'
$container.style.backgroundImage = "url('#{imgUrl}')"
$container.style.backgroundSize = "cover"
if $('.b-article__cover.is-cover-not-full')
$('.b-article__cover.is-cover-not-full').parentNode.style.background = '#fff'
if ($ '.js-editable')
for $figure in ($$ 'figure')
$figure.editable = false
for $figcaption in ($$ 'figcaption')
$figcaption.editable = true
require './editor/main.coffee'
if not window.location.hash or ( window.location.hash isnt '#_=_' )
return
if window.history and window.history.replaceState
return window.history.replaceState "", document.title, window.location.pathname
scroll =
top: document.body.scrollTop
left: document.body.scrollLeft
window.location.hash = ""
document.body.scrollTop = scroll.top
document.body.scrollLeft = scroll.left
)()
|
[
{
"context": "(and sometimes even the number 1).\n\tTOKEN_ALPHA: 'bcdfghjkmnpqrstvwxyz'\n\tTOKEN_NUMERICS: '123456789'\n\n\t_randomString: (l",
"end": 737,
"score": 0.9874871373176575,
"start": 717,
"tag": "KEY",
"value": "bcdfghjkmnpqrstvwxyz"
},
{
"context": "N_ALPHA: 'bcdfghjkmnpqrstvwxyz'\n\tTOKEN_NUMERICS: '123456789'\n\n\t_randomString: (length, alphabet) ->\n\t\tresult ",
"end": 766,
"score": 0.8875929117202759,
"start": 757,
"tag": "KEY",
"value": "123456789"
},
{
"context": "okenGenerator.TOKEN_ALPHA\n\t\t)\n\t\tfullToken = \"#{numerics}#{token}\"\n\t\treturn { token: fullToken, numericPref",
"end": 1532,
"score": 0.6661254167556763,
"start": 1526,
"tag": "KEY",
"value": "erics}"
}
] | app/coffee/Features/Project/ProjectTokenGenerator.coffee | shyoshyo/web-sharelatex | 1 | crypto = require 'crypto'
V1Api = require('../V1/V1Api')
Async = require('async')
logger = require('logger-sharelatex')
# This module mirrors the token generation in Overleaf (`random_token.rb`),
# for the purposes of implementing token-based project access, like the
# 'unlisted-projects' feature in Overleaf
module.exports = ProjectTokenGenerator =
# (From Overleaf `random_token.rb`)
# Letters (not numbers! see generate_token) used in tokens. They're all
# consonants, to avoid embarassing words (I can't think of any that use only
# a y), and lower case "l" is omitted, because in many fonts it is
# indistinguishable from an upper case "I" (and sometimes even the number 1).
TOKEN_ALPHA: 'bcdfghjkmnpqrstvwxyz'
TOKEN_NUMERICS: '123456789'
_randomString: (length, alphabet) ->
result = crypto.randomBytes(length).toJSON().data.map(
(b) -> alphabet[b % alphabet.length]
).join('')
return result
# Generate a 12-char token with only characters from TOKEN_ALPHA,
# suitable for use as a read-only token for a project
readOnlyToken: () ->
return ProjectTokenGenerator._randomString(
12,
ProjectTokenGenerator.TOKEN_ALPHA
)
# Generate a longer token, with a numeric prefix,
# suitable for use as a read-and-write token for a project
readAndWriteToken: () ->
numerics = ProjectTokenGenerator._randomString(
10,
ProjectTokenGenerator.TOKEN_NUMERICS
)
token = ProjectTokenGenerator._randomString(
12,
ProjectTokenGenerator.TOKEN_ALPHA
)
fullToken = "#{numerics}#{token}"
return { token: fullToken, numericPrefix: numerics }
generateUniqueReadOnlyToken: (callback=(err, token)->) ->
Async.retry 10
, (cb) ->
token = ProjectTokenGenerator.readOnlyToken()
logger.log {token}, "Generated read-only token"
V1Api.request {
url: "/api/v1/sharelatex/docs/read_token/#{token}/exists",
json: true
}, (err, response, body) ->
return cb(err) if err?
if response.statusCode != 200
return cb(new Error("non-200 response from v1 read-token-exists api: #{response.statusCode}"))
if body.exists == true
cb(new Error("token already exists in v1: #{token}"))
else
logger.log {token}, "Read-only token does not exist in v1, good to use"
cb(null, token)
, callback
| 78301 | crypto = require 'crypto'
V1Api = require('../V1/V1Api')
Async = require('async')
logger = require('logger-sharelatex')
# This module mirrors the token generation in Overleaf (`random_token.rb`),
# for the purposes of implementing token-based project access, like the
# 'unlisted-projects' feature in Overleaf
module.exports = ProjectTokenGenerator =
# (From Overleaf `random_token.rb`)
# Letters (not numbers! see generate_token) used in tokens. They're all
# consonants, to avoid embarassing words (I can't think of any that use only
# a y), and lower case "l" is omitted, because in many fonts it is
# indistinguishable from an upper case "I" (and sometimes even the number 1).
TOKEN_ALPHA: '<KEY>'
TOKEN_NUMERICS: '<KEY>'
_randomString: (length, alphabet) ->
result = crypto.randomBytes(length).toJSON().data.map(
(b) -> alphabet[b % alphabet.length]
).join('')
return result
# Generate a 12-char token with only characters from TOKEN_ALPHA,
# suitable for use as a read-only token for a project
readOnlyToken: () ->
return ProjectTokenGenerator._randomString(
12,
ProjectTokenGenerator.TOKEN_ALPHA
)
# Generate a longer token, with a numeric prefix,
# suitable for use as a read-and-write token for a project
readAndWriteToken: () ->
numerics = ProjectTokenGenerator._randomString(
10,
ProjectTokenGenerator.TOKEN_NUMERICS
)
token = ProjectTokenGenerator._randomString(
12,
ProjectTokenGenerator.TOKEN_ALPHA
)
fullToken = "#{num<KEY>#{token}"
return { token: fullToken, numericPrefix: numerics }
generateUniqueReadOnlyToken: (callback=(err, token)->) ->
Async.retry 10
, (cb) ->
token = ProjectTokenGenerator.readOnlyToken()
logger.log {token}, "Generated read-only token"
V1Api.request {
url: "/api/v1/sharelatex/docs/read_token/#{token}/exists",
json: true
}, (err, response, body) ->
return cb(err) if err?
if response.statusCode != 200
return cb(new Error("non-200 response from v1 read-token-exists api: #{response.statusCode}"))
if body.exists == true
cb(new Error("token already exists in v1: #{token}"))
else
logger.log {token}, "Read-only token does not exist in v1, good to use"
cb(null, token)
, callback
| true | crypto = require 'crypto'
V1Api = require('../V1/V1Api')
Async = require('async')
logger = require('logger-sharelatex')
# This module mirrors the token generation in Overleaf (`random_token.rb`),
# for the purposes of implementing token-based project access, like the
# 'unlisted-projects' feature in Overleaf
module.exports = ProjectTokenGenerator =
# (From Overleaf `random_token.rb`)
# Letters (not numbers! see generate_token) used in tokens. They're all
# consonants, to avoid embarassing words (I can't think of any that use only
# a y), and lower case "l" is omitted, because in many fonts it is
# indistinguishable from an upper case "I" (and sometimes even the number 1).
TOKEN_ALPHA: 'PI:KEY:<KEY>END_PI'
TOKEN_NUMERICS: 'PI:KEY:<KEY>END_PI'
_randomString: (length, alphabet) ->
result = crypto.randomBytes(length).toJSON().data.map(
(b) -> alphabet[b % alphabet.length]
).join('')
return result
# Generate a 12-char token with only characters from TOKEN_ALPHA,
# suitable for use as a read-only token for a project
readOnlyToken: () ->
return ProjectTokenGenerator._randomString(
12,
ProjectTokenGenerator.TOKEN_ALPHA
)
# Generate a longer token, with a numeric prefix,
# suitable for use as a read-and-write token for a project
readAndWriteToken: () ->
numerics = ProjectTokenGenerator._randomString(
10,
ProjectTokenGenerator.TOKEN_NUMERICS
)
token = ProjectTokenGenerator._randomString(
12,
ProjectTokenGenerator.TOKEN_ALPHA
)
fullToken = "#{numPI:KEY:<KEY>END_PI#{token}"
return { token: fullToken, numericPrefix: numerics }
generateUniqueReadOnlyToken: (callback=(err, token)->) ->
Async.retry 10
, (cb) ->
token = ProjectTokenGenerator.readOnlyToken()
logger.log {token}, "Generated read-only token"
V1Api.request {
url: "/api/v1/sharelatex/docs/read_token/#{token}/exists",
json: true
}, (err, response, body) ->
return cb(err) if err?
if response.statusCode != 200
return cb(new Error("non-200 response from v1 read-token-exists api: #{response.statusCode}"))
if body.exists == true
cb(new Error("token already exists in v1: #{token}"))
else
logger.log {token}, "Read-only token does not exist in v1, good to use"
cb(null, token)
, callback
|
[
{
"context": " AttributeName: keys[0]\n KeyType: type.toUpperCase()\n })\n awsParams.GlobalSecondaryI",
"end": 4141,
"score": 0.8062832355499268,
"start": 4130,
"tag": "KEY",
"value": "toUpperCase"
}
] | src/dynasty.coffee | brianknight10/dynasty | 0 | # Main Dynasty Class
aws = require('aws-sdk')
_ = require('lodash')
Promise = require('bluebird')
debug = require('debug')('dynasty')
https = require('https')
# See http://vq.io/19EiASB
typeToAwsType =
string: 'S'
string_set: 'SS'
number: 'N'
number_set: 'NS'
binary: 'B'
binary_set: 'BS'
lib = require('./lib')
Table = lib.Table
class Dynasty
constructor: (credentials, url) ->
debug "dynasty constructed."
# Default to credentials passed in, if any
if credentials.region
credentials.region = credentials.region
# Fall back on env variables
else if process.env.AWS_DEFAULT_REGION
credentials.region = process.env.AWS_DEFAULT_REGION
else
credentials.region = 'us-east-1'
if !credentials.accessKeyId
credentials.accessKeyId = process.env.AWS_ACCESS_KEY_ID
if !credentials.secretAccessKey
credentials.accessKeyId = process.env.AWS_SECRET_ACCESS_KEY
# Lock API version
credentials.apiVersion = '2012-08-10'
if url and _.isString url
debug "connecting to local dynamo at #{url}"
credentials.endpoint = new aws.Endpoint url
@dynamo = new aws.DynamoDB credentials
Promise.promisifyAll(@dynamo, {suffix: 'Promise'})
@name = 'Dynasty'
@tables = {}
loadAllTables: =>
@list()
.then (data) =>
for tableName in data.TableNames
@table(tableName)
return @tables
# Given a name, return a Table object
table: (name) ->
@tables[name] = @tables[name] || new Table this, name
###
Table Operations
###
# Alter an existing table. Wrapper around AWS updateTable
alter: (name, params, callback) ->
debug "alter() - #{name}, #{JSON.stringify(params, null, 4)}"
# We'll accept either an object with a key of throughput or just
# an object with the throughput info
throughput = params.throughput || params
awsParams =
TableName: name
ProvisionedThroughput:
ReadCapacityUnits: throughput.read
WriteCapacityUnits: throughput.write
@dynamo.updateTablePromise(awsParams).nodeify(callback)
# Create a new table. Wrapper around AWS createTable
create: (name, params, callback = null) ->
debug "create() - #{name}, #{JSON.stringify(params, null, 4)}"
throughput = params.throughput || {read: 10, write: 5}
keySchema = [
KeyType: 'HASH'
AttributeName: params.key_schema.hash[0]
]
attributeDefinitions = [
AttributeName: params.key_schema.hash[0]
AttributeType: typeToAwsType[params.key_schema.hash[1]]
]
if params.key_schema.range?
keySchema.push
KeyType: 'RANGE',
AttributeName: params.key_schema.range[0]
attributeDefinitions.push
AttributeName: params.key_schema.range[0]
AttributeType: typeToAwsType[params.key_schema.range[1]]
awsParams =
AttributeDefinitions: attributeDefinitions
TableName: name
KeySchema: keySchema
ProvisionedThroughput:
ReadCapacityUnits: throughput.read
WriteCapacityUnits: throughput.write
# Add GlobalSecondaryIndexes to awsParams if provided
if params.global_secondary_indexes?
awsParams.GlobalSecondaryIndexes = []
# Verify valid GSI
for index in params.global_secondary_indexes
key_schema = index.key_schema
# Must provide hash type
unless key_schema.hash?
throw TypeError 'Missing hash index for GlobalSecondaryIndex'
typesProvided = Object.keys(key_schema).length
# Provide 1-2 types for GSI
if typesProvided.length > 2 or typesProvided.length < 1
throw RangeError 'Expected one or two types for GlobalSecondaryIndex'
# Providing 2 types but the second isn't range type
if typesProvided.length is 2 and not key_schema.range?
throw TypeError 'Two types provided but the second isn\'t range'
# Push each index
for index in params.global_secondary_indexes
keySchema = []
for type, keys of index.key_schema
keySchema.push({
AttributeName: keys[0]
KeyType: type.toUpperCase()
})
awsParams.GlobalSecondaryIndexes.push {
IndexName: index.index_name
KeySchema: keySchema
Projection:
ProjectionType: index.projection_type.toUpperCase()
# Use the provided or default throughput
ProvisionedThroughput: unless index.provisioned_throughput? then awsParams.ProvisionedThroughput else {
ReadCapacityUnits: index.provisioned_throughput.read
WriteCapacityUnits: index.provisioned_throughput.write
}
}
# Add key name to attributeDefinitions
for type, keys of index.key_schema
awsParams.AttributeDefinitions.push {
AttributeName: keys[0]
AttributeType: typeToAwsType[keys[1]]
} if awsParams.AttributeDefinitions.filter( (ad) -> ad.AttributeName == keys[0] ).length == 0
debug "creating table with params #{JSON.stringify(awsParams, null, 4)}"
@dynamo.createTablePromise(awsParams).nodeify(callback)
# describe
describe: (name, callback) ->
debug "describe() - #{name}"
@dynamo.describeTablePromise(TableName: name).nodeify(callback)
# Drop a table. Wrapper around AWS deleteTable
drop: (name, callback = null) ->
debug "drop() - #{name}"
params =
TableName: name
@dynamo.deleteTablePromise(params).nodeify(callback)
# List tables. Wrapper around AWS listTables
list: (params, callback) ->
debug "list() - #{params}"
awsParams = {}
if params isnt null
if _.isString params
awsParams.ExclusiveStartTableName = params
else if _.isFunction params
callback = params
else if _.isObject params
if params.limit is not null
awsParams.Limit = params.limit
else if params.start is not null
awsParams.ExclusiveStartTableName = params.start
@dynamo.listTablesPromise(awsParams).nodeify(callback)
module.exports = (credentials, url) -> new Dynasty(credentials, url)
| 3686 | # Main Dynasty Class
aws = require('aws-sdk')
_ = require('lodash')
Promise = require('bluebird')
debug = require('debug')('dynasty')
https = require('https')
# See http://vq.io/19EiASB
typeToAwsType =
string: 'S'
string_set: 'SS'
number: 'N'
number_set: 'NS'
binary: 'B'
binary_set: 'BS'
lib = require('./lib')
Table = lib.Table
class Dynasty
constructor: (credentials, url) ->
debug "dynasty constructed."
# Default to credentials passed in, if any
if credentials.region
credentials.region = credentials.region
# Fall back on env variables
else if process.env.AWS_DEFAULT_REGION
credentials.region = process.env.AWS_DEFAULT_REGION
else
credentials.region = 'us-east-1'
if !credentials.accessKeyId
credentials.accessKeyId = process.env.AWS_ACCESS_KEY_ID
if !credentials.secretAccessKey
credentials.accessKeyId = process.env.AWS_SECRET_ACCESS_KEY
# Lock API version
credentials.apiVersion = '2012-08-10'
if url and _.isString url
debug "connecting to local dynamo at #{url}"
credentials.endpoint = new aws.Endpoint url
@dynamo = new aws.DynamoDB credentials
Promise.promisifyAll(@dynamo, {suffix: 'Promise'})
@name = 'Dynasty'
@tables = {}
loadAllTables: =>
@list()
.then (data) =>
for tableName in data.TableNames
@table(tableName)
return @tables
# Given a name, return a Table object
table: (name) ->
@tables[name] = @tables[name] || new Table this, name
###
Table Operations
###
# Alter an existing table. Wrapper around AWS updateTable
alter: (name, params, callback) ->
debug "alter() - #{name}, #{JSON.stringify(params, null, 4)}"
# We'll accept either an object with a key of throughput or just
# an object with the throughput info
throughput = params.throughput || params
awsParams =
TableName: name
ProvisionedThroughput:
ReadCapacityUnits: throughput.read
WriteCapacityUnits: throughput.write
@dynamo.updateTablePromise(awsParams).nodeify(callback)
# Create a new table. Wrapper around AWS createTable
create: (name, params, callback = null) ->
debug "create() - #{name}, #{JSON.stringify(params, null, 4)}"
throughput = params.throughput || {read: 10, write: 5}
keySchema = [
KeyType: 'HASH'
AttributeName: params.key_schema.hash[0]
]
attributeDefinitions = [
AttributeName: params.key_schema.hash[0]
AttributeType: typeToAwsType[params.key_schema.hash[1]]
]
if params.key_schema.range?
keySchema.push
KeyType: 'RANGE',
AttributeName: params.key_schema.range[0]
attributeDefinitions.push
AttributeName: params.key_schema.range[0]
AttributeType: typeToAwsType[params.key_schema.range[1]]
awsParams =
AttributeDefinitions: attributeDefinitions
TableName: name
KeySchema: keySchema
ProvisionedThroughput:
ReadCapacityUnits: throughput.read
WriteCapacityUnits: throughput.write
# Add GlobalSecondaryIndexes to awsParams if provided
if params.global_secondary_indexes?
awsParams.GlobalSecondaryIndexes = []
# Verify valid GSI
for index in params.global_secondary_indexes
key_schema = index.key_schema
# Must provide hash type
unless key_schema.hash?
throw TypeError 'Missing hash index for GlobalSecondaryIndex'
typesProvided = Object.keys(key_schema).length
# Provide 1-2 types for GSI
if typesProvided.length > 2 or typesProvided.length < 1
throw RangeError 'Expected one or two types for GlobalSecondaryIndex'
# Providing 2 types but the second isn't range type
if typesProvided.length is 2 and not key_schema.range?
throw TypeError 'Two types provided but the second isn\'t range'
# Push each index
for index in params.global_secondary_indexes
keySchema = []
for type, keys of index.key_schema
keySchema.push({
AttributeName: keys[0]
KeyType: type.<KEY>()
})
awsParams.GlobalSecondaryIndexes.push {
IndexName: index.index_name
KeySchema: keySchema
Projection:
ProjectionType: index.projection_type.toUpperCase()
# Use the provided or default throughput
ProvisionedThroughput: unless index.provisioned_throughput? then awsParams.ProvisionedThroughput else {
ReadCapacityUnits: index.provisioned_throughput.read
WriteCapacityUnits: index.provisioned_throughput.write
}
}
# Add key name to attributeDefinitions
for type, keys of index.key_schema
awsParams.AttributeDefinitions.push {
AttributeName: keys[0]
AttributeType: typeToAwsType[keys[1]]
} if awsParams.AttributeDefinitions.filter( (ad) -> ad.AttributeName == keys[0] ).length == 0
debug "creating table with params #{JSON.stringify(awsParams, null, 4)}"
@dynamo.createTablePromise(awsParams).nodeify(callback)
# describe
describe: (name, callback) ->
debug "describe() - #{name}"
@dynamo.describeTablePromise(TableName: name).nodeify(callback)
# Drop a table. Wrapper around AWS deleteTable
drop: (name, callback = null) ->
debug "drop() - #{name}"
params =
TableName: name
@dynamo.deleteTablePromise(params).nodeify(callback)
# List tables. Wrapper around AWS listTables
list: (params, callback) ->
debug "list() - #{params}"
awsParams = {}
if params isnt null
if _.isString params
awsParams.ExclusiveStartTableName = params
else if _.isFunction params
callback = params
else if _.isObject params
if params.limit is not null
awsParams.Limit = params.limit
else if params.start is not null
awsParams.ExclusiveStartTableName = params.start
@dynamo.listTablesPromise(awsParams).nodeify(callback)
module.exports = (credentials, url) -> new Dynasty(credentials, url)
| true | # Main Dynasty Class
aws = require('aws-sdk')
_ = require('lodash')
Promise = require('bluebird')
debug = require('debug')('dynasty')
https = require('https')
# See http://vq.io/19EiASB
typeToAwsType =
string: 'S'
string_set: 'SS'
number: 'N'
number_set: 'NS'
binary: 'B'
binary_set: 'BS'
lib = require('./lib')
Table = lib.Table
class Dynasty
constructor: (credentials, url) ->
debug "dynasty constructed."
# Default to credentials passed in, if any
if credentials.region
credentials.region = credentials.region
# Fall back on env variables
else if process.env.AWS_DEFAULT_REGION
credentials.region = process.env.AWS_DEFAULT_REGION
else
credentials.region = 'us-east-1'
if !credentials.accessKeyId
credentials.accessKeyId = process.env.AWS_ACCESS_KEY_ID
if !credentials.secretAccessKey
credentials.accessKeyId = process.env.AWS_SECRET_ACCESS_KEY
# Lock API version
credentials.apiVersion = '2012-08-10'
if url and _.isString url
debug "connecting to local dynamo at #{url}"
credentials.endpoint = new aws.Endpoint url
@dynamo = new aws.DynamoDB credentials
Promise.promisifyAll(@dynamo, {suffix: 'Promise'})
@name = 'Dynasty'
@tables = {}
loadAllTables: =>
@list()
.then (data) =>
for tableName in data.TableNames
@table(tableName)
return @tables
# Given a name, return a Table object
table: (name) ->
@tables[name] = @tables[name] || new Table this, name
###
Table Operations
###
# Alter an existing table. Wrapper around AWS updateTable
alter: (name, params, callback) ->
debug "alter() - #{name}, #{JSON.stringify(params, null, 4)}"
# We'll accept either an object with a key of throughput or just
# an object with the throughput info
throughput = params.throughput || params
awsParams =
TableName: name
ProvisionedThroughput:
ReadCapacityUnits: throughput.read
WriteCapacityUnits: throughput.write
@dynamo.updateTablePromise(awsParams).nodeify(callback)
# Create a new table. Wrapper around AWS createTable
create: (name, params, callback = null) ->
debug "create() - #{name}, #{JSON.stringify(params, null, 4)}"
throughput = params.throughput || {read: 10, write: 5}
keySchema = [
KeyType: 'HASH'
AttributeName: params.key_schema.hash[0]
]
attributeDefinitions = [
AttributeName: params.key_schema.hash[0]
AttributeType: typeToAwsType[params.key_schema.hash[1]]
]
if params.key_schema.range?
keySchema.push
KeyType: 'RANGE',
AttributeName: params.key_schema.range[0]
attributeDefinitions.push
AttributeName: params.key_schema.range[0]
AttributeType: typeToAwsType[params.key_schema.range[1]]
awsParams =
AttributeDefinitions: attributeDefinitions
TableName: name
KeySchema: keySchema
ProvisionedThroughput:
ReadCapacityUnits: throughput.read
WriteCapacityUnits: throughput.write
# Add GlobalSecondaryIndexes to awsParams if provided
if params.global_secondary_indexes?
awsParams.GlobalSecondaryIndexes = []
# Verify valid GSI
for index in params.global_secondary_indexes
key_schema = index.key_schema
# Must provide hash type
unless key_schema.hash?
throw TypeError 'Missing hash index for GlobalSecondaryIndex'
typesProvided = Object.keys(key_schema).length
# Provide 1-2 types for GSI
if typesProvided.length > 2 or typesProvided.length < 1
throw RangeError 'Expected one or two types for GlobalSecondaryIndex'
# Providing 2 types but the second isn't range type
if typesProvided.length is 2 and not key_schema.range?
throw TypeError 'Two types provided but the second isn\'t range'
# Push each index
for index in params.global_secondary_indexes
keySchema = []
for type, keys of index.key_schema
keySchema.push({
AttributeName: keys[0]
KeyType: type.PI:KEY:<KEY>END_PI()
})
awsParams.GlobalSecondaryIndexes.push {
IndexName: index.index_name
KeySchema: keySchema
Projection:
ProjectionType: index.projection_type.toUpperCase()
# Use the provided or default throughput
ProvisionedThroughput: unless index.provisioned_throughput? then awsParams.ProvisionedThroughput else {
ReadCapacityUnits: index.provisioned_throughput.read
WriteCapacityUnits: index.provisioned_throughput.write
}
}
# Add key name to attributeDefinitions
for type, keys of index.key_schema
awsParams.AttributeDefinitions.push {
AttributeName: keys[0]
AttributeType: typeToAwsType[keys[1]]
} if awsParams.AttributeDefinitions.filter( (ad) -> ad.AttributeName == keys[0] ).length == 0
debug "creating table with params #{JSON.stringify(awsParams, null, 4)}"
@dynamo.createTablePromise(awsParams).nodeify(callback)
# describe
describe: (name, callback) ->
debug "describe() - #{name}"
@dynamo.describeTablePromise(TableName: name).nodeify(callback)
# Drop a table. Wrapper around AWS deleteTable
drop: (name, callback = null) ->
debug "drop() - #{name}"
params =
TableName: name
@dynamo.deleteTablePromise(params).nodeify(callback)
# List tables. Wrapper around AWS listTables
list: (params, callback) ->
debug "list() - #{params}"
awsParams = {}
if params isnt null
if _.isString params
awsParams.ExclusiveStartTableName = params
else if _.isFunction params
callback = params
else if _.isObject params
if params.limit is not null
awsParams.Limit = params.limit
else if params.start is not null
awsParams.ExclusiveStartTableName = params.start
@dynamo.listTablesPromise(awsParams).nodeify(callback)
module.exports = (credentials, url) -> new Dynasty(credentials, url)
|
[
{
"context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan",
"end": 18,
"score": 0.999885082244873,
"start": 10,
"tag": "NAME",
"value": "Tim Knip"
},
{
"context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\n#= require new_src/loaders/collada/input\n\nclass ",
"end": 110,
"score": 0.9999260306358337,
"start": 86,
"tag": "EMAIL",
"value": "aladjev.andrew@gmail.com"
}
] | source/javascripts/new_src/loaders/collada/sampler.coffee | andrew-aladev/three.js | 0 | # @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
# @author aladjev.andrew@gmail.com
#= require new_src/loaders/collada/input
class Sampler
constructor: (animation) ->
@id = ""
@animation = animation
@inputs = []
@input = null
@output = null
@strideOut = null
@interpolation = null
@startTime = null
@endTime = null
@duration = 0
parse: (element) ->
@id = element.getAttribute "id"
@inputs = []
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
unless child.nodeType is 1
continue
switch child.nodeName
when "input"
@inputs.push new THREE.Collada.Input().parse child
this
create: ->
length = @inputs.length
for i in [0...length]
input = @inputs[i]
source = @animation.source[input.source]
switch input.semantic
when "INPUT"
@input = source.read()
when "OUTPUT"
@output = source.read()
@strideOut = source.accessor.stride
when "INTERPOLATION"
@interpolation = source.read()
when "IN_TANGENT", "OUT_TANGENT"
else
console.warn input.semantic
@startTime = 0
@endTime = 0
@duration = 0
if @input.length
@startTime = 100000000
@endTime = -100000000
length = @input.length
for i in [0...length]
@startTime = Math.min @startTime, @input[i]
@endTime = Math.max @endTime, @input[i]
@duration = @endTime - @startTime
getData: (type, ndx) ->
if type is "matrix" and @strideOut is 16
data = @output[ndx]
else if @strideOut > 1
data = []
ndx *= @strideOut
for i in [0...@strideOut]
data[i] = @output[ndx + i]
if @strideOut is 3
switch type
when "rotate", "translate"
fixCoords data, -1
when "scale"
fixCoords data, 1
else if @strideOut is 4 and type is "matrix"
fixCoords data, -1
else
data = @output[ndx]
data
namespace "THREE.Collada", (exports) ->
exports.Sampler = Sampler | 202295 | # @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com
# @author <EMAIL>
#= require new_src/loaders/collada/input
class Sampler
constructor: (animation) ->
@id = ""
@animation = animation
@inputs = []
@input = null
@output = null
@strideOut = null
@interpolation = null
@startTime = null
@endTime = null
@duration = 0
parse: (element) ->
@id = element.getAttribute "id"
@inputs = []
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
unless child.nodeType is 1
continue
switch child.nodeName
when "input"
@inputs.push new THREE.Collada.Input().parse child
this
create: ->
length = @inputs.length
for i in [0...length]
input = @inputs[i]
source = @animation.source[input.source]
switch input.semantic
when "INPUT"
@input = source.read()
when "OUTPUT"
@output = source.read()
@strideOut = source.accessor.stride
when "INTERPOLATION"
@interpolation = source.read()
when "IN_TANGENT", "OUT_TANGENT"
else
console.warn input.semantic
@startTime = 0
@endTime = 0
@duration = 0
if @input.length
@startTime = 100000000
@endTime = -100000000
length = @input.length
for i in [0...length]
@startTime = Math.min @startTime, @input[i]
@endTime = Math.max @endTime, @input[i]
@duration = @endTime - @startTime
getData: (type, ndx) ->
if type is "matrix" and @strideOut is 16
data = @output[ndx]
else if @strideOut > 1
data = []
ndx *= @strideOut
for i in [0...@strideOut]
data[i] = @output[ndx + i]
if @strideOut is 3
switch type
when "rotate", "translate"
fixCoords data, -1
when "scale"
fixCoords data, 1
else if @strideOut is 4 and type is "matrix"
fixCoords data, -1
else
data = @output[ndx]
data
namespace "THREE.Collada", (exports) ->
exports.Sampler = Sampler | true | # @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com
# @author PI:EMAIL:<EMAIL>END_PI
#= require new_src/loaders/collada/input
class Sampler
constructor: (animation) ->
@id = ""
@animation = animation
@inputs = []
@input = null
@output = null
@strideOut = null
@interpolation = null
@startTime = null
@endTime = null
@duration = 0
parse: (element) ->
@id = element.getAttribute "id"
@inputs = []
length = element.childNodes.length
for i in [0...length]
child = element.childNodes[i]
unless child.nodeType is 1
continue
switch child.nodeName
when "input"
@inputs.push new THREE.Collada.Input().parse child
this
create: ->
length = @inputs.length
for i in [0...length]
input = @inputs[i]
source = @animation.source[input.source]
switch input.semantic
when "INPUT"
@input = source.read()
when "OUTPUT"
@output = source.read()
@strideOut = source.accessor.stride
when "INTERPOLATION"
@interpolation = source.read()
when "IN_TANGENT", "OUT_TANGENT"
else
console.warn input.semantic
@startTime = 0
@endTime = 0
@duration = 0
if @input.length
@startTime = 100000000
@endTime = -100000000
length = @input.length
for i in [0...length]
@startTime = Math.min @startTime, @input[i]
@endTime = Math.max @endTime, @input[i]
@duration = @endTime - @startTime
getData: (type, ndx) ->
if type is "matrix" and @strideOut is 16
data = @output[ndx]
else if @strideOut > 1
data = []
ndx *= @strideOut
for i in [0...@strideOut]
data[i] = @output[ndx + i]
if @strideOut is 3
switch type
when "rotate", "translate"
fixCoords data, -1
when "scale"
fixCoords data, 1
else if @strideOut is 4 and type is "matrix"
fixCoords data, -1
else
data = @output[ndx]
data
namespace "THREE.Collada", (exports) ->
exports.Sampler = Sampler |
[
{
"context": "\n\nconf = new Config(\n {\n key1: {\n key2: \"value\"\n key3: null\n }\n }\n)\n\ndescribe \"Config\",",
"end": 88,
"score": 0.7093852162361145,
"start": 83,
"tag": "KEY",
"value": "value"
}
] | tests/config_test.coffee | bahiamartins/stacktic | 1 | Config = require("../lib/config")
conf = new Config(
{
key1: {
key2: "value"
key3: null
}
}
)
describe "Config", ->
describe "#get", ->
it "should return the right value", ->
conf.get("key1.key2").should.equal "value"
it "should return null if key is missing and default is not provided", ->
(conf.get("undefined1.undefined2.undefined3") is null).should.be.true
it "should return default if key is missing and default present", ->
conf.get("undefined1.undefined2.undefined3", "default").should.equal "default"
it "should return default if key is null and default present", ->
conf.get("key1.key3", "default").should.equal "default"
describe "#set", ->
it "should be chainable", ->
conf.set("key1.key4", "newValue").should.be.instanceOf(Config)
it "should set the right value", ->
conf.set("key1.key5", "newValue").get("key1.key5").should.equal "newValue"
it "should create containing objects if they not exists", ->
(->
conf.set("undef.undef.undef.key7", "newValue").get("undef.undef.undef.key7").should.equal "newValue"
).should.not.throw
it "should return null if key is missing and default is not provided", ->
(conf.get("undefined1.undefined2.undefined3") is null).should.be.true
it "should return default if key is missing and default present", ->
conf.get("undefined1.undefined2.undefined3", "default").should.equal "default"
it "should return default if key is null and default present", ->
conf.get("key1.key3", "default").should.equal "default"
| 164257 | Config = require("../lib/config")
conf = new Config(
{
key1: {
key2: "<KEY>"
key3: null
}
}
)
describe "Config", ->
describe "#get", ->
it "should return the right value", ->
conf.get("key1.key2").should.equal "value"
it "should return null if key is missing and default is not provided", ->
(conf.get("undefined1.undefined2.undefined3") is null).should.be.true
it "should return default if key is missing and default present", ->
conf.get("undefined1.undefined2.undefined3", "default").should.equal "default"
it "should return default if key is null and default present", ->
conf.get("key1.key3", "default").should.equal "default"
describe "#set", ->
it "should be chainable", ->
conf.set("key1.key4", "newValue").should.be.instanceOf(Config)
it "should set the right value", ->
conf.set("key1.key5", "newValue").get("key1.key5").should.equal "newValue"
it "should create containing objects if they not exists", ->
(->
conf.set("undef.undef.undef.key7", "newValue").get("undef.undef.undef.key7").should.equal "newValue"
).should.not.throw
it "should return null if key is missing and default is not provided", ->
(conf.get("undefined1.undefined2.undefined3") is null).should.be.true
it "should return default if key is missing and default present", ->
conf.get("undefined1.undefined2.undefined3", "default").should.equal "default"
it "should return default if key is null and default present", ->
conf.get("key1.key3", "default").should.equal "default"
| true | Config = require("../lib/config")
conf = new Config(
{
key1: {
key2: "PI:KEY:<KEY>END_PI"
key3: null
}
}
)
describe "Config", ->
describe "#get", ->
it "should return the right value", ->
conf.get("key1.key2").should.equal "value"
it "should return null if key is missing and default is not provided", ->
(conf.get("undefined1.undefined2.undefined3") is null).should.be.true
it "should return default if key is missing and default present", ->
conf.get("undefined1.undefined2.undefined3", "default").should.equal "default"
it "should return default if key is null and default present", ->
conf.get("key1.key3", "default").should.equal "default"
describe "#set", ->
it "should be chainable", ->
conf.set("key1.key4", "newValue").should.be.instanceOf(Config)
it "should set the right value", ->
conf.set("key1.key5", "newValue").get("key1.key5").should.equal "newValue"
it "should create containing objects if they not exists", ->
(->
conf.set("undef.undef.undef.key7", "newValue").get("undef.undef.undef.key7").should.equal "newValue"
).should.not.throw
it "should return null if key is missing and default is not provided", ->
(conf.get("undefined1.undefined2.undefined3") is null).should.be.true
it "should return default if key is missing and default present", ->
conf.get("undefined1.undefined2.undefined3", "default").should.equal "default"
it "should return default if key is null and default present", ->
conf.get("key1.key3", "default").should.equal "default"
|
[
{
"context": "vision\"\nlocation: \"Newcastle\"\nphase: \"beta\"\nsro: \"Graeme Wallace\"\nservice_man: \"Naomi Bell\"\nphase_history:\n disco",
"end": 296,
"score": 0.9998790621757507,
"start": 282,
"tag": "NAME",
"value": "Graeme Wallace"
},
{
"context": "phase: \"beta\"\nsro: \"Graeme Wallace\"\nservice_man: \"Naomi Bell\"\nphase_history:\n discovery: [\n {\n label:",
"end": 322,
"score": 0.9998868703842163,
"start": 312,
"tag": "NAME",
"value": "Naomi Bell"
}
] | app/data/projects/get-state-pension.cson | tsmorgan/dwp-ux-work | 0 | id: 0
name: "Get your State Pension"
description: "Lets users get their State Pension and maintain accurate payments as part of a seamless end to end journey for users accessing retirement provision services."
theme: "Retirement Provision"
location: "Newcastle"
phase: "beta"
sro: "Graeme Wallace"
service_man: "Naomi Bell"
phase_history:
discovery: [
{
label: "Completed"
date: "August 2015"
}
]
alpha: [
{
label: "Completed"
date: "December 2015"
}
]
beta: [
{
label: "Started"
date: "January 2016"
}
{
label: "Private beta predicted"
date: "October 2016"
}
{
label: "Public beta predicted"
date: "April 2017"
}
]
priority: "High"
prototype: "https://getyourstatepension.herokuapp.com/"
showntells: [
"14 September 2016, 12:00"
"26 October 2016, 12:00"
"7 December 2016, 12:00"
] | 114816 | id: 0
name: "Get your State Pension"
description: "Lets users get their State Pension and maintain accurate payments as part of a seamless end to end journey for users accessing retirement provision services."
theme: "Retirement Provision"
location: "Newcastle"
phase: "beta"
sro: "<NAME>"
service_man: "<NAME>"
phase_history:
discovery: [
{
label: "Completed"
date: "August 2015"
}
]
alpha: [
{
label: "Completed"
date: "December 2015"
}
]
beta: [
{
label: "Started"
date: "January 2016"
}
{
label: "Private beta predicted"
date: "October 2016"
}
{
label: "Public beta predicted"
date: "April 2017"
}
]
priority: "High"
prototype: "https://getyourstatepension.herokuapp.com/"
showntells: [
"14 September 2016, 12:00"
"26 October 2016, 12:00"
"7 December 2016, 12:00"
] | true | id: 0
name: "Get your State Pension"
description: "Lets users get their State Pension and maintain accurate payments as part of a seamless end to end journey for users accessing retirement provision services."
theme: "Retirement Provision"
location: "Newcastle"
phase: "beta"
sro: "PI:NAME:<NAME>END_PI"
service_man: "PI:NAME:<NAME>END_PI"
phase_history:
discovery: [
{
label: "Completed"
date: "August 2015"
}
]
alpha: [
{
label: "Completed"
date: "December 2015"
}
]
beta: [
{
label: "Started"
date: "January 2016"
}
{
label: "Private beta predicted"
date: "October 2016"
}
{
label: "Public beta predicted"
date: "April 2017"
}
]
priority: "High"
prototype: "https://getyourstatepension.herokuapp.com/"
showntells: [
"14 September 2016, 12:00"
"26 October 2016, 12:00"
"7 December 2016, 12:00"
] |
[
{
"context": "Handle opening and closing modal windows.\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@l",
"end": 70,
"score": 0.9998849034309387,
"start": 56,
"tag": "NAME",
"value": "Destin Moulton"
},
{
"context": ".\n\n@author Destin Moulton\n@git https://github.com/destinmoulton/wolfcage\n@license MIT\n\nComponent of the Wolfram C",
"end": 108,
"score": 0.9935623407363892,
"start": 95,
"tag": "USERNAME",
"value": "destinmoulton"
}
] | src/modals/Modal.coffee | destinmoulton/cagen | 0 | ###
Handle opening and closing modal windows.
@author Destin Moulton
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
###
DOM = require("../DOM.coffee")
class Modal
constructor:()->
@elVeil = DOM.elemById("MODAL", "VEIL")
@elModal = DOM.elemById("MODAL", "MODAL")
@elTitle = DOM.elemById("MODAL", "TITLE")
@elBody = DOM.elemById("MODAL", "BODY")
elClose = DOM.elemById("MODAL", "CLOSE")
elClose.addEventListener("click",
()=>
@close()
)
open: (title, body)->
@elTitle.innerHTML = title
@elBody.innerHTML = body
modalLeft = (@elVeil.offsetWidth - @elModal.offsetWidth)/2
@elModal.style.left = "#{modalLeft}px"
@elVeil.style.visibility = "visible"
@elModal.style.visibility = "visible"
close: ()->
@elModal.style.visibility = "hidden"
@elVeil.style.visibility = "hidden"
@elBody.innerHTML = ""
@elTitle.innerHTML = ""
module.exports = Modal | 84186 | ###
Handle opening and closing modal windows.
@author <NAME>
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
###
DOM = require("../DOM.coffee")
class Modal
constructor:()->
@elVeil = DOM.elemById("MODAL", "VEIL")
@elModal = DOM.elemById("MODAL", "MODAL")
@elTitle = DOM.elemById("MODAL", "TITLE")
@elBody = DOM.elemById("MODAL", "BODY")
elClose = DOM.elemById("MODAL", "CLOSE")
elClose.addEventListener("click",
()=>
@close()
)
open: (title, body)->
@elTitle.innerHTML = title
@elBody.innerHTML = body
modalLeft = (@elVeil.offsetWidth - @elModal.offsetWidth)/2
@elModal.style.left = "#{modalLeft}px"
@elVeil.style.visibility = "visible"
@elModal.style.visibility = "visible"
close: ()->
@elModal.style.visibility = "hidden"
@elVeil.style.visibility = "hidden"
@elBody.innerHTML = ""
@elTitle.innerHTML = ""
module.exports = Modal | true | ###
Handle opening and closing modal windows.
@author PI:NAME:<NAME>END_PI
@git https://github.com/destinmoulton/wolfcage
@license MIT
Component of the Wolfram Cellular Automata Generator (WolfCage)
###
DOM = require("../DOM.coffee")
class Modal
constructor:()->
@elVeil = DOM.elemById("MODAL", "VEIL")
@elModal = DOM.elemById("MODAL", "MODAL")
@elTitle = DOM.elemById("MODAL", "TITLE")
@elBody = DOM.elemById("MODAL", "BODY")
elClose = DOM.elemById("MODAL", "CLOSE")
elClose.addEventListener("click",
()=>
@close()
)
open: (title, body)->
@elTitle.innerHTML = title
@elBody.innerHTML = body
modalLeft = (@elVeil.offsetWidth - @elModal.offsetWidth)/2
@elModal.style.left = "#{modalLeft}px"
@elVeil.style.visibility = "visible"
@elModal.style.visibility = "visible"
close: ()->
@elModal.style.visibility = "hidden"
@elVeil.style.visibility = "hidden"
@elBody.innerHTML = ""
@elTitle.innerHTML = ""
module.exports = Modal |
[
{
"context": "Disallows nesting string interpolations.\n# @author Julian Rosse\n###\n'use strict'\n\n#------------------------------",
"end": 84,
"score": 0.9998594522476196,
"start": 72,
"tag": "NAME",
"value": "Julian Rosse"
}
] | src/tests/rules/no-nested-interpolation.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Disallows nesting string interpolations.
# @author Julian Rosse
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-nested-interpolation'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
### eslint-disable coffee/no-template-curly-in-string ###
ruleTester.run 'no-nested-interpolation', rule,
valid: ['"Book by #{firstName.toUpperCase()} #{lastName.toUpperCase()}"']
invalid: [
code: 'str = "Book by #{"#{firstName} #{lastName}".toUpperCase()}"'
errors: [
messageId: 'dontNest'
line: 1
column: 18
]
,
code: 'str1 = "string #{"interpolation #{"inception"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 18
]
,
code: 'str2 = "going #{"in #{"even #{"deeper"}"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 17
,
messageId: 'dontNest'
line: 1
column: 23
]
,
code: 'str3 = "#{"multiple #{"warnings"}"} for #{"diff #{"nestings"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 11
,
messageId: 'dontNest'
line: 1
column: 43
]
,
code: '''
///
#{"a#{b}"}
///
'''
errors: [
messageId: 'dontNest'
line: 2
column: 5
]
,
code: '''
"""
#{///
a#{b}
///}
"""
'''
errors: [
messageId: 'dontNest'
line: 2
column: 5
]
]
| 139455 | ###*
# @fileoverview Disallows nesting string interpolations.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-nested-interpolation'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
### eslint-disable coffee/no-template-curly-in-string ###
ruleTester.run 'no-nested-interpolation', rule,
valid: ['"Book by #{firstName.toUpperCase()} #{lastName.toUpperCase()}"']
invalid: [
code: 'str = "Book by #{"#{firstName} #{lastName}".toUpperCase()}"'
errors: [
messageId: 'dontNest'
line: 1
column: 18
]
,
code: 'str1 = "string #{"interpolation #{"inception"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 18
]
,
code: 'str2 = "going #{"in #{"even #{"deeper"}"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 17
,
messageId: 'dontNest'
line: 1
column: 23
]
,
code: 'str3 = "#{"multiple #{"warnings"}"} for #{"diff #{"nestings"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 11
,
messageId: 'dontNest'
line: 1
column: 43
]
,
code: '''
///
#{"a#{b}"}
///
'''
errors: [
messageId: 'dontNest'
line: 2
column: 5
]
,
code: '''
"""
#{///
a#{b}
///}
"""
'''
errors: [
messageId: 'dontNest'
line: 2
column: 5
]
]
| true | ###*
# @fileoverview Disallows nesting string interpolations.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-nested-interpolation'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
### eslint-disable coffee/no-template-curly-in-string ###
ruleTester.run 'no-nested-interpolation', rule,
valid: ['"Book by #{firstName.toUpperCase()} #{lastName.toUpperCase()}"']
invalid: [
code: 'str = "Book by #{"#{firstName} #{lastName}".toUpperCase()}"'
errors: [
messageId: 'dontNest'
line: 1
column: 18
]
,
code: 'str1 = "string #{"interpolation #{"inception"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 18
]
,
code: 'str2 = "going #{"in #{"even #{"deeper"}"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 17
,
messageId: 'dontNest'
line: 1
column: 23
]
,
code: 'str3 = "#{"multiple #{"warnings"}"} for #{"diff #{"nestings"}"}"'
errors: [
messageId: 'dontNest'
line: 1
column: 11
,
messageId: 'dontNest'
line: 1
column: 43
]
,
code: '''
///
#{"a#{b}"}
///
'''
errors: [
messageId: 'dontNest'
line: 2
column: 5
]
,
code: '''
"""
#{///
a#{b}
///}
"""
'''
errors: [
messageId: 'dontNest'
line: 2
column: 5
]
]
|
[
{
"context": ">\n device.type = 'ios'\n device.token = 'ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa'\n\n android = sinon.spy(device, 'sendAndroid'",
"end": 1743,
"score": 0.9424774050712585,
"start": 1679,
"tag": "KEY",
"value": "ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa"
},
{
"context": ">\n device.type = 'ios'\n device.token = 'ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa'\n device.sendIOS '3424', 'text'\n\n it 'sho",
"end": 2121,
"score": 0.936030387878418,
"start": 2057,
"tag": "KEY",
"value": "ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa"
},
{
"context": ">\n device.type = 'ios'\n device.token = 'ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa'\n device.sendIOS '3424', 'text', 0, yes\n\n ",
"end": 2313,
"score": 0.9318571090698242,
"start": 2249,
"tag": "KEY",
"value": "ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa"
},
{
"context": ">\n device.type = 'ios'\n device.token = 'GGGGG'\n device.sendIOS '3424', 'text'\n\n describe ",
"end": 2473,
"score": 0.8440987467765808,
"start": 2468,
"tag": "PASSWORD",
"value": "GGGGG"
},
{
"context": "en: 'old'\n type: 'android'\n token: 'tokentoken'\n\n update = sinon.spy(Device, 'updateDevice'",
"end": 4003,
"score": 0.7577078938484192,
"start": 3993,
"tag": "PASSWORD",
"value": "tokentoken"
}
] | test/unit/device.coffee | ethanmick/fastchat-server | 7 | 'use strict'
#
# FastChat
# 2015
#
should = require('chai').should()
Device = require '../../lib/model/device'
User = require '../../lib/model/user'
sinon = require 'sinon'
mongoose = require 'mongoose'
Q = require 'q'
describe 'Device', ->
before (done)->
mongoose.connect 'mongodb://localhost/test'
db = mongoose.connection
db.once 'open', ->
Device.remove {}, (err)->
done()
describe 'Sending', ->
device = null
beforeEach ->
device = new Device
it 'should not send if inactive', ->
device.active = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'Should not send if logged out', ->
device.loggedIn = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'should not send a message if you are both', ->
device.loggedIn = no
device.active = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'should send an android message', ->
device.type = 'android'
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send('213', 'Message', 5)
android.calledOnce.should.be.ok
ios.calledOnce.should.be.false
it 'should send an ios message', ->
device.type = 'ios'
device.token = 'ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa'
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send('3424', 'text', 1)
android.calledOnce.should.be.false
ios.calledOnce.should.be.ok
it 'should set iOS badge to 0 if not given a badge', ->
device.type = 'ios'
device.token = 'ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa'
device.sendIOS '3424', 'text'
it 'should set contentAvailable', ->
device.type = 'ios'
device.token = 'ba60aa0fa63e3ad5d3b0a35e389d391f48f945f1be8a8731da2b48979c80dcfa'
device.sendIOS '3424', 'text', 0, yes
it 'should throw an error with a bad token for ios', ->
device.type = 'ios'
device.token = 'GGGGG'
device.sendIOS '3424', 'text'
describe 'Logout', ->
it 'should log out', ->
device = new Device
device.loggedIn.should.be.true
device.active.should.be.true
promise = device.logout()
device.loggedIn.should.be.false
Q.isPromise(promise).should.be.true
describe 'Creating and Updating', ->
it 'should throw an error without a token', (done)->
Device.createOrUpdate().fail (err)->
err.message.should.equal 'Validation failed'
done()
.done()
it 'should throw an error without a type', (done)->
Device.createOrUpdate({}, 'token').fail (err)->
err.message.should.equal 'Validation failed'
done()
it 'should throw an error with windows phone', (done)->
Device.createOrUpdate({}, 'token', 'windows-phone').fail (err)->
err.message.should.equal 'Validation failed'
done()
it 'should create a new device when not found', (done)->
user = new User()
sinon.stub(user, 'saveQ').returns( Q() )
create = sinon.spy(Device, 'createDevice')
sinon.stub(Device, 'findOneQ').returns( Q(null) )
Device.createOrUpdate(user, 'token', 'android', 'sessiontoken').then ->
create.called.should.be.true
Device.findOneQ.restore()
done()
it 'should find the device and update it', (done)->
user = new User()
device = new Device
active: no
loggedIn: no
accessToken: 'old'
type: 'android'
token: 'tokentoken'
update = sinon.spy(Device, 'updateDevice')
sinon.stub(Device, 'findOneQ').returns( Q(device) )
Device.createOrUpdate(user, 'token', 'android', 'sessiontoken').then ->
update.called.should.be.true
Device.findOneQ.restore()
done()
.done()
after (done)->
mongoose.disconnect()
done()
| 187706 | 'use strict'
#
# FastChat
# 2015
#
should = require('chai').should()
Device = require '../../lib/model/device'
User = require '../../lib/model/user'
sinon = require 'sinon'
mongoose = require 'mongoose'
Q = require 'q'
describe 'Device', ->
before (done)->
mongoose.connect 'mongodb://localhost/test'
db = mongoose.connection
db.once 'open', ->
Device.remove {}, (err)->
done()
describe 'Sending', ->
device = null
beforeEach ->
device = new Device
it 'should not send if inactive', ->
device.active = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'Should not send if logged out', ->
device.loggedIn = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'should not send a message if you are both', ->
device.loggedIn = no
device.active = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'should send an android message', ->
device.type = 'android'
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send('213', 'Message', 5)
android.calledOnce.should.be.ok
ios.calledOnce.should.be.false
it 'should send an ios message', ->
device.type = 'ios'
device.token = '<KEY>'
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send('3424', 'text', 1)
android.calledOnce.should.be.false
ios.calledOnce.should.be.ok
it 'should set iOS badge to 0 if not given a badge', ->
device.type = 'ios'
device.token = '<KEY>'
device.sendIOS '3424', 'text'
it 'should set contentAvailable', ->
device.type = 'ios'
device.token = '<KEY>'
device.sendIOS '3424', 'text', 0, yes
it 'should throw an error with a bad token for ios', ->
device.type = 'ios'
device.token = '<PASSWORD>'
device.sendIOS '3424', 'text'
describe 'Logout', ->
it 'should log out', ->
device = new Device
device.loggedIn.should.be.true
device.active.should.be.true
promise = device.logout()
device.loggedIn.should.be.false
Q.isPromise(promise).should.be.true
describe 'Creating and Updating', ->
it 'should throw an error without a token', (done)->
Device.createOrUpdate().fail (err)->
err.message.should.equal 'Validation failed'
done()
.done()
it 'should throw an error without a type', (done)->
Device.createOrUpdate({}, 'token').fail (err)->
err.message.should.equal 'Validation failed'
done()
it 'should throw an error with windows phone', (done)->
Device.createOrUpdate({}, 'token', 'windows-phone').fail (err)->
err.message.should.equal 'Validation failed'
done()
it 'should create a new device when not found', (done)->
user = new User()
sinon.stub(user, 'saveQ').returns( Q() )
create = sinon.spy(Device, 'createDevice')
sinon.stub(Device, 'findOneQ').returns( Q(null) )
Device.createOrUpdate(user, 'token', 'android', 'sessiontoken').then ->
create.called.should.be.true
Device.findOneQ.restore()
done()
it 'should find the device and update it', (done)->
user = new User()
device = new Device
active: no
loggedIn: no
accessToken: 'old'
type: 'android'
token: '<PASSWORD>'
update = sinon.spy(Device, 'updateDevice')
sinon.stub(Device, 'findOneQ').returns( Q(device) )
Device.createOrUpdate(user, 'token', 'android', 'sessiontoken').then ->
update.called.should.be.true
Device.findOneQ.restore()
done()
.done()
after (done)->
mongoose.disconnect()
done()
| true | 'use strict'
#
# FastChat
# 2015
#
should = require('chai').should()
Device = require '../../lib/model/device'
User = require '../../lib/model/user'
sinon = require 'sinon'
mongoose = require 'mongoose'
Q = require 'q'
describe 'Device', ->
before (done)->
mongoose.connect 'mongodb://localhost/test'
db = mongoose.connection
db.once 'open', ->
Device.remove {}, (err)->
done()
describe 'Sending', ->
device = null
beforeEach ->
device = new Device
it 'should not send if inactive', ->
device.active = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'Should not send if logged out', ->
device.loggedIn = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'should not send a message if you are both', ->
device.loggedIn = no
device.active = no
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send()
android.calledOnce.should.be.false
ios.calledOnce.should.be.false
it 'should send an android message', ->
device.type = 'android'
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send('213', 'Message', 5)
android.calledOnce.should.be.ok
ios.calledOnce.should.be.false
it 'should send an ios message', ->
device.type = 'ios'
device.token = 'PI:KEY:<KEY>END_PI'
android = sinon.spy(device, 'sendAndroid')
ios = sinon.spy(device, 'sendIOS')
device.send('3424', 'text', 1)
android.calledOnce.should.be.false
ios.calledOnce.should.be.ok
it 'should set iOS badge to 0 if not given a badge', ->
device.type = 'ios'
device.token = 'PI:KEY:<KEY>END_PI'
device.sendIOS '3424', 'text'
it 'should set contentAvailable', ->
device.type = 'ios'
device.token = 'PI:KEY:<KEY>END_PI'
device.sendIOS '3424', 'text', 0, yes
it 'should throw an error with a bad token for ios', ->
device.type = 'ios'
device.token = 'PI:PASSWORD:<PASSWORD>END_PI'
device.sendIOS '3424', 'text'
describe 'Logout', ->
it 'should log out', ->
device = new Device
device.loggedIn.should.be.true
device.active.should.be.true
promise = device.logout()
device.loggedIn.should.be.false
Q.isPromise(promise).should.be.true
describe 'Creating and Updating', ->
it 'should throw an error without a token', (done)->
Device.createOrUpdate().fail (err)->
err.message.should.equal 'Validation failed'
done()
.done()
it 'should throw an error without a type', (done)->
Device.createOrUpdate({}, 'token').fail (err)->
err.message.should.equal 'Validation failed'
done()
it 'should throw an error with windows phone', (done)->
Device.createOrUpdate({}, 'token', 'windows-phone').fail (err)->
err.message.should.equal 'Validation failed'
done()
it 'should create a new device when not found', (done)->
user = new User()
sinon.stub(user, 'saveQ').returns( Q() )
create = sinon.spy(Device, 'createDevice')
sinon.stub(Device, 'findOneQ').returns( Q(null) )
Device.createOrUpdate(user, 'token', 'android', 'sessiontoken').then ->
create.called.should.be.true
Device.findOneQ.restore()
done()
it 'should find the device and update it', (done)->
user = new User()
device = new Device
active: no
loggedIn: no
accessToken: 'old'
type: 'android'
token: 'PI:PASSWORD:<PASSWORD>END_PI'
update = sinon.spy(Device, 'updateDevice')
sinon.stub(Device, 'findOneQ').returns( Q(device) )
Device.createOrUpdate(user, 'token', 'android', 'sessiontoken').then ->
update.called.should.be.true
Device.findOneQ.restore()
done()
.done()
after (done)->
mongoose.disconnect()
done()
|
[
{
"context": "authenticateFieldDBAuthService\n username: username\n password: password\n authUrl: @",
"end": 3307,
"score": 0.9988651275634766,
"start": 3299,
"tag": "USERNAME",
"value": "username"
},
{
"context": "e\n username: username\n password: password\n authUrl: @get('activeServer')?.get('url",
"end": 3336,
"score": 0.9992422461509705,
"start": 3328,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "rl')\n else\n @authenticateOLD username: username, password: password\n\n authenticateOLD: (creden",
"end": 3443,
"score": 0.9985947012901306,
"start": 3435,
"tag": "USERNAME",
"value": "username"
},
{
"context": " @authenticateOLD username: username, password: password\n\n authenticateOLD: (credentials) ->\n task",
"end": 3463,
"score": 0.9990767240524292,
"start": 3455,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "d is true\n @set\n username: credentials.username\n loggedIn: true\n logged",
"end": 4023,
"score": 0.999445915222168,
"start": 4003,
"tag": "USERNAME",
"value": "credentials.username"
},
{
"context": "sedResult) =>\n @set\n username: credentials.username,\n password: credentials.password, # TO",
"end": 5312,
"score": 0.9984565377235413,
"start": 5292,
"tag": "USERNAME",
"value": "credentials.username"
},
{
"context": "rname: credentials.username,\n password: credentials.password, # TODO dont need this!\n loggedInUser:",
"end": 5356,
"score": 0.998873233795166,
"start": 5336,
"tag": "PASSWORD",
"value": "credentials.password"
},
{
"context": "seDBURL(responseJSON.user)\n username: credentials.username,\n password: credentials.password,\n ",
"end": 6798,
"score": 0.9981915950775146,
"start": 6778,
"tag": "USERNAME",
"value": "credentials.username"
},
{
"context": "ame: credentials.username,\n password: credentials.password,\n gravatar: responseJSON.user.gravat",
"end": 6844,
"score": 0.9990801811218262,
"start": 6824,
"tag": "PASSWORD",
"value": "credentials.password"
},
{
"context": " onload: (responseJSON) =>\n # TODO @jrwdunham: this responseJSON has a roles Array attribute wh",
"end": 7872,
"score": 0.9955414533615112,
"start": 7862,
"tag": "USERNAME",
"value": "@jrwdunham"
},
{
"context": "', FieldDB.FieldDBObject.application\n # TODO: @cesine: I'm getting \"`authentication.logout` is not a fu",
"end": 12337,
"score": 0.9973304271697998,
"start": 12330,
"tag": "USERNAME",
"value": "@cesine"
},
{
"context": " @authenticateAttemptDone taskId\n # TODO @cesine: what other kinds of responses to registration re",
"end": 15983,
"score": 0.9989272952079773,
"start": 15976,
"tag": "USERNAME",
"value": "@cesine"
},
{
"context": "ent'\n type: 'OLD'\n url: 'http://127.0.0.1:5000'\n serverCode: null\n corpus",
"end": 18056,
"score": 0.9997017979621887,
"start": 18047,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " # user-configurable.\n # QUESTION: @cesine: how is the elicitor of a FieldDB\n #",
"end": 27461,
"score": 0.9909626841545105,
"start": 27454,
"tag": "USERNAME",
"value": "@cesine"
}
] | app/scripts/models/application-settings.coffee | OpenSourceFieldlinguistics/dative | 7 | define [
'./base'
'./server'
'./parser-task-set'
'./keyboard-preference-set'
'./morphology'
'./language-model'
'./../collections/servers'
'./../utils/utils'
'./../utils/globals'
# 'FieldDB'
], (BaseModel, ServerModel, ParserTaskSetModel, KeyboardPreferenceSetModel,
MorphologyModel, LanguageModelModel, ServersCollection, utils, globals) ->
# Application Settings Model
# --------------------------
#
# Holds Dative's application settings. Persisted in the browser using
# localStorage.
#
# Also contains the authentication logic.
class ApplicationSettingsModel extends BaseModel
modelClassName2model:
'MorphologyModel': MorphologyModel
'LanguageModelModel': LanguageModelModel
initialize: ->
@fetch()
# fieldDBTempApp = new (FieldDB.App)(@get('fieldDBApplication'))
# fieldDBTempApp.authentication.eventDispatcher = Backbone
@listenTo Backbone, 'authenticate:login', @authenticate
@listenTo Backbone, 'authenticate:logout', @logout
@listenTo Backbone, 'authenticate:register', @register
@listenTo @, 'change:activeServer', @activeServerChanged
if @get('activeServer')
activeServer = @get 'activeServer'
if activeServer instanceof ServerModel
@listenTo activeServer, 'change:url', @activeServerURLChanged
if not Modernizr.localstorage
throw new Error 'localStorage unavailable in this browser, please upgrade.'
@setVersion()
# set app version from package.json
setVersion: ->
if @get('version') is 'da'
$.ajax
url: 'package.json',
type: 'GET'
dataType: 'json'
error: (jqXHR, textStatus, errorThrown) ->
console.log "Ajax request for package.json threw an error:
#{errorThrown}"
success: (packageDetails, textStatus, jqXHR) =>
@set 'version', packageDetails.version
activeServerChanged: ->
#console.log 'active server has changed says the app settings model'
if @get('fieldDBApplication')
@get('fieldDBApplication').website = @get('activeServer').get('website')
@get('fieldDBApplication').brand = @get('activeServer').get('brand') or
@get('activeServer').get('userFriendlyServerName')
@get('fieldDBApplication').brandLowerCase =
@get('activeServer').get('brandLowerCase') or
@get('activeServer').get('serverCode')
activeServerURLChanged: ->
#console.log 'active server URL has changed says the app settings model'
getURL: ->
url = @get('activeServer')?.get('url')
if url.slice(-1) is '/' then url.slice(0, -1) else url
getCorpusServerURL: ->
@get('activeServer')?.get 'corpusUrl'
getServerCode: ->
@get('activeServer')?.get 'serverCode'
authenticateAttemptDone: (taskId) ->
Backbone.trigger 'longTask:deregister', taskId
Backbone.trigger 'authenticate:end'
# Login (a.k.a. authenticate)
#=========================================================================
# Attempt to authenticate with the passed-in credentials
authenticate: (username, password) ->
if @get('activeServer')?.get('type') is 'FieldDB'
@authenticateFieldDBAuthService
username: username
password: password
authUrl: @get('activeServer')?.get('url')
else
@authenticateOLD username: username, password: password
authenticateOLD: (credentials) ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
@constructor.cors.request(
method: 'POST'
timeout: 20000
url: "#{@getURL()}/login/authenticate"
payload: credentials
onload: (responseJSON) =>
@authenticateAttemptDone taskId
Backbone.trigger 'authenticateEnd'
if responseJSON.authenticated is true
@set
username: credentials.username
loggedIn: true
loggedInUser: responseJSON.user
homepage: responseJSON.homepage
@save()
Backbone.trigger 'authenticateSuccess'
else
Backbone.trigger 'authenticateFail', responseJSON
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
authenticateFieldDBAuthService: (credentials) =>
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
if not @get 'fieldDBApplication'
@set 'fieldDBApplication', FieldDB.FieldDBObject.application
if not @get('fieldDBApplication').authentication or not @get('fieldDBApplication').authentication.login
@get('fieldDBApplication').authentication = new FieldDB.Authentication()
@get('fieldDBApplication').authentication.login(credentials).then(
(promisedResult) =>
@set
username: credentials.username,
password: credentials.password, # TODO dont need this!
loggedInUser: @get('fieldDBApplication').authentication.user
@save()
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateSuccess'
@authenticateAttemptDone taskId
,
(error) =>
@authenticateAttemptDone taskId
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON.userFriendlyErrors
).fail (error) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
# This is the to-be-deprecated version that has been made obsolete by
# `authenticateFieldDBAuthService` above.
authenticateFieldDBAuthService_: (credentials) =>
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
@constructor.cors.request(
method: 'POST'
timeout: 20000
url: "#{@getURL()}/login"
payload: credentials
onload: (responseJSON) =>
if responseJSON.user
# Remember the corpusServiceURL so we can logout.
@get('activeServer')?.set(
'corpusServerURL', @getFieldDBBaseDBURL(responseJSON.user))
@set
baseDBURL: @getFieldDBBaseDBURL(responseJSON.user)
username: credentials.username,
password: credentials.password,
gravatar: responseJSON.user.gravatar,
loggedInUser: responseJSON.user
@save()
credentials.name = credentials.username
@authenticateFieldDBCorpusService credentials, taskId
else
Backbone.trigger 'authenticateFail', responseJSON.userFriendlyErrors
@authenticateAttemptDone taskId
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
authenticateFieldDBCorpusService: (credentials, taskId) ->
@constructor.cors.request(
method: 'POST'
timeout: 3000
url: "#{@get('baseDBURL')}/_session"
payload: credentials
onload: (responseJSON) =>
# TODO @jrwdunham: this responseJSON has a roles Array attribute which
# references more corpora than I'm seeing from the `corpusteam`
# request. Why the discrepancy?
Backbone.trigger 'authenticateEnd'
@authenticateAttemptDone taskId
if responseJSON.ok
@set
loggedIn: true
loggedInUserRoles: responseJSON.roles
@save()
Backbone.trigger 'authenticateSuccess'
else
Backbone.trigger 'authenticateFail', responseJSON
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
localStorageKey: 'dativeApplicationSettings'
# An extremely simple re-implementation of `save`: we just JSON-ify the app
# settings and store them in localStorage.
save: ->
localStorage.setItem @localStorageKey,
JSON.stringify(@attributes)
# Fetching means simply getting the app settings JSON object from
# localStorage and setting it to the present model. Certain attributes are
# evaluated to other Backbone models; handling this conversion is the job
# of `backbonify`.
fetch: (options) ->
if localStorage.getItem @localStorageKey
applicationSettingsObject =
JSON.parse(localStorage.getItem(@localStorageKey))
applicationSettingsObject = @fix applicationSettingsObject
applicationSettingsObject = @backbonify applicationSettingsObject
@set applicationSettingsObject
@usingDefaults = false
else
@usingDefaults = true
@save()
# Fix the application settings, if necessary. This is necessary when Dative
# has been updated but the user's application settings object, as persisted
# in their `localStorage`, was built using an older version of Dative. If
# the app settings are out-of-date, then Dative may break.
# Note: `aso` is the Application Settings Object.
# The `ns` (namespace) param is good for debugging.
fix: (aso, defaults=null, ns='') ->
defaults = defaults or @defaults()
if 'attributes' of defaults
defaults = defaults.attributes
for attr, defval of defaults
if attr not of aso
aso[attr] = defval
# Recursively call `@fix` if the default val is an object.
else if ((@utils.type(defval) == 'object') and
not ((defval instanceof Backbone.Model) or
(defval instanceof Backbone.Collection)))
aso[attr] = @fix aso[attr], defval, "#{ns}.#{attr}"
for attr of aso
if attr not of defaults
delete aso[attr]
return aso
# Logout
#=========================================================================
logout: ->
if @get('activeServer')?.get('type') is 'FieldDB'
@logoutFieldDB()
else
@logoutOLD()
logoutOLD: ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'logout', taskId
Backbone.trigger 'logoutStart'
@constructor.cors.request(
url: "#{@getURL()}/login/logout"
method: 'GET'
timeout: 3000
onload: (responseJSON, xhr) =>
@authenticateAttemptDone taskId
Backbone.trigger 'logoutEnd'
if responseJSON.authenticated is false or
(xhr.status is 401 and
responseJSON.error is "Authentication is required to access this
resource.")
@set loggedIn: false, homepage: null
@save()
Backbone.trigger 'logoutSuccess'
else
Backbone.trigger 'logoutFail'
onerror: (responseJSON) =>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
Backbone.trigger 'logoutFail'
ontimeout: =>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
Backbone.trigger 'logoutFail', error: 'Request timed out'
)
logoutFieldDB: ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'logout', taskId
Backbone.trigger 'logoutStart'
if not @get 'fieldDBApplication'
@set 'fieldDBApplication', FieldDB.FieldDBObject.application
# TODO: @cesine: I'm getting "`authentication.logout` is not a function"
# errors here ...
@get('fieldDBApplication').authentication
.logout({letClientHandleCleanUp: 'dontReloadWeNeedToCleanUpInDativeClient'})
.then(
(responseJSON) =>
@set
fieldDBApplication: null
loggedIn: false
activeFieldDBCorpus: null
activeFieldDBCorpusTitle: null
@save()
Backbone.trigger 'logoutSuccess'
,
(reason) ->
Backbone.trigger 'logoutFail', reason.userFriendlyErrors.join ' '
).done(
=>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
)
# Check if logged in
#=========================================================================
# Check if we are already logged in.
checkIfLoggedIn: ->
if @get('activeServer')?.get('type') is 'FieldDB'
@checkIfLoggedInFieldDB()
else
@checkIfLoggedInOLD()
# Check with the OLD if we are logged in. We ask for the speakers. and
# trigger 'authenticateFail' if we can't get them.
checkIfLoggedInOLD: ->
taskId = @guid()
Backbone.trigger('longTask:register', 'checking if already logged in',
taskId)
@constructor.cors.request(
url: "#{@getURL()}/speakers"
timeout: 3000
onload: (responseJSON) =>
@authenticateAttemptDone(taskId)
if utils.type(responseJSON) is 'array'
@set 'loggedIn', true
@save()
Backbone.trigger 'authenticateSuccess'
else
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail'
onerror: (responseJSON) =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone(taskId)
ontimeout: =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone(taskId)
)
checkIfLoggedInFieldDB: ->
taskId = @guid()
Backbone.trigger('longTask:register', 'checking if already logged in',
taskId)
FieldDB.Database::resumeAuthenticationSession().then(
(sessionInfo) =>
if sessionInfo.ok and sessionInfo.userCtx.name
@set 'loggedIn', true
@save()
Backbone.trigger 'authenticateSuccess'
else
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail'
,
(reason) =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', reason
).done(=> @authenticateAttemptDone taskId)
# Register a new user
# =========================================================================
# `RegisterDialogView` should never allow an OLD registration attempt.
register: (params) ->
if @get('activeServer')?.get('type') is 'FieldDB'
@registerFieldDB params
registerFieldDB: (params) ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'registering a new user', taskId
params.authUrl = @getURL()
params.appVersionWhenCreated = "v#{@get('version')}da"
@constructor.cors.request(
url: "#{@getURL()}/register"
payload: params
method: 'POST'
timeout: 10000 # FieldDB auth can take some time to register a new user ...
onload: (responseJSON) =>
@authenticateAttemptDone taskId
# TODO @cesine: what other kinds of responses to registration requests
# can the auth service make?
if responseJSON.user?
user = responseJSON.user
Backbone.trigger 'register:success', responseJSON
else
Backbone.trigger 'register:fail', responseJSON.userFriendlyErrors
onerror: (responseJSON) =>
@authenticateAttemptDone taskId
Backbone.trigger 'register:fail', 'server responded with error'
ontimeout: =>
@authenticateAttemptDone taskId
Backbone.trigger 'register:fail', 'Request timed out'
)
idAttribute: 'id'
# Transform certain attribute values of the `appSetObj`
# object into Backbone collections/models and return the `appSetObj`.
backbonify: (appSetObj) ->
serverModelsArray = ((new ServerModel(s)) for s in appSetObj.servers)
appSetObj.servers = new ServersCollection(serverModelsArray)
activeServer = appSetObj.activeServer
if activeServer
appSetObj.activeServer = appSetObj.servers.get activeServer.id
longRunningTasks = appSetObj.longRunningTasks
for task in appSetObj.longRunningTasks
task.resourceModel =
new @modelClassName2model[task.modelClassName](task.resourceModel)
for task in appSetObj.longRunningTasksTerminated
task.resourceModel =
new @modelClassName2model[task.modelClassName](task.resourceModel)
appSetObj.parserTaskSet = new ParserTaskSetModel(appSetObj.parserTaskSet)
appSetObj.keyboardPreferenceSet =
new KeyboardPreferenceSetModel(appSetObj.keyboardPreferenceSet)
appSetObj
############################################################################
# Defaults
############################################################################
defaults: ->
# Default servers are provided at runtime using servers.json
server =
new ServerModel
id: @guid()
name: 'OLD Local Development'
type: 'OLD'
url: 'http://127.0.0.1:5000'
serverCode: null
corpusServerURL: null
website: 'http://www.onlinelinguisticdatabase.org'
servers = new ServersCollection([server])
parserTaskSetModel = new ParserTaskSetModel()
keyboardPreferenceSetModel = new KeyboardPreferenceSetModel()
id: @guid()
activeServer: servers.at 0
loggedIn: false
loggedInUser: null
loggedInUserRoles: []
# An OLD will send an object representing the home page when a user
# successfully logs in, if there is such a page named 'home'.
homepage: null
baseDBURL: null
username: ''
# This gets set to `true` as soon as the user makes modifications to the
# list of servers. This allows us to avoid over-writing the
# user-specified servers with those supplied by Dative in servers.json.
serversModified: false
# This contains the array of objects contstituting the last set of
# servers that Dative has sent us. We use this to decide whether to
# prompt/annoy the user to merge these servers into their own.
lastSeenServersFromDative: null
servers: servers
# serverTypes: ['FieldDB', 'OLD']
serverTypes: ['OLD']
fieldDBServerCodes: [
'localhost'
'testing'
'beta'
'production'
'mcgill'
'concordia'
'dyslexdisorth'
]
# TODO: remove the activeFieldDBCorpusTitle and related attributes. We
# should simply store a real `CorpusModel` as the value of
# `activeFieldDBCorpus`. Note that `AppView` adds
# `activeFieldDBCorpusModel` and stores a Backbone model there. This all
# needs to be cleaned up.
activeFieldDBCorpus: null
activeFieldDBCorpusTitle: null
languagesDisplaySettings:
itemsPerPage: 100
dataLabelsVisible: true
allFormsExpanded: false
formsDisplaySettings:
itemsPerPage: 10
dataLabelsVisible: false
allFormsExpanded: false
subcorporaDisplaySettings:
itemsPerPage: 10
dataLabelsVisible: true
allSubcorporaExpanded: false
phonologiesDisplaySettings:
itemsPerPage: 1
dataLabelsVisible: true
allPhonologiesExpanded: false
morphologiesDisplaySettings:
itemsPerPage: 1
dataLabelsVisible: true
allMorphologiesExpanded: false
activeJQueryUITheme: 'pepper-grinder'
defaultJQueryUITheme: 'pepper-grinder'
jQueryUIThemes: [
['ui-lightness', 'UI lightness']
['ui-darkness', 'UI darkness']
['smoothness', 'Smoothness']
['start', 'Start']
['redmond', 'Redmond']
['sunny', 'Sunny']
['overcast', 'Overcast']
['le-frog', 'Le Frog']
['flick', 'Flick']
['pepper-grinder', 'Pepper Grinder']
['eggplant', 'Eggplant']
['dark-hive', 'Dark Hive']
['cupertino', 'Cupertino']
['south-street', 'South Street']
['blitzer', 'Blitzer']
['humanity', 'Humanity']
['hot-sneaks', 'Hot Sneaks']
['excite-bike', 'Excite Bike']
['vader', 'Vader']
['dot-luv', 'Dot Luv']
['mint-choc', 'Mint Choc']
['black-tie', 'Black Tie']
['trontastic', 'Trontastic']
['swanky-purse', 'Swanky Purse']
]
# Use this to limit how many "long-running" tasks can be initiated from
# within the app. A "long-running task" is a request to the server that
# requires polling to know when it has terminated, e.g., phonology
# compilation, morphology generation and compilation, etc.
# NOTE !IMPORTANT: the OLD has a single foma worker and all requests to
# compile FST-based resources appear to enter into a queue. This means
# that a 3s request made while a 1h request is ongoing will take 1h1s!
# Not good ...
longRunningTasksMax: 2
# An array of objects with keys `resourceName`, `taskName`,
# `taskStartTimestamp`, and `taskPreviousUUID`.
longRunningTasks: []
# An array of objects with keys `resourceName`, `taskName`,
# `taskStartTimestamp`, and `taskPreviousUUID`.
longRunningTasksTerminated: []
# IME types that can be uploaded (to an OLD server, at least).
# TODO: this should be expanded and/or made backend-specific.
allowedFileTypes: [
'application/pdf'
'image/gif'
'image/jpeg'
'image/png'
'audio/mpeg'
'audio/mp3'
'audio/ogg'
'audio/x-wav'
'audio/wav'
'video/mpeg'
'video/mp4'
'video/ogg'
'video/quicktime'
'video/x-ms-wmv'
]
version: 'da'
parserTaskSet: parserTaskSetModel
keyboardPreferenceSet: keyboardPreferenceSetModel
# This object contains metadata about Dative resources, i.e., forms,
# files, etc.
# TODO: resource display settings (e.g., `formsDisplaySettings` above)
# should be migrated here.
resources:
forms:
# Array of form attributes that are "sticky", i.e., that will stick
# around and whose values in the most recent add request will be the
# defaults for subsequent add requests.
stickyAttributes: []
# Array of form attributes that *may* be specified as "sticky".
possiblyStickyAttributes: [
'date_elicited'
'elicitation_method'
'elicitor'
'source'
'speaker'
'status'
'syntactic_category'
'tags'
]
# This will be populated by the resources collection upon successful
# add requests. It will map attribute names in `stickyAttributes`
# above to their values in the most recent successful add request.
pastValues: {}
# These objects define metadata on the fields of form resources.
# Note that there are separate metadata objects for OLD fields and
# for FieldDB fields.
fieldsMeta:
OLD:
grammaticality: [
'grammaticality'
]
# IGT OLD Form Attributes.
igt: [
'narrow_phonetic_transcription'
'phonetic_transcription'
'transcription'
'morpheme_break'
'morpheme_gloss'
]
# Note: this is currently not being used (just being consistent
# with the FieldDB `fieldsMeta` object below)
translation: [
'translations'
]
# Secondary OLD Form Attributes.
secondary: [
'syntactic_category_string'
'break_gloss_category'
'comments'
'speaker_comments'
'elicitation_method'
'tags'
'syntactic_category'
'date_elicited'
'speaker'
'elicitor'
'enterer'
'datetime_entered'
'modifier'
'datetime_modified'
'verifier'
'source'
'files'
#'collections' # Does the OLD provide the collections when the forms resource is fetched?
'syntax'
'semantics'
'status'
'UUID'
'id'
]
readonly: [
'syntactic_category_string'
'break_gloss_category'
'enterer'
'datetime_entered'
'modifier'
'datetime_modified'
'UUID'
'id'
]
# This array may contain the names of OLD form attributes that should
# be hidden. This is the (for now only client-side-stored) data
# structure that users manipulate in the settings widget of a
# `FormView` instance.
hidden: [
'narrow_phonetic_transcription'
'phonetic_transcription'
'verifier'
]
FieldDB:
# This is the set of form attributes that are considered by
# Dative to denote grammaticalities.
grammaticality: [
'judgement'
]
# IGT FieldDB form attributes.
# The returned array defines the "IGT" attributes of a FieldDB
# form (along with their order). These are those that are aligned
# into columns of one word each when displayed in an IGT view.
igt: [
'utterance'
'morphemes'
'gloss'
]
# This is the set of form attributes that are considered by
# Dative to denote a translation.
translation: [
'translation'
]
# Secondary FieldDB form attributes.
# The returned array defines the order of how the secondary
# attributes are displayed. It is defined in
# models/application-settings because it should ultimately be
# user-configurable.
# QUESTION: @cesine: how is the elicitor of a FieldDB
# datum/session documented?
# TODO: `audioVideo`, `images`
secondary: [
'syntacticCategory'
'comments'
'tags'
'dateElicited' # session field
'language' # session field
'dialect' # session field
'consultants' # session field
'enteredByUser'
'dateEntered'
'modifiedByUser'
'dateModified'
'syntacticTreeLatex'
'validationStatus'
'timestamp' # make this visible?
'id'
]
# These read-only fields will not be given input fields in
# add/update interfaces.
readonly: [
'enteredByUser'
'dateEntered'
'modifiedByUser'
'dateModified'
]
| 91606 | define [
'./base'
'./server'
'./parser-task-set'
'./keyboard-preference-set'
'./morphology'
'./language-model'
'./../collections/servers'
'./../utils/utils'
'./../utils/globals'
# 'FieldDB'
], (BaseModel, ServerModel, ParserTaskSetModel, KeyboardPreferenceSetModel,
MorphologyModel, LanguageModelModel, ServersCollection, utils, globals) ->
# Application Settings Model
# --------------------------
#
# Holds Dative's application settings. Persisted in the browser using
# localStorage.
#
# Also contains the authentication logic.
class ApplicationSettingsModel extends BaseModel
modelClassName2model:
'MorphologyModel': MorphologyModel
'LanguageModelModel': LanguageModelModel
initialize: ->
@fetch()
# fieldDBTempApp = new (FieldDB.App)(@get('fieldDBApplication'))
# fieldDBTempApp.authentication.eventDispatcher = Backbone
@listenTo Backbone, 'authenticate:login', @authenticate
@listenTo Backbone, 'authenticate:logout', @logout
@listenTo Backbone, 'authenticate:register', @register
@listenTo @, 'change:activeServer', @activeServerChanged
if @get('activeServer')
activeServer = @get 'activeServer'
if activeServer instanceof ServerModel
@listenTo activeServer, 'change:url', @activeServerURLChanged
if not Modernizr.localstorage
throw new Error 'localStorage unavailable in this browser, please upgrade.'
@setVersion()
# set app version from package.json
setVersion: ->
if @get('version') is 'da'
$.ajax
url: 'package.json',
type: 'GET'
dataType: 'json'
error: (jqXHR, textStatus, errorThrown) ->
console.log "Ajax request for package.json threw an error:
#{errorThrown}"
success: (packageDetails, textStatus, jqXHR) =>
@set 'version', packageDetails.version
activeServerChanged: ->
#console.log 'active server has changed says the app settings model'
if @get('fieldDBApplication')
@get('fieldDBApplication').website = @get('activeServer').get('website')
@get('fieldDBApplication').brand = @get('activeServer').get('brand') or
@get('activeServer').get('userFriendlyServerName')
@get('fieldDBApplication').brandLowerCase =
@get('activeServer').get('brandLowerCase') or
@get('activeServer').get('serverCode')
activeServerURLChanged: ->
#console.log 'active server URL has changed says the app settings model'
getURL: ->
url = @get('activeServer')?.get('url')
if url.slice(-1) is '/' then url.slice(0, -1) else url
getCorpusServerURL: ->
@get('activeServer')?.get 'corpusUrl'
getServerCode: ->
@get('activeServer')?.get 'serverCode'
authenticateAttemptDone: (taskId) ->
Backbone.trigger 'longTask:deregister', taskId
Backbone.trigger 'authenticate:end'
# Login (a.k.a. authenticate)
#=========================================================================
# Attempt to authenticate with the passed-in credentials
authenticate: (username, password) ->
if @get('activeServer')?.get('type') is 'FieldDB'
@authenticateFieldDBAuthService
username: username
password: <PASSWORD>
authUrl: @get('activeServer')?.get('url')
else
@authenticateOLD username: username, password: <PASSWORD>
authenticateOLD: (credentials) ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
@constructor.cors.request(
method: 'POST'
timeout: 20000
url: "#{@getURL()}/login/authenticate"
payload: credentials
onload: (responseJSON) =>
@authenticateAttemptDone taskId
Backbone.trigger 'authenticateEnd'
if responseJSON.authenticated is true
@set
username: credentials.username
loggedIn: true
loggedInUser: responseJSON.user
homepage: responseJSON.homepage
@save()
Backbone.trigger 'authenticateSuccess'
else
Backbone.trigger 'authenticateFail', responseJSON
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
authenticateFieldDBAuthService: (credentials) =>
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
if not @get 'fieldDBApplication'
@set 'fieldDBApplication', FieldDB.FieldDBObject.application
if not @get('fieldDBApplication').authentication or not @get('fieldDBApplication').authentication.login
@get('fieldDBApplication').authentication = new FieldDB.Authentication()
@get('fieldDBApplication').authentication.login(credentials).then(
(promisedResult) =>
@set
username: credentials.username,
password: <PASSWORD>, # TODO dont need this!
loggedInUser: @get('fieldDBApplication').authentication.user
@save()
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateSuccess'
@authenticateAttemptDone taskId
,
(error) =>
@authenticateAttemptDone taskId
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON.userFriendlyErrors
).fail (error) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
# This is the to-be-deprecated version that has been made obsolete by
# `authenticateFieldDBAuthService` above.
authenticateFieldDBAuthService_: (credentials) =>
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
@constructor.cors.request(
method: 'POST'
timeout: 20000
url: "#{@getURL()}/login"
payload: credentials
onload: (responseJSON) =>
if responseJSON.user
# Remember the corpusServiceURL so we can logout.
@get('activeServer')?.set(
'corpusServerURL', @getFieldDBBaseDBURL(responseJSON.user))
@set
baseDBURL: @getFieldDBBaseDBURL(responseJSON.user)
username: credentials.username,
password: <PASSWORD>,
gravatar: responseJSON.user.gravatar,
loggedInUser: responseJSON.user
@save()
credentials.name = credentials.username
@authenticateFieldDBCorpusService credentials, taskId
else
Backbone.trigger 'authenticateFail', responseJSON.userFriendlyErrors
@authenticateAttemptDone taskId
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
authenticateFieldDBCorpusService: (credentials, taskId) ->
@constructor.cors.request(
method: 'POST'
timeout: 3000
url: "#{@get('baseDBURL')}/_session"
payload: credentials
onload: (responseJSON) =>
# TODO @jrwdunham: this responseJSON has a roles Array attribute which
# references more corpora than I'm seeing from the `corpusteam`
# request. Why the discrepancy?
Backbone.trigger 'authenticateEnd'
@authenticateAttemptDone taskId
if responseJSON.ok
@set
loggedIn: true
loggedInUserRoles: responseJSON.roles
@save()
Backbone.trigger 'authenticateSuccess'
else
Backbone.trigger 'authenticateFail', responseJSON
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
localStorageKey: 'dativeApplicationSettings'
# An extremely simple re-implementation of `save`: we just JSON-ify the app
# settings and store them in localStorage.
save: ->
localStorage.setItem @localStorageKey,
JSON.stringify(@attributes)
# Fetching means simply getting the app settings JSON object from
# localStorage and setting it to the present model. Certain attributes are
# evaluated to other Backbone models; handling this conversion is the job
# of `backbonify`.
fetch: (options) ->
if localStorage.getItem @localStorageKey
applicationSettingsObject =
JSON.parse(localStorage.getItem(@localStorageKey))
applicationSettingsObject = @fix applicationSettingsObject
applicationSettingsObject = @backbonify applicationSettingsObject
@set applicationSettingsObject
@usingDefaults = false
else
@usingDefaults = true
@save()
# Fix the application settings, if necessary. This is necessary when Dative
# has been updated but the user's application settings object, as persisted
# in their `localStorage`, was built using an older version of Dative. If
# the app settings are out-of-date, then Dative may break.
# Note: `aso` is the Application Settings Object.
# The `ns` (namespace) param is good for debugging.
fix: (aso, defaults=null, ns='') ->
defaults = defaults or @defaults()
if 'attributes' of defaults
defaults = defaults.attributes
for attr, defval of defaults
if attr not of aso
aso[attr] = defval
# Recursively call `@fix` if the default val is an object.
else if ((@utils.type(defval) == 'object') and
not ((defval instanceof Backbone.Model) or
(defval instanceof Backbone.Collection)))
aso[attr] = @fix aso[attr], defval, "#{ns}.#{attr}"
for attr of aso
if attr not of defaults
delete aso[attr]
return aso
# Logout
#=========================================================================
logout: ->
if @get('activeServer')?.get('type') is 'FieldDB'
@logoutFieldDB()
else
@logoutOLD()
logoutOLD: ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'logout', taskId
Backbone.trigger 'logoutStart'
@constructor.cors.request(
url: "#{@getURL()}/login/logout"
method: 'GET'
timeout: 3000
onload: (responseJSON, xhr) =>
@authenticateAttemptDone taskId
Backbone.trigger 'logoutEnd'
if responseJSON.authenticated is false or
(xhr.status is 401 and
responseJSON.error is "Authentication is required to access this
resource.")
@set loggedIn: false, homepage: null
@save()
Backbone.trigger 'logoutSuccess'
else
Backbone.trigger 'logoutFail'
onerror: (responseJSON) =>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
Backbone.trigger 'logoutFail'
ontimeout: =>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
Backbone.trigger 'logoutFail', error: 'Request timed out'
)
logoutFieldDB: ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'logout', taskId
Backbone.trigger 'logoutStart'
if not @get 'fieldDBApplication'
@set 'fieldDBApplication', FieldDB.FieldDBObject.application
# TODO: @cesine: I'm getting "`authentication.logout` is not a function"
# errors here ...
@get('fieldDBApplication').authentication
.logout({letClientHandleCleanUp: 'dontReloadWeNeedToCleanUpInDativeClient'})
.then(
(responseJSON) =>
@set
fieldDBApplication: null
loggedIn: false
activeFieldDBCorpus: null
activeFieldDBCorpusTitle: null
@save()
Backbone.trigger 'logoutSuccess'
,
(reason) ->
Backbone.trigger 'logoutFail', reason.userFriendlyErrors.join ' '
).done(
=>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
)
# Check if logged in
#=========================================================================
# Check if we are already logged in.
checkIfLoggedIn: ->
if @get('activeServer')?.get('type') is 'FieldDB'
@checkIfLoggedInFieldDB()
else
@checkIfLoggedInOLD()
# Check with the OLD if we are logged in. We ask for the speakers. and
# trigger 'authenticateFail' if we can't get them.
checkIfLoggedInOLD: ->
taskId = @guid()
Backbone.trigger('longTask:register', 'checking if already logged in',
taskId)
@constructor.cors.request(
url: "#{@getURL()}/speakers"
timeout: 3000
onload: (responseJSON) =>
@authenticateAttemptDone(taskId)
if utils.type(responseJSON) is 'array'
@set 'loggedIn', true
@save()
Backbone.trigger 'authenticateSuccess'
else
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail'
onerror: (responseJSON) =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone(taskId)
ontimeout: =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone(taskId)
)
checkIfLoggedInFieldDB: ->
taskId = @guid()
Backbone.trigger('longTask:register', 'checking if already logged in',
taskId)
FieldDB.Database::resumeAuthenticationSession().then(
(sessionInfo) =>
if sessionInfo.ok and sessionInfo.userCtx.name
@set 'loggedIn', true
@save()
Backbone.trigger 'authenticateSuccess'
else
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail'
,
(reason) =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', reason
).done(=> @authenticateAttemptDone taskId)
# Register a new user
# =========================================================================
# `RegisterDialogView` should never allow an OLD registration attempt.
register: (params) ->
if @get('activeServer')?.get('type') is 'FieldDB'
@registerFieldDB params
registerFieldDB: (params) ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'registering a new user', taskId
params.authUrl = @getURL()
params.appVersionWhenCreated = "v#{@get('version')}da"
@constructor.cors.request(
url: "#{@getURL()}/register"
payload: params
method: 'POST'
timeout: 10000 # FieldDB auth can take some time to register a new user ...
onload: (responseJSON) =>
@authenticateAttemptDone taskId
# TODO @cesine: what other kinds of responses to registration requests
# can the auth service make?
if responseJSON.user?
user = responseJSON.user
Backbone.trigger 'register:success', responseJSON
else
Backbone.trigger 'register:fail', responseJSON.userFriendlyErrors
onerror: (responseJSON) =>
@authenticateAttemptDone taskId
Backbone.trigger 'register:fail', 'server responded with error'
ontimeout: =>
@authenticateAttemptDone taskId
Backbone.trigger 'register:fail', 'Request timed out'
)
idAttribute: 'id'
# Transform certain attribute values of the `appSetObj`
# object into Backbone collections/models and return the `appSetObj`.
backbonify: (appSetObj) ->
serverModelsArray = ((new ServerModel(s)) for s in appSetObj.servers)
appSetObj.servers = new ServersCollection(serverModelsArray)
activeServer = appSetObj.activeServer
if activeServer
appSetObj.activeServer = appSetObj.servers.get activeServer.id
longRunningTasks = appSetObj.longRunningTasks
for task in appSetObj.longRunningTasks
task.resourceModel =
new @modelClassName2model[task.modelClassName](task.resourceModel)
for task in appSetObj.longRunningTasksTerminated
task.resourceModel =
new @modelClassName2model[task.modelClassName](task.resourceModel)
appSetObj.parserTaskSet = new ParserTaskSetModel(appSetObj.parserTaskSet)
appSetObj.keyboardPreferenceSet =
new KeyboardPreferenceSetModel(appSetObj.keyboardPreferenceSet)
appSetObj
############################################################################
# Defaults
############################################################################
defaults: ->
# Default servers are provided at runtime using servers.json
server =
new ServerModel
id: @guid()
name: 'OLD Local Development'
type: 'OLD'
url: 'http://127.0.0.1:5000'
serverCode: null
corpusServerURL: null
website: 'http://www.onlinelinguisticdatabase.org'
servers = new ServersCollection([server])
parserTaskSetModel = new ParserTaskSetModel()
keyboardPreferenceSetModel = new KeyboardPreferenceSetModel()
id: @guid()
activeServer: servers.at 0
loggedIn: false
loggedInUser: null
loggedInUserRoles: []
# An OLD will send an object representing the home page when a user
# successfully logs in, if there is such a page named 'home'.
homepage: null
baseDBURL: null
username: ''
# This gets set to `true` as soon as the user makes modifications to the
# list of servers. This allows us to avoid over-writing the
# user-specified servers with those supplied by Dative in servers.json.
serversModified: false
# This contains the array of objects contstituting the last set of
# servers that Dative has sent us. We use this to decide whether to
# prompt/annoy the user to merge these servers into their own.
lastSeenServersFromDative: null
servers: servers
# serverTypes: ['FieldDB', 'OLD']
serverTypes: ['OLD']
fieldDBServerCodes: [
'localhost'
'testing'
'beta'
'production'
'mcgill'
'concordia'
'dyslexdisorth'
]
# TODO: remove the activeFieldDBCorpusTitle and related attributes. We
# should simply store a real `CorpusModel` as the value of
# `activeFieldDBCorpus`. Note that `AppView` adds
# `activeFieldDBCorpusModel` and stores a Backbone model there. This all
# needs to be cleaned up.
activeFieldDBCorpus: null
activeFieldDBCorpusTitle: null
languagesDisplaySettings:
itemsPerPage: 100
dataLabelsVisible: true
allFormsExpanded: false
formsDisplaySettings:
itemsPerPage: 10
dataLabelsVisible: false
allFormsExpanded: false
subcorporaDisplaySettings:
itemsPerPage: 10
dataLabelsVisible: true
allSubcorporaExpanded: false
phonologiesDisplaySettings:
itemsPerPage: 1
dataLabelsVisible: true
allPhonologiesExpanded: false
morphologiesDisplaySettings:
itemsPerPage: 1
dataLabelsVisible: true
allMorphologiesExpanded: false
activeJQueryUITheme: 'pepper-grinder'
defaultJQueryUITheme: 'pepper-grinder'
jQueryUIThemes: [
['ui-lightness', 'UI lightness']
['ui-darkness', 'UI darkness']
['smoothness', 'Smoothness']
['start', 'Start']
['redmond', 'Redmond']
['sunny', 'Sunny']
['overcast', 'Overcast']
['le-frog', 'Le Frog']
['flick', 'Flick']
['pepper-grinder', 'Pepper Grinder']
['eggplant', 'Eggplant']
['dark-hive', 'Dark Hive']
['cupertino', 'Cupertino']
['south-street', 'South Street']
['blitzer', 'Blitzer']
['humanity', 'Humanity']
['hot-sneaks', 'Hot Sneaks']
['excite-bike', 'Excite Bike']
['vader', 'Vader']
['dot-luv', 'Dot Luv']
['mint-choc', 'Mint Choc']
['black-tie', 'Black Tie']
['trontastic', 'Trontastic']
['swanky-purse', 'Swanky Purse']
]
# Use this to limit how many "long-running" tasks can be initiated from
# within the app. A "long-running task" is a request to the server that
# requires polling to know when it has terminated, e.g., phonology
# compilation, morphology generation and compilation, etc.
# NOTE !IMPORTANT: the OLD has a single foma worker and all requests to
# compile FST-based resources appear to enter into a queue. This means
# that a 3s request made while a 1h request is ongoing will take 1h1s!
# Not good ...
longRunningTasksMax: 2
# An array of objects with keys `resourceName`, `taskName`,
# `taskStartTimestamp`, and `taskPreviousUUID`.
longRunningTasks: []
# An array of objects with keys `resourceName`, `taskName`,
# `taskStartTimestamp`, and `taskPreviousUUID`.
longRunningTasksTerminated: []
# IME types that can be uploaded (to an OLD server, at least).
# TODO: this should be expanded and/or made backend-specific.
allowedFileTypes: [
'application/pdf'
'image/gif'
'image/jpeg'
'image/png'
'audio/mpeg'
'audio/mp3'
'audio/ogg'
'audio/x-wav'
'audio/wav'
'video/mpeg'
'video/mp4'
'video/ogg'
'video/quicktime'
'video/x-ms-wmv'
]
version: 'da'
parserTaskSet: parserTaskSetModel
keyboardPreferenceSet: keyboardPreferenceSetModel
# This object contains metadata about Dative resources, i.e., forms,
# files, etc.
# TODO: resource display settings (e.g., `formsDisplaySettings` above)
# should be migrated here.
resources:
forms:
# Array of form attributes that are "sticky", i.e., that will stick
# around and whose values in the most recent add request will be the
# defaults for subsequent add requests.
stickyAttributes: []
# Array of form attributes that *may* be specified as "sticky".
possiblyStickyAttributes: [
'date_elicited'
'elicitation_method'
'elicitor'
'source'
'speaker'
'status'
'syntactic_category'
'tags'
]
# This will be populated by the resources collection upon successful
# add requests. It will map attribute names in `stickyAttributes`
# above to their values in the most recent successful add request.
pastValues: {}
# These objects define metadata on the fields of form resources.
# Note that there are separate metadata objects for OLD fields and
# for FieldDB fields.
fieldsMeta:
OLD:
grammaticality: [
'grammaticality'
]
# IGT OLD Form Attributes.
igt: [
'narrow_phonetic_transcription'
'phonetic_transcription'
'transcription'
'morpheme_break'
'morpheme_gloss'
]
# Note: this is currently not being used (just being consistent
# with the FieldDB `fieldsMeta` object below)
translation: [
'translations'
]
# Secondary OLD Form Attributes.
secondary: [
'syntactic_category_string'
'break_gloss_category'
'comments'
'speaker_comments'
'elicitation_method'
'tags'
'syntactic_category'
'date_elicited'
'speaker'
'elicitor'
'enterer'
'datetime_entered'
'modifier'
'datetime_modified'
'verifier'
'source'
'files'
#'collections' # Does the OLD provide the collections when the forms resource is fetched?
'syntax'
'semantics'
'status'
'UUID'
'id'
]
readonly: [
'syntactic_category_string'
'break_gloss_category'
'enterer'
'datetime_entered'
'modifier'
'datetime_modified'
'UUID'
'id'
]
# This array may contain the names of OLD form attributes that should
# be hidden. This is the (for now only client-side-stored) data
# structure that users manipulate in the settings widget of a
# `FormView` instance.
hidden: [
'narrow_phonetic_transcription'
'phonetic_transcription'
'verifier'
]
FieldDB:
# This is the set of form attributes that are considered by
# Dative to denote grammaticalities.
grammaticality: [
'judgement'
]
# IGT FieldDB form attributes.
# The returned array defines the "IGT" attributes of a FieldDB
# form (along with their order). These are those that are aligned
# into columns of one word each when displayed in an IGT view.
igt: [
'utterance'
'morphemes'
'gloss'
]
# This is the set of form attributes that are considered by
# Dative to denote a translation.
translation: [
'translation'
]
# Secondary FieldDB form attributes.
# The returned array defines the order of how the secondary
# attributes are displayed. It is defined in
# models/application-settings because it should ultimately be
# user-configurable.
# QUESTION: @cesine: how is the elicitor of a FieldDB
# datum/session documented?
# TODO: `audioVideo`, `images`
secondary: [
'syntacticCategory'
'comments'
'tags'
'dateElicited' # session field
'language' # session field
'dialect' # session field
'consultants' # session field
'enteredByUser'
'dateEntered'
'modifiedByUser'
'dateModified'
'syntacticTreeLatex'
'validationStatus'
'timestamp' # make this visible?
'id'
]
# These read-only fields will not be given input fields in
# add/update interfaces.
readonly: [
'enteredByUser'
'dateEntered'
'modifiedByUser'
'dateModified'
]
| true | define [
'./base'
'./server'
'./parser-task-set'
'./keyboard-preference-set'
'./morphology'
'./language-model'
'./../collections/servers'
'./../utils/utils'
'./../utils/globals'
# 'FieldDB'
], (BaseModel, ServerModel, ParserTaskSetModel, KeyboardPreferenceSetModel,
MorphologyModel, LanguageModelModel, ServersCollection, utils, globals) ->
# Application Settings Model
# --------------------------
#
# Holds Dative's application settings. Persisted in the browser using
# localStorage.
#
# Also contains the authentication logic.
class ApplicationSettingsModel extends BaseModel
modelClassName2model:
'MorphologyModel': MorphologyModel
'LanguageModelModel': LanguageModelModel
initialize: ->
@fetch()
# fieldDBTempApp = new (FieldDB.App)(@get('fieldDBApplication'))
# fieldDBTempApp.authentication.eventDispatcher = Backbone
@listenTo Backbone, 'authenticate:login', @authenticate
@listenTo Backbone, 'authenticate:logout', @logout
@listenTo Backbone, 'authenticate:register', @register
@listenTo @, 'change:activeServer', @activeServerChanged
if @get('activeServer')
activeServer = @get 'activeServer'
if activeServer instanceof ServerModel
@listenTo activeServer, 'change:url', @activeServerURLChanged
if not Modernizr.localstorage
throw new Error 'localStorage unavailable in this browser, please upgrade.'
@setVersion()
# set app version from package.json
setVersion: ->
if @get('version') is 'da'
$.ajax
url: 'package.json',
type: 'GET'
dataType: 'json'
error: (jqXHR, textStatus, errorThrown) ->
console.log "Ajax request for package.json threw an error:
#{errorThrown}"
success: (packageDetails, textStatus, jqXHR) =>
@set 'version', packageDetails.version
activeServerChanged: ->
#console.log 'active server has changed says the app settings model'
if @get('fieldDBApplication')
@get('fieldDBApplication').website = @get('activeServer').get('website')
@get('fieldDBApplication').brand = @get('activeServer').get('brand') or
@get('activeServer').get('userFriendlyServerName')
@get('fieldDBApplication').brandLowerCase =
@get('activeServer').get('brandLowerCase') or
@get('activeServer').get('serverCode')
activeServerURLChanged: ->
#console.log 'active server URL has changed says the app settings model'
getURL: ->
url = @get('activeServer')?.get('url')
if url.slice(-1) is '/' then url.slice(0, -1) else url
getCorpusServerURL: ->
@get('activeServer')?.get 'corpusUrl'
getServerCode: ->
@get('activeServer')?.get 'serverCode'
authenticateAttemptDone: (taskId) ->
Backbone.trigger 'longTask:deregister', taskId
Backbone.trigger 'authenticate:end'
# Login (a.k.a. authenticate)
#=========================================================================
# Attempt to authenticate with the passed-in credentials
authenticate: (username, password) ->
if @get('activeServer')?.get('type') is 'FieldDB'
@authenticateFieldDBAuthService
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
authUrl: @get('activeServer')?.get('url')
else
@authenticateOLD username: username, password: PI:PASSWORD:<PASSWORD>END_PI
authenticateOLD: (credentials) ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
@constructor.cors.request(
method: 'POST'
timeout: 20000
url: "#{@getURL()}/login/authenticate"
payload: credentials
onload: (responseJSON) =>
@authenticateAttemptDone taskId
Backbone.trigger 'authenticateEnd'
if responseJSON.authenticated is true
@set
username: credentials.username
loggedIn: true
loggedInUser: responseJSON.user
homepage: responseJSON.homepage
@save()
Backbone.trigger 'authenticateSuccess'
else
Backbone.trigger 'authenticateFail', responseJSON
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
authenticateFieldDBAuthService: (credentials) =>
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
if not @get 'fieldDBApplication'
@set 'fieldDBApplication', FieldDB.FieldDBObject.application
if not @get('fieldDBApplication').authentication or not @get('fieldDBApplication').authentication.login
@get('fieldDBApplication').authentication = new FieldDB.Authentication()
@get('fieldDBApplication').authentication.login(credentials).then(
(promisedResult) =>
@set
username: credentials.username,
password: PI:PASSWORD:<PASSWORD>END_PI, # TODO dont need this!
loggedInUser: @get('fieldDBApplication').authentication.user
@save()
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateSuccess'
@authenticateAttemptDone taskId
,
(error) =>
@authenticateAttemptDone taskId
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON.userFriendlyErrors
).fail (error) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
# This is the to-be-deprecated version that has been made obsolete by
# `authenticateFieldDBAuthService` above.
authenticateFieldDBAuthService_: (credentials) =>
taskId = @guid()
Backbone.trigger 'longTask:register', 'authenticating', taskId
Backbone.trigger 'authenticateStart'
@constructor.cors.request(
method: 'POST'
timeout: 20000
url: "#{@getURL()}/login"
payload: credentials
onload: (responseJSON) =>
if responseJSON.user
# Remember the corpusServiceURL so we can logout.
@get('activeServer')?.set(
'corpusServerURL', @getFieldDBBaseDBURL(responseJSON.user))
@set
baseDBURL: @getFieldDBBaseDBURL(responseJSON.user)
username: credentials.username,
password: PI:PASSWORD:<PASSWORD>END_PI,
gravatar: responseJSON.user.gravatar,
loggedInUser: responseJSON.user
@save()
credentials.name = credentials.username
@authenticateFieldDBCorpusService credentials, taskId
else
Backbone.trigger 'authenticateFail', responseJSON.userFriendlyErrors
@authenticateAttemptDone taskId
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
authenticateFieldDBCorpusService: (credentials, taskId) ->
@constructor.cors.request(
method: 'POST'
timeout: 3000
url: "#{@get('baseDBURL')}/_session"
payload: credentials
onload: (responseJSON) =>
# TODO @jrwdunham: this responseJSON has a roles Array attribute which
# references more corpora than I'm seeing from the `corpusteam`
# request. Why the discrepancy?
Backbone.trigger 'authenticateEnd'
@authenticateAttemptDone taskId
if responseJSON.ok
@set
loggedIn: true
loggedInUserRoles: responseJSON.roles
@save()
Backbone.trigger 'authenticateSuccess'
else
Backbone.trigger 'authenticateFail', responseJSON
onerror: (responseJSON) =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone taskId
ontimeout: =>
Backbone.trigger 'authenticateEnd'
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone taskId
)
localStorageKey: 'dativeApplicationSettings'
# An extremely simple re-implementation of `save`: we just JSON-ify the app
# settings and store them in localStorage.
save: ->
localStorage.setItem @localStorageKey,
JSON.stringify(@attributes)
# Fetching means simply getting the app settings JSON object from
# localStorage and setting it to the present model. Certain attributes are
# evaluated to other Backbone models; handling this conversion is the job
# of `backbonify`.
fetch: (options) ->
if localStorage.getItem @localStorageKey
applicationSettingsObject =
JSON.parse(localStorage.getItem(@localStorageKey))
applicationSettingsObject = @fix applicationSettingsObject
applicationSettingsObject = @backbonify applicationSettingsObject
@set applicationSettingsObject
@usingDefaults = false
else
@usingDefaults = true
@save()
# Fix the application settings, if necessary. This is necessary when Dative
# has been updated but the user's application settings object, as persisted
# in their `localStorage`, was built using an older version of Dative. If
# the app settings are out-of-date, then Dative may break.
# Note: `aso` is the Application Settings Object.
# The `ns` (namespace) param is good for debugging.
fix: (aso, defaults=null, ns='') ->
defaults = defaults or @defaults()
if 'attributes' of defaults
defaults = defaults.attributes
for attr, defval of defaults
if attr not of aso
aso[attr] = defval
# Recursively call `@fix` if the default val is an object.
else if ((@utils.type(defval) == 'object') and
not ((defval instanceof Backbone.Model) or
(defval instanceof Backbone.Collection)))
aso[attr] = @fix aso[attr], defval, "#{ns}.#{attr}"
for attr of aso
if attr not of defaults
delete aso[attr]
return aso
# Logout
#=========================================================================
logout: ->
if @get('activeServer')?.get('type') is 'FieldDB'
@logoutFieldDB()
else
@logoutOLD()
logoutOLD: ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'logout', taskId
Backbone.trigger 'logoutStart'
@constructor.cors.request(
url: "#{@getURL()}/login/logout"
method: 'GET'
timeout: 3000
onload: (responseJSON, xhr) =>
@authenticateAttemptDone taskId
Backbone.trigger 'logoutEnd'
if responseJSON.authenticated is false or
(xhr.status is 401 and
responseJSON.error is "Authentication is required to access this
resource.")
@set loggedIn: false, homepage: null
@save()
Backbone.trigger 'logoutSuccess'
else
Backbone.trigger 'logoutFail'
onerror: (responseJSON) =>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
Backbone.trigger 'logoutFail'
ontimeout: =>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
Backbone.trigger 'logoutFail', error: 'Request timed out'
)
logoutFieldDB: ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'logout', taskId
Backbone.trigger 'logoutStart'
if not @get 'fieldDBApplication'
@set 'fieldDBApplication', FieldDB.FieldDBObject.application
# TODO: @cesine: I'm getting "`authentication.logout` is not a function"
# errors here ...
@get('fieldDBApplication').authentication
.logout({letClientHandleCleanUp: 'dontReloadWeNeedToCleanUpInDativeClient'})
.then(
(responseJSON) =>
@set
fieldDBApplication: null
loggedIn: false
activeFieldDBCorpus: null
activeFieldDBCorpusTitle: null
@save()
Backbone.trigger 'logoutSuccess'
,
(reason) ->
Backbone.trigger 'logoutFail', reason.userFriendlyErrors.join ' '
).done(
=>
Backbone.trigger 'logoutEnd'
@authenticateAttemptDone taskId
)
# Check if logged in
#=========================================================================
# Check if we are already logged in.
checkIfLoggedIn: ->
if @get('activeServer')?.get('type') is 'FieldDB'
@checkIfLoggedInFieldDB()
else
@checkIfLoggedInOLD()
# Check with the OLD if we are logged in. We ask for the speakers. and
# trigger 'authenticateFail' if we can't get them.
checkIfLoggedInOLD: ->
taskId = @guid()
Backbone.trigger('longTask:register', 'checking if already logged in',
taskId)
@constructor.cors.request(
url: "#{@getURL()}/speakers"
timeout: 3000
onload: (responseJSON) =>
@authenticateAttemptDone(taskId)
if utils.type(responseJSON) is 'array'
@set 'loggedIn', true
@save()
Backbone.trigger 'authenticateSuccess'
else
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail'
onerror: (responseJSON) =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', responseJSON
@authenticateAttemptDone(taskId)
ontimeout: =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', error: 'Request timed out'
@authenticateAttemptDone(taskId)
)
checkIfLoggedInFieldDB: ->
taskId = @guid()
Backbone.trigger('longTask:register', 'checking if already logged in',
taskId)
FieldDB.Database::resumeAuthenticationSession().then(
(sessionInfo) =>
if sessionInfo.ok and sessionInfo.userCtx.name
@set 'loggedIn', true
@save()
Backbone.trigger 'authenticateSuccess'
else
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail'
,
(reason) =>
@set 'loggedIn', false
@save()
Backbone.trigger 'authenticateFail', reason
).done(=> @authenticateAttemptDone taskId)
# Register a new user
# =========================================================================
# `RegisterDialogView` should never allow an OLD registration attempt.
register: (params) ->
if @get('activeServer')?.get('type') is 'FieldDB'
@registerFieldDB params
registerFieldDB: (params) ->
taskId = @guid()
Backbone.trigger 'longTask:register', 'registering a new user', taskId
params.authUrl = @getURL()
params.appVersionWhenCreated = "v#{@get('version')}da"
@constructor.cors.request(
url: "#{@getURL()}/register"
payload: params
method: 'POST'
timeout: 10000 # FieldDB auth can take some time to register a new user ...
onload: (responseJSON) =>
@authenticateAttemptDone taskId
# TODO @cesine: what other kinds of responses to registration requests
# can the auth service make?
if responseJSON.user?
user = responseJSON.user
Backbone.trigger 'register:success', responseJSON
else
Backbone.trigger 'register:fail', responseJSON.userFriendlyErrors
onerror: (responseJSON) =>
@authenticateAttemptDone taskId
Backbone.trigger 'register:fail', 'server responded with error'
ontimeout: =>
@authenticateAttemptDone taskId
Backbone.trigger 'register:fail', 'Request timed out'
)
idAttribute: 'id'
# Transform certain attribute values of the `appSetObj`
# object into Backbone collections/models and return the `appSetObj`.
backbonify: (appSetObj) ->
serverModelsArray = ((new ServerModel(s)) for s in appSetObj.servers)
appSetObj.servers = new ServersCollection(serverModelsArray)
activeServer = appSetObj.activeServer
if activeServer
appSetObj.activeServer = appSetObj.servers.get activeServer.id
longRunningTasks = appSetObj.longRunningTasks
for task in appSetObj.longRunningTasks
task.resourceModel =
new @modelClassName2model[task.modelClassName](task.resourceModel)
for task in appSetObj.longRunningTasksTerminated
task.resourceModel =
new @modelClassName2model[task.modelClassName](task.resourceModel)
appSetObj.parserTaskSet = new ParserTaskSetModel(appSetObj.parserTaskSet)
appSetObj.keyboardPreferenceSet =
new KeyboardPreferenceSetModel(appSetObj.keyboardPreferenceSet)
appSetObj
############################################################################
# Defaults
############################################################################
defaults: ->
# Default servers are provided at runtime using servers.json
server =
new ServerModel
id: @guid()
name: 'OLD Local Development'
type: 'OLD'
url: 'http://127.0.0.1:5000'
serverCode: null
corpusServerURL: null
website: 'http://www.onlinelinguisticdatabase.org'
servers = new ServersCollection([server])
parserTaskSetModel = new ParserTaskSetModel()
keyboardPreferenceSetModel = new KeyboardPreferenceSetModel()
id: @guid()
activeServer: servers.at 0
loggedIn: false
loggedInUser: null
loggedInUserRoles: []
# An OLD will send an object representing the home page when a user
# successfully logs in, if there is such a page named 'home'.
homepage: null
baseDBURL: null
username: ''
# This gets set to `true` as soon as the user makes modifications to the
# list of servers. This allows us to avoid over-writing the
# user-specified servers with those supplied by Dative in servers.json.
serversModified: false
# This contains the array of objects contstituting the last set of
# servers that Dative has sent us. We use this to decide whether to
# prompt/annoy the user to merge these servers into their own.
lastSeenServersFromDative: null
servers: servers
# serverTypes: ['FieldDB', 'OLD']
serverTypes: ['OLD']
fieldDBServerCodes: [
'localhost'
'testing'
'beta'
'production'
'mcgill'
'concordia'
'dyslexdisorth'
]
# TODO: remove the activeFieldDBCorpusTitle and related attributes. We
# should simply store a real `CorpusModel` as the value of
# `activeFieldDBCorpus`. Note that `AppView` adds
# `activeFieldDBCorpusModel` and stores a Backbone model there. This all
# needs to be cleaned up.
activeFieldDBCorpus: null
activeFieldDBCorpusTitle: null
languagesDisplaySettings:
itemsPerPage: 100
dataLabelsVisible: true
allFormsExpanded: false
formsDisplaySettings:
itemsPerPage: 10
dataLabelsVisible: false
allFormsExpanded: false
subcorporaDisplaySettings:
itemsPerPage: 10
dataLabelsVisible: true
allSubcorporaExpanded: false
phonologiesDisplaySettings:
itemsPerPage: 1
dataLabelsVisible: true
allPhonologiesExpanded: false
morphologiesDisplaySettings:
itemsPerPage: 1
dataLabelsVisible: true
allMorphologiesExpanded: false
activeJQueryUITheme: 'pepper-grinder'
defaultJQueryUITheme: 'pepper-grinder'
jQueryUIThemes: [
['ui-lightness', 'UI lightness']
['ui-darkness', 'UI darkness']
['smoothness', 'Smoothness']
['start', 'Start']
['redmond', 'Redmond']
['sunny', 'Sunny']
['overcast', 'Overcast']
['le-frog', 'Le Frog']
['flick', 'Flick']
['pepper-grinder', 'Pepper Grinder']
['eggplant', 'Eggplant']
['dark-hive', 'Dark Hive']
['cupertino', 'Cupertino']
['south-street', 'South Street']
['blitzer', 'Blitzer']
['humanity', 'Humanity']
['hot-sneaks', 'Hot Sneaks']
['excite-bike', 'Excite Bike']
['vader', 'Vader']
['dot-luv', 'Dot Luv']
['mint-choc', 'Mint Choc']
['black-tie', 'Black Tie']
['trontastic', 'Trontastic']
['swanky-purse', 'Swanky Purse']
]
# Use this to limit how many "long-running" tasks can be initiated from
# within the app. A "long-running task" is a request to the server that
# requires polling to know when it has terminated, e.g., phonology
# compilation, morphology generation and compilation, etc.
# NOTE !IMPORTANT: the OLD has a single foma worker and all requests to
# compile FST-based resources appear to enter into a queue. This means
# that a 3s request made while a 1h request is ongoing will take 1h1s!
# Not good ...
longRunningTasksMax: 2
# An array of objects with keys `resourceName`, `taskName`,
# `taskStartTimestamp`, and `taskPreviousUUID`.
longRunningTasks: []
# An array of objects with keys `resourceName`, `taskName`,
# `taskStartTimestamp`, and `taskPreviousUUID`.
longRunningTasksTerminated: []
# IME types that can be uploaded (to an OLD server, at least).
# TODO: this should be expanded and/or made backend-specific.
allowedFileTypes: [
'application/pdf'
'image/gif'
'image/jpeg'
'image/png'
'audio/mpeg'
'audio/mp3'
'audio/ogg'
'audio/x-wav'
'audio/wav'
'video/mpeg'
'video/mp4'
'video/ogg'
'video/quicktime'
'video/x-ms-wmv'
]
version: 'da'
parserTaskSet: parserTaskSetModel
keyboardPreferenceSet: keyboardPreferenceSetModel
# This object contains metadata about Dative resources, i.e., forms,
# files, etc.
# TODO: resource display settings (e.g., `formsDisplaySettings` above)
# should be migrated here.
resources:
forms:
# Array of form attributes that are "sticky", i.e., that will stick
# around and whose values in the most recent add request will be the
# defaults for subsequent add requests.
stickyAttributes: []
# Array of form attributes that *may* be specified as "sticky".
possiblyStickyAttributes: [
'date_elicited'
'elicitation_method'
'elicitor'
'source'
'speaker'
'status'
'syntactic_category'
'tags'
]
# This will be populated by the resources collection upon successful
# add requests. It will map attribute names in `stickyAttributes`
# above to their values in the most recent successful add request.
pastValues: {}
# These objects define metadata on the fields of form resources.
# Note that there are separate metadata objects for OLD fields and
# for FieldDB fields.
fieldsMeta:
OLD:
grammaticality: [
'grammaticality'
]
# IGT OLD Form Attributes.
igt: [
'narrow_phonetic_transcription'
'phonetic_transcription'
'transcription'
'morpheme_break'
'morpheme_gloss'
]
# Note: this is currently not being used (just being consistent
# with the FieldDB `fieldsMeta` object below)
translation: [
'translations'
]
# Secondary OLD Form Attributes.
secondary: [
'syntactic_category_string'
'break_gloss_category'
'comments'
'speaker_comments'
'elicitation_method'
'tags'
'syntactic_category'
'date_elicited'
'speaker'
'elicitor'
'enterer'
'datetime_entered'
'modifier'
'datetime_modified'
'verifier'
'source'
'files'
#'collections' # Does the OLD provide the collections when the forms resource is fetched?
'syntax'
'semantics'
'status'
'UUID'
'id'
]
readonly: [
'syntactic_category_string'
'break_gloss_category'
'enterer'
'datetime_entered'
'modifier'
'datetime_modified'
'UUID'
'id'
]
# This array may contain the names of OLD form attributes that should
# be hidden. This is the (for now only client-side-stored) data
# structure that users manipulate in the settings widget of a
# `FormView` instance.
hidden: [
'narrow_phonetic_transcription'
'phonetic_transcription'
'verifier'
]
FieldDB:
# This is the set of form attributes that are considered by
# Dative to denote grammaticalities.
grammaticality: [
'judgement'
]
# IGT FieldDB form attributes.
# The returned array defines the "IGT" attributes of a FieldDB
# form (along with their order). These are those that are aligned
# into columns of one word each when displayed in an IGT view.
igt: [
'utterance'
'morphemes'
'gloss'
]
# This is the set of form attributes that are considered by
# Dative to denote a translation.
translation: [
'translation'
]
# Secondary FieldDB form attributes.
# The returned array defines the order of how the secondary
# attributes are displayed. It is defined in
# models/application-settings because it should ultimately be
# user-configurable.
# QUESTION: @cesine: how is the elicitor of a FieldDB
# datum/session documented?
# TODO: `audioVideo`, `images`
secondary: [
'syntacticCategory'
'comments'
'tags'
'dateElicited' # session field
'language' # session field
'dialect' # session field
'consultants' # session field
'enteredByUser'
'dateEntered'
'modifiedByUser'
'dateModified'
'syntacticTreeLatex'
'validationStatus'
'timestamp' # make this visible?
'id'
]
# These read-only fields will not be given input fields in
# add/update interfaces.
readonly: [
'enteredByUser'
'dateEntered'
'modifiedByUser'
'dateModified'
]
|
[
{
"context": "bject', ->\n t = TypeInfo(min: undefined, name:'Test')\n should.exist t\n t.should.be.equal TypeIn",
"end": 836,
"score": 0.530400812625885,
"start": 832,
"tag": "NAME",
"value": "Test"
},
{
"context": "eInfo('Test')\n t.should.have.property 'name', 'Test'\n it 'should create type info object directly', ",
"end": 1118,
"score": 0.5226017832756042,
"start": 1114,
"tag": "NAME",
"value": "Test"
},
{
"context": "m json', ->\n t = TypeInfo.fromJson('{\"name\":\"Test\"}')\n should.exist t\n t.should.be.equal ",
"end": 2261,
"score": 0.8762965202331543,
"start": 2257,
"tag": "NAME",
"value": "Test"
},
{
"context": "nfo('Test')\n t.should.have.property 'name', 'Test'\n it 'should create type info object from json",
"end": 2370,
"score": 0.8891370892524719,
"start": 2366,
"tag": "NAME",
"value": "Test"
},
{
"context": "m json', ->\n t = TypeInfo.fromJson('{\"name\":\"Test\",\"min\":2, \"max\":3}')\n should.exist t\n t",
"end": 2468,
"score": 0.9137822985649109,
"start": 2464,
"tag": "NAME",
"value": "Test"
},
{
"context": "ty 'min', 2\n t.should.have.property 'name', 'Test'\n it 'should create Value object from json', -",
"end": 2674,
"score": 0.9471893906593323,
"start": 2670,
"tag": "NAME",
"value": "Test"
},
{
"context": "m json', ->\n t = TypeInfo.fromJson('{\"name\":\"Test\",\"min\":2, \"max\":3, \"value\":3}')\n should.exis",
"end": 2768,
"score": 0.943999171257019,
"start": 2764,
"tag": "NAME",
"value": "Test"
},
{
"context": "tType\n t = TypeInfo.createFromJson('{\"name\":\"Test\",\"min\":1, \"max\":10}')\n should.exist t\n ",
"end": 3358,
"score": 0.913833737373352,
"start": 3354,
"tag": "NAME",
"value": "Test"
},
{
"context": " object from json', ->\n obj =\n name: 'Test'\n min:2\n max:6\n value:5\n ",
"end": 3649,
"score": 0.9992351531982422,
"start": 3645,
"tag": "NAME",
"value": "Test"
},
{
"context": "ect(result).to.be.deep.equal min:1, max:3, name: 'Test'\n\n it 'should export to a plain object', ->\n ",
"end": 4791,
"score": 0.9742462635040283,
"start": 4787,
"tag": "NAME",
"value": "Test"
},
{
"context": "ect(result).to.be.deep.equal min:1, max:3, name: 'Test', value:2\n describe '.toString', ->\n it 'shou",
"end": 5174,
"score": 0.6200308799743652,
"start": 5170,
"tag": "NAME",
"value": "Test"
}
] | test/index-test.coffee | snowyu/abstract-type.js | 0 | extend = require 'util-ex/lib/extend'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
TypeInfo = require '../src'
Value = require '../src/value'
Attributes = require '../src/attributes'
setImmediate = setImmediate || process.nextTick
register = TypeInfo.register
class TestType
constructor: ->return super
$attributes: Attributes
min:
type: 'Number'
max:
type: 'Number'
describe 'TypeInfo', ->
before ->
result = register TestType
result.should.be.true
after ->
TypeInfo.unregister 'Test'
it 'should get singleton type info object', ->
t = TypeInfo(min: undefined, name:'Test')
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', 'Test'
it 'should get type info object directly', ->
t = TestType(min: undefined)
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', 'Test'
it 'should create type info object directly', ->
t = TestType min:2
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.have.property 'min', 2
t.should.have.property 'name', 'Test'
it 'should change the name', ->
t = TestType min:2
t = t.createType name: 'abc'
should.exist t
expect(t).have.property 'name', 'abc'
describe '#create()', ->
it 'should create a new type object', ->
t = TypeInfo.create 'Test'
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.be.instanceOf TestType
t.should.have.property 'name', 'Test'
describe '.pathArray()', ->
it 'should get default type path array', ->
t = TypeInfo('Test')
t.pathArray().should.be.deep.equal ['type','Test']
it 'should get cutomize root type path array', ->
old = TypeInfo.ROOT_NAME
TypeInfo.ROOT_NAME = 'atype'
t = TypeInfo('Test')
t.pathArray().should.be.deep.equal ['atype','Test']
TypeInfo.ROOT_NAME = old
describe '.fromJson()', ->
it 'should get type info object from json', ->
t = TypeInfo.fromJson('{"name":"Test"}')
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', 'Test'
it 'should create type info object from json', ->
t = TypeInfo.fromJson('{"name":"Test","min":2, "max":3}')
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.have.property 'max', 3
t.should.have.property 'min', 2
t.should.have.property 'name', 'Test'
it 'should create Value object from json', ->
t = TypeInfo.fromJson('{"name":"Test","min":2, "max":3, "value":3}')
should.exist t
t.should.be.instanceOf Value
vType = t.$type
vType.should.be.instanceOf TestType
vType.should.be.not.equal TypeInfo('Test')
vType.should.have.property 'max', 3
vType.should.have.property 'min', 2
(''+t).should.be.equal '3'
(t + 3).should.be.equal 6
describe '.createFromJson()', ->
it 'should create a new type info object from json', ->
T = TypeInfo.registeredClass 'Test'
should.exist T
T.should.be.equal TestType
t = TypeInfo.createFromJson('{"name":"Test","min":1, "max":10}')
should.exist t
t.should.be.instanceOf TestType
t.should.not.be.equal TypeInfo('Test')
t.should.have.property 'max', 10
t.should.have.property 'min', 1
it 'should create a new value object from json', ->
obj =
name: 'Test'
min:2
max:6
value:5
t = TypeInfo.createFromJson JSON.stringify obj
should.exist t
t.should.be.instanceOf Value
vType = t.$type
vType.should.be.instanceOf TestType
vType.should.not.be.equal TypeInfo('Test')
vType.should.have.property 'max', 6
vType.should.have.property 'min', 2
(''+t).should.be.equal '5'
(t + 3).should.be.equal 8
describe '.validate', ->
it 'should validate required value', ->
validator = TypeInfo('Test').createType required: true
result = validator.validate null, false
result.should.be.equal false
validator.errors.should.be.deep.equal [{'message': 'is required','name': '[type Test]'}]
it 'should validate required value and throw error', ->
validator = TypeInfo('Test').createType required: true
should.throw validator.validate.bind(validator, null), 'is an invalid'
describe '.toObject', ->
it 'should export to a plain object with name', ->
t = TestType::createType(min:1, max:3)
result = t.toObject()
expect(result).to.be.deep.equal min:1, max:3, name: 'Test'
it 'should export to a plain object', ->
t = TestType::createType(min:1, max:3)
result = t.toObject(null, false)
expect(result).to.be.deep.equal min:1, max:3
it 'should export to a plain object with value', ->
t = TestType::createType(min:1, max:3)
result = t.toObject(value:2)
expect(result).to.be.deep.equal min:1, max:3, name: 'Test', value:2
describe '.toString', ->
it 'should be to string', ->
t = TestType()
result = t.toString()
expect(result).to.be.equal '[type Test]'
describe '.cloneType', ->
it 'should clone type', ->
t = TestType::createType(min:1, max:3)
result = t.cloneType()
expect(t.isSame result).to.be.true
describe '.inspect', ->
it 'should inspect', ->
t = TestType::createType(min:1, max:3)
result = t.inspect()
expect(result).to.be.equal '<type "Test": "min":1,"max":3>'
| 104687 | extend = require 'util-ex/lib/extend'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
TypeInfo = require '../src'
Value = require '../src/value'
Attributes = require '../src/attributes'
setImmediate = setImmediate || process.nextTick
register = TypeInfo.register
class TestType
constructor: ->return super
$attributes: Attributes
min:
type: 'Number'
max:
type: 'Number'
describe 'TypeInfo', ->
before ->
result = register TestType
result.should.be.true
after ->
TypeInfo.unregister 'Test'
it 'should get singleton type info object', ->
t = TypeInfo(min: undefined, name:'<NAME>')
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', 'Test'
it 'should get type info object directly', ->
t = TestType(min: undefined)
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', '<NAME>'
it 'should create type info object directly', ->
t = TestType min:2
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.have.property 'min', 2
t.should.have.property 'name', 'Test'
it 'should change the name', ->
t = TestType min:2
t = t.createType name: 'abc'
should.exist t
expect(t).have.property 'name', 'abc'
describe '#create()', ->
it 'should create a new type object', ->
t = TypeInfo.create 'Test'
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.be.instanceOf TestType
t.should.have.property 'name', 'Test'
describe '.pathArray()', ->
it 'should get default type path array', ->
t = TypeInfo('Test')
t.pathArray().should.be.deep.equal ['type','Test']
it 'should get cutomize root type path array', ->
old = TypeInfo.ROOT_NAME
TypeInfo.ROOT_NAME = 'atype'
t = TypeInfo('Test')
t.pathArray().should.be.deep.equal ['atype','Test']
TypeInfo.ROOT_NAME = old
describe '.fromJson()', ->
it 'should get type info object from json', ->
t = TypeInfo.fromJson('{"name":"<NAME>"}')
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', '<NAME>'
it 'should create type info object from json', ->
t = TypeInfo.fromJson('{"name":"<NAME>","min":2, "max":3}')
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.have.property 'max', 3
t.should.have.property 'min', 2
t.should.have.property 'name', '<NAME>'
it 'should create Value object from json', ->
t = TypeInfo.fromJson('{"name":"<NAME>","min":2, "max":3, "value":3}')
should.exist t
t.should.be.instanceOf Value
vType = t.$type
vType.should.be.instanceOf TestType
vType.should.be.not.equal TypeInfo('Test')
vType.should.have.property 'max', 3
vType.should.have.property 'min', 2
(''+t).should.be.equal '3'
(t + 3).should.be.equal 6
describe '.createFromJson()', ->
it 'should create a new type info object from json', ->
T = TypeInfo.registeredClass 'Test'
should.exist T
T.should.be.equal TestType
t = TypeInfo.createFromJson('{"name":"<NAME>","min":1, "max":10}')
should.exist t
t.should.be.instanceOf TestType
t.should.not.be.equal TypeInfo('Test')
t.should.have.property 'max', 10
t.should.have.property 'min', 1
it 'should create a new value object from json', ->
obj =
name: '<NAME>'
min:2
max:6
value:5
t = TypeInfo.createFromJson JSON.stringify obj
should.exist t
t.should.be.instanceOf Value
vType = t.$type
vType.should.be.instanceOf TestType
vType.should.not.be.equal TypeInfo('Test')
vType.should.have.property 'max', 6
vType.should.have.property 'min', 2
(''+t).should.be.equal '5'
(t + 3).should.be.equal 8
describe '.validate', ->
it 'should validate required value', ->
validator = TypeInfo('Test').createType required: true
result = validator.validate null, false
result.should.be.equal false
validator.errors.should.be.deep.equal [{'message': 'is required','name': '[type Test]'}]
it 'should validate required value and throw error', ->
validator = TypeInfo('Test').createType required: true
should.throw validator.validate.bind(validator, null), 'is an invalid'
describe '.toObject', ->
it 'should export to a plain object with name', ->
t = TestType::createType(min:1, max:3)
result = t.toObject()
expect(result).to.be.deep.equal min:1, max:3, name: '<NAME>'
it 'should export to a plain object', ->
t = TestType::createType(min:1, max:3)
result = t.toObject(null, false)
expect(result).to.be.deep.equal min:1, max:3
it 'should export to a plain object with value', ->
t = TestType::createType(min:1, max:3)
result = t.toObject(value:2)
expect(result).to.be.deep.equal min:1, max:3, name: '<NAME>', value:2
describe '.toString', ->
it 'should be to string', ->
t = TestType()
result = t.toString()
expect(result).to.be.equal '[type Test]'
describe '.cloneType', ->
it 'should clone type', ->
t = TestType::createType(min:1, max:3)
result = t.cloneType()
expect(t.isSame result).to.be.true
describe '.inspect', ->
it 'should inspect', ->
t = TestType::createType(min:1, max:3)
result = t.inspect()
expect(result).to.be.equal '<type "Test": "min":1,"max":3>'
| true | extend = require 'util-ex/lib/extend'
chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
should = chai.should()
expect = chai.expect
assert = chai.assert
chai.use(sinonChai)
TypeInfo = require '../src'
Value = require '../src/value'
Attributes = require '../src/attributes'
setImmediate = setImmediate || process.nextTick
register = TypeInfo.register
class TestType
constructor: ->return super
$attributes: Attributes
min:
type: 'Number'
max:
type: 'Number'
describe 'TypeInfo', ->
before ->
result = register TestType
result.should.be.true
after ->
TypeInfo.unregister 'Test'
it 'should get singleton type info object', ->
t = TypeInfo(min: undefined, name:'PI:NAME:<NAME>END_PI')
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', 'Test'
it 'should get type info object directly', ->
t = TestType(min: undefined)
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', 'PI:NAME:<NAME>END_PI'
it 'should create type info object directly', ->
t = TestType min:2
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.have.property 'min', 2
t.should.have.property 'name', 'Test'
it 'should change the name', ->
t = TestType min:2
t = t.createType name: 'abc'
should.exist t
expect(t).have.property 'name', 'abc'
describe '#create()', ->
it 'should create a new type object', ->
t = TypeInfo.create 'Test'
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.be.instanceOf TestType
t.should.have.property 'name', 'Test'
describe '.pathArray()', ->
it 'should get default type path array', ->
t = TypeInfo('Test')
t.pathArray().should.be.deep.equal ['type','Test']
it 'should get cutomize root type path array', ->
old = TypeInfo.ROOT_NAME
TypeInfo.ROOT_NAME = 'atype'
t = TypeInfo('Test')
t.pathArray().should.be.deep.equal ['atype','Test']
TypeInfo.ROOT_NAME = old
describe '.fromJson()', ->
it 'should get type info object from json', ->
t = TypeInfo.fromJson('{"name":"PI:NAME:<NAME>END_PI"}')
should.exist t
t.should.be.equal TypeInfo('Test')
t.should.have.property 'name', 'PI:NAME:<NAME>END_PI'
it 'should create type info object from json', ->
t = TypeInfo.fromJson('{"name":"PI:NAME:<NAME>END_PI","min":2, "max":3}')
should.exist t
t.should.be.not.equal TypeInfo('Test')
t.should.have.property 'max', 3
t.should.have.property 'min', 2
t.should.have.property 'name', 'PI:NAME:<NAME>END_PI'
it 'should create Value object from json', ->
t = TypeInfo.fromJson('{"name":"PI:NAME:<NAME>END_PI","min":2, "max":3, "value":3}')
should.exist t
t.should.be.instanceOf Value
vType = t.$type
vType.should.be.instanceOf TestType
vType.should.be.not.equal TypeInfo('Test')
vType.should.have.property 'max', 3
vType.should.have.property 'min', 2
(''+t).should.be.equal '3'
(t + 3).should.be.equal 6
describe '.createFromJson()', ->
it 'should create a new type info object from json', ->
T = TypeInfo.registeredClass 'Test'
should.exist T
T.should.be.equal TestType
t = TypeInfo.createFromJson('{"name":"PI:NAME:<NAME>END_PI","min":1, "max":10}')
should.exist t
t.should.be.instanceOf TestType
t.should.not.be.equal TypeInfo('Test')
t.should.have.property 'max', 10
t.should.have.property 'min', 1
it 'should create a new value object from json', ->
obj =
name: 'PI:NAME:<NAME>END_PI'
min:2
max:6
value:5
t = TypeInfo.createFromJson JSON.stringify obj
should.exist t
t.should.be.instanceOf Value
vType = t.$type
vType.should.be.instanceOf TestType
vType.should.not.be.equal TypeInfo('Test')
vType.should.have.property 'max', 6
vType.should.have.property 'min', 2
(''+t).should.be.equal '5'
(t + 3).should.be.equal 8
describe '.validate', ->
it 'should validate required value', ->
validator = TypeInfo('Test').createType required: true
result = validator.validate null, false
result.should.be.equal false
validator.errors.should.be.deep.equal [{'message': 'is required','name': '[type Test]'}]
it 'should validate required value and throw error', ->
validator = TypeInfo('Test').createType required: true
should.throw validator.validate.bind(validator, null), 'is an invalid'
describe '.toObject', ->
it 'should export to a plain object with name', ->
t = TestType::createType(min:1, max:3)
result = t.toObject()
expect(result).to.be.deep.equal min:1, max:3, name: 'PI:NAME:<NAME>END_PI'
it 'should export to a plain object', ->
t = TestType::createType(min:1, max:3)
result = t.toObject(null, false)
expect(result).to.be.deep.equal min:1, max:3
it 'should export to a plain object with value', ->
t = TestType::createType(min:1, max:3)
result = t.toObject(value:2)
expect(result).to.be.deep.equal min:1, max:3, name: 'PI:NAME:<NAME>END_PI', value:2
describe '.toString', ->
it 'should be to string', ->
t = TestType()
result = t.toString()
expect(result).to.be.equal '[type Test]'
describe '.cloneType', ->
it 'should clone type', ->
t = TestType::createType(min:1, max:3)
result = t.cloneType()
expect(t.isSame result).to.be.true
describe '.inspect', ->
it 'should inspect', ->
t = TestType::createType(min:1, max:3)
result = t.inspect()
expect(result).to.be.equal '<type "Test": "min":1,"max":3>'
|
[
{
"context": "ream. Use at your own risk!\n@version 0.0.2\n@author Se7enSky studio <info@se7ensky.com>\n###\n\n###! jquery",
"end": 129,
"score": 0.5366671085357666,
"start": 127,
"tag": "USERNAME",
"value": "Se"
},
{
"context": "own risk!\n@version 0.0.2\n@author Se7enSky studio <info@se7ensky.com>\n###\n\n###! jquery-bulb 0.0.2 http://github.com/Se",
"end": 161,
"score": 0.9999245405197144,
"start": 144,
"tag": "EMAIL",
"value": "info@se7ensky.com"
},
{
"context": "om>\n###\n\n###! jquery-bulb 0.0.2 http://github.com/Se7enSky/jquery-bulb###\n\nplugin = ($) ->\n\n\t\"use strict\"\n\n\t",
"end": 217,
"score": 0.9960271120071411,
"start": 209,
"tag": "USERNAME",
"value": "Se7enSky"
}
] | jquery-bulb.coffee | SE7ENSKY/jquery-bulb | 2 | ###
@name jquery-bulb
@description Slice/split DOM. Decouple element from stream. Use at your own risk!
@version 0.0.2
@author Se7enSky studio <info@se7ensky.com>
###
###! jquery-bulb 0.0.2 http://github.com/Se7enSky/jquery-bulb###
plugin = ($) ->
"use strict"
bulb = ($el) ->
$parent = $el.parent()
$parentClone = $parent.clone().empty()
$el.nextAll().appendTo $parentClone
$parentClone.insertAfter $parent
$el.insertAfter $parent
$parent.remove() if $parent.children().length is 0
$.fn.bulb = (selector, parent = yes) ->
@each ->
if selector? and $(@).closest(selector).length isnt 0
bulb $(@) while not $(@).parent().is selector
bulb $(@) if parent
@
# UMD
if typeof define is 'function' and define.amd # AMD
define(['jquery'], plugin)
else # browser globals
plugin(jQuery) | 209432 | ###
@name jquery-bulb
@description Slice/split DOM. Decouple element from stream. Use at your own risk!
@version 0.0.2
@author Se7enSky studio <<EMAIL>>
###
###! jquery-bulb 0.0.2 http://github.com/Se7enSky/jquery-bulb###
plugin = ($) ->
"use strict"
bulb = ($el) ->
$parent = $el.parent()
$parentClone = $parent.clone().empty()
$el.nextAll().appendTo $parentClone
$parentClone.insertAfter $parent
$el.insertAfter $parent
$parent.remove() if $parent.children().length is 0
$.fn.bulb = (selector, parent = yes) ->
@each ->
if selector? and $(@).closest(selector).length isnt 0
bulb $(@) while not $(@).parent().is selector
bulb $(@) if parent
@
# UMD
if typeof define is 'function' and define.amd # AMD
define(['jquery'], plugin)
else # browser globals
plugin(jQuery) | true | ###
@name jquery-bulb
@description Slice/split DOM. Decouple element from stream. Use at your own risk!
@version 0.0.2
@author Se7enSky studio <PI:EMAIL:<EMAIL>END_PI>
###
###! jquery-bulb 0.0.2 http://github.com/Se7enSky/jquery-bulb###
plugin = ($) ->
"use strict"
bulb = ($el) ->
$parent = $el.parent()
$parentClone = $parent.clone().empty()
$el.nextAll().appendTo $parentClone
$parentClone.insertAfter $parent
$el.insertAfter $parent
$parent.remove() if $parent.children().length is 0
$.fn.bulb = (selector, parent = yes) ->
@each ->
if selector? and $(@).closest(selector).length isnt 0
bulb $(@) while not $(@).parent().is selector
bulb $(@) if parent
@
# UMD
if typeof define is 'function' and define.amd # AMD
define(['jquery'], plugin)
else # browser globals
plugin(jQuery) |
[
{
"context": "gramming for microcontrollers\n# Copyright (c) 2018 Jon Nordby <jononor@gmail.com>\n# MicroFlo may be freely dist",
"end": 90,
"score": 0.9998380541801453,
"start": 80,
"tag": "NAME",
"value": "Jon Nordby"
},
{
"context": "microcontrollers\n# Copyright (c) 2018 Jon Nordby <jononor@gmail.com>\n# MicroFlo may be freely distributed under the M",
"end": 109,
"score": 0.9999328851699829,
"start": 92,
"tag": "EMAIL",
"value": "jononor@gmail.com"
}
] | test/devicecommunication.coffee | microflo/microflo | 136 | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2018 Jon Nordby <jononor@gmail.com>
# MicroFlo may be freely distributed under the MIT license
###
chai = require('chai')
devicecommunication = require('../lib/devicecommunication')
{ DeviceTransport, DeviceCommunication } = devicecommunication
commandstream = require('../lib/commandstream')
cmdFormat = commandstream.cmdFormat
class FakeTransport extends DeviceTransport
constructor: () ->
super()
@requests = []
@responses = []
@onRequest = null
getTransportType: () ->
return 'fake'
write: (buffer, callback) ->
@requests.push buffer
@onRequest buffer if @onRequest
return callback null
fromDevice: (buffer) ->
@emit 'data', buffer
openResp = (request) ->
magic = request.slice(0, -1).toString('utf-8')
if magic == cmdFormat.magicString
requestId = request.readUInt8 cmdFormat.commandSize-1
response = Buffer.alloc(cmdFormat.commandSize)
response.fill 0
response.writeUInt8 requestId, 0
response.writeUInt8 cmdFormat.commands.CommunicationOpen.id, 1
return response
pingResponse = (request) ->
requestId = request.readUInt8 0
type = request.readUInt8 1
response = Buffer.from request
if type == cmdFormat.commands.Ping.id
response.writeUInt8 cmdFormat.commands.Pong.id, 1
return response
clearResponse = (request) ->
requestId = request.readUInt8 0
type = request.readUInt8 1
response = Buffer.from request
if type == cmdFormat.commands.ClearNodes.id
#response.fill 0
response.writeUInt8 requestId, 0
response.writeUInt8 cmdFormat.commands.NodesCleared.id, 1
return response
describe 'DeviceCommunication', ->
transport = null
device = null
beforeEach ->
transport = new FakeTransport
device = new DeviceCommunication transport, { timeout: 50 }
transport.onRequest = null
return
afterEach ->
return
describe 'open()', ->
describe 'without response', ->
it 'should give timeout', () ->
device.open().catch (err) ->
chai.expect(err.message).to.contain 'did not respond'
describe 'with success', ->
it 'should return response', () ->
transport.onRequest = (request) ->
r = openResp request
transport.fromDevice r
return device.open()
describe 'ping()', ->
it 'should return pong', () ->
transport.onRequest = (request) ->
r = openResp request
r = pingResponse(request) if not r
transport.fromDevice r
device.open().then (res) ->
return device.ping()
describe 'sendCommands', ->
describe 'with one command', ->
it 'should return responses', (done) ->
transport.onRequest = (request) ->
r = openResp request
r = clearResponse(request) if not r
transport.fromDevice r
req = Buffer.alloc cmdFormat.commandSize
commandstream.commands.graph.clear {}, req, 0
device.open().then (res) ->
device.sendCommands req, (err, res) ->
chai.expect(err).to.be.null
chai.expect(res).to.have.length 1
return done()
.catch done
return null
describe 'with multiple commands', ->
it 'should return responses', (done) ->
transport.onRequest = (request) ->
r = openResp request
r = clearResponse(request) if not r
r = pingResponse(request) if not r
chai.expect(r).to.exist
transport.fromDevice r
messages = [
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
]
buffer = Buffer.alloc cmdFormat.commandSize*messages.length
index = 0
for m in messages
index = commandstream.toCommandStreamBuffer m, null, {}, {}, buffer, index
device.open().then () ->
device.sendCommands buffer, (err, res) ->
chai.expect(err).to.be.null
return done()
.catch done
return null
describe 'with timeout', ->
it 'should return error', (done) ->
transport.onRequest = (request) ->
r = openResp request
if r
transport.fromDevice r
r = clearResponse(request) if not r
r = pingResponse(request) if not r
chai.expect(r).to.exist
#transport.fromDevice r # cause timeout
messages = [
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
]
buffer = Buffer.alloc cmdFormat.commandSize*messages.length
index = 0
for m in messages
index = commandstream.toCommandStreamBuffer m, null, {}, {}, buffer, index
device.open().then () ->
device.sendCommands buffer, (err, res) ->
chai.expect(err).to.exist
chai.expect(err.message).to.include 'did not respond'
return done()
.catch done
return null
describe 'with error', ->
it 'should return error'
| 119787 | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2018 <NAME> <<EMAIL>>
# MicroFlo may be freely distributed under the MIT license
###
chai = require('chai')
devicecommunication = require('../lib/devicecommunication')
{ DeviceTransport, DeviceCommunication } = devicecommunication
commandstream = require('../lib/commandstream')
cmdFormat = commandstream.cmdFormat
class FakeTransport extends DeviceTransport
constructor: () ->
super()
@requests = []
@responses = []
@onRequest = null
getTransportType: () ->
return 'fake'
write: (buffer, callback) ->
@requests.push buffer
@onRequest buffer if @onRequest
return callback null
fromDevice: (buffer) ->
@emit 'data', buffer
openResp = (request) ->
magic = request.slice(0, -1).toString('utf-8')
if magic == cmdFormat.magicString
requestId = request.readUInt8 cmdFormat.commandSize-1
response = Buffer.alloc(cmdFormat.commandSize)
response.fill 0
response.writeUInt8 requestId, 0
response.writeUInt8 cmdFormat.commands.CommunicationOpen.id, 1
return response
pingResponse = (request) ->
requestId = request.readUInt8 0
type = request.readUInt8 1
response = Buffer.from request
if type == cmdFormat.commands.Ping.id
response.writeUInt8 cmdFormat.commands.Pong.id, 1
return response
clearResponse = (request) ->
requestId = request.readUInt8 0
type = request.readUInt8 1
response = Buffer.from request
if type == cmdFormat.commands.ClearNodes.id
#response.fill 0
response.writeUInt8 requestId, 0
response.writeUInt8 cmdFormat.commands.NodesCleared.id, 1
return response
describe 'DeviceCommunication', ->
transport = null
device = null
beforeEach ->
transport = new FakeTransport
device = new DeviceCommunication transport, { timeout: 50 }
transport.onRequest = null
return
afterEach ->
return
describe 'open()', ->
describe 'without response', ->
it 'should give timeout', () ->
device.open().catch (err) ->
chai.expect(err.message).to.contain 'did not respond'
describe 'with success', ->
it 'should return response', () ->
transport.onRequest = (request) ->
r = openResp request
transport.fromDevice r
return device.open()
describe 'ping()', ->
it 'should return pong', () ->
transport.onRequest = (request) ->
r = openResp request
r = pingResponse(request) if not r
transport.fromDevice r
device.open().then (res) ->
return device.ping()
describe 'sendCommands', ->
describe 'with one command', ->
it 'should return responses', (done) ->
transport.onRequest = (request) ->
r = openResp request
r = clearResponse(request) if not r
transport.fromDevice r
req = Buffer.alloc cmdFormat.commandSize
commandstream.commands.graph.clear {}, req, 0
device.open().then (res) ->
device.sendCommands req, (err, res) ->
chai.expect(err).to.be.null
chai.expect(res).to.have.length 1
return done()
.catch done
return null
describe 'with multiple commands', ->
it 'should return responses', (done) ->
transport.onRequest = (request) ->
r = openResp request
r = clearResponse(request) if not r
r = pingResponse(request) if not r
chai.expect(r).to.exist
transport.fromDevice r
messages = [
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
]
buffer = Buffer.alloc cmdFormat.commandSize*messages.length
index = 0
for m in messages
index = commandstream.toCommandStreamBuffer m, null, {}, {}, buffer, index
device.open().then () ->
device.sendCommands buffer, (err, res) ->
chai.expect(err).to.be.null
return done()
.catch done
return null
describe 'with timeout', ->
it 'should return error', (done) ->
transport.onRequest = (request) ->
r = openResp request
if r
transport.fromDevice r
r = clearResponse(request) if not r
r = pingResponse(request) if not r
chai.expect(r).to.exist
#transport.fromDevice r # cause timeout
messages = [
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
]
buffer = Buffer.alloc cmdFormat.commandSize*messages.length
index = 0
for m in messages
index = commandstream.toCommandStreamBuffer m, null, {}, {}, buffer, index
device.open().then () ->
device.sendCommands buffer, (err, res) ->
chai.expect(err).to.exist
chai.expect(err.message).to.include 'did not respond'
return done()
.catch done
return null
describe 'with error', ->
it 'should return error'
| true | ### MicroFlo - Flow-Based Programming for microcontrollers
# Copyright (c) 2018 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# MicroFlo may be freely distributed under the MIT license
###
chai = require('chai')
devicecommunication = require('../lib/devicecommunication')
{ DeviceTransport, DeviceCommunication } = devicecommunication
commandstream = require('../lib/commandstream')
cmdFormat = commandstream.cmdFormat
class FakeTransport extends DeviceTransport
constructor: () ->
super()
@requests = []
@responses = []
@onRequest = null
getTransportType: () ->
return 'fake'
write: (buffer, callback) ->
@requests.push buffer
@onRequest buffer if @onRequest
return callback null
fromDevice: (buffer) ->
@emit 'data', buffer
openResp = (request) ->
magic = request.slice(0, -1).toString('utf-8')
if magic == cmdFormat.magicString
requestId = request.readUInt8 cmdFormat.commandSize-1
response = Buffer.alloc(cmdFormat.commandSize)
response.fill 0
response.writeUInt8 requestId, 0
response.writeUInt8 cmdFormat.commands.CommunicationOpen.id, 1
return response
pingResponse = (request) ->
requestId = request.readUInt8 0
type = request.readUInt8 1
response = Buffer.from request
if type == cmdFormat.commands.Ping.id
response.writeUInt8 cmdFormat.commands.Pong.id, 1
return response
clearResponse = (request) ->
requestId = request.readUInt8 0
type = request.readUInt8 1
response = Buffer.from request
if type == cmdFormat.commands.ClearNodes.id
#response.fill 0
response.writeUInt8 requestId, 0
response.writeUInt8 cmdFormat.commands.NodesCleared.id, 1
return response
describe 'DeviceCommunication', ->
transport = null
device = null
beforeEach ->
transport = new FakeTransport
device = new DeviceCommunication transport, { timeout: 50 }
transport.onRequest = null
return
afterEach ->
return
describe 'open()', ->
describe 'without response', ->
it 'should give timeout', () ->
device.open().catch (err) ->
chai.expect(err.message).to.contain 'did not respond'
describe 'with success', ->
it 'should return response', () ->
transport.onRequest = (request) ->
r = openResp request
transport.fromDevice r
return device.open()
describe 'ping()', ->
it 'should return pong', () ->
transport.onRequest = (request) ->
r = openResp request
r = pingResponse(request) if not r
transport.fromDevice r
device.open().then (res) ->
return device.ping()
describe 'sendCommands', ->
describe 'with one command', ->
it 'should return responses', (done) ->
transport.onRequest = (request) ->
r = openResp request
r = clearResponse(request) if not r
transport.fromDevice r
req = Buffer.alloc cmdFormat.commandSize
commandstream.commands.graph.clear {}, req, 0
device.open().then (res) ->
device.sendCommands req, (err, res) ->
chai.expect(err).to.be.null
chai.expect(res).to.have.length 1
return done()
.catch done
return null
describe 'with multiple commands', ->
it 'should return responses', (done) ->
transport.onRequest = (request) ->
r = openResp request
r = clearResponse(request) if not r
r = pingResponse(request) if not r
chai.expect(r).to.exist
transport.fromDevice r
messages = [
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
]
buffer = Buffer.alloc cmdFormat.commandSize*messages.length
index = 0
for m in messages
index = commandstream.toCommandStreamBuffer m, null, {}, {}, buffer, index
device.open().then () ->
device.sendCommands buffer, (err, res) ->
chai.expect(err).to.be.null
return done()
.catch done
return null
describe 'with timeout', ->
it 'should return error', (done) ->
transport.onRequest = (request) ->
r = openResp request
if r
transport.fromDevice r
r = clearResponse(request) if not r
r = pingResponse(request) if not r
chai.expect(r).to.exist
#transport.fromDevice r # cause timeout
messages = [
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
{ protocol: 'graph', command: 'clear', payload: {} }
{ protocol: 'microflo', command: 'ping', payload: {} }
]
buffer = Buffer.alloc cmdFormat.commandSize*messages.length
index = 0
for m in messages
index = commandstream.toCommandStreamBuffer m, null, {}, {}, buffer, index
device.open().then () ->
device.sendCommands buffer, (err, res) ->
chai.expect(err).to.exist
chai.expect(err.message).to.include 'did not respond'
return done()
.catch done
return null
describe 'with error', ->
it 'should return error'
|
[
{
"context": "# Try POH\n# author: Leonardone @ NEETSDKASU\n# ==================================",
"end": 30,
"score": 0.9995328783988953,
"start": 20,
"tag": "NAME",
"value": "Leonardone"
},
{
"context": "# Try POH\n# author: Leonardone @ NEETSDKASU\n# ===============================================",
"end": 43,
"score": 0.7335941195487976,
"start": 33,
"tag": "USERNAME",
"value": "NEETSDKASU"
}
] | POH8/Seifuku/Main.coffee | neetsdkasu/Paiza-POH-MyAnswers | 3 | # Try POH
# author: Leonardone @ NEETSDKASU
# ===================================================
solve = (mr) ->
c = mr.gss().map (x) -> switch x
when 'J' then 11
when 'Q' then 12
when 'K' then 13
when 'A' then 14
when '2' then 15
else parseInt x
r = (0 for _ in [0...52])
k = 1
j = -1
t = 0
while k < 53
for i in [0...52]
if i is j
t = 0
j = -1
continue if r[i] > 0
if t < c[i]
r[i] = k
t = c[i]
j = i
k++
console.log r.join '\n'
# ===================================================
(() ->
buf = ''
process.stdin.setEncoding 'utf8'
process.stdin.on 'data', (data) -> buf += data.toString()
process.stdin.on 'end', () ->
lines = buf.split '\n'
cur = 0
gs = -> lines[cur++]
gi = -> parseInt gs()
gss = -> gs().split ' '
gis = -> gss().map (x) -> parseInt x
ngt = (n, f) -> f() for _ in [1..n]
ngs = (n) -> ngt n, gs
ngi = (n) -> ngt n, gi
ngss = (n) -> ngt n, gss
ngis = (n) -> ngt n, gis
solve "gs": gs, "gi": gi, "gss": gss, "gis": gis, "ngs": ngs, "ngi": ngi, "ngss": ngss, "ngis": ngis
)()
# ===================================================
| 69839 | # Try POH
# author: <NAME> @ NEETSDKASU
# ===================================================
solve = (mr) ->
c = mr.gss().map (x) -> switch x
when 'J' then 11
when 'Q' then 12
when 'K' then 13
when 'A' then 14
when '2' then 15
else parseInt x
r = (0 for _ in [0...52])
k = 1
j = -1
t = 0
while k < 53
for i in [0...52]
if i is j
t = 0
j = -1
continue if r[i] > 0
if t < c[i]
r[i] = k
t = c[i]
j = i
k++
console.log r.join '\n'
# ===================================================
(() ->
buf = ''
process.stdin.setEncoding 'utf8'
process.stdin.on 'data', (data) -> buf += data.toString()
process.stdin.on 'end', () ->
lines = buf.split '\n'
cur = 0
gs = -> lines[cur++]
gi = -> parseInt gs()
gss = -> gs().split ' '
gis = -> gss().map (x) -> parseInt x
ngt = (n, f) -> f() for _ in [1..n]
ngs = (n) -> ngt n, gs
ngi = (n) -> ngt n, gi
ngss = (n) -> ngt n, gss
ngis = (n) -> ngt n, gis
solve "gs": gs, "gi": gi, "gss": gss, "gis": gis, "ngs": ngs, "ngi": ngi, "ngss": ngss, "ngis": ngis
)()
# ===================================================
| true | # Try POH
# author: PI:NAME:<NAME>END_PI @ NEETSDKASU
# ===================================================
solve = (mr) ->
c = mr.gss().map (x) -> switch x
when 'J' then 11
when 'Q' then 12
when 'K' then 13
when 'A' then 14
when '2' then 15
else parseInt x
r = (0 for _ in [0...52])
k = 1
j = -1
t = 0
while k < 53
for i in [0...52]
if i is j
t = 0
j = -1
continue if r[i] > 0
if t < c[i]
r[i] = k
t = c[i]
j = i
k++
console.log r.join '\n'
# ===================================================
(() ->
buf = ''
process.stdin.setEncoding 'utf8'
process.stdin.on 'data', (data) -> buf += data.toString()
process.stdin.on 'end', () ->
lines = buf.split '\n'
cur = 0
gs = -> lines[cur++]
gi = -> parseInt gs()
gss = -> gs().split ' '
gis = -> gss().map (x) -> parseInt x
ngt = (n, f) -> f() for _ in [1..n]
ngs = (n) -> ngt n, gs
ngi = (n) -> ngt n, gi
ngss = (n) -> ngt n, gss
ngis = (n) -> ngt n, gis
solve "gs": gs, "gi": gi, "gss": gss, "gis": gis, "ngs": ngs, "ngi": ngi, "ngss": ngss, "ngis": ngis
)()
# ===================================================
|
[
{
"context": "0}).toDate()\n\n usersData = [\n {name: 'Matteo', created: now},\n {name: 'Antonio', create",
"end": 645,
"score": 0.9997730851173401,
"start": 639,
"tag": "NAME",
"value": "Matteo"
},
{
"context": " {name: 'Matteo', created: now},\n {name: 'Antonio', created: beforeTenHours},\n {name: 'Danie",
"end": 686,
"score": 0.9997317790985107,
"start": 679,
"tag": "NAME",
"value": "Antonio"
},
{
"context": "tonio', created: beforeTenHours},\n {name: 'Daniele', created: afterTenHours},\n {name: 'Marian",
"end": 738,
"score": 0.9997792840003967,
"start": 731,
"tag": "NAME",
"value": "Daniele"
},
{
"context": "aniele', created: afterTenHours},\n {name: 'Mariangela'},\n ]\n\n User.create usersData, (err, us",
"end": 792,
"score": 0.999793529510498,
"start": 782,
"tag": "NAME",
"value": "Mariangela"
}
] | test/operators.test.coffee | mrbatista/loopback-connector-arangodb | 15 | moment = require('moment')
should = require('./init');
describe 'operators', () ->
db = null
User = null
before (done) ->
db = getDataSource()
User = db.define 'User', {
name: String,
email: String,
age: Number,
created: Date,
}
User.destroyAll(done)
describe 'between', () ->
beforeEach () -> User.destroyAll()
it 'found data that match operator criteria - date type', (done) ->
now = moment().toDate();
beforeTenHours = moment(now).subtract({hours: 10}).toDate()
afterTenHours = moment(now).add({hours: 10}).toDate()
usersData = [
{name: 'Matteo', created: now},
{name: 'Antonio', created: beforeTenHours},
{name: 'Daniele', created: afterTenHours},
{name: 'Mariangela'},
]
User.create usersData, (err, users) ->
return done err if err
users.should.have.lengthOf(4)
filter = {where: {created: {between: [beforeTenHours, afterTenHours]}}}
User.find filter, (err, users) ->
return done err if err
users.should.have.lengthOf(3)
filter = {where: {created: {between: [now, afterTenHours]}}}
User.find filter, (err, users) ->
return done err if err
users.should.have.lengthOf(2)
done()
| 189841 | moment = require('moment')
should = require('./init');
describe 'operators', () ->
db = null
User = null
before (done) ->
db = getDataSource()
User = db.define 'User', {
name: String,
email: String,
age: Number,
created: Date,
}
User.destroyAll(done)
describe 'between', () ->
beforeEach () -> User.destroyAll()
it 'found data that match operator criteria - date type', (done) ->
now = moment().toDate();
beforeTenHours = moment(now).subtract({hours: 10}).toDate()
afterTenHours = moment(now).add({hours: 10}).toDate()
usersData = [
{name: '<NAME>', created: now},
{name: '<NAME>', created: beforeTenHours},
{name: '<NAME>', created: afterTenHours},
{name: '<NAME>'},
]
User.create usersData, (err, users) ->
return done err if err
users.should.have.lengthOf(4)
filter = {where: {created: {between: [beforeTenHours, afterTenHours]}}}
User.find filter, (err, users) ->
return done err if err
users.should.have.lengthOf(3)
filter = {where: {created: {between: [now, afterTenHours]}}}
User.find filter, (err, users) ->
return done err if err
users.should.have.lengthOf(2)
done()
| true | moment = require('moment')
should = require('./init');
describe 'operators', () ->
db = null
User = null
before (done) ->
db = getDataSource()
User = db.define 'User', {
name: String,
email: String,
age: Number,
created: Date,
}
User.destroyAll(done)
describe 'between', () ->
beforeEach () -> User.destroyAll()
it 'found data that match operator criteria - date type', (done) ->
now = moment().toDate();
beforeTenHours = moment(now).subtract({hours: 10}).toDate()
afterTenHours = moment(now).add({hours: 10}).toDate()
usersData = [
{name: 'PI:NAME:<NAME>END_PI', created: now},
{name: 'PI:NAME:<NAME>END_PI', created: beforeTenHours},
{name: 'PI:NAME:<NAME>END_PI', created: afterTenHours},
{name: 'PI:NAME:<NAME>END_PI'},
]
User.create usersData, (err, users) ->
return done err if err
users.should.have.lengthOf(4)
filter = {where: {created: {between: [beforeTenHours, afterTenHours]}}}
User.find filter, (err, users) ->
return done err if err
users.should.have.lengthOf(3)
filter = {where: {created: {between: [now, afterTenHours]}}}
User.find filter, (err, users) ->
return done err if err
users.should.have.lengthOf(2)
done()
|
[
{
"context": "u to use cool motion blur svg effect\n#\n# @author Olivier Bossel <olivier.bossel@gmail.com>\n# @created 20.01.16\n#",
"end": 124,
"score": 0.9998793005943298,
"start": 110,
"tag": "NAME",
"value": "Olivier Bossel"
},
{
"context": "ion blur svg effect\n#\n# @author Olivier Bossel <olivier.bossel@gmail.com>\n# @created 20.01.16\n# @updated 20.01.16\n# @ver",
"end": 150,
"score": 0.9999300241470337,
"start": 126,
"tag": "EMAIL",
"value": "olivier.bossel@gmail.com"
}
] | node_modules/sugarcss/coffee/sugar-motion-blur.coffee | hagsey/nlpt2 | 0 | ###
# Sugar-motion-blur.js
#
# This little js file allow you to use cool motion blur svg effect
#
# @author Olivier Bossel <olivier.bossel@gmail.com>
# @created 20.01.16
# @updated 20.01.16
# @version 1.0.0
###
((factory) ->
if typeof define == 'function' and define.amd
# AMD. Register as an anonymous module.
define [ ], factory
else if typeof exports == 'object'
# Node/CommonJS
factory()
else
# Browser globals
factory()
return
) () ->
window.SugarMotionBlur =
# track if already inited
_inited : false
# enabled
enabled : true
###
Init
###
init : () ->
# update inited state
@_inited = true
# wait until the dom is loaded
if document.readyState == 'interactive' then @_init()
else document.addEventListener 'DOMContentLoaded', (e) => @_init()
###
Internal init
###
_init : ->
# do nothing if not enabled
return if not @enabled
# put filters into page
@_injectFilter()
# listen for animations
@_listenAnimation()
###
Inject filter
###
_injectFilter : ->
# blur
style = ['position:absolute;','left:-1000px;']
if /Chrome/.test(navigator.userAgent) and /Google Inc/.test(navigator.vendor)
style.push 'display:none;'
blur = """
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="#{style.join(' ')}">
<defs>
<filter id="blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="0,0" />
</filter>
</defs>
</svg>
"""
blur_elm = document.createElement 'div'
blur_elm.innerHTML = blur
@blur_defs = blur_elm.querySelector 'defs'
@blur_svg = blur_elm.firstChild
@blur = blur_elm.querySelector '#blur'
# append filters to page
body = document.querySelector('body')
body.appendChild @blur_svg
###
Listen for animations
###
_listenAnimation : ->
document.addEventListener 'animationiteration', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
cancelAnimationFrame elm._blurAnimationFrame
@_handleFilter elm
document.addEventListener 'transitionstart', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
cancelAnimationFrame elm._blurAnimationFrame
@_handleFilter elm
document.addEventListener 'move', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
@_setMotionBlur elm
###
Handle filter
###
_handleFilter : (elm, recursive = false) ->
if not recursive
elm._step = 0
# set the blur
diff = @_setMotionBlur elm
# detect when need to stop animation
if diff.xDiff <= 0 and diff.yDiff <= 0
elm._step ?= 0
elm._step += 1
if elm._step >= 10
elm._step = 0
return
# request an animation frame
elm._blurAnimationFrame = requestAnimationFrame () =>
@_handleFilter elm, true
###
# Set motion blur
###
_setMotionBlur : (elm) ->
# clone the filter if not already the case
if not elm._blurFilter
# clone the filter tag in svg
elm._blurFilter = @blur.cloneNode true
# set a new id
id = 'blurFilter' + @_uniqId()
elm._blurFilter.setAttribute 'id', id
# append new filter in defs
@blur_defs.appendChild elm._blurFilter
# set the new filter to element
@_applyFilter elm, 'url("#'+id+'")'
# get the last position for the first time
elm._lastPos = @_offset elm
# request an animation frame
amount = elm.dataset.motionBlur || 0.5
elm._currentPos = @_offset elm
xDiff = Math.abs(elm._currentPos.left - elm._lastPos.left) * amount
yDiff = Math.abs(elm._currentPos.top - elm._lastPos.top) * amount
# set the blur effect
elm._blurFilter.firstElementChild.setAttribute 'stdDeviation', xDiff+','+yDiff
# save the last position
elm._lastPos = @_offset elm
return {
xDiff : xDiff
yDiff : yDiff
}
###
Get translate values
###
_getTranslate : (elm, what) ->
return if !window.getComputedStyle
style = getComputedStyle(elm)
transform = style.transform or style.webkitTransform or style.mozTransform
mat = transform.match(/^matrix3d\((.+)\)$/)
if mat
idx =
x : 12
y : 13
z : 14
return parseFloat(mat[1].split(', ')[idx[what]])
mat = transform.match(/^matrix\((.+)\)$/)
idx =
x : 4,
y : 5,
z : 6
if mat then parseFloat(mat[1].split(', ')[idx[what]]) else 0
###
Get element position
###
_offset : (elm) ->
box = elm.getBoundingClientRect()
body = document.body
docEl = document.documentElement
scrollTop = window.pageYOffset or docEl.scrollTop or body.scrollTop
scrollLeft = window.pageXOffset or docEl.scrollLeft or body.scrollLeft
clientTop = docEl.clientTop or body.clientTop or 0
clientLeft = docEl.clientLeft or body.clientLeft or 0
transX = @_getTranslate elm, 'x'
transY = @_getTranslate elm, 'y'
top = box.top + scrollTop - clientTop + transY
left = box.left + scrollLeft - clientLeft + transX
return {
top: Math.round(top)
left: Math.round(left)
}
###
Apply filter
###
_applyFilter : (elm, filter) ->
for vendor in ["-webkit-", "-moz-", "-ms-", "o-", ""]
elm.style[vendor+'filter'] = filter
###
UniqId
###
_uniqId : ->
return new Date().getTime() + Math.round(Math.random() * 999999999);
n = Math.floor(Math.random()*11);
k = Math.floor(Math.random()* 1000000);
m = String.fromCharCode(n)+k;
return m.trim()
# init the filter
SugarMotionBlur.init()
# return the Sugar object
SugarMotionBlur | 73188 | ###
# Sugar-motion-blur.js
#
# This little js file allow you to use cool motion blur svg effect
#
# @author <NAME> <<EMAIL>>
# @created 20.01.16
# @updated 20.01.16
# @version 1.0.0
###
((factory) ->
if typeof define == 'function' and define.amd
# AMD. Register as an anonymous module.
define [ ], factory
else if typeof exports == 'object'
# Node/CommonJS
factory()
else
# Browser globals
factory()
return
) () ->
window.SugarMotionBlur =
# track if already inited
_inited : false
# enabled
enabled : true
###
Init
###
init : () ->
# update inited state
@_inited = true
# wait until the dom is loaded
if document.readyState == 'interactive' then @_init()
else document.addEventListener 'DOMContentLoaded', (e) => @_init()
###
Internal init
###
_init : ->
# do nothing if not enabled
return if not @enabled
# put filters into page
@_injectFilter()
# listen for animations
@_listenAnimation()
###
Inject filter
###
_injectFilter : ->
# blur
style = ['position:absolute;','left:-1000px;']
if /Chrome/.test(navigator.userAgent) and /Google Inc/.test(navigator.vendor)
style.push 'display:none;'
blur = """
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="#{style.join(' ')}">
<defs>
<filter id="blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="0,0" />
</filter>
</defs>
</svg>
"""
blur_elm = document.createElement 'div'
blur_elm.innerHTML = blur
@blur_defs = blur_elm.querySelector 'defs'
@blur_svg = blur_elm.firstChild
@blur = blur_elm.querySelector '#blur'
# append filters to page
body = document.querySelector('body')
body.appendChild @blur_svg
###
Listen for animations
###
_listenAnimation : ->
document.addEventListener 'animationiteration', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
cancelAnimationFrame elm._blurAnimationFrame
@_handleFilter elm
document.addEventListener 'transitionstart', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
cancelAnimationFrame elm._blurAnimationFrame
@_handleFilter elm
document.addEventListener 'move', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
@_setMotionBlur elm
###
Handle filter
###
_handleFilter : (elm, recursive = false) ->
if not recursive
elm._step = 0
# set the blur
diff = @_setMotionBlur elm
# detect when need to stop animation
if diff.xDiff <= 0 and diff.yDiff <= 0
elm._step ?= 0
elm._step += 1
if elm._step >= 10
elm._step = 0
return
# request an animation frame
elm._blurAnimationFrame = requestAnimationFrame () =>
@_handleFilter elm, true
###
# Set motion blur
###
_setMotionBlur : (elm) ->
# clone the filter if not already the case
if not elm._blurFilter
# clone the filter tag in svg
elm._blurFilter = @blur.cloneNode true
# set a new id
id = 'blurFilter' + @_uniqId()
elm._blurFilter.setAttribute 'id', id
# append new filter in defs
@blur_defs.appendChild elm._blurFilter
# set the new filter to element
@_applyFilter elm, 'url("#'+id+'")'
# get the last position for the first time
elm._lastPos = @_offset elm
# request an animation frame
amount = elm.dataset.motionBlur || 0.5
elm._currentPos = @_offset elm
xDiff = Math.abs(elm._currentPos.left - elm._lastPos.left) * amount
yDiff = Math.abs(elm._currentPos.top - elm._lastPos.top) * amount
# set the blur effect
elm._blurFilter.firstElementChild.setAttribute 'stdDeviation', xDiff+','+yDiff
# save the last position
elm._lastPos = @_offset elm
return {
xDiff : xDiff
yDiff : yDiff
}
###
Get translate values
###
_getTranslate : (elm, what) ->
return if !window.getComputedStyle
style = getComputedStyle(elm)
transform = style.transform or style.webkitTransform or style.mozTransform
mat = transform.match(/^matrix3d\((.+)\)$/)
if mat
idx =
x : 12
y : 13
z : 14
return parseFloat(mat[1].split(', ')[idx[what]])
mat = transform.match(/^matrix\((.+)\)$/)
idx =
x : 4,
y : 5,
z : 6
if mat then parseFloat(mat[1].split(', ')[idx[what]]) else 0
###
Get element position
###
_offset : (elm) ->
box = elm.getBoundingClientRect()
body = document.body
docEl = document.documentElement
scrollTop = window.pageYOffset or docEl.scrollTop or body.scrollTop
scrollLeft = window.pageXOffset or docEl.scrollLeft or body.scrollLeft
clientTop = docEl.clientTop or body.clientTop or 0
clientLeft = docEl.clientLeft or body.clientLeft or 0
transX = @_getTranslate elm, 'x'
transY = @_getTranslate elm, 'y'
top = box.top + scrollTop - clientTop + transY
left = box.left + scrollLeft - clientLeft + transX
return {
top: Math.round(top)
left: Math.round(left)
}
###
Apply filter
###
_applyFilter : (elm, filter) ->
for vendor in ["-webkit-", "-moz-", "-ms-", "o-", ""]
elm.style[vendor+'filter'] = filter
###
UniqId
###
_uniqId : ->
return new Date().getTime() + Math.round(Math.random() * 999999999);
n = Math.floor(Math.random()*11);
k = Math.floor(Math.random()* 1000000);
m = String.fromCharCode(n)+k;
return m.trim()
# init the filter
SugarMotionBlur.init()
# return the Sugar object
SugarMotionBlur | true | ###
# Sugar-motion-blur.js
#
# This little js file allow you to use cool motion blur svg effect
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# @created 20.01.16
# @updated 20.01.16
# @version 1.0.0
###
((factory) ->
if typeof define == 'function' and define.amd
# AMD. Register as an anonymous module.
define [ ], factory
else if typeof exports == 'object'
# Node/CommonJS
factory()
else
# Browser globals
factory()
return
) () ->
window.SugarMotionBlur =
# track if already inited
_inited : false
# enabled
enabled : true
###
Init
###
init : () ->
# update inited state
@_inited = true
# wait until the dom is loaded
if document.readyState == 'interactive' then @_init()
else document.addEventListener 'DOMContentLoaded', (e) => @_init()
###
Internal init
###
_init : ->
# do nothing if not enabled
return if not @enabled
# put filters into page
@_injectFilter()
# listen for animations
@_listenAnimation()
###
Inject filter
###
_injectFilter : ->
# blur
style = ['position:absolute;','left:-1000px;']
if /Chrome/.test(navigator.userAgent) and /Google Inc/.test(navigator.vendor)
style.push 'display:none;'
blur = """
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="#{style.join(' ')}">
<defs>
<filter id="blur">
<feGaussianBlur in="SourceGraphic" stdDeviation="0,0" />
</filter>
</defs>
</svg>
"""
blur_elm = document.createElement 'div'
blur_elm.innerHTML = blur
@blur_defs = blur_elm.querySelector 'defs'
@blur_svg = blur_elm.firstChild
@blur = blur_elm.querySelector '#blur'
# append filters to page
body = document.querySelector('body')
body.appendChild @blur_svg
###
Listen for animations
###
_listenAnimation : ->
document.addEventListener 'animationiteration', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
cancelAnimationFrame elm._blurAnimationFrame
@_handleFilter elm
document.addEventListener 'transitionstart', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
cancelAnimationFrame elm._blurAnimationFrame
@_handleFilter elm
document.addEventListener 'move', (e) =>
elm = e.target
if elm.dataset.motionBlur != undefined
@_setMotionBlur elm
###
Handle filter
###
_handleFilter : (elm, recursive = false) ->
if not recursive
elm._step = 0
# set the blur
diff = @_setMotionBlur elm
# detect when need to stop animation
if diff.xDiff <= 0 and diff.yDiff <= 0
elm._step ?= 0
elm._step += 1
if elm._step >= 10
elm._step = 0
return
# request an animation frame
elm._blurAnimationFrame = requestAnimationFrame () =>
@_handleFilter elm, true
###
# Set motion blur
###
_setMotionBlur : (elm) ->
# clone the filter if not already the case
if not elm._blurFilter
# clone the filter tag in svg
elm._blurFilter = @blur.cloneNode true
# set a new id
id = 'blurFilter' + @_uniqId()
elm._blurFilter.setAttribute 'id', id
# append new filter in defs
@blur_defs.appendChild elm._blurFilter
# set the new filter to element
@_applyFilter elm, 'url("#'+id+'")'
# get the last position for the first time
elm._lastPos = @_offset elm
# request an animation frame
amount = elm.dataset.motionBlur || 0.5
elm._currentPos = @_offset elm
xDiff = Math.abs(elm._currentPos.left - elm._lastPos.left) * amount
yDiff = Math.abs(elm._currentPos.top - elm._lastPos.top) * amount
# set the blur effect
elm._blurFilter.firstElementChild.setAttribute 'stdDeviation', xDiff+','+yDiff
# save the last position
elm._lastPos = @_offset elm
return {
xDiff : xDiff
yDiff : yDiff
}
###
Get translate values
###
_getTranslate : (elm, what) ->
return if !window.getComputedStyle
style = getComputedStyle(elm)
transform = style.transform or style.webkitTransform or style.mozTransform
mat = transform.match(/^matrix3d\((.+)\)$/)
if mat
idx =
x : 12
y : 13
z : 14
return parseFloat(mat[1].split(', ')[idx[what]])
mat = transform.match(/^matrix\((.+)\)$/)
idx =
x : 4,
y : 5,
z : 6
if mat then parseFloat(mat[1].split(', ')[idx[what]]) else 0
###
Get element position
###
_offset : (elm) ->
box = elm.getBoundingClientRect()
body = document.body
docEl = document.documentElement
scrollTop = window.pageYOffset or docEl.scrollTop or body.scrollTop
scrollLeft = window.pageXOffset or docEl.scrollLeft or body.scrollLeft
clientTop = docEl.clientTop or body.clientTop or 0
clientLeft = docEl.clientLeft or body.clientLeft or 0
transX = @_getTranslate elm, 'x'
transY = @_getTranslate elm, 'y'
top = box.top + scrollTop - clientTop + transY
left = box.left + scrollLeft - clientLeft + transX
return {
top: Math.round(top)
left: Math.round(left)
}
###
Apply filter
###
_applyFilter : (elm, filter) ->
for vendor in ["-webkit-", "-moz-", "-ms-", "o-", ""]
elm.style[vendor+'filter'] = filter
###
UniqId
###
_uniqId : ->
return new Date().getTime() + Math.round(Math.random() * 999999999);
n = Math.floor(Math.random()*11);
k = Math.floor(Math.random()* 1000000);
m = String.fromCharCode(n)+k;
return m.trim()
# init the filter
SugarMotionBlur.init()
# return the Sugar object
SugarMotionBlur |
[
{
"context": "###!\nCopyright (c) 2002-2017 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 44,
"score": 0.6278381943702698,
"start": 34,
"tag": "NAME",
"value": "Technology"
}
] | src/components/D3Visualization/lib/visualization/utils/textMeasurement.coffee | yezonggang/zcfx-admin-master | 24 | ###!
Copyright (c) 2002-2017 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.utils.measureText = do ->
measureUsingCanvas = (text, font) ->
canvasSelection = d3.select('canvas#textMeasurementCanvas').data([this])
canvasSelection.enter().append('canvas')
.attr('id', 'textMeasurementCanvas')
.style('display', 'none')
canvas = canvasSelection.node()
context = canvas.getContext('2d')
context.font = font
context.measureText(text).width
cache = do () ->
cacheSize = 10000
map = {}
list = []
(key, calc) ->
cached = map[key]
if cached
cached
else
result = calc()
if (list.length > cacheSize)
delete map[list.splice(0, 1)]
list.push(key)
map[key] = result
return (text, fontFamily, fontSize) ->
font = 'normal normal normal ' + fontSize + 'px/normal ' + fontFamily;
cache(text + font, () ->
measureUsingCanvas(text, font)
)
| 191771 | ###!
Copyright (c) 2002-2017 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.utils.measureText = do ->
measureUsingCanvas = (text, font) ->
canvasSelection = d3.select('canvas#textMeasurementCanvas').data([this])
canvasSelection.enter().append('canvas')
.attr('id', 'textMeasurementCanvas')
.style('display', 'none')
canvas = canvasSelection.node()
context = canvas.getContext('2d')
context.font = font
context.measureText(text).width
cache = do () ->
cacheSize = 10000
map = {}
list = []
(key, calc) ->
cached = map[key]
if cached
cached
else
result = calc()
if (list.length > cacheSize)
delete map[list.splice(0, 1)]
list.push(key)
map[key] = result
return (text, fontFamily, fontSize) ->
font = 'normal normal normal ' + fontSize + 'px/normal ' + fontFamily;
cache(text + font, () ->
measureUsingCanvas(text, font)
)
| true | ###!
Copyright (c) 2002-2017 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.utils.measureText = do ->
measureUsingCanvas = (text, font) ->
canvasSelection = d3.select('canvas#textMeasurementCanvas').data([this])
canvasSelection.enter().append('canvas')
.attr('id', 'textMeasurementCanvas')
.style('display', 'none')
canvas = canvasSelection.node()
context = canvas.getContext('2d')
context.font = font
context.measureText(text).width
cache = do () ->
cacheSize = 10000
map = {}
list = []
(key, calc) ->
cached = map[key]
if cached
cached
else
result = calc()
if (list.length > cacheSize)
delete map[list.splice(0, 1)]
list.push(key)
map[key] = result
return (text, fontFamily, fontSize) ->
font = 'normal normal normal ' + fontSize + 'px/normal ' + fontFamily;
cache(text + font, () ->
measureUsingCanvas(text, font)
)
|
[
{
"context": "WEBMp_Admin_Login'\n\t\t\tlang: 'de'\n\t\t\tAdminPassword: @password\n\n\tcreateFormData: (enable) ->\n\t\tmethod: 'POST'\n\t\t",
"end": 532,
"score": 0.8117743730545044,
"start": 523,
"tag": "PASSWORD",
"value": "@password"
},
{
"context": "-enable': enable\n\t\t\t'ssh-password': if enable then @password else null\n\t\t\t'ssh-timer-connect': @connec",
"end": 700,
"score": 0.5830195546150208,
"start": 700,
"tag": "PASSWORD",
"value": ""
},
{
"context": "s\n\t\t\turl: \"ssh://admin@#{@hostname}/\"\n\t\t\tpassword: @password\n\t\t\tconnectTime: @connectTime\n\t\t\tsessionTime: @ses",
"end": 1721,
"score": 0.9984610080718994,
"start": 1712,
"tag": "PASSWORD",
"value": "@password"
}
] | lib/OpenStageSsh.coffee | sja/openstage-ssh | 1 | 'use strict'
request = require 'request'
Q = require 'q'
util = require 'util'
{EventEmitter} = require 'events'
module.exports = class OpenStageSsh extends EventEmitter
constructor: (@hostname = 'openstage', @password = '', @debug = false) ->
@url = "https://#{@hostname}/page.cmd"
Q.longStackSupport = @debug
@request = request.defaults
jar: true
rejectUnauthorized: false
url: @url
createFormAuthData : ->
method: 'POST'
form:
page_submit: 'WEBMp_Admin_Login'
lang: 'de'
AdminPassword: @password
createFormData: (enable) ->
method: 'POST'
form:
page_submit: 'WEBM_Admin_SecureShell'
lang: 'de'
'ssh-enable': enable
'ssh-password': if enable then @password else null
'ssh-timer-connect': @connectTime
'ssh-timer-session': @sessionTime
createStatusParams: ->
qs:
page: 'WEBM_Admin_SecureShell'
lang: 'de'
createLogoutParams: ->
qs:
user: 'none'
lang: 'de'
switchSsh: (enable) ->
Q.nfcall(@request, @createFormData(enable)).then (results) =>
resp = results[0]
body = results[1]
if resp.statusCode isnt 200
throw new Error "Something went wrong, request to enable SSH failed."
success = body.match(/class=.success/i)?
if success and @debug
if enable
console.log "Enabled SSH for #{@sessionTime} Minutes. You can log in within #{@connectTime} Minutes."
else
console.log "Disabled SSH."
else if @debug
console.log "Request was successful but no success message was found. Therefore SSH status is unknown."
console.log "This can be the case if you're using a firmware version I don't know. Contact me in this case."
success: success
url: "ssh://admin@#{@hostname}/"
password: @password
connectTime: @connectTime
sessionTime: @sessionTime
_queryState: ->
params = @createStatusParams()
Q.nfcall(@request, params).then (results) ->
body = results[1]
match = body.match /name=\Wssh-enable\W[^>]*(checked)/i
match?[1] is 'checked'
_failHandler: (err) ->
console.error "Failure!"
throw err
_resetReminder: ->
clearTimeout(@timeoutConnect) if @timeoutConnect
clearTimeout(@timeoutSession) if @timeoutSession
_setReminder: ->
@_resetReminder()
@timeoutConnect = setTimeout =>
@emit "connectTimeout", @hostname
, @connectTime * 60 * 1000
@timeoutSession = setTimeout =>
@emit "sessionTimeout", @hostname
, @sessionTime * 60 * 1000
login: ->
Q.nfcall(@request, @createFormAuthData()).then (results) ->
if results[0].statusCode isnt 200
throw new Error "Request error, status code was #{results[0].statusCode}!"
if results[1].match(/Authentication failed/i)
throw new Error "Authentication error, wrong password for user 'admin'?"
logout: ->
Q.nfcall(@request, @createLogoutParams()).then (results) ->
if results[0].statusCode isnt 200
throw new Error "Error logging out!"
getState: (callback) ->
@login()
.then( => @_queryState() )
.catch( @_failHandler )
.finally( => @logout() )
.done(callback)
enable: (@connectTime = 10, @sessionTime = 60, callback) ->
if typeof @connectTime is 'function'
callback = @connectTime
@connectTime = 10
@login().then( =>
@_setReminder()
@switchSsh(true) )
.finally( => @logout() )
.catch( @_failHandler )
.done(callback)
disable: (callback) ->
@login().then( =>
@switchSsh(false)
@_resetReminder())
.finally( => @logout() )
.catch( @_failHandler )
.done(callback)
| 63740 | 'use strict'
request = require 'request'
Q = require 'q'
util = require 'util'
{EventEmitter} = require 'events'
module.exports = class OpenStageSsh extends EventEmitter
constructor: (@hostname = 'openstage', @password = '', @debug = false) ->
@url = "https://#{@hostname}/page.cmd"
Q.longStackSupport = @debug
@request = request.defaults
jar: true
rejectUnauthorized: false
url: @url
createFormAuthData : ->
method: 'POST'
form:
page_submit: 'WEBMp_Admin_Login'
lang: 'de'
AdminPassword: <PASSWORD>
createFormData: (enable) ->
method: 'POST'
form:
page_submit: 'WEBM_Admin_SecureShell'
lang: 'de'
'ssh-enable': enable
'ssh-password': if enable then<PASSWORD> @password else null
'ssh-timer-connect': @connectTime
'ssh-timer-session': @sessionTime
createStatusParams: ->
qs:
page: 'WEBM_Admin_SecureShell'
lang: 'de'
createLogoutParams: ->
qs:
user: 'none'
lang: 'de'
switchSsh: (enable) ->
Q.nfcall(@request, @createFormData(enable)).then (results) =>
resp = results[0]
body = results[1]
if resp.statusCode isnt 200
throw new Error "Something went wrong, request to enable SSH failed."
success = body.match(/class=.success/i)?
if success and @debug
if enable
console.log "Enabled SSH for #{@sessionTime} Minutes. You can log in within #{@connectTime} Minutes."
else
console.log "Disabled SSH."
else if @debug
console.log "Request was successful but no success message was found. Therefore SSH status is unknown."
console.log "This can be the case if you're using a firmware version I don't know. Contact me in this case."
success: success
url: "ssh://admin@#{@hostname}/"
password: <PASSWORD>
connectTime: @connectTime
sessionTime: @sessionTime
_queryState: ->
params = @createStatusParams()
Q.nfcall(@request, params).then (results) ->
body = results[1]
match = body.match /name=\Wssh-enable\W[^>]*(checked)/i
match?[1] is 'checked'
_failHandler: (err) ->
console.error "Failure!"
throw err
_resetReminder: ->
clearTimeout(@timeoutConnect) if @timeoutConnect
clearTimeout(@timeoutSession) if @timeoutSession
_setReminder: ->
@_resetReminder()
@timeoutConnect = setTimeout =>
@emit "connectTimeout", @hostname
, @connectTime * 60 * 1000
@timeoutSession = setTimeout =>
@emit "sessionTimeout", @hostname
, @sessionTime * 60 * 1000
login: ->
Q.nfcall(@request, @createFormAuthData()).then (results) ->
if results[0].statusCode isnt 200
throw new Error "Request error, status code was #{results[0].statusCode}!"
if results[1].match(/Authentication failed/i)
throw new Error "Authentication error, wrong password for user 'admin'?"
logout: ->
Q.nfcall(@request, @createLogoutParams()).then (results) ->
if results[0].statusCode isnt 200
throw new Error "Error logging out!"
getState: (callback) ->
@login()
.then( => @_queryState() )
.catch( @_failHandler )
.finally( => @logout() )
.done(callback)
enable: (@connectTime = 10, @sessionTime = 60, callback) ->
if typeof @connectTime is 'function'
callback = @connectTime
@connectTime = 10
@login().then( =>
@_setReminder()
@switchSsh(true) )
.finally( => @logout() )
.catch( @_failHandler )
.done(callback)
disable: (callback) ->
@login().then( =>
@switchSsh(false)
@_resetReminder())
.finally( => @logout() )
.catch( @_failHandler )
.done(callback)
| true | 'use strict'
request = require 'request'
Q = require 'q'
util = require 'util'
{EventEmitter} = require 'events'
module.exports = class OpenStageSsh extends EventEmitter
constructor: (@hostname = 'openstage', @password = '', @debug = false) ->
@url = "https://#{@hostname}/page.cmd"
Q.longStackSupport = @debug
@request = request.defaults
jar: true
rejectUnauthorized: false
url: @url
createFormAuthData : ->
method: 'POST'
form:
page_submit: 'WEBMp_Admin_Login'
lang: 'de'
AdminPassword: PI:PASSWORD:<PASSWORD>END_PI
createFormData: (enable) ->
method: 'POST'
form:
page_submit: 'WEBM_Admin_SecureShell'
lang: 'de'
'ssh-enable': enable
'ssh-password': if enable thenPI:PASSWORD:<PASSWORD>END_PI @password else null
'ssh-timer-connect': @connectTime
'ssh-timer-session': @sessionTime
createStatusParams: ->
qs:
page: 'WEBM_Admin_SecureShell'
lang: 'de'
createLogoutParams: ->
qs:
user: 'none'
lang: 'de'
switchSsh: (enable) ->
Q.nfcall(@request, @createFormData(enable)).then (results) =>
resp = results[0]
body = results[1]
if resp.statusCode isnt 200
throw new Error "Something went wrong, request to enable SSH failed."
success = body.match(/class=.success/i)?
if success and @debug
if enable
console.log "Enabled SSH for #{@sessionTime} Minutes. You can log in within #{@connectTime} Minutes."
else
console.log "Disabled SSH."
else if @debug
console.log "Request was successful but no success message was found. Therefore SSH status is unknown."
console.log "This can be the case if you're using a firmware version I don't know. Contact me in this case."
success: success
url: "ssh://admin@#{@hostname}/"
password: PI:PASSWORD:<PASSWORD>END_PI
connectTime: @connectTime
sessionTime: @sessionTime
_queryState: ->
params = @createStatusParams()
Q.nfcall(@request, params).then (results) ->
body = results[1]
match = body.match /name=\Wssh-enable\W[^>]*(checked)/i
match?[1] is 'checked'
_failHandler: (err) ->
console.error "Failure!"
throw err
_resetReminder: ->
clearTimeout(@timeoutConnect) if @timeoutConnect
clearTimeout(@timeoutSession) if @timeoutSession
_setReminder: ->
@_resetReminder()
@timeoutConnect = setTimeout =>
@emit "connectTimeout", @hostname
, @connectTime * 60 * 1000
@timeoutSession = setTimeout =>
@emit "sessionTimeout", @hostname
, @sessionTime * 60 * 1000
login: ->
Q.nfcall(@request, @createFormAuthData()).then (results) ->
if results[0].statusCode isnt 200
throw new Error "Request error, status code was #{results[0].statusCode}!"
if results[1].match(/Authentication failed/i)
throw new Error "Authentication error, wrong password for user 'admin'?"
logout: ->
Q.nfcall(@request, @createLogoutParams()).then (results) ->
if results[0].statusCode isnt 200
throw new Error "Error logging out!"
getState: (callback) ->
@login()
.then( => @_queryState() )
.catch( @_failHandler )
.finally( => @logout() )
.done(callback)
enable: (@connectTime = 10, @sessionTime = 60, callback) ->
if typeof @connectTime is 'function'
callback = @connectTime
@connectTime = 10
@login().then( =>
@_setReminder()
@switchSsh(true) )
.finally( => @logout() )
.catch( @_failHandler )
.done(callback)
disable: (callback) ->
@login().then( =>
@switchSsh(false)
@_resetReminder())
.finally( => @logout() )
.catch( @_failHandler )
.done(callback)
|
[
{
"context": " flag: 'o'\n ,\n name: 'two'\n flag: 't'\n ]\n\n ",
"end": 3628,
"score": 0.6138232350349426,
"start": 3625,
"tag": "NAME",
"value": "two"
}
] | spec/args.spec.coffee | bbc/stubby4node | 0 | assert = require 'assert'
sut = null
describe 'args', ->
beforeEach ->
sut = require '../lib/console/args'
describe 'parse', ->
describe 'flags', ->
it 'should parse a flag without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, ['-f']
assert result.flag is true
it 'should parse two flags without parameters', ->
options = [
name: 'one'
flag: 'o'
,
name: 'two'
flag: 't'
]
result = sut.parse options, ['-ot']
assert result.one is true
assert result.two is true
it 'should default to false for flag without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, []
assert result.flag is false
it 'should parse a flag with parameters', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
]
result = sut.parse options, ['-f', expected]
assert result.flag is expected
it 'should parse two flags with parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
param: 'named'
]
result = sut.parse options, ['-o', 'one', '-t', 'two']
assert result.one is 'one'
assert result.two is 'two'
it 'should be default if flag not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, []
assert result.flag is expected
it 'should be default if flag parameter not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['-f']
assert result.flag is expected
it 'should be default if flag parameter skipped', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['-f', '-z']
assert result.flag is expected
it 'should parse a flag with parameters combined with a flag without parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
]
result = sut.parse options, ['-ot', 'one']
assert result.one is 'one'
assert result.two is true
describe 'names', ->
it 'should parse a name without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, ['--flag']
assert result.flag is true
it 'should parse two names without parameters', ->
options = [
name: 'one'
flag: 'o'
,
name: 'two'
flag: 't'
]
result = sut.parse options, ['--one', '--two']
assert result.one is true
assert result.two is true
it 'should default to false for name without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, []
assert result.flag is false
it 'should parse a name with parameters', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
]
result = sut.parse options, ['--flag', expected]
assert result.flag is expected
it 'should parse two names with parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
param: 'named'
]
result = sut.parse options, ['--one', 'one', '--two', 'two']
assert result.one is 'one'
assert result.two is 'two'
it 'should be default if name not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, []
assert result.flag is expected
it 'should be default if name parameter not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['--flag']
assert result.flag is expected
it 'should be default if name parameter skipped', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['--flag', '--another-flag']
assert result.flag is expected
| 147038 | assert = require 'assert'
sut = null
describe 'args', ->
beforeEach ->
sut = require '../lib/console/args'
describe 'parse', ->
describe 'flags', ->
it 'should parse a flag without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, ['-f']
assert result.flag is true
it 'should parse two flags without parameters', ->
options = [
name: 'one'
flag: 'o'
,
name: 'two'
flag: 't'
]
result = sut.parse options, ['-ot']
assert result.one is true
assert result.two is true
it 'should default to false for flag without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, []
assert result.flag is false
it 'should parse a flag with parameters', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
]
result = sut.parse options, ['-f', expected]
assert result.flag is expected
it 'should parse two flags with parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
param: 'named'
]
result = sut.parse options, ['-o', 'one', '-t', 'two']
assert result.one is 'one'
assert result.two is 'two'
it 'should be default if flag not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, []
assert result.flag is expected
it 'should be default if flag parameter not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['-f']
assert result.flag is expected
it 'should be default if flag parameter skipped', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['-f', '-z']
assert result.flag is expected
it 'should parse a flag with parameters combined with a flag without parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
]
result = sut.parse options, ['-ot', 'one']
assert result.one is 'one'
assert result.two is true
describe 'names', ->
it 'should parse a name without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, ['--flag']
assert result.flag is true
it 'should parse two names without parameters', ->
options = [
name: 'one'
flag: 'o'
,
name: '<NAME>'
flag: 't'
]
result = sut.parse options, ['--one', '--two']
assert result.one is true
assert result.two is true
it 'should default to false for name without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, []
assert result.flag is false
it 'should parse a name with parameters', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
]
result = sut.parse options, ['--flag', expected]
assert result.flag is expected
it 'should parse two names with parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
param: 'named'
]
result = sut.parse options, ['--one', 'one', '--two', 'two']
assert result.one is 'one'
assert result.two is 'two'
it 'should be default if name not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, []
assert result.flag is expected
it 'should be default if name parameter not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['--flag']
assert result.flag is expected
it 'should be default if name parameter skipped', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['--flag', '--another-flag']
assert result.flag is expected
| true | assert = require 'assert'
sut = null
describe 'args', ->
beforeEach ->
sut = require '../lib/console/args'
describe 'parse', ->
describe 'flags', ->
it 'should parse a flag without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, ['-f']
assert result.flag is true
it 'should parse two flags without parameters', ->
options = [
name: 'one'
flag: 'o'
,
name: 'two'
flag: 't'
]
result = sut.parse options, ['-ot']
assert result.one is true
assert result.two is true
it 'should default to false for flag without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, []
assert result.flag is false
it 'should parse a flag with parameters', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
]
result = sut.parse options, ['-f', expected]
assert result.flag is expected
it 'should parse two flags with parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
param: 'named'
]
result = sut.parse options, ['-o', 'one', '-t', 'two']
assert result.one is 'one'
assert result.two is 'two'
it 'should be default if flag not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, []
assert result.flag is expected
it 'should be default if flag parameter not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['-f']
assert result.flag is expected
it 'should be default if flag parameter skipped', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['-f', '-z']
assert result.flag is expected
it 'should parse a flag with parameters combined with a flag without parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
]
result = sut.parse options, ['-ot', 'one']
assert result.one is 'one'
assert result.two is true
describe 'names', ->
it 'should parse a name without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, ['--flag']
assert result.flag is true
it 'should parse two names without parameters', ->
options = [
name: 'one'
flag: 'o'
,
name: 'PI:NAME:<NAME>END_PI'
flag: 't'
]
result = sut.parse options, ['--one', '--two']
assert result.one is true
assert result.two is true
it 'should default to false for name without parameters', ->
options = [
name: 'flag'
flag: 'f'
]
result = sut.parse options, []
assert result.flag is false
it 'should parse a name with parameters', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
]
result = sut.parse options, ['--flag', expected]
assert result.flag is expected
it 'should parse two names with parameters', ->
options = [
name: 'one'
flag: 'o'
param: 'named'
,
name: 'two'
flag: 't'
param: 'named'
]
result = sut.parse options, ['--one', 'one', '--two', 'two']
assert result.one is 'one'
assert result.two is 'two'
it 'should be default if name not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, []
assert result.flag is expected
it 'should be default if name parameter not supplied', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['--flag']
assert result.flag is expected
it 'should be default if name parameter skipped', ->
expected = 'a_value'
options = [
name: 'flag'
flag: 'f'
param: 'anything'
default: expected
]
result = sut.parse options, ['--flag', '--another-flag']
assert result.flag is expected
|
[
{
"context": "to keypresses, loosely\n# based on [keymaster.js by Thomas Fuchs](https://github.com/madrobby/keymaster/)\n#\n# __Th",
"end": 98,
"score": 0.9998378753662109,
"start": 86,
"tag": "NAME",
"value": "Thomas Fuchs"
},
{
"context": "[keymaster.js by Thomas Fuchs](https://github.com/madrobby/keymaster/)\n#\n# __There are two ways to bind acti",
"end": 127,
"score": 0.9993674755096436,
"start": 119,
"tag": "USERNAME",
"value": "madrobby"
}
] | src/keys.coffee | andrewberls/kona | 4 | # An interface for binding actions to keypresses, loosely
# based on [keymaster.js by Thomas Fuchs](https://github.com/madrobby/keymaster/)
#
# __There are two ways to bind actions to keys:__
#
# 1) Define the `Kona.Keys.keydown()` function to handle events
#
# This function is directly bound the DOM keydown event, and will be
# called with the __name__ of each pressed key. For example:
#
# Kona.Keys.keydown = (key) ->
# switch key
# when 'left' then player.direction.dx = -1
# when 'right' then player.direction.dx = 1
# when 'up' then player.jump()
# when 'space' then player.fire()
#
# 2) Bind a handler function to a specific key. The method takes a string name and
# callback function invoked whenever that key is pressed.
#
# Kona.Keys.bind 'a', ->
# console.log "You pressed a!"
Kona.Keys =
# Mapping of special names --> keycode
_keycodes: {
'enter': 13, 'return' : 13,
'esc' : 27, 'escape' : 27,
'ctrl' : 17, 'control': 17,
'left' : 37, 'up' : 38,
'right': 39, 'down' : 40,
'shift': 16,
'space': 32
}
# Mapping of Keycodes --> Names
_names: {
13: 'enter',
16: 'shift',
17: 'ctrl',
27: 'esc',
32: 'space',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
65: 'a',
66: 'b',
67: 'c',
68: 'd',
69: 'e',
70: 'f',
71: 'g',
72: 'h',
73: 'i',
74: 'j',
75: 'k',
76: 'l',
77: 'm',
78: 'n',
79: 'o',
80: 'p',
81: 'q',
82: 'r',
83: 's',
84: 't',
85: 'u',
86: 'v',
87: 'w',
88: 'x',
89: 'y',
90: 'z'
}
# Strips whitespace from String `key` selector and return its
# corresponding keycode
#
# Ex: keyCodeFor('enter') => 13
#
# Returns Number
keyCodeFor: (key) ->
key = key.replace(/\s/g, '')
@_keycodes[key] || key.toUpperCase().charCodeAt(0)
# Parse and save key binding/handler function pair
#
# Options:
# key - The String key name to bind to, ex: `'b'`
# handler - The handler function to invoke when key is pressed
#
# Returns nothing
bind: (key, fn) -> Kona.Events.bind("key_#{@keyCodeFor(key)}", fn)
# Remove all handler bindings for a key
#
# key - A String key name
#
# Returns nothing
unbind: (key) -> Kona.Events.unbind("key_#{@keyCodeFor(key)}")
# Internally invoke the associated handler function when a bound key is pressed,
# and stops further event propagation
dispatch: (event) ->
keycode = @eventKeyCode(event)
return if @reject(event)
Kona.Events.trigger("key_#{keycode}")
# Ignore keypresses from elements that take keyboard data input,
# such as textareas. Returns Boolean
reject: (event) ->
_.contains ['INPUT', 'SELECT', 'TEXTAREA'], event.target.tagName
# Get the name of a key from a DOM event. Returns String
keycodeName: (event) ->
@_names[ @eventKeyCode(event) ]
# Get the keycode for a DOM keyboard event. Returns Integer
eventKeyCode: (event) -> event.which || event.keyCode
Kona.ready ->
# Wire up keydown and keyup events to associated handlers if they exist
document.body.onkeydown = (e) ->
name = Kona.Keys.keycodeName(e)
Kona.Keys.keydown(name) if Kona.Keys.keydown
# Set global key dispatch on the document bound to Kona.Keys context
document.body.onkeyup = (e) ->
name = Kona.Keys.keycodeName(e)
Kona.Keys.keyup(name) if Kona.Keys.keyup
document.addEventListener('keydown', Kona.Keys.dispatch.bind(Kona.Keys), false)
| 143237 | # An interface for binding actions to keypresses, loosely
# based on [keymaster.js by <NAME>](https://github.com/madrobby/keymaster/)
#
# __There are two ways to bind actions to keys:__
#
# 1) Define the `Kona.Keys.keydown()` function to handle events
#
# This function is directly bound the DOM keydown event, and will be
# called with the __name__ of each pressed key. For example:
#
# Kona.Keys.keydown = (key) ->
# switch key
# when 'left' then player.direction.dx = -1
# when 'right' then player.direction.dx = 1
# when 'up' then player.jump()
# when 'space' then player.fire()
#
# 2) Bind a handler function to a specific key. The method takes a string name and
# callback function invoked whenever that key is pressed.
#
# Kona.Keys.bind 'a', ->
# console.log "You pressed a!"
Kona.Keys =
# Mapping of special names --> keycode
_keycodes: {
'enter': 13, 'return' : 13,
'esc' : 27, 'escape' : 27,
'ctrl' : 17, 'control': 17,
'left' : 37, 'up' : 38,
'right': 39, 'down' : 40,
'shift': 16,
'space': 32
}
# Mapping of Keycodes --> Names
_names: {
13: 'enter',
16: 'shift',
17: 'ctrl',
27: 'esc',
32: 'space',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
65: 'a',
66: 'b',
67: 'c',
68: 'd',
69: 'e',
70: 'f',
71: 'g',
72: 'h',
73: 'i',
74: 'j',
75: 'k',
76: 'l',
77: 'm',
78: 'n',
79: 'o',
80: 'p',
81: 'q',
82: 'r',
83: 's',
84: 't',
85: 'u',
86: 'v',
87: 'w',
88: 'x',
89: 'y',
90: 'z'
}
# Strips whitespace from String `key` selector and return its
# corresponding keycode
#
# Ex: keyCodeFor('enter') => 13
#
# Returns Number
keyCodeFor: (key) ->
key = key.replace(/\s/g, '')
@_keycodes[key] || key.toUpperCase().charCodeAt(0)
# Parse and save key binding/handler function pair
#
# Options:
# key - The String key name to bind to, ex: `'b'`
# handler - The handler function to invoke when key is pressed
#
# Returns nothing
bind: (key, fn) -> Kona.Events.bind("key_#{@keyCodeFor(key)}", fn)
# Remove all handler bindings for a key
#
# key - A String key name
#
# Returns nothing
unbind: (key) -> Kona.Events.unbind("key_#{@keyCodeFor(key)}")
# Internally invoke the associated handler function when a bound key is pressed,
# and stops further event propagation
dispatch: (event) ->
keycode = @eventKeyCode(event)
return if @reject(event)
Kona.Events.trigger("key_#{keycode}")
# Ignore keypresses from elements that take keyboard data input,
# such as textareas. Returns Boolean
reject: (event) ->
_.contains ['INPUT', 'SELECT', 'TEXTAREA'], event.target.tagName
# Get the name of a key from a DOM event. Returns String
keycodeName: (event) ->
@_names[ @eventKeyCode(event) ]
# Get the keycode for a DOM keyboard event. Returns Integer
eventKeyCode: (event) -> event.which || event.keyCode
Kona.ready ->
# Wire up keydown and keyup events to associated handlers if they exist
document.body.onkeydown = (e) ->
name = Kona.Keys.keycodeName(e)
Kona.Keys.keydown(name) if Kona.Keys.keydown
# Set global key dispatch on the document bound to Kona.Keys context
document.body.onkeyup = (e) ->
name = Kona.Keys.keycodeName(e)
Kona.Keys.keyup(name) if Kona.Keys.keyup
document.addEventListener('keydown', Kona.Keys.dispatch.bind(Kona.Keys), false)
| true | # An interface for binding actions to keypresses, loosely
# based on [keymaster.js by PI:NAME:<NAME>END_PI](https://github.com/madrobby/keymaster/)
#
# __There are two ways to bind actions to keys:__
#
# 1) Define the `Kona.Keys.keydown()` function to handle events
#
# This function is directly bound the DOM keydown event, and will be
# called with the __name__ of each pressed key. For example:
#
# Kona.Keys.keydown = (key) ->
# switch key
# when 'left' then player.direction.dx = -1
# when 'right' then player.direction.dx = 1
# when 'up' then player.jump()
# when 'space' then player.fire()
#
# 2) Bind a handler function to a specific key. The method takes a string name and
# callback function invoked whenever that key is pressed.
#
# Kona.Keys.bind 'a', ->
# console.log "You pressed a!"
Kona.Keys =
# Mapping of special names --> keycode
_keycodes: {
'enter': 13, 'return' : 13,
'esc' : 27, 'escape' : 27,
'ctrl' : 17, 'control': 17,
'left' : 37, 'up' : 38,
'right': 39, 'down' : 40,
'shift': 16,
'space': 32
}
# Mapping of Keycodes --> Names
_names: {
13: 'enter',
16: 'shift',
17: 'ctrl',
27: 'esc',
32: 'space',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
48: '0',
49: '1',
50: '2',
51: '3',
52: '4',
53: '5',
54: '6',
55: '7',
56: '8',
57: '9',
65: 'a',
66: 'b',
67: 'c',
68: 'd',
69: 'e',
70: 'f',
71: 'g',
72: 'h',
73: 'i',
74: 'j',
75: 'k',
76: 'l',
77: 'm',
78: 'n',
79: 'o',
80: 'p',
81: 'q',
82: 'r',
83: 's',
84: 't',
85: 'u',
86: 'v',
87: 'w',
88: 'x',
89: 'y',
90: 'z'
}
# Strips whitespace from String `key` selector and return its
# corresponding keycode
#
# Ex: keyCodeFor('enter') => 13
#
# Returns Number
keyCodeFor: (key) ->
key = key.replace(/\s/g, '')
@_keycodes[key] || key.toUpperCase().charCodeAt(0)
# Parse and save key binding/handler function pair
#
# Options:
# key - The String key name to bind to, ex: `'b'`
# handler - The handler function to invoke when key is pressed
#
# Returns nothing
bind: (key, fn) -> Kona.Events.bind("key_#{@keyCodeFor(key)}", fn)
# Remove all handler bindings for a key
#
# key - A String key name
#
# Returns nothing
unbind: (key) -> Kona.Events.unbind("key_#{@keyCodeFor(key)}")
# Internally invoke the associated handler function when a bound key is pressed,
# and stops further event propagation
dispatch: (event) ->
keycode = @eventKeyCode(event)
return if @reject(event)
Kona.Events.trigger("key_#{keycode}")
# Ignore keypresses from elements that take keyboard data input,
# such as textareas. Returns Boolean
reject: (event) ->
_.contains ['INPUT', 'SELECT', 'TEXTAREA'], event.target.tagName
# Get the name of a key from a DOM event. Returns String
keycodeName: (event) ->
@_names[ @eventKeyCode(event) ]
# Get the keycode for a DOM keyboard event. Returns Integer
eventKeyCode: (event) -> event.which || event.keyCode
Kona.ready ->
# Wire up keydown and keyup events to associated handlers if they exist
document.body.onkeydown = (e) ->
name = Kona.Keys.keycodeName(e)
Kona.Keys.keydown(name) if Kona.Keys.keydown
# Set global key dispatch on the document bound to Kona.Keys context
document.body.onkeyup = (e) ->
name = Kona.Keys.keycodeName(e)
Kona.Keys.keyup(name) if Kona.Keys.keyup
document.addEventListener('keydown', Kona.Keys.dispatch.bind(Kona.Keys), false)
|
[
{
"context": "strings passed to the RegExp constructor\n# @author Michael Ficarra\n###\n\n'use strict'\n\n#-----------------------------",
"end": 96,
"score": 0.9998405575752258,
"start": 81,
"tag": "NAME",
"value": "Michael Ficarra"
}
] | src/tests/rules/no-invalid-regexp.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Validate strings passed to the RegExp constructor
# @author Michael Ficarra
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-invalid-regexp'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-invalid-regexp', rule,
valid: [
"RegExp('')"
'RegExp()'
"RegExp('.', 'g')"
"new RegExp('.')"
'new RegExp'
"new RegExp('.', 'im')"
"global.RegExp('\\\\')"
"new RegExp('.', y)"
,
code: "new RegExp('.', 'y')", options: [allowConstructorFlags: ['y']]
,
code: "new RegExp('.', 'u')", options: [allowConstructorFlags: ['U']]
,
code: "new RegExp('.', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
code: "new RegExp('/', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
code: "new RegExp('\\/', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
"new RegExp('.', 'y')"
"new RegExp('.', 'u')"
"new RegExp('.', 'yu')"
"new RegExp('/', 'yu')"
"new RegExp('\\/', 'yu')"
"new RegExp('\\\\u{65}', 'u')"
"new RegExp('[\\u{0}-\\u{1F}]', 'u')"
"new RegExp('.', 's')"
"new RegExp('(?<=a)b')"
"new RegExp('(?<!a)b')"
"new RegExp('(?<a>b)\\k<a>')"
"new RegExp('(?<a>b)\\k<a>', 'u')"
"new RegExp('\\p{Letter}', 'u')"
]
invalid: [
code: "RegExp('[')"
errors: [
message: 'Invalid regular expression: /[/: Unterminated character class.'
type: 'CallExpression'
]
,
code: "RegExp('.', 'z')"
errors: [
message: "Invalid flags supplied to RegExp constructor 'z'."
type: 'CallExpression'
]
,
code: "new RegExp(')')"
errors: [
message: "Invalid regular expression: /)/: Unmatched ')'."
type: 'NewExpression'
]
]
| 90909 | ###*
# @fileoverview Validate strings passed to the RegExp constructor
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-invalid-regexp'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-invalid-regexp', rule,
valid: [
"RegExp('')"
'RegExp()'
"RegExp('.', 'g')"
"new RegExp('.')"
'new RegExp'
"new RegExp('.', 'im')"
"global.RegExp('\\\\')"
"new RegExp('.', y)"
,
code: "new RegExp('.', 'y')", options: [allowConstructorFlags: ['y']]
,
code: "new RegExp('.', 'u')", options: [allowConstructorFlags: ['U']]
,
code: "new RegExp('.', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
code: "new RegExp('/', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
code: "new RegExp('\\/', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
"new RegExp('.', 'y')"
"new RegExp('.', 'u')"
"new RegExp('.', 'yu')"
"new RegExp('/', 'yu')"
"new RegExp('\\/', 'yu')"
"new RegExp('\\\\u{65}', 'u')"
"new RegExp('[\\u{0}-\\u{1F}]', 'u')"
"new RegExp('.', 's')"
"new RegExp('(?<=a)b')"
"new RegExp('(?<!a)b')"
"new RegExp('(?<a>b)\\k<a>')"
"new RegExp('(?<a>b)\\k<a>', 'u')"
"new RegExp('\\p{Letter}', 'u')"
]
invalid: [
code: "RegExp('[')"
errors: [
message: 'Invalid regular expression: /[/: Unterminated character class.'
type: 'CallExpression'
]
,
code: "RegExp('.', 'z')"
errors: [
message: "Invalid flags supplied to RegExp constructor 'z'."
type: 'CallExpression'
]
,
code: "new RegExp(')')"
errors: [
message: "Invalid regular expression: /)/: Unmatched ')'."
type: 'NewExpression'
]
]
| true | ###*
# @fileoverview Validate strings passed to the RegExp constructor
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/no-invalid-regexp'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-invalid-regexp', rule,
valid: [
"RegExp('')"
'RegExp()'
"RegExp('.', 'g')"
"new RegExp('.')"
'new RegExp'
"new RegExp('.', 'im')"
"global.RegExp('\\\\')"
"new RegExp('.', y)"
,
code: "new RegExp('.', 'y')", options: [allowConstructorFlags: ['y']]
,
code: "new RegExp('.', 'u')", options: [allowConstructorFlags: ['U']]
,
code: "new RegExp('.', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
code: "new RegExp('/', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
code: "new RegExp('\\/', 'yu')"
options: [allowConstructorFlags: ['y', 'u']]
,
"new RegExp('.', 'y')"
"new RegExp('.', 'u')"
"new RegExp('.', 'yu')"
"new RegExp('/', 'yu')"
"new RegExp('\\/', 'yu')"
"new RegExp('\\\\u{65}', 'u')"
"new RegExp('[\\u{0}-\\u{1F}]', 'u')"
"new RegExp('.', 's')"
"new RegExp('(?<=a)b')"
"new RegExp('(?<!a)b')"
"new RegExp('(?<a>b)\\k<a>')"
"new RegExp('(?<a>b)\\k<a>', 'u')"
"new RegExp('\\p{Letter}', 'u')"
]
invalid: [
code: "RegExp('[')"
errors: [
message: 'Invalid regular expression: /[/: Unterminated character class.'
type: 'CallExpression'
]
,
code: "RegExp('.', 'z')"
errors: [
message: "Invalid flags supplied to RegExp constructor 'z'."
type: 'CallExpression'
]
,
code: "new RegExp(')')"
errors: [
message: "Invalid regular expression: /)/: Unmatched ')'."
type: 'NewExpression'
]
]
|
[
{
"context": "ntTools.ToolShelf.stow(@, 'video')\n\n @label = 'Lien Viméo ou Youtube'\n @icon = 'youtube'\n\n @canApply:",
"end": 36391,
"score": 0.8706701993942261,
"start": 36381,
"tag": "NAME",
"value": "Lien Viméo"
}
] | src/scripts/tools.coffee | Selbahc/ct-bgd | 0 | class ContentTools.ToolShelf
# The `ToolShelf` class allows tools to be stored using a name (string) as a
# reference. Using a tools name makes is cleaner when defining a set of
# tools to populate the `ToolboxUI` widget.
@_tools = {}
@stow: (cls, name) ->
# Stow a tool on the shelf
@_tools[name] = cls
@fetch: (name) ->
# Fetch a tool from the shelf by it's name
unless @_tools[name]
throw new Error("`#{name}` has not been stowed on the tool shelf")
return @_tools[name]
class ContentTools.Tool
# The `Tool` class defines a common API for editor tools. All tools should
# inherit from the `Tool` class.
#
# Tools classes are designed to be used direct not as instances of the
# class, every property and method for a tool is held against the class.
#
# A tool is effectively a collection of functions (class methods) with a set
# of configuration settings (class properties). For this reason they are
# defined using static classes.
@label = 'Tool'
@icon = 'tool'
# Most tools require an element that they can be applied to, but there are
# exceptions (such as undo/redo). In these cases you can set the
# `requiresElement` flag to false so that the toolbox will not automatically
# disable the tool because there is not element focused.
@requiresElement = true
# Class methods
@canApply: (element, selection) ->
# Return true if the tool can be applied to the specified
# element and selection.
return false
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the specified
# element and selection.
return false
@apply: (element, selection, callback) ->
# Apply the tool to the specified element and selection
throw new Error('Not implemented')
@editor: () ->
# Return an instance of the ContentTools.EditorApp
return ContentTools.EditorApp.get()
@dispatchEditorEvent: (name, detail) ->
# Dispatch an event against the editor
@editor().dispatchEvent(@editor().createEvent(name, detail))
# Private class methods
@_insertAt: (element) ->
# Find insert node and index for inserting an element after the
# specified element.
insertNode = element
if insertNode.parent().type() != 'Region'
insertNode = element.closest (node) ->
return node.parent().type() is 'Region'
insertIndex = insertNode.parent().children.indexOf(insertNode) + 1
return [insertNode, insertIndex]
# Common tools
class ContentTools.Tools.Bold extends ContentTools.Tool
# Make the current selection of text (non)bold (e.g <b>foo</b>).
ContentTools.ToolShelf.stow(@, 'bold')
@label = 'Bold'
@icon = 'bold'
@tagName = 'b'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
unless element.content
return false
return selection and not selection.isCollapsed()
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if element.content is undefined or not element.content.length()
return false
[from, to] = selection.get()
if from == to
to += 1
return element.content.slice(from, to).hasTags(@tagName, true)
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
element.storeState()
[from, to] = selection.get()
if @isApplied(element, selection)
element.content = element.content.unformat(
from,
to,
new HTMLString.Tag(@tagName)
)
else
element.content = element.content.format(
from,
to,
new HTMLString.Tag(@tagName)
)
element.content.optimize()
element.updateInnerHTML()
element.taint()
element.restoreState()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Italic extends ContentTools.Tools.Bold
# Make the current selection of text (non)italic (e.g <i>foo</i>).
ContentTools.ToolShelf.stow(@, 'italic')
@label = 'Italic'
@icon = 'italic'
@tagName = 'i'
class ContentTools.Tools.Link extends ContentTools.Tools.Bold
# Insert/Remove a link.
ContentTools.ToolShelf.stow(@, 'link')
@label = 'Link'
@icon = 'link'
@tagName = 'a'
@getAttr: (attrName, element, selection) ->
# Get an attribute for the element and selection
# Images
if element.type() is 'Image'
if element.a
return element.a[attrName]
# Fixtures
else if element.isFixed() and element.tagName() is 'a'
return element.attr(attrName)
# Text
else
# Find the first character in the selected text that has an `a` tag
# and return the named attributes value.
[from, to] = selection.get()
selectedContent = element.content.slice(from, to)
for c in selectedContent.characters
if not c.hasTags('a')
continue
for tag in c.tags()
if tag.name() == 'a'
return tag.attr(attrName)
return ''
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.type() is 'Image'
return true
else if element.isFixed() and element.tagName() is 'a'
return true
else
# Must support content
unless element.content
return false
# A selection must exist
if not selection
return false
# If the selection is collapsed then it must be within an existing
# link.
if selection.isCollapsed()
character = element.content.characters[selection.get()[0]]
if not character or not character.hasTags('a')
return false
return true
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if element.type() is 'Image'
return element.a
else if element.isFixed() and element.tagName() is 'a'
return true
else
return super(element, selection)
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
applied = false
# Prepare text elements for adding a link
if element.type() is 'Image'
# Images
rect = element.domElement().getBoundingClientRect()
else if element.isFixed() and element.tagName() is 'a'
# Fixtures
rect = element.domElement().getBoundingClientRect()
else
# If the selection is collapsed then we need to select the entire
# entire link.
if selection.isCollapsed()
# Find the bounds of the link
characters = element.content.characters
starts = selection.get(0)[0]
ends = starts
while starts > 0 and characters[starts - 1].hasTags('a')
starts -= 1
while ends < characters.length and characters[ends].hasTags('a')
ends += 1
# Select the link in full
selection = new ContentSelect.Range(starts, ends)
selection.select(element.domElement())
# Text elements
element.storeState()
# Add a fake selection wrapper to the selected text so that it
# appears to be selected when the focus is lost by the element.
selectTag = new HTMLString.Tag('span', {'class': 'ct--puesdo-select'})
[from, to] = selection.get()
element.content = element.content.format(from, to, selectTag)
element.updateInnerHTML()
# Measure a rectangle of the content selected so we can position the
# dialog centrally.
domElement = element.domElement()
measureSpan = domElement.getElementsByClassName('ct--puesdo-select')
rect = measureSpan[0].getBoundingClientRect()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI(transparent=true, allowScrolling=true)
# When the modal is clicked on the dialog should close
modal.addEventListener 'click', () ->
@unmount()
dialog.hide()
if element.content
# Remove the fake selection from the element
element.content = element.content.unformat(from, to, selectTag)
element.updateInnerHTML()
# Restore the selection
element.restoreState()
callback(applied)
# Dispatch `applied` event
if applied
ContentTools.Tools.Link.dispatchEditorEvent(
'tool-applied',
toolDetail
)
# Dialog
dialog = new ContentTools.LinkDialog(
@getAttr('href', element, selection),
@getAttr('target', element, selection)
)
# Get the scroll position required for the dialog
[scrollX, scrollY] = ContentTools.getScrollPosition()
dialog.position([
rect.left + (rect.width / 2) + scrollX,
rect.top + (rect.height / 2) + scrollY
])
dialog.addEventListener 'save', (ev) ->
detail = ev.detail()
applied = true
# Add the link
if element.type() is 'Image'
# Images
#
# Note: When we add/remove links any alignment class needs to be
# moved to either the link (on adding a link) or the image (on
# removing a link). Alignment classes are mutually exclusive.
alignmentClassNames = [
'align-center',
'align-left',
'align-right'
]
if detail.href
element.a = {href: detail.href}
if element.a
element.a.class = element.a['class']
if detail.target
element.a.target = detail.target
for className in alignmentClassNames
if element.hasCSSClass(className)
element.removeCSSClass(className)
element.a['class'] = className
break
else
linkClasses = []
if element.a['class']
linkClasses = element.a['class'].split(' ')
for className in alignmentClassNames
if linkClasses.indexOf(className) > -1
element.addCSSClass(className)
break
element.a = null
element.unmount()
element.mount()
else if element.isFixed() and element.tagName() is 'a'
# Fixtures
element.attr('href', detail.href)
else
# Text elements
# Clear any existing link
element.content = element.content.unformat(from, to, 'a')
# If specified add the new link
if detail.href
a = new HTMLString.Tag('a', detail)
element.content = element.content.format(from, to, a)
element.content.optimize()
element.updateInnerHTML()
# Make sure the element is marked as tainted
element.taint()
# Close the modal and dialog
modal.dispatchEvent(modal.createEvent('click'))
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Heading extends ContentTools.Tool
# Convert the current text block to a heading (e.g <h1>foo</h1>)
ContentTools.ToolShelf.stow(@, 'heading')
@label = 'Heading'
@icon = 'heading'
@tagName = 'h1'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element.content != undefined and
['Text', 'PreText'].indexOf(element.type()) != -1
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if not element.content
return false
if ['Text', 'PreText'].indexOf(element.type()) == -1
return false
return element.tagName() == @tagName
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Apply the tool to the current element
element.storeState()
# If the tag is a PreText tag then we need to handle the convert the
# element not just the tag name.
if element.type() is 'PreText'
# Convert the element to a Text element first
content = element.content.html().replace(/ /g, ' ')
textElement = new ContentEdit.Text(@tagName, {}, content)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(textElement, insertAt)
# Restore selection
element.blur()
textElement.focus()
textElement.selection(selection)
else
# Change the text elements tag name
# Remove any CSS classes from the element
element.removeAttr('class')
# If the element already has the same tag name as the tool will
# apply revert the element to a paragraph.
if element.tagName() == @tagName
element.tagName('p')
else
element.tagName(@tagName)
element.restoreState()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
callback(true)
class ContentTools.Tools.Subheading extends ContentTools.Tools.Heading
# Convert the current text block to a subheading (e.g <h2>foo</h2>)
ContentTools.ToolShelf.stow(@, 'subheading')
@label = 'Subheading'
@icon = 'subheading'
@tagName = 'h2'
class ContentTools.Tools.Paragraph extends ContentTools.Tools.Heading
# Convert the current text block to a paragraph (e.g <p>foo</p>)
ContentTools.ToolShelf.stow(@, 'paragraph')
@label = 'Paragraph'
@icon = 'paragraph'
@tagName = 'p'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element != undefined
@apply: (element, selection, callback) ->
# Apply the tool to the current element
forceAdd = @editor().ctrlDown()
if ContentTools.Tools.Heading.canApply(element) and not forceAdd
# If the element is a top level text element and the user hasn't
# indicated they want to force add a new paragraph convert it to a
# paragraph in-place.
return super(element, selection, callback)
else
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If the element isn't a text element find the nearest top level
# node and insert a new paragraph element after it.
if element.parent().type() != 'Region'
element = element.closest (node) ->
return node.parent().type() is 'Region'
region = element.parent()
paragraph = new ContentEdit.Text('p')
region.attach(paragraph, region.children.indexOf(element) + 1)
# Give the newely inserted paragraph focus
paragraph.focus()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Preformatted extends ContentTools.Tools.Heading
# Convert the current text block to a preformatted block (e.g <pre>foo</pre)
ContentTools.ToolShelf.stow(@, 'preformatted')
@label = 'Preformatted'
@icon = 'preformatted'
@tagName = 'pre'
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If the element is already a PreText element then convert it to a
# paragraph instead.
if element.type() is 'PreText'
ContentTools.Tools.Paragraph.apply(element, selection, callback)
return
# Escape the contents of the existing element
text = element.content.text()
# Create a new pre-text element using the current elements content
preText = new ContentEdit.PreText(
'pre', {},
HTMLString.String.encode(text)
)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(preText, insertAt)
# Restore selection
element.blur()
preText.focus()
preText.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.AlignLeft extends ContentTools.Tool
# Apply a class to left align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-left')
@label = 'Align left'
@icon = 'align-left'
@className = 'text-left'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.content != undefined
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if not @canApply(element)
return false
# List items and table cells use child nodes to manage their content
# which don't support classes, so we need to check the parent.
if element.type() in ['ListItemText', 'TableCellText']
element = element.parent()
return element.hasCSSClass(@className)
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# List items and table cells use child nodes to manage their content
# which don't support classes, so we need to use the parent.
if element.type() in ['ListItemText', 'TableCellText']
element = element.parent()
# Remove any existing text alignment classes applied
alignmentClassNames = [
ContentTools.Tools.AlignLeft.className,
ContentTools.Tools.AlignCenter.className,
ContentTools.Tools.AlignRight.className
]
for className in alignmentClassNames
if element.hasCSSClass(className)
element.removeCSSClass(className)
# If we're removing the class associated with the tool then we
# can return early (this allows the tool to be toggled on/off).
if className == @className
return callback(true)
# Add the alignment class to the element
element.addCSSClass(@className)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.AlignCenter extends ContentTools.Tools.AlignLeft
# Apply a class to center align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-center')
@label = 'Align center'
@icon = 'align-center'
@className = 'text-center'
class ContentTools.Tools.AlignRight extends ContentTools.Tools.AlignLeft
# Apply a class to right align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-right')
@label = 'Align right'
@icon = 'align-right'
@className = 'text-right'
class ContentTools.Tools.UnorderedList extends ContentTools.Tool
# Set an element as an unordered list.
ContentTools.ToolShelf.stow(@, 'unordered-list')
@label = 'Bullet list'
@icon = 'unordered-list'
@listTag = 'ul'
@canApply: (element, selection) ->
if element.isFixed()
return false
# Return true if the tool can be applied to the current
# element/selection.
return element.content != undefined and
element.parent().type() in ['Region', 'ListItem']
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
if element.parent().type() is 'ListItem'
# Find the parent list and change it to an unordered list
element.storeState()
list = element.closest (node) ->
return node.type() is 'List'
list.tagName(@listTag)
element.restoreState()
else
# Convert the element to a list
# Create a new list using the current elements content
listItemText = new ContentEdit.ListItemText(element.content.copy())
listItem = new ContentEdit.ListItem()
listItem.attach(listItemText)
list = new ContentEdit.List(@listTag, {})
list.attach(listItem)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(list, insertAt)
# Restore selection
listItemText.focus()
listItemText.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.OrderedList extends ContentTools.Tools.UnorderedList
# Set an element as an ordered list.
ContentTools.ToolShelf.stow(@, 'ordered-list')
@label = 'Numbers list'
@icon = 'ordered-list'
@listTag = 'ol'
class ContentTools.Tools.Table extends ContentTools.Tool
# Insert/Update a Table.
ContentTools.ToolShelf.stow(@, 'table')
@label = 'Table'
@icon = 'table'
# Class methods
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element != undefined
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# If the element is part of a table find the parent table
table = element.closest (node) ->
return node and node.type() is 'Table'
# Dialog
dialog = new ContentTools.TableDialog(table)
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
tableCfg = ev.detail()
# This flag indicates if we can restore the previous elements focus
# and state or if we need to change the focus to the first cell in
# the table.
keepFocus = true
if table
# Update the existing table
@_updateTable(tableCfg, table)
# Check if the current element is still part of the table after
# being updated.
keepFocus = element.closest (node) ->
return node and node.type() is 'Table'
else
# Create a new table
table = @_createTable(tableCfg)
# Insert it into the document
[node, index] = @_insertAt(element)
node.parent().attach(table, index)
keepFocus = false
if keepFocus
element.restoreState()
else
# Focus on the first cell in the table e.g:
#
# TableSection > TableRow > TableCell > TableCellText
table.firstSection().children[0].children[0].children[0].focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
# Private class methods
@_adjustColumns: (section, columns) ->
# Adjust the number of columns in a table section
for row in section.children
cellTag = row.children[0].tagName()
currentColumns = row.children.length
diff = columns - currentColumns
if diff < 0
# Remove columns
for i in [diff...0]
cell = row.children[row.children.length - 1]
row.detach(cell)
else if diff > 0
# Add columns
for i in [0...diff]
cell = new ContentEdit.TableCell(cellTag)
row.attach(cell)
cellText = new ContentEdit.TableCellText('')
cell.attach(cellText)
@_createTable: (tableCfg) ->
# Create a new table element from the specified configuration
table = new ContentEdit.Table()
# Head
if tableCfg.head
head = @_createTableSection('thead', 'th', tableCfg.columns)
table.attach(head)
# Body
body = @_createTableSection('tbody', 'td', tableCfg.columns)
table.attach(body)
# Foot
if tableCfg.foot
foot = @_createTableSection('tfoot', 'td', tableCfg.columns)
table.attach(foot)
return table
@_createTableSection: (sectionTag, cellTag, columns) ->
# Create a new table section element
section = new ContentEdit.TableSection(sectionTag)
row = new ContentEdit.TableRow()
section.attach(row)
for i in [0...columns]
cell = new ContentEdit.TableCell(cellTag)
row.attach(cell)
cellText = new ContentEdit.TableCellText('')
cell.attach(cellText)
return section
@_updateTable: (tableCfg, table) ->
# Update an existing table
# Remove any sections no longer required
if not tableCfg.head and table.thead()
table.detach(table.thead())
if not tableCfg.foot and table.tfoot()
table.detach(table.tfoot())
# Increase or decrease the number of columns
columns = table.firstSection().children[0].children.length
if tableCfg.columns != columns
for section in table.children
@_adjustColumns(section, tableCfg.columns)
# Add any new sections
if tableCfg.head and not table.thead()
head = @_createTableSection('thead', 'th', tableCfg.columns)
table.attach(head, 0)
if tableCfg.foot and not table.tfoot()
foot = @_createTableSection('tfoot', 'td', tableCfg.columns)
table.attach(foot)
class ContentTools.Tools.Indent extends ContentTools.Tool
# Indent a list item.
ContentTools.ToolShelf.stow(@, 'indent')
@label = 'Indent'
@icon = 'indent'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.parent().type() is 'ListItem' and
element.parent().parent().children.indexOf(element.parent()) > 0
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Indent the list item
element.parent().indent()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Unindent extends ContentTools.Tool
# Unindent a list item.
ContentTools.ToolShelf.stow(@, 'unindent')
@label = 'Unindent'
@icon = 'unindent'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.parent().type() is 'ListItem'
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Indent the list item
element.parent().unindent()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.LineBreak extends ContentTools.Tool
# Insert a line break in to the current element at the specified selection.
ContentTools.ToolShelf.stow(@, 'line-break')
@label = 'Line break'
@icon = 'line-break'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.content
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Insert a BR at the current in index
cursor = selection.get()[0] + 1
tip = element.content.substring(0, selection.get()[0])
tail = element.content.substring(selection.get()[1])
br = new HTMLString.String('<br>', element.content.preserveWhitespace())
element.content = tip.concat(br, tail)
element.updateInnerHTML()
element.taint()
# Restore the selection
selection.set(cursor, cursor)
element.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Image extends ContentTools.Tool
# Insert an image.
ContentTools.ToolShelf.stow(@, 'image')
@label = 'Image'
@icon = 'image'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
unless element.type() is 'ImageFixture'
return false
return true
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.ImageDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
imageURL = detail.imageURL
imageSize = detail.imageSize
imageAttrs = detail.imageAttrs
if not imageAttrs
imageAttrs = {}
imageAttrs.height = imageSize[1]
imageAttrs.src = imageURL
imageAttrs.width = imageSize[0]
if element.type() is 'ImageFixture'
# Configure the image source against the fixture
element.src(imageURL)
else
# Create the new image
image = new ContentEdit.Image(imageAttrs)
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(image, index)
# Focus the new image
image.focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Video extends ContentTools.Tool
# Insert a video.
ContentTools.ToolShelf.stow(@, 'video')
@label = 'Lien Viméo ou Youtube'
@icon = 'youtube'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return not element.isFixed()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.VideoDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
url = ev.detail().url
if url
# Create the new video
video = new ContentEdit.Video(
'iframe', {
'frameborder': 0,
'height': ContentTools.DEFAULT_VIDEO_HEIGHT,
'src': url,
'width': ContentTools.DEFAULT_VIDEO_WIDTH
})
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(video, index)
# Focus the new video
video.focus()
else
# Nothing to do restore state
if element.restoreState
element.restoreState()
modal.hide()
dialog.hide()
applied = url != ''
callback(applied)
# Dispatch `applied` event
if applied
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Undo extends ContentTools.Tool
# Undo an action.
ContentTools.ToolShelf.stow(@, 'undo')
@label = 'Undo'
@icon = 'undo'
@requiresElement = false
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
app = ContentTools.EditorApp.get()
return app.history and app.history.canUndo()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
app = @editor()
# Revert the document to the previous state
app.history.stopWatching()
snapshot = app.history.undo()
app.revertToSnapshot(snapshot)
app.history.watch()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Redo extends ContentTools.Tool
# Redo an action.
ContentTools.ToolShelf.stow(@, 'redo')
@label = 'Redo'
@icon = 'redo'
@requiresElement = false
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
app = ContentTools.EditorApp.get()
return app.history and app.history.canRedo()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
app = ContentTools.EditorApp.get()
# Revert the document to the next state
app.history.stopWatching()
snapshot = app.history.redo()
app.revertToSnapshot(snapshot)
app.history.watch()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Remove extends ContentTools.Tool
# Remove the current element.
ContentTools.ToolShelf.stow(@, 'remove')
@label = 'Remove'
@icon = 'remove'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return not element.isFixed()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Apply the tool to the current element
app = @editor()
# Blur the element before it's removed otherwise it will retain focus
# even when detached.
element.blur()
# Focus on the next element
if element.nextContent()
element.nextContent().focus()
else if element.previousContent()
element.previousContent().focus()
# Check the element is still mounted (some elements may automatically
# remove themselves when they lose focus, for example empty text
# elements.
if not element.isMounted()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
return
# Remove the element
switch element.type()
when 'ListItemText'
# Delete the associated list or list item
if app.ctrlDown()
list = element.closest (node) ->
return node.parent().type() is 'Region'
list.parent().detach(list)
else
element.parent().parent().detach(element.parent())
break
when 'TableCellText'
# Delete the associated table or table row
if app.ctrlDown()
table = element.closest (node) ->
return node.type() is 'Table'
table.parent().detach(table)
else
row = element.parent().parent()
row.parent().detach(row)
break
else
element.parent().detach(element)
break
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Underline extends ContentTools.Tools.Bold
# Make the current selection of text (non)underline (e.g <u>foo</u>).
ContentTools.ToolShelf.stow(@, 'underline')
@label = 'Underline'
@icon = 'underline'
@tagName = 'u'
class ContentTools.Tools.VideoAudio extends ContentTools.Tool
# Insert an audio or video file.
ContentTools.ToolShelf.stow(@, 'video-audio')
@label = 'Fichier Vidéo ou Audio'
@icon = 'file-play'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
unless element.type() is 'ImageFixture'
return false
return true
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.VideoAudioDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
fileURL = detail.fileURL
fileType = detail.fileType
if element.type() is 'ImageFixture'
# Configure the image source against the fixture
element.src(fileURL)
else
# Insert the video
if fileType is 'video/mp4'
fileElt = new ContentEdit.Video(
'video', {
'controls': '',
'height': ContentTools.DEFAULT_VIDEO_HEIGHT,
'src': fileURL,
'width': ContentTools.DEFAULT_VIDEO_WIDTH
})
if fileType is 'audio/mpeg'
fileElt = new ContentEdit.Video(
'audio', {
'controls': '',
'data-ce-moveable': '',
'style': "width:#{ContentTools.DEFAULT_VIDEO_WIDTH}px; min-height: 40px;",
'src': fileURL,
})
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(fileElt, index)
# Focus the new image
fileElt.focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show() | 156021 | class ContentTools.ToolShelf
# The `ToolShelf` class allows tools to be stored using a name (string) as a
# reference. Using a tools name makes is cleaner when defining a set of
# tools to populate the `ToolboxUI` widget.
@_tools = {}
@stow: (cls, name) ->
# Stow a tool on the shelf
@_tools[name] = cls
@fetch: (name) ->
# Fetch a tool from the shelf by it's name
unless @_tools[name]
throw new Error("`#{name}` has not been stowed on the tool shelf")
return @_tools[name]
class ContentTools.Tool
# The `Tool` class defines a common API for editor tools. All tools should
# inherit from the `Tool` class.
#
# Tools classes are designed to be used direct not as instances of the
# class, every property and method for a tool is held against the class.
#
# A tool is effectively a collection of functions (class methods) with a set
# of configuration settings (class properties). For this reason they are
# defined using static classes.
@label = 'Tool'
@icon = 'tool'
# Most tools require an element that they can be applied to, but there are
# exceptions (such as undo/redo). In these cases you can set the
# `requiresElement` flag to false so that the toolbox will not automatically
# disable the tool because there is not element focused.
@requiresElement = true
# Class methods
@canApply: (element, selection) ->
# Return true if the tool can be applied to the specified
# element and selection.
return false
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the specified
# element and selection.
return false
@apply: (element, selection, callback) ->
# Apply the tool to the specified element and selection
throw new Error('Not implemented')
@editor: () ->
# Return an instance of the ContentTools.EditorApp
return ContentTools.EditorApp.get()
@dispatchEditorEvent: (name, detail) ->
# Dispatch an event against the editor
@editor().dispatchEvent(@editor().createEvent(name, detail))
# Private class methods
@_insertAt: (element) ->
# Find insert node and index for inserting an element after the
# specified element.
insertNode = element
if insertNode.parent().type() != 'Region'
insertNode = element.closest (node) ->
return node.parent().type() is 'Region'
insertIndex = insertNode.parent().children.indexOf(insertNode) + 1
return [insertNode, insertIndex]
# Common tools
class ContentTools.Tools.Bold extends ContentTools.Tool
# Make the current selection of text (non)bold (e.g <b>foo</b>).
ContentTools.ToolShelf.stow(@, 'bold')
@label = 'Bold'
@icon = 'bold'
@tagName = 'b'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
unless element.content
return false
return selection and not selection.isCollapsed()
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if element.content is undefined or not element.content.length()
return false
[from, to] = selection.get()
if from == to
to += 1
return element.content.slice(from, to).hasTags(@tagName, true)
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
element.storeState()
[from, to] = selection.get()
if @isApplied(element, selection)
element.content = element.content.unformat(
from,
to,
new HTMLString.Tag(@tagName)
)
else
element.content = element.content.format(
from,
to,
new HTMLString.Tag(@tagName)
)
element.content.optimize()
element.updateInnerHTML()
element.taint()
element.restoreState()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Italic extends ContentTools.Tools.Bold
# Make the current selection of text (non)italic (e.g <i>foo</i>).
ContentTools.ToolShelf.stow(@, 'italic')
@label = 'Italic'
@icon = 'italic'
@tagName = 'i'
class ContentTools.Tools.Link extends ContentTools.Tools.Bold
# Insert/Remove a link.
ContentTools.ToolShelf.stow(@, 'link')
@label = 'Link'
@icon = 'link'
@tagName = 'a'
@getAttr: (attrName, element, selection) ->
# Get an attribute for the element and selection
# Images
if element.type() is 'Image'
if element.a
return element.a[attrName]
# Fixtures
else if element.isFixed() and element.tagName() is 'a'
return element.attr(attrName)
# Text
else
# Find the first character in the selected text that has an `a` tag
# and return the named attributes value.
[from, to] = selection.get()
selectedContent = element.content.slice(from, to)
for c in selectedContent.characters
if not c.hasTags('a')
continue
for tag in c.tags()
if tag.name() == 'a'
return tag.attr(attrName)
return ''
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.type() is 'Image'
return true
else if element.isFixed() and element.tagName() is 'a'
return true
else
# Must support content
unless element.content
return false
# A selection must exist
if not selection
return false
# If the selection is collapsed then it must be within an existing
# link.
if selection.isCollapsed()
character = element.content.characters[selection.get()[0]]
if not character or not character.hasTags('a')
return false
return true
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if element.type() is 'Image'
return element.a
else if element.isFixed() and element.tagName() is 'a'
return true
else
return super(element, selection)
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
applied = false
# Prepare text elements for adding a link
if element.type() is 'Image'
# Images
rect = element.domElement().getBoundingClientRect()
else if element.isFixed() and element.tagName() is 'a'
# Fixtures
rect = element.domElement().getBoundingClientRect()
else
# If the selection is collapsed then we need to select the entire
# entire link.
if selection.isCollapsed()
# Find the bounds of the link
characters = element.content.characters
starts = selection.get(0)[0]
ends = starts
while starts > 0 and characters[starts - 1].hasTags('a')
starts -= 1
while ends < characters.length and characters[ends].hasTags('a')
ends += 1
# Select the link in full
selection = new ContentSelect.Range(starts, ends)
selection.select(element.domElement())
# Text elements
element.storeState()
# Add a fake selection wrapper to the selected text so that it
# appears to be selected when the focus is lost by the element.
selectTag = new HTMLString.Tag('span', {'class': 'ct--puesdo-select'})
[from, to] = selection.get()
element.content = element.content.format(from, to, selectTag)
element.updateInnerHTML()
# Measure a rectangle of the content selected so we can position the
# dialog centrally.
domElement = element.domElement()
measureSpan = domElement.getElementsByClassName('ct--puesdo-select')
rect = measureSpan[0].getBoundingClientRect()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI(transparent=true, allowScrolling=true)
# When the modal is clicked on the dialog should close
modal.addEventListener 'click', () ->
@unmount()
dialog.hide()
if element.content
# Remove the fake selection from the element
element.content = element.content.unformat(from, to, selectTag)
element.updateInnerHTML()
# Restore the selection
element.restoreState()
callback(applied)
# Dispatch `applied` event
if applied
ContentTools.Tools.Link.dispatchEditorEvent(
'tool-applied',
toolDetail
)
# Dialog
dialog = new ContentTools.LinkDialog(
@getAttr('href', element, selection),
@getAttr('target', element, selection)
)
# Get the scroll position required for the dialog
[scrollX, scrollY] = ContentTools.getScrollPosition()
dialog.position([
rect.left + (rect.width / 2) + scrollX,
rect.top + (rect.height / 2) + scrollY
])
dialog.addEventListener 'save', (ev) ->
detail = ev.detail()
applied = true
# Add the link
if element.type() is 'Image'
# Images
#
# Note: When we add/remove links any alignment class needs to be
# moved to either the link (on adding a link) or the image (on
# removing a link). Alignment classes are mutually exclusive.
alignmentClassNames = [
'align-center',
'align-left',
'align-right'
]
if detail.href
element.a = {href: detail.href}
if element.a
element.a.class = element.a['class']
if detail.target
element.a.target = detail.target
for className in alignmentClassNames
if element.hasCSSClass(className)
element.removeCSSClass(className)
element.a['class'] = className
break
else
linkClasses = []
if element.a['class']
linkClasses = element.a['class'].split(' ')
for className in alignmentClassNames
if linkClasses.indexOf(className) > -1
element.addCSSClass(className)
break
element.a = null
element.unmount()
element.mount()
else if element.isFixed() and element.tagName() is 'a'
# Fixtures
element.attr('href', detail.href)
else
# Text elements
# Clear any existing link
element.content = element.content.unformat(from, to, 'a')
# If specified add the new link
if detail.href
a = new HTMLString.Tag('a', detail)
element.content = element.content.format(from, to, a)
element.content.optimize()
element.updateInnerHTML()
# Make sure the element is marked as tainted
element.taint()
# Close the modal and dialog
modal.dispatchEvent(modal.createEvent('click'))
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Heading extends ContentTools.Tool
# Convert the current text block to a heading (e.g <h1>foo</h1>)
ContentTools.ToolShelf.stow(@, 'heading')
@label = 'Heading'
@icon = 'heading'
@tagName = 'h1'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element.content != undefined and
['Text', 'PreText'].indexOf(element.type()) != -1
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if not element.content
return false
if ['Text', 'PreText'].indexOf(element.type()) == -1
return false
return element.tagName() == @tagName
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Apply the tool to the current element
element.storeState()
# If the tag is a PreText tag then we need to handle the convert the
# element not just the tag name.
if element.type() is 'PreText'
# Convert the element to a Text element first
content = element.content.html().replace(/ /g, ' ')
textElement = new ContentEdit.Text(@tagName, {}, content)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(textElement, insertAt)
# Restore selection
element.blur()
textElement.focus()
textElement.selection(selection)
else
# Change the text elements tag name
# Remove any CSS classes from the element
element.removeAttr('class')
# If the element already has the same tag name as the tool will
# apply revert the element to a paragraph.
if element.tagName() == @tagName
element.tagName('p')
else
element.tagName(@tagName)
element.restoreState()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
callback(true)
class ContentTools.Tools.Subheading extends ContentTools.Tools.Heading
# Convert the current text block to a subheading (e.g <h2>foo</h2>)
ContentTools.ToolShelf.stow(@, 'subheading')
@label = 'Subheading'
@icon = 'subheading'
@tagName = 'h2'
class ContentTools.Tools.Paragraph extends ContentTools.Tools.Heading
# Convert the current text block to a paragraph (e.g <p>foo</p>)
ContentTools.ToolShelf.stow(@, 'paragraph')
@label = 'Paragraph'
@icon = 'paragraph'
@tagName = 'p'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element != undefined
@apply: (element, selection, callback) ->
# Apply the tool to the current element
forceAdd = @editor().ctrlDown()
if ContentTools.Tools.Heading.canApply(element) and not forceAdd
# If the element is a top level text element and the user hasn't
# indicated they want to force add a new paragraph convert it to a
# paragraph in-place.
return super(element, selection, callback)
else
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If the element isn't a text element find the nearest top level
# node and insert a new paragraph element after it.
if element.parent().type() != 'Region'
element = element.closest (node) ->
return node.parent().type() is 'Region'
region = element.parent()
paragraph = new ContentEdit.Text('p')
region.attach(paragraph, region.children.indexOf(element) + 1)
# Give the newely inserted paragraph focus
paragraph.focus()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Preformatted extends ContentTools.Tools.Heading
# Convert the current text block to a preformatted block (e.g <pre>foo</pre)
ContentTools.ToolShelf.stow(@, 'preformatted')
@label = 'Preformatted'
@icon = 'preformatted'
@tagName = 'pre'
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If the element is already a PreText element then convert it to a
# paragraph instead.
if element.type() is 'PreText'
ContentTools.Tools.Paragraph.apply(element, selection, callback)
return
# Escape the contents of the existing element
text = element.content.text()
# Create a new pre-text element using the current elements content
preText = new ContentEdit.PreText(
'pre', {},
HTMLString.String.encode(text)
)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(preText, insertAt)
# Restore selection
element.blur()
preText.focus()
preText.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.AlignLeft extends ContentTools.Tool
# Apply a class to left align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-left')
@label = 'Align left'
@icon = 'align-left'
@className = 'text-left'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.content != undefined
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if not @canApply(element)
return false
# List items and table cells use child nodes to manage their content
# which don't support classes, so we need to check the parent.
if element.type() in ['ListItemText', 'TableCellText']
element = element.parent()
return element.hasCSSClass(@className)
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# List items and table cells use child nodes to manage their content
# which don't support classes, so we need to use the parent.
if element.type() in ['ListItemText', 'TableCellText']
element = element.parent()
# Remove any existing text alignment classes applied
alignmentClassNames = [
ContentTools.Tools.AlignLeft.className,
ContentTools.Tools.AlignCenter.className,
ContentTools.Tools.AlignRight.className
]
for className in alignmentClassNames
if element.hasCSSClass(className)
element.removeCSSClass(className)
# If we're removing the class associated with the tool then we
# can return early (this allows the tool to be toggled on/off).
if className == @className
return callback(true)
# Add the alignment class to the element
element.addCSSClass(@className)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.AlignCenter extends ContentTools.Tools.AlignLeft
# Apply a class to center align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-center')
@label = 'Align center'
@icon = 'align-center'
@className = 'text-center'
class ContentTools.Tools.AlignRight extends ContentTools.Tools.AlignLeft
# Apply a class to right align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-right')
@label = 'Align right'
@icon = 'align-right'
@className = 'text-right'
class ContentTools.Tools.UnorderedList extends ContentTools.Tool
# Set an element as an unordered list.
ContentTools.ToolShelf.stow(@, 'unordered-list')
@label = 'Bullet list'
@icon = 'unordered-list'
@listTag = 'ul'
@canApply: (element, selection) ->
if element.isFixed()
return false
# Return true if the tool can be applied to the current
# element/selection.
return element.content != undefined and
element.parent().type() in ['Region', 'ListItem']
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
if element.parent().type() is 'ListItem'
# Find the parent list and change it to an unordered list
element.storeState()
list = element.closest (node) ->
return node.type() is 'List'
list.tagName(@listTag)
element.restoreState()
else
# Convert the element to a list
# Create a new list using the current elements content
listItemText = new ContentEdit.ListItemText(element.content.copy())
listItem = new ContentEdit.ListItem()
listItem.attach(listItemText)
list = new ContentEdit.List(@listTag, {})
list.attach(listItem)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(list, insertAt)
# Restore selection
listItemText.focus()
listItemText.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.OrderedList extends ContentTools.Tools.UnorderedList
# Set an element as an ordered list.
ContentTools.ToolShelf.stow(@, 'ordered-list')
@label = 'Numbers list'
@icon = 'ordered-list'
@listTag = 'ol'
class ContentTools.Tools.Table extends ContentTools.Tool
# Insert/Update a Table.
ContentTools.ToolShelf.stow(@, 'table')
@label = 'Table'
@icon = 'table'
# Class methods
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element != undefined
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# If the element is part of a table find the parent table
table = element.closest (node) ->
return node and node.type() is 'Table'
# Dialog
dialog = new ContentTools.TableDialog(table)
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
tableCfg = ev.detail()
# This flag indicates if we can restore the previous elements focus
# and state or if we need to change the focus to the first cell in
# the table.
keepFocus = true
if table
# Update the existing table
@_updateTable(tableCfg, table)
# Check if the current element is still part of the table after
# being updated.
keepFocus = element.closest (node) ->
return node and node.type() is 'Table'
else
# Create a new table
table = @_createTable(tableCfg)
# Insert it into the document
[node, index] = @_insertAt(element)
node.parent().attach(table, index)
keepFocus = false
if keepFocus
element.restoreState()
else
# Focus on the first cell in the table e.g:
#
# TableSection > TableRow > TableCell > TableCellText
table.firstSection().children[0].children[0].children[0].focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
# Private class methods
@_adjustColumns: (section, columns) ->
# Adjust the number of columns in a table section
for row in section.children
cellTag = row.children[0].tagName()
currentColumns = row.children.length
diff = columns - currentColumns
if diff < 0
# Remove columns
for i in [diff...0]
cell = row.children[row.children.length - 1]
row.detach(cell)
else if diff > 0
# Add columns
for i in [0...diff]
cell = new ContentEdit.TableCell(cellTag)
row.attach(cell)
cellText = new ContentEdit.TableCellText('')
cell.attach(cellText)
@_createTable: (tableCfg) ->
# Create a new table element from the specified configuration
table = new ContentEdit.Table()
# Head
if tableCfg.head
head = @_createTableSection('thead', 'th', tableCfg.columns)
table.attach(head)
# Body
body = @_createTableSection('tbody', 'td', tableCfg.columns)
table.attach(body)
# Foot
if tableCfg.foot
foot = @_createTableSection('tfoot', 'td', tableCfg.columns)
table.attach(foot)
return table
@_createTableSection: (sectionTag, cellTag, columns) ->
# Create a new table section element
section = new ContentEdit.TableSection(sectionTag)
row = new ContentEdit.TableRow()
section.attach(row)
for i in [0...columns]
cell = new ContentEdit.TableCell(cellTag)
row.attach(cell)
cellText = new ContentEdit.TableCellText('')
cell.attach(cellText)
return section
@_updateTable: (tableCfg, table) ->
# Update an existing table
# Remove any sections no longer required
if not tableCfg.head and table.thead()
table.detach(table.thead())
if not tableCfg.foot and table.tfoot()
table.detach(table.tfoot())
# Increase or decrease the number of columns
columns = table.firstSection().children[0].children.length
if tableCfg.columns != columns
for section in table.children
@_adjustColumns(section, tableCfg.columns)
# Add any new sections
if tableCfg.head and not table.thead()
head = @_createTableSection('thead', 'th', tableCfg.columns)
table.attach(head, 0)
if tableCfg.foot and not table.tfoot()
foot = @_createTableSection('tfoot', 'td', tableCfg.columns)
table.attach(foot)
class ContentTools.Tools.Indent extends ContentTools.Tool
# Indent a list item.
ContentTools.ToolShelf.stow(@, 'indent')
@label = 'Indent'
@icon = 'indent'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.parent().type() is 'ListItem' and
element.parent().parent().children.indexOf(element.parent()) > 0
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Indent the list item
element.parent().indent()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Unindent extends ContentTools.Tool
# Unindent a list item.
ContentTools.ToolShelf.stow(@, 'unindent')
@label = 'Unindent'
@icon = 'unindent'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.parent().type() is 'ListItem'
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Indent the list item
element.parent().unindent()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.LineBreak extends ContentTools.Tool
# Insert a line break in to the current element at the specified selection.
ContentTools.ToolShelf.stow(@, 'line-break')
@label = 'Line break'
@icon = 'line-break'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.content
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Insert a BR at the current in index
cursor = selection.get()[0] + 1
tip = element.content.substring(0, selection.get()[0])
tail = element.content.substring(selection.get()[1])
br = new HTMLString.String('<br>', element.content.preserveWhitespace())
element.content = tip.concat(br, tail)
element.updateInnerHTML()
element.taint()
# Restore the selection
selection.set(cursor, cursor)
element.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Image extends ContentTools.Tool
# Insert an image.
ContentTools.ToolShelf.stow(@, 'image')
@label = 'Image'
@icon = 'image'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
unless element.type() is 'ImageFixture'
return false
return true
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.ImageDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
imageURL = detail.imageURL
imageSize = detail.imageSize
imageAttrs = detail.imageAttrs
if not imageAttrs
imageAttrs = {}
imageAttrs.height = imageSize[1]
imageAttrs.src = imageURL
imageAttrs.width = imageSize[0]
if element.type() is 'ImageFixture'
# Configure the image source against the fixture
element.src(imageURL)
else
# Create the new image
image = new ContentEdit.Image(imageAttrs)
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(image, index)
# Focus the new image
image.focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Video extends ContentTools.Tool
# Insert a video.
ContentTools.ToolShelf.stow(@, 'video')
@label = '<NAME> ou Youtube'
@icon = 'youtube'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return not element.isFixed()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.VideoDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
url = ev.detail().url
if url
# Create the new video
video = new ContentEdit.Video(
'iframe', {
'frameborder': 0,
'height': ContentTools.DEFAULT_VIDEO_HEIGHT,
'src': url,
'width': ContentTools.DEFAULT_VIDEO_WIDTH
})
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(video, index)
# Focus the new video
video.focus()
else
# Nothing to do restore state
if element.restoreState
element.restoreState()
modal.hide()
dialog.hide()
applied = url != ''
callback(applied)
# Dispatch `applied` event
if applied
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Undo extends ContentTools.Tool
# Undo an action.
ContentTools.ToolShelf.stow(@, 'undo')
@label = 'Undo'
@icon = 'undo'
@requiresElement = false
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
app = ContentTools.EditorApp.get()
return app.history and app.history.canUndo()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
app = @editor()
# Revert the document to the previous state
app.history.stopWatching()
snapshot = app.history.undo()
app.revertToSnapshot(snapshot)
app.history.watch()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Redo extends ContentTools.Tool
# Redo an action.
ContentTools.ToolShelf.stow(@, 'redo')
@label = 'Redo'
@icon = 'redo'
@requiresElement = false
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
app = ContentTools.EditorApp.get()
return app.history and app.history.canRedo()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
app = ContentTools.EditorApp.get()
# Revert the document to the next state
app.history.stopWatching()
snapshot = app.history.redo()
app.revertToSnapshot(snapshot)
app.history.watch()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Remove extends ContentTools.Tool
# Remove the current element.
ContentTools.ToolShelf.stow(@, 'remove')
@label = 'Remove'
@icon = 'remove'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return not element.isFixed()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Apply the tool to the current element
app = @editor()
# Blur the element before it's removed otherwise it will retain focus
# even when detached.
element.blur()
# Focus on the next element
if element.nextContent()
element.nextContent().focus()
else if element.previousContent()
element.previousContent().focus()
# Check the element is still mounted (some elements may automatically
# remove themselves when they lose focus, for example empty text
# elements.
if not element.isMounted()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
return
# Remove the element
switch element.type()
when 'ListItemText'
# Delete the associated list or list item
if app.ctrlDown()
list = element.closest (node) ->
return node.parent().type() is 'Region'
list.parent().detach(list)
else
element.parent().parent().detach(element.parent())
break
when 'TableCellText'
# Delete the associated table or table row
if app.ctrlDown()
table = element.closest (node) ->
return node.type() is 'Table'
table.parent().detach(table)
else
row = element.parent().parent()
row.parent().detach(row)
break
else
element.parent().detach(element)
break
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Underline extends ContentTools.Tools.Bold
# Make the current selection of text (non)underline (e.g <u>foo</u>).
ContentTools.ToolShelf.stow(@, 'underline')
@label = 'Underline'
@icon = 'underline'
@tagName = 'u'
class ContentTools.Tools.VideoAudio extends ContentTools.Tool
# Insert an audio or video file.
ContentTools.ToolShelf.stow(@, 'video-audio')
@label = 'Fichier Vidéo ou Audio'
@icon = 'file-play'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
unless element.type() is 'ImageFixture'
return false
return true
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.VideoAudioDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
fileURL = detail.fileURL
fileType = detail.fileType
if element.type() is 'ImageFixture'
# Configure the image source against the fixture
element.src(fileURL)
else
# Insert the video
if fileType is 'video/mp4'
fileElt = new ContentEdit.Video(
'video', {
'controls': '',
'height': ContentTools.DEFAULT_VIDEO_HEIGHT,
'src': fileURL,
'width': ContentTools.DEFAULT_VIDEO_WIDTH
})
if fileType is 'audio/mpeg'
fileElt = new ContentEdit.Video(
'audio', {
'controls': '',
'data-ce-moveable': '',
'style': "width:#{ContentTools.DEFAULT_VIDEO_WIDTH}px; min-height: 40px;",
'src': fileURL,
})
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(fileElt, index)
# Focus the new image
fileElt.focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show() | true | class ContentTools.ToolShelf
# The `ToolShelf` class allows tools to be stored using a name (string) as a
# reference. Using a tools name makes is cleaner when defining a set of
# tools to populate the `ToolboxUI` widget.
@_tools = {}
@stow: (cls, name) ->
# Stow a tool on the shelf
@_tools[name] = cls
@fetch: (name) ->
# Fetch a tool from the shelf by it's name
unless @_tools[name]
throw new Error("`#{name}` has not been stowed on the tool shelf")
return @_tools[name]
class ContentTools.Tool
# The `Tool` class defines a common API for editor tools. All tools should
# inherit from the `Tool` class.
#
# Tools classes are designed to be used direct not as instances of the
# class, every property and method for a tool is held against the class.
#
# A tool is effectively a collection of functions (class methods) with a set
# of configuration settings (class properties). For this reason they are
# defined using static classes.
@label = 'Tool'
@icon = 'tool'
# Most tools require an element that they can be applied to, but there are
# exceptions (such as undo/redo). In these cases you can set the
# `requiresElement` flag to false so that the toolbox will not automatically
# disable the tool because there is not element focused.
@requiresElement = true
# Class methods
@canApply: (element, selection) ->
# Return true if the tool can be applied to the specified
# element and selection.
return false
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the specified
# element and selection.
return false
@apply: (element, selection, callback) ->
# Apply the tool to the specified element and selection
throw new Error('Not implemented')
@editor: () ->
# Return an instance of the ContentTools.EditorApp
return ContentTools.EditorApp.get()
@dispatchEditorEvent: (name, detail) ->
# Dispatch an event against the editor
@editor().dispatchEvent(@editor().createEvent(name, detail))
# Private class methods
@_insertAt: (element) ->
# Find insert node and index for inserting an element after the
# specified element.
insertNode = element
if insertNode.parent().type() != 'Region'
insertNode = element.closest (node) ->
return node.parent().type() is 'Region'
insertIndex = insertNode.parent().children.indexOf(insertNode) + 1
return [insertNode, insertIndex]
# Common tools
class ContentTools.Tools.Bold extends ContentTools.Tool
# Make the current selection of text (non)bold (e.g <b>foo</b>).
ContentTools.ToolShelf.stow(@, 'bold')
@label = 'Bold'
@icon = 'bold'
@tagName = 'b'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
unless element.content
return false
return selection and not selection.isCollapsed()
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if element.content is undefined or not element.content.length()
return false
[from, to] = selection.get()
if from == to
to += 1
return element.content.slice(from, to).hasTags(@tagName, true)
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
element.storeState()
[from, to] = selection.get()
if @isApplied(element, selection)
element.content = element.content.unformat(
from,
to,
new HTMLString.Tag(@tagName)
)
else
element.content = element.content.format(
from,
to,
new HTMLString.Tag(@tagName)
)
element.content.optimize()
element.updateInnerHTML()
element.taint()
element.restoreState()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Italic extends ContentTools.Tools.Bold
# Make the current selection of text (non)italic (e.g <i>foo</i>).
ContentTools.ToolShelf.stow(@, 'italic')
@label = 'Italic'
@icon = 'italic'
@tagName = 'i'
class ContentTools.Tools.Link extends ContentTools.Tools.Bold
# Insert/Remove a link.
ContentTools.ToolShelf.stow(@, 'link')
@label = 'Link'
@icon = 'link'
@tagName = 'a'
@getAttr: (attrName, element, selection) ->
# Get an attribute for the element and selection
# Images
if element.type() is 'Image'
if element.a
return element.a[attrName]
# Fixtures
else if element.isFixed() and element.tagName() is 'a'
return element.attr(attrName)
# Text
else
# Find the first character in the selected text that has an `a` tag
# and return the named attributes value.
[from, to] = selection.get()
selectedContent = element.content.slice(from, to)
for c in selectedContent.characters
if not c.hasTags('a')
continue
for tag in c.tags()
if tag.name() == 'a'
return tag.attr(attrName)
return ''
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.type() is 'Image'
return true
else if element.isFixed() and element.tagName() is 'a'
return true
else
# Must support content
unless element.content
return false
# A selection must exist
if not selection
return false
# If the selection is collapsed then it must be within an existing
# link.
if selection.isCollapsed()
character = element.content.characters[selection.get()[0]]
if not character or not character.hasTags('a')
return false
return true
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if element.type() is 'Image'
return element.a
else if element.isFixed() and element.tagName() is 'a'
return true
else
return super(element, selection)
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
applied = false
# Prepare text elements for adding a link
if element.type() is 'Image'
# Images
rect = element.domElement().getBoundingClientRect()
else if element.isFixed() and element.tagName() is 'a'
# Fixtures
rect = element.domElement().getBoundingClientRect()
else
# If the selection is collapsed then we need to select the entire
# entire link.
if selection.isCollapsed()
# Find the bounds of the link
characters = element.content.characters
starts = selection.get(0)[0]
ends = starts
while starts > 0 and characters[starts - 1].hasTags('a')
starts -= 1
while ends < characters.length and characters[ends].hasTags('a')
ends += 1
# Select the link in full
selection = new ContentSelect.Range(starts, ends)
selection.select(element.domElement())
# Text elements
element.storeState()
# Add a fake selection wrapper to the selected text so that it
# appears to be selected when the focus is lost by the element.
selectTag = new HTMLString.Tag('span', {'class': 'ct--puesdo-select'})
[from, to] = selection.get()
element.content = element.content.format(from, to, selectTag)
element.updateInnerHTML()
# Measure a rectangle of the content selected so we can position the
# dialog centrally.
domElement = element.domElement()
measureSpan = domElement.getElementsByClassName('ct--puesdo-select')
rect = measureSpan[0].getBoundingClientRect()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI(transparent=true, allowScrolling=true)
# When the modal is clicked on the dialog should close
modal.addEventListener 'click', () ->
@unmount()
dialog.hide()
if element.content
# Remove the fake selection from the element
element.content = element.content.unformat(from, to, selectTag)
element.updateInnerHTML()
# Restore the selection
element.restoreState()
callback(applied)
# Dispatch `applied` event
if applied
ContentTools.Tools.Link.dispatchEditorEvent(
'tool-applied',
toolDetail
)
# Dialog
dialog = new ContentTools.LinkDialog(
@getAttr('href', element, selection),
@getAttr('target', element, selection)
)
# Get the scroll position required for the dialog
[scrollX, scrollY] = ContentTools.getScrollPosition()
dialog.position([
rect.left + (rect.width / 2) + scrollX,
rect.top + (rect.height / 2) + scrollY
])
dialog.addEventListener 'save', (ev) ->
detail = ev.detail()
applied = true
# Add the link
if element.type() is 'Image'
# Images
#
# Note: When we add/remove links any alignment class needs to be
# moved to either the link (on adding a link) or the image (on
# removing a link). Alignment classes are mutually exclusive.
alignmentClassNames = [
'align-center',
'align-left',
'align-right'
]
if detail.href
element.a = {href: detail.href}
if element.a
element.a.class = element.a['class']
if detail.target
element.a.target = detail.target
for className in alignmentClassNames
if element.hasCSSClass(className)
element.removeCSSClass(className)
element.a['class'] = className
break
else
linkClasses = []
if element.a['class']
linkClasses = element.a['class'].split(' ')
for className in alignmentClassNames
if linkClasses.indexOf(className) > -1
element.addCSSClass(className)
break
element.a = null
element.unmount()
element.mount()
else if element.isFixed() and element.tagName() is 'a'
# Fixtures
element.attr('href', detail.href)
else
# Text elements
# Clear any existing link
element.content = element.content.unformat(from, to, 'a')
# If specified add the new link
if detail.href
a = new HTMLString.Tag('a', detail)
element.content = element.content.format(from, to, a)
element.content.optimize()
element.updateInnerHTML()
# Make sure the element is marked as tainted
element.taint()
# Close the modal and dialog
modal.dispatchEvent(modal.createEvent('click'))
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Heading extends ContentTools.Tool
# Convert the current text block to a heading (e.g <h1>foo</h1>)
ContentTools.ToolShelf.stow(@, 'heading')
@label = 'Heading'
@icon = 'heading'
@tagName = 'h1'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element.content != undefined and
['Text', 'PreText'].indexOf(element.type()) != -1
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if not element.content
return false
if ['Text', 'PreText'].indexOf(element.type()) == -1
return false
return element.tagName() == @tagName
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Apply the tool to the current element
element.storeState()
# If the tag is a PreText tag then we need to handle the convert the
# element not just the tag name.
if element.type() is 'PreText'
# Convert the element to a Text element first
content = element.content.html().replace(/ /g, ' ')
textElement = new ContentEdit.Text(@tagName, {}, content)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(textElement, insertAt)
# Restore selection
element.blur()
textElement.focus()
textElement.selection(selection)
else
# Change the text elements tag name
# Remove any CSS classes from the element
element.removeAttr('class')
# If the element already has the same tag name as the tool will
# apply revert the element to a paragraph.
if element.tagName() == @tagName
element.tagName('p')
else
element.tagName(@tagName)
element.restoreState()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
callback(true)
class ContentTools.Tools.Subheading extends ContentTools.Tools.Heading
# Convert the current text block to a subheading (e.g <h2>foo</h2>)
ContentTools.ToolShelf.stow(@, 'subheading')
@label = 'Subheading'
@icon = 'subheading'
@tagName = 'h2'
class ContentTools.Tools.Paragraph extends ContentTools.Tools.Heading
# Convert the current text block to a paragraph (e.g <p>foo</p>)
ContentTools.ToolShelf.stow(@, 'paragraph')
@label = 'Paragraph'
@icon = 'paragraph'
@tagName = 'p'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element != undefined
@apply: (element, selection, callback) ->
# Apply the tool to the current element
forceAdd = @editor().ctrlDown()
if ContentTools.Tools.Heading.canApply(element) and not forceAdd
# If the element is a top level text element and the user hasn't
# indicated they want to force add a new paragraph convert it to a
# paragraph in-place.
return super(element, selection, callback)
else
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If the element isn't a text element find the nearest top level
# node and insert a new paragraph element after it.
if element.parent().type() != 'Region'
element = element.closest (node) ->
return node.parent().type() is 'Region'
region = element.parent()
paragraph = new ContentEdit.Text('p')
region.attach(paragraph, region.children.indexOf(element) + 1)
# Give the newely inserted paragraph focus
paragraph.focus()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Preformatted extends ContentTools.Tools.Heading
# Convert the current text block to a preformatted block (e.g <pre>foo</pre)
ContentTools.ToolShelf.stow(@, 'preformatted')
@label = 'Preformatted'
@icon = 'preformatted'
@tagName = 'pre'
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If the element is already a PreText element then convert it to a
# paragraph instead.
if element.type() is 'PreText'
ContentTools.Tools.Paragraph.apply(element, selection, callback)
return
# Escape the contents of the existing element
text = element.content.text()
# Create a new pre-text element using the current elements content
preText = new ContentEdit.PreText(
'pre', {},
HTMLString.String.encode(text)
)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(preText, insertAt)
# Restore selection
element.blur()
preText.focus()
preText.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.AlignLeft extends ContentTools.Tool
# Apply a class to left align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-left')
@label = 'Align left'
@icon = 'align-left'
@className = 'text-left'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.content != undefined
@isApplied: (element, selection) ->
# Return true if the tool is currently applied to the current
# element/selection.
if not @canApply(element)
return false
# List items and table cells use child nodes to manage their content
# which don't support classes, so we need to check the parent.
if element.type() in ['ListItemText', 'TableCellText']
element = element.parent()
return element.hasCSSClass(@className)
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# List items and table cells use child nodes to manage their content
# which don't support classes, so we need to use the parent.
if element.type() in ['ListItemText', 'TableCellText']
element = element.parent()
# Remove any existing text alignment classes applied
alignmentClassNames = [
ContentTools.Tools.AlignLeft.className,
ContentTools.Tools.AlignCenter.className,
ContentTools.Tools.AlignRight.className
]
for className in alignmentClassNames
if element.hasCSSClass(className)
element.removeCSSClass(className)
# If we're removing the class associated with the tool then we
# can return early (this allows the tool to be toggled on/off).
if className == @className
return callback(true)
# Add the alignment class to the element
element.addCSSClass(@className)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.AlignCenter extends ContentTools.Tools.AlignLeft
# Apply a class to center align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-center')
@label = 'Align center'
@icon = 'align-center'
@className = 'text-center'
class ContentTools.Tools.AlignRight extends ContentTools.Tools.AlignLeft
# Apply a class to right align the contents of the current text block.
ContentTools.ToolShelf.stow(@, 'align-right')
@label = 'Align right'
@icon = 'align-right'
@className = 'text-right'
class ContentTools.Tools.UnorderedList extends ContentTools.Tool
# Set an element as an unordered list.
ContentTools.ToolShelf.stow(@, 'unordered-list')
@label = 'Bullet list'
@icon = 'unordered-list'
@listTag = 'ul'
@canApply: (element, selection) ->
if element.isFixed()
return false
# Return true if the tool can be applied to the current
# element/selection.
return element.content != undefined and
element.parent().type() in ['Region', 'ListItem']
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
if element.parent().type() is 'ListItem'
# Find the parent list and change it to an unordered list
element.storeState()
list = element.closest (node) ->
return node.type() is 'List'
list.tagName(@listTag)
element.restoreState()
else
# Convert the element to a list
# Create a new list using the current elements content
listItemText = new ContentEdit.ListItemText(element.content.copy())
listItem = new ContentEdit.ListItem()
listItem.attach(listItemText)
list = new ContentEdit.List(@listTag, {})
list.attach(listItem)
# Remove the current element from the region
parent = element.parent()
insertAt = parent.children.indexOf(element)
parent.detach(element)
parent.attach(list, insertAt)
# Restore selection
listItemText.focus()
listItemText.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.OrderedList extends ContentTools.Tools.UnorderedList
# Set an element as an ordered list.
ContentTools.ToolShelf.stow(@, 'ordered-list')
@label = 'Numbers list'
@icon = 'ordered-list'
@listTag = 'ol'
class ContentTools.Tools.Table extends ContentTools.Tool
# Insert/Update a Table.
ContentTools.ToolShelf.stow(@, 'table')
@label = 'Table'
@icon = 'table'
# Class methods
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
return false
return element != undefined
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# If the element is part of a table find the parent table
table = element.closest (node) ->
return node and node.type() is 'Table'
# Dialog
dialog = new ContentTools.TableDialog(table)
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
tableCfg = ev.detail()
# This flag indicates if we can restore the previous elements focus
# and state or if we need to change the focus to the first cell in
# the table.
keepFocus = true
if table
# Update the existing table
@_updateTable(tableCfg, table)
# Check if the current element is still part of the table after
# being updated.
keepFocus = element.closest (node) ->
return node and node.type() is 'Table'
else
# Create a new table
table = @_createTable(tableCfg)
# Insert it into the document
[node, index] = @_insertAt(element)
node.parent().attach(table, index)
keepFocus = false
if keepFocus
element.restoreState()
else
# Focus on the first cell in the table e.g:
#
# TableSection > TableRow > TableCell > TableCellText
table.firstSection().children[0].children[0].children[0].focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
# Private class methods
@_adjustColumns: (section, columns) ->
# Adjust the number of columns in a table section
for row in section.children
cellTag = row.children[0].tagName()
currentColumns = row.children.length
diff = columns - currentColumns
if diff < 0
# Remove columns
for i in [diff...0]
cell = row.children[row.children.length - 1]
row.detach(cell)
else if diff > 0
# Add columns
for i in [0...diff]
cell = new ContentEdit.TableCell(cellTag)
row.attach(cell)
cellText = new ContentEdit.TableCellText('')
cell.attach(cellText)
@_createTable: (tableCfg) ->
# Create a new table element from the specified configuration
table = new ContentEdit.Table()
# Head
if tableCfg.head
head = @_createTableSection('thead', 'th', tableCfg.columns)
table.attach(head)
# Body
body = @_createTableSection('tbody', 'td', tableCfg.columns)
table.attach(body)
# Foot
if tableCfg.foot
foot = @_createTableSection('tfoot', 'td', tableCfg.columns)
table.attach(foot)
return table
@_createTableSection: (sectionTag, cellTag, columns) ->
# Create a new table section element
section = new ContentEdit.TableSection(sectionTag)
row = new ContentEdit.TableRow()
section.attach(row)
for i in [0...columns]
cell = new ContentEdit.TableCell(cellTag)
row.attach(cell)
cellText = new ContentEdit.TableCellText('')
cell.attach(cellText)
return section
@_updateTable: (tableCfg, table) ->
# Update an existing table
# Remove any sections no longer required
if not tableCfg.head and table.thead()
table.detach(table.thead())
if not tableCfg.foot and table.tfoot()
table.detach(table.tfoot())
# Increase or decrease the number of columns
columns = table.firstSection().children[0].children.length
if tableCfg.columns != columns
for section in table.children
@_adjustColumns(section, tableCfg.columns)
# Add any new sections
if tableCfg.head and not table.thead()
head = @_createTableSection('thead', 'th', tableCfg.columns)
table.attach(head, 0)
if tableCfg.foot and not table.tfoot()
foot = @_createTableSection('tfoot', 'td', tableCfg.columns)
table.attach(foot)
class ContentTools.Tools.Indent extends ContentTools.Tool
# Indent a list item.
ContentTools.ToolShelf.stow(@, 'indent')
@label = 'Indent'
@icon = 'indent'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.parent().type() is 'ListItem' and
element.parent().parent().children.indexOf(element.parent()) > 0
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Indent the list item
element.parent().indent()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Unindent extends ContentTools.Tool
# Unindent a list item.
ContentTools.ToolShelf.stow(@, 'unindent')
@label = 'Unindent'
@icon = 'unindent'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.parent().type() is 'ListItem'
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Indent the list item
element.parent().unindent()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.LineBreak extends ContentTools.Tool
# Insert a line break in to the current element at the specified selection.
ContentTools.ToolShelf.stow(@, 'line-break')
@label = 'Line break'
@icon = 'line-break'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return element.content
@apply: (element, selection, callback) ->
# Apply the tool to the current element
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Insert a BR at the current in index
cursor = selection.get()[0] + 1
tip = element.content.substring(0, selection.get()[0])
tail = element.content.substring(selection.get()[1])
br = new HTMLString.String('<br>', element.content.preserveWhitespace())
element.content = tip.concat(br, tail)
element.updateInnerHTML()
element.taint()
# Restore the selection
selection.set(cursor, cursor)
element.selection(selection)
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Image extends ContentTools.Tool
# Insert an image.
ContentTools.ToolShelf.stow(@, 'image')
@label = 'Image'
@icon = 'image'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
unless element.type() is 'ImageFixture'
return false
return true
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.ImageDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
imageURL = detail.imageURL
imageSize = detail.imageSize
imageAttrs = detail.imageAttrs
if not imageAttrs
imageAttrs = {}
imageAttrs.height = imageSize[1]
imageAttrs.src = imageURL
imageAttrs.width = imageSize[0]
if element.type() is 'ImageFixture'
# Configure the image source against the fixture
element.src(imageURL)
else
# Create the new image
image = new ContentEdit.Image(imageAttrs)
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(image, index)
# Focus the new image
image.focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Video extends ContentTools.Tool
# Insert a video.
ContentTools.ToolShelf.stow(@, 'video')
@label = 'PI:NAME:<NAME>END_PI ou Youtube'
@icon = 'youtube'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return not element.isFixed()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.VideoDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
url = ev.detail().url
if url
# Create the new video
video = new ContentEdit.Video(
'iframe', {
'frameborder': 0,
'height': ContentTools.DEFAULT_VIDEO_HEIGHT,
'src': url,
'width': ContentTools.DEFAULT_VIDEO_WIDTH
})
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(video, index)
# Focus the new video
video.focus()
else
# Nothing to do restore state
if element.restoreState
element.restoreState()
modal.hide()
dialog.hide()
applied = url != ''
callback(applied)
# Dispatch `applied` event
if applied
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show()
class ContentTools.Tools.Undo extends ContentTools.Tool
# Undo an action.
ContentTools.ToolShelf.stow(@, 'undo')
@label = 'Undo'
@icon = 'undo'
@requiresElement = false
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
app = ContentTools.EditorApp.get()
return app.history and app.history.canUndo()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
app = @editor()
# Revert the document to the previous state
app.history.stopWatching()
snapshot = app.history.undo()
app.revertToSnapshot(snapshot)
app.history.watch()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Redo extends ContentTools.Tool
# Redo an action.
ContentTools.ToolShelf.stow(@, 'redo')
@label = 'Redo'
@icon = 'redo'
@requiresElement = false
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
app = ContentTools.EditorApp.get()
return app.history and app.history.canRedo()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
app = ContentTools.EditorApp.get()
# Revert the document to the next state
app.history.stopWatching()
snapshot = app.history.redo()
app.revertToSnapshot(snapshot)
app.history.watch()
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Remove extends ContentTools.Tool
# Remove the current element.
ContentTools.ToolShelf.stow(@, 'remove')
@label = 'Remove'
@icon = 'remove'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
return not element.isFixed()
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# Apply the tool to the current element
app = @editor()
# Blur the element before it's removed otherwise it will retain focus
# even when detached.
element.blur()
# Focus on the next element
if element.nextContent()
element.nextContent().focus()
else if element.previousContent()
element.previousContent().focus()
# Check the element is still mounted (some elements may automatically
# remove themselves when they lose focus, for example empty text
# elements.
if not element.isMounted()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
return
# Remove the element
switch element.type()
when 'ListItemText'
# Delete the associated list or list item
if app.ctrlDown()
list = element.closest (node) ->
return node.parent().type() is 'Region'
list.parent().detach(list)
else
element.parent().parent().detach(element.parent())
break
when 'TableCellText'
# Delete the associated table or table row
if app.ctrlDown()
table = element.closest (node) ->
return node.type() is 'Table'
table.parent().detach(table)
else
row = element.parent().parent()
row.parent().detach(row)
break
else
element.parent().detach(element)
break
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
class ContentTools.Tools.Underline extends ContentTools.Tools.Bold
# Make the current selection of text (non)underline (e.g <u>foo</u>).
ContentTools.ToolShelf.stow(@, 'underline')
@label = 'Underline'
@icon = 'underline'
@tagName = 'u'
class ContentTools.Tools.VideoAudio extends ContentTools.Tool
# Insert an audio or video file.
ContentTools.ToolShelf.stow(@, 'video-audio')
@label = 'Fichier Vidéo ou Audio'
@icon = 'file-play'
@canApply: (element, selection) ->
# Return true if the tool can be applied to the current
# element/selection.
if element.isFixed()
unless element.type() is 'ImageFixture'
return false
return true
@apply: (element, selection, callback) ->
# Dispatch `apply` event
toolDetail = {
'tool': this,
'element': element,
'selection': selection
}
if not @dispatchEditorEvent('tool-apply', toolDetail)
return
# If supported allow store the state for restoring once the dialog is
# cancelled.
if element.storeState
element.storeState()
# Set-up the dialog
app = ContentTools.EditorApp.get()
# Modal
modal = new ContentTools.ModalUI()
# Dialog
dialog = new ContentTools.VideoAudioDialog()
# Support cancelling the dialog
dialog.addEventListener 'cancel', () =>
modal.hide()
dialog.hide()
if element.restoreState
element.restoreState()
callback(false)
# Support saving the dialog
dialog.addEventListener 'save', (ev) =>
detail = ev.detail()
fileURL = detail.fileURL
fileType = detail.fileType
if element.type() is 'ImageFixture'
# Configure the image source against the fixture
element.src(fileURL)
else
# Insert the video
if fileType is 'video/mp4'
fileElt = new ContentEdit.Video(
'video', {
'controls': '',
'height': ContentTools.DEFAULT_VIDEO_HEIGHT,
'src': fileURL,
'width': ContentTools.DEFAULT_VIDEO_WIDTH
})
if fileType is 'audio/mpeg'
fileElt = new ContentEdit.Video(
'audio', {
'controls': '',
'data-ce-moveable': '',
'style': "width:#{ContentTools.DEFAULT_VIDEO_WIDTH}px; min-height: 40px;",
'src': fileURL,
})
# Find insert position
[node, index] = @_insertAt(element)
node.parent().attach(fileElt, index)
# Focus the new image
fileElt.focus()
modal.hide()
dialog.hide()
callback(true)
# Dispatch `applied` event
@dispatchEditorEvent('tool-applied', toolDetail)
# Show the dialog
app.attach(modal)
app.attach(dialog)
modal.show()
dialog.show() |
[
{
"context": " 'a.d',\n 'e.f.g',\n ]\n obj = [\n {name: 'alice', age: 17}\n {name: 'bob', age: 32}\n {name: ",
"end": 324,
"score": 0.9996612071990967,
"start": 319,
"tag": "NAME",
"value": "alice"
},
{
"context": " obj = [\n {name: 'alice', age: 17}\n {name: 'bob', age: 32}\n {name: 'charlie', age: 25}\n ]\n _",
"end": 351,
"score": 0.9996590614318848,
"start": 348,
"tag": "NAME",
"value": "bob"
},
{
"context": ", age: 17}\n {name: 'bob', age: 32}\n {name: 'charlie', age: 25}\n ]\n _keys = objelity.deepKeys(obj)\n ",
"end": 382,
"score": 0.9993078708648682,
"start": 375,
"tag": "NAME",
"value": "charlie"
}
] | coffee/test/index.test.coffee | mick-whats/objelity | 0 | objelity = require('../')
{test} = require 'ava'
test 'deepKeys', (t) ->
obj =
a:
b:
c: [1,2,3]
d: new Date()
e:
f:
g: 'h'
_keys = objelity.deepKeys(obj)
t.deepEqual _keys, [
'a.b.c.0',
'a.b.c.1',
'a.b.c.2',
'a.d',
'e.f.g',
]
obj = [
{name: 'alice', age: 17}
{name: 'bob', age: 32}
{name: 'charlie', age: 25}
]
_keys = objelity.deepKeys(obj)
t.deepEqual _keys, [
'0.name',
'0.age',
'1.name',
'1.age',
'2.name',
'2.age',
]
test 'commonPath(pathStrings)', (t) ->
paths = [
'a.b.c.d.e.f',
'a.b.c.x.z',
'a.b.c',
'a.b.c.d.s',
]
t.deepEqual objelity.commonPath(paths),['a','b','c']
test 'commonPath(pathStrings)', (t) ->
paths = [
'a.b.c.d.e.f',
'd.e.f',
]
t.deepEqual objelity.commonPath(paths),[]
test 'commonPath(pathArray)', (t) ->
paths = [
['a','b','c','d','e']
['a','b','c','x','z','q']
['a','b','c','g','r']
['a','b','c','s']
['a','b','c']
]
t.deepEqual objelity.commonPath(paths),['a','b','c']
test 'compactObject(obj)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.compactObject(obj), {
aaa:
bbb:
ccc: 1
ddd: 0
hhh:
iii:
jjj: true
}
test 'flattenObject(obj)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.flattenObject(obj), {
aaa_bbb_ccc: 1,
aaa_bbb_ddd: 0,
aaa_eee_fff: undefined,
aaa_eee_ggg: null,
aaa_hhh_iii_jjj: true,
}
test 'flattenObject(obj, separator)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.flattenObject(obj, '-'), {
'aaa-bbb-ccc': 1,
'aaa-bbb-ddd': 0,
'aaa-eee-fff': undefined,
'aaa-eee-ggg': null,
'aaa-hhh-iii-jjj': true,
}
test 'eachObject(obj, fn)', (t) ->
t.plan(4)
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
objelity.eachObject obj, (val,path,index,object) ->
if path.includes('aaa.bbb.ccc')
t.is val, 1
else if path.includes('aaa.bbb.ddd')
t.is val, 2
else if path.includes('aaa.eee.fff')
t.is val, 3
else if path.includes('aaa.eee.ggg')
t.is val, 4
return
test 'mapObject(obj, fn) with sum', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.mapObject obj, (val,path,index,object) ->
return val * 2
t.deepEqual newObj, {
aaa:
bbb:
ccc: 2
ddd: 4
eee:
fff: 6
ggg: 8
}
test 'mapObject(obj, fn) with returned array', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
newObj = objelity.mapObject obj, (val,path,index,object) ->
if path.match(/aaa\.bbb/)
newPath = path.replace('aaa.bbb','xxx')
return [newPath, val]
else
return [path, val]
t.deepEqual newObj, {
xxx:
ccc: 1
ddd: 0
aaa:
eee:
fff: undefined
ggg: null
}
test 'mapObject(obj, fn) with returned object', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
newObj = objelity.mapObject obj, (val,path,index,object) ->
if path.match(/aaa\.bbb/)
newPath = path.replace('aaa.bbb','xxx')
return {[newPath]: val}
else
return {[path]: val}
t.deepEqual newObj, {
xxx:
ccc: 1
ddd: 0
aaa:
eee:
fff: undefined
ggg: null
}
test 'toText(obj)', (t) ->
obj = {a: 1}
_t = objelity.toText(obj)
t.not _t, '{"a": 1}'
t.regex _t, /{\s{2,}"a": 1\n}/
test 'toText(arr)', (t) ->
obj = [1,2,3]
_t = objelity.toText(obj)
t.not _t, '[1,2,3]'
t.regex _t, /\[\n\s{2}1,\n\s{2}2,\n\s{2}3\s{1}\]/
test 'toText(fn)', (t) ->
obj = => return true
_t = objelity.toText(obj)
t.regex _t, /\(\(\)\s=>\s{\n\s{6}return true;\n\s{4}}\)\(\)/
test 'toText(str)', (t) ->
obj = 'str'
_t = objelity.toText(obj)
t.is _t, 'str'
test 'toText(num)', (t) ->
obj = 123
_t = objelity.toText(obj)
t.is _t, '123'
test 'toText(undefined)', (t) ->
obj = undefined
_t = objelity.toText(obj)
t.is _t, 'undefined'
test 'toText(null)', (t) ->
obj = null
_t = objelity.toText(obj)
t.is _t, 'null'
test 'toText(true)', (t) ->
obj = true
_t = objelity.toText(obj)
t.is _t, 'true'
test 'toText(NaN)', (t) ->
obj = NaN
_t = objelity.toText(obj)
t.is _t, 'NaN'
test 'rejectObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.rejectObject obj, (val, path, index, object) ->
return val % 2 is 0
t.deepEqual newObj, {
aaa:
bbb:
ccc: 1
eee:
fff: 3
}
test 'rejectObject(obj, array)', (t) ->
obj =
a: 1
b: 2
c: 3
t.deepEqual objelity.rejectObject(obj, ['b']), {a:1, c:3}
test 'rejectObject(obj, nestedArray)', (t) ->
obj =
a:
aa: 11
bb: 22
b: 2
c: 3
t.deepEqual objelity.rejectObject(obj, ['a']), {b:2, c:3}
t.deepEqual objelity.rejectObject(obj, ['a.b','c']), {a:{aa:11}, b:2}
test 'filterObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.filterObject obj, (val, path, index, object) ->
return val % 2 is 0
t.deepEqual newObj, {
aaa:
bbb:
ddd: 2
eee:
ggg: 4
}
test 'filterObject(obj, array)', (t) ->
obj =
a: 1
b: 2
c: 3
t.deepEqual objelity.filterObject(obj, ['a','c']), {a:1, c:3}
test 'filterObject(obj, nestedArray)', (t) ->
obj =
a:
aa: 11
bb: 22
b: 2
c: 3
t.deepEqual objelity.filterObject(obj, ['a','c']), {a:{aa:11, bb:22}, c:3}
t.deepEqual objelity.filterObject(obj, ['a.b','c']), {a:{bb:22}, c:3}
test 'to string of deep keys', (t) ->
obj =
str: 'string1'
num: 123
arr:[
true,
false
undefined
]
o:
sym: Symbol("foo")
nil: null
fn: (-> false)
newObj = objelity.toStringOfDeepKeys(obj)
t.deepEqual newObj,{
str: 'string1'
num: 123
arr:[
true
false
'[object Undefined]'
]
o:
sym: 'Symbol(foo)'
nil: '[object Null]'
fn: "function () {\n return false;\n }"
}
getObject = ->
{
num: 123
str: 'string'
bool1: true
bool2: false
nul: null
und: undefined
arr: ['a','r','r']
buf: new Buffer('')
fn: -> true
gfn: -> yield 0
args: arguments
obcr: Object.create(null)
date: new Date(Date.UTC(2018,9,15))
reg: /foo/
newreg: new RegExp('foo')
err: new Error('unknown error')
symbol: Symbol('str')
map: new Map([['a',1],['b',2]])
weakMap: new WeakMap()
set: new Set([1,2,'3'])
weakSet: new WeakSet()
int8Array: new Int8Array([1,9876543210,-9876543210])
uint8Array: new Uint8Array([1,9876543210,-9876543210])
uint8ClampedArray: new Uint8ClampedArray([1,9876543210,-9876543210])
int16Array: new Int16Array([1,9876543210,-9876543210])
uint16Array: new Uint16Array([1,9876543210,-9876543210])
int32Array: new Int32Array([1,9876543210,-9876543210])
uint32Array: new Uint32Array([1,9876543210,-9876543210])
float32Array: new Float32Array([1,9876543210,-9876543210])
float64Array: new Float64Array([1,9876543210,-9876543210])
nan: 0/0
}
test 'stringify diff', (t) ->
a = objelity.stringify(getObject(999),null,2)
aa = JSON.parse(a)
c = JSON.stringify(getObject(999),null,2)
cc = JSON.parse(c)
t.notDeepEqual aa,cc
t.snapshot a
t.snapshot c
test 'stringify primitive', (t) ->
t.is objelity.stringify('str'), '"str"'
t.is objelity.stringify(123), '123'
t.is objelity.stringify(true), 'true'
t.is objelity.stringify(false), 'false'
t.is objelity.stringify(null), 'null'
t.is objelity.stringify(undefined), '"[object Undefined] undefined"'
t.is objelity.stringify(NaN), '"[object Number] NaN"'
t.is objelity.stringify([1,2,3]), '[1,2,3]'
test 'stringify readme', (t) ->
obj =
undefined: undefined
function: -> true
generator: -> yield 0
RegExp: /foo/
newReg: new RegExp('foo')
err: new Error('unknown error')
# symbol: Symbol('str')
# map: new Map([['a',1],['b',2]])
# weakMap: new WeakMap()
# set: new Set([1,2,'3'])
# weakSet: new WeakSet()
NaN: 0/0
a = objelity.stringify(obj,null,2)
aa = JSON.parse(a)
c = JSON.stringify(obj,null,2)
cc = JSON.parse(c)
t.snapshot aa
t.snapshot cc
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
path.includes('aaa')
t.deepEqual res,1
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
val % 2 is 0
t.deepEqual res,2
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
/fff|ggg/.test(path)
t.deepEqual res,3
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
path.includes('aaa')
t.deepEqual res,{aaa:{bbb:{ccc:1}}}
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
val % 2 is 0
t.deepEqual res,{aaa:{bbb:{ddd:2}}}
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
/fff|ggg/.test(path)
t.deepEqual res,{aaa:{eee:{fff:3}}} | 36945 | objelity = require('../')
{test} = require 'ava'
test 'deepKeys', (t) ->
obj =
a:
b:
c: [1,2,3]
d: new Date()
e:
f:
g: 'h'
_keys = objelity.deepKeys(obj)
t.deepEqual _keys, [
'a.b.c.0',
'a.b.c.1',
'a.b.c.2',
'a.d',
'e.f.g',
]
obj = [
{name: '<NAME>', age: 17}
{name: '<NAME>', age: 32}
{name: '<NAME>', age: 25}
]
_keys = objelity.deepKeys(obj)
t.deepEqual _keys, [
'0.name',
'0.age',
'1.name',
'1.age',
'2.name',
'2.age',
]
test 'commonPath(pathStrings)', (t) ->
paths = [
'a.b.c.d.e.f',
'a.b.c.x.z',
'a.b.c',
'a.b.c.d.s',
]
t.deepEqual objelity.commonPath(paths),['a','b','c']
test 'commonPath(pathStrings)', (t) ->
paths = [
'a.b.c.d.e.f',
'd.e.f',
]
t.deepEqual objelity.commonPath(paths),[]
test 'commonPath(pathArray)', (t) ->
paths = [
['a','b','c','d','e']
['a','b','c','x','z','q']
['a','b','c','g','r']
['a','b','c','s']
['a','b','c']
]
t.deepEqual objelity.commonPath(paths),['a','b','c']
test 'compactObject(obj)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.compactObject(obj), {
aaa:
bbb:
ccc: 1
ddd: 0
hhh:
iii:
jjj: true
}
test 'flattenObject(obj)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.flattenObject(obj), {
aaa_bbb_ccc: 1,
aaa_bbb_ddd: 0,
aaa_eee_fff: undefined,
aaa_eee_ggg: null,
aaa_hhh_iii_jjj: true,
}
test 'flattenObject(obj, separator)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.flattenObject(obj, '-'), {
'aaa-bbb-ccc': 1,
'aaa-bbb-ddd': 0,
'aaa-eee-fff': undefined,
'aaa-eee-ggg': null,
'aaa-hhh-iii-jjj': true,
}
test 'eachObject(obj, fn)', (t) ->
t.plan(4)
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
objelity.eachObject obj, (val,path,index,object) ->
if path.includes('aaa.bbb.ccc')
t.is val, 1
else if path.includes('aaa.bbb.ddd')
t.is val, 2
else if path.includes('aaa.eee.fff')
t.is val, 3
else if path.includes('aaa.eee.ggg')
t.is val, 4
return
test 'mapObject(obj, fn) with sum', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.mapObject obj, (val,path,index,object) ->
return val * 2
t.deepEqual newObj, {
aaa:
bbb:
ccc: 2
ddd: 4
eee:
fff: 6
ggg: 8
}
test 'mapObject(obj, fn) with returned array', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
newObj = objelity.mapObject obj, (val,path,index,object) ->
if path.match(/aaa\.bbb/)
newPath = path.replace('aaa.bbb','xxx')
return [newPath, val]
else
return [path, val]
t.deepEqual newObj, {
xxx:
ccc: 1
ddd: 0
aaa:
eee:
fff: undefined
ggg: null
}
test 'mapObject(obj, fn) with returned object', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
newObj = objelity.mapObject obj, (val,path,index,object) ->
if path.match(/aaa\.bbb/)
newPath = path.replace('aaa.bbb','xxx')
return {[newPath]: val}
else
return {[path]: val}
t.deepEqual newObj, {
xxx:
ccc: 1
ddd: 0
aaa:
eee:
fff: undefined
ggg: null
}
test 'toText(obj)', (t) ->
obj = {a: 1}
_t = objelity.toText(obj)
t.not _t, '{"a": 1}'
t.regex _t, /{\s{2,}"a": 1\n}/
test 'toText(arr)', (t) ->
obj = [1,2,3]
_t = objelity.toText(obj)
t.not _t, '[1,2,3]'
t.regex _t, /\[\n\s{2}1,\n\s{2}2,\n\s{2}3\s{1}\]/
test 'toText(fn)', (t) ->
obj = => return true
_t = objelity.toText(obj)
t.regex _t, /\(\(\)\s=>\s{\n\s{6}return true;\n\s{4}}\)\(\)/
test 'toText(str)', (t) ->
obj = 'str'
_t = objelity.toText(obj)
t.is _t, 'str'
test 'toText(num)', (t) ->
obj = 123
_t = objelity.toText(obj)
t.is _t, '123'
test 'toText(undefined)', (t) ->
obj = undefined
_t = objelity.toText(obj)
t.is _t, 'undefined'
test 'toText(null)', (t) ->
obj = null
_t = objelity.toText(obj)
t.is _t, 'null'
test 'toText(true)', (t) ->
obj = true
_t = objelity.toText(obj)
t.is _t, 'true'
test 'toText(NaN)', (t) ->
obj = NaN
_t = objelity.toText(obj)
t.is _t, 'NaN'
test 'rejectObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.rejectObject obj, (val, path, index, object) ->
return val % 2 is 0
t.deepEqual newObj, {
aaa:
bbb:
ccc: 1
eee:
fff: 3
}
test 'rejectObject(obj, array)', (t) ->
obj =
a: 1
b: 2
c: 3
t.deepEqual objelity.rejectObject(obj, ['b']), {a:1, c:3}
test 'rejectObject(obj, nestedArray)', (t) ->
obj =
a:
aa: 11
bb: 22
b: 2
c: 3
t.deepEqual objelity.rejectObject(obj, ['a']), {b:2, c:3}
t.deepEqual objelity.rejectObject(obj, ['a.b','c']), {a:{aa:11}, b:2}
test 'filterObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.filterObject obj, (val, path, index, object) ->
return val % 2 is 0
t.deepEqual newObj, {
aaa:
bbb:
ddd: 2
eee:
ggg: 4
}
test 'filterObject(obj, array)', (t) ->
obj =
a: 1
b: 2
c: 3
t.deepEqual objelity.filterObject(obj, ['a','c']), {a:1, c:3}
test 'filterObject(obj, nestedArray)', (t) ->
obj =
a:
aa: 11
bb: 22
b: 2
c: 3
t.deepEqual objelity.filterObject(obj, ['a','c']), {a:{aa:11, bb:22}, c:3}
t.deepEqual objelity.filterObject(obj, ['a.b','c']), {a:{bb:22}, c:3}
test 'to string of deep keys', (t) ->
obj =
str: 'string1'
num: 123
arr:[
true,
false
undefined
]
o:
sym: Symbol("foo")
nil: null
fn: (-> false)
newObj = objelity.toStringOfDeepKeys(obj)
t.deepEqual newObj,{
str: 'string1'
num: 123
arr:[
true
false
'[object Undefined]'
]
o:
sym: 'Symbol(foo)'
nil: '[object Null]'
fn: "function () {\n return false;\n }"
}
getObject = ->
{
num: 123
str: 'string'
bool1: true
bool2: false
nul: null
und: undefined
arr: ['a','r','r']
buf: new Buffer('')
fn: -> true
gfn: -> yield 0
args: arguments
obcr: Object.create(null)
date: new Date(Date.UTC(2018,9,15))
reg: /foo/
newreg: new RegExp('foo')
err: new Error('unknown error')
symbol: Symbol('str')
map: new Map([['a',1],['b',2]])
weakMap: new WeakMap()
set: new Set([1,2,'3'])
weakSet: new WeakSet()
int8Array: new Int8Array([1,9876543210,-9876543210])
uint8Array: new Uint8Array([1,9876543210,-9876543210])
uint8ClampedArray: new Uint8ClampedArray([1,9876543210,-9876543210])
int16Array: new Int16Array([1,9876543210,-9876543210])
uint16Array: new Uint16Array([1,9876543210,-9876543210])
int32Array: new Int32Array([1,9876543210,-9876543210])
uint32Array: new Uint32Array([1,9876543210,-9876543210])
float32Array: new Float32Array([1,9876543210,-9876543210])
float64Array: new Float64Array([1,9876543210,-9876543210])
nan: 0/0
}
test 'stringify diff', (t) ->
a = objelity.stringify(getObject(999),null,2)
aa = JSON.parse(a)
c = JSON.stringify(getObject(999),null,2)
cc = JSON.parse(c)
t.notDeepEqual aa,cc
t.snapshot a
t.snapshot c
test 'stringify primitive', (t) ->
t.is objelity.stringify('str'), '"str"'
t.is objelity.stringify(123), '123'
t.is objelity.stringify(true), 'true'
t.is objelity.stringify(false), 'false'
t.is objelity.stringify(null), 'null'
t.is objelity.stringify(undefined), '"[object Undefined] undefined"'
t.is objelity.stringify(NaN), '"[object Number] NaN"'
t.is objelity.stringify([1,2,3]), '[1,2,3]'
test 'stringify readme', (t) ->
obj =
undefined: undefined
function: -> true
generator: -> yield 0
RegExp: /foo/
newReg: new RegExp('foo')
err: new Error('unknown error')
# symbol: Symbol('str')
# map: new Map([['a',1],['b',2]])
# weakMap: new WeakMap()
# set: new Set([1,2,'3'])
# weakSet: new WeakSet()
NaN: 0/0
a = objelity.stringify(obj,null,2)
aa = JSON.parse(a)
c = JSON.stringify(obj,null,2)
cc = JSON.parse(c)
t.snapshot aa
t.snapshot cc
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
path.includes('aaa')
t.deepEqual res,1
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
val % 2 is 0
t.deepEqual res,2
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
/fff|ggg/.test(path)
t.deepEqual res,3
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
path.includes('aaa')
t.deepEqual res,{aaa:{bbb:{ccc:1}}}
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
val % 2 is 0
t.deepEqual res,{aaa:{bbb:{ddd:2}}}
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
/fff|ggg/.test(path)
t.deepEqual res,{aaa:{eee:{fff:3}}} | true | objelity = require('../')
{test} = require 'ava'
test 'deepKeys', (t) ->
obj =
a:
b:
c: [1,2,3]
d: new Date()
e:
f:
g: 'h'
_keys = objelity.deepKeys(obj)
t.deepEqual _keys, [
'a.b.c.0',
'a.b.c.1',
'a.b.c.2',
'a.d',
'e.f.g',
]
obj = [
{name: 'PI:NAME:<NAME>END_PI', age: 17}
{name: 'PI:NAME:<NAME>END_PI', age: 32}
{name: 'PI:NAME:<NAME>END_PI', age: 25}
]
_keys = objelity.deepKeys(obj)
t.deepEqual _keys, [
'0.name',
'0.age',
'1.name',
'1.age',
'2.name',
'2.age',
]
test 'commonPath(pathStrings)', (t) ->
paths = [
'a.b.c.d.e.f',
'a.b.c.x.z',
'a.b.c',
'a.b.c.d.s',
]
t.deepEqual objelity.commonPath(paths),['a','b','c']
test 'commonPath(pathStrings)', (t) ->
paths = [
'a.b.c.d.e.f',
'd.e.f',
]
t.deepEqual objelity.commonPath(paths),[]
test 'commonPath(pathArray)', (t) ->
paths = [
['a','b','c','d','e']
['a','b','c','x','z','q']
['a','b','c','g','r']
['a','b','c','s']
['a','b','c']
]
t.deepEqual objelity.commonPath(paths),['a','b','c']
test 'compactObject(obj)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.compactObject(obj), {
aaa:
bbb:
ccc: 1
ddd: 0
hhh:
iii:
jjj: true
}
test 'flattenObject(obj)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.flattenObject(obj), {
aaa_bbb_ccc: 1,
aaa_bbb_ddd: 0,
aaa_eee_fff: undefined,
aaa_eee_ggg: null,
aaa_hhh_iii_jjj: true,
}
test 'flattenObject(obj, separator)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
hhh:
iii:
jjj: true
t.deepEqual objelity.flattenObject(obj, '-'), {
'aaa-bbb-ccc': 1,
'aaa-bbb-ddd': 0,
'aaa-eee-fff': undefined,
'aaa-eee-ggg': null,
'aaa-hhh-iii-jjj': true,
}
test 'eachObject(obj, fn)', (t) ->
t.plan(4)
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
objelity.eachObject obj, (val,path,index,object) ->
if path.includes('aaa.bbb.ccc')
t.is val, 1
else if path.includes('aaa.bbb.ddd')
t.is val, 2
else if path.includes('aaa.eee.fff')
t.is val, 3
else if path.includes('aaa.eee.ggg')
t.is val, 4
return
test 'mapObject(obj, fn) with sum', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.mapObject obj, (val,path,index,object) ->
return val * 2
t.deepEqual newObj, {
aaa:
bbb:
ccc: 2
ddd: 4
eee:
fff: 6
ggg: 8
}
test 'mapObject(obj, fn) with returned array', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
newObj = objelity.mapObject obj, (val,path,index,object) ->
if path.match(/aaa\.bbb/)
newPath = path.replace('aaa.bbb','xxx')
return [newPath, val]
else
return [path, val]
t.deepEqual newObj, {
xxx:
ccc: 1
ddd: 0
aaa:
eee:
fff: undefined
ggg: null
}
test 'mapObject(obj, fn) with returned object', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 0
eee:
fff: undefined
ggg: null
newObj = objelity.mapObject obj, (val,path,index,object) ->
if path.match(/aaa\.bbb/)
newPath = path.replace('aaa.bbb','xxx')
return {[newPath]: val}
else
return {[path]: val}
t.deepEqual newObj, {
xxx:
ccc: 1
ddd: 0
aaa:
eee:
fff: undefined
ggg: null
}
test 'toText(obj)', (t) ->
obj = {a: 1}
_t = objelity.toText(obj)
t.not _t, '{"a": 1}'
t.regex _t, /{\s{2,}"a": 1\n}/
test 'toText(arr)', (t) ->
obj = [1,2,3]
_t = objelity.toText(obj)
t.not _t, '[1,2,3]'
t.regex _t, /\[\n\s{2}1,\n\s{2}2,\n\s{2}3\s{1}\]/
test 'toText(fn)', (t) ->
obj = => return true
_t = objelity.toText(obj)
t.regex _t, /\(\(\)\s=>\s{\n\s{6}return true;\n\s{4}}\)\(\)/
test 'toText(str)', (t) ->
obj = 'str'
_t = objelity.toText(obj)
t.is _t, 'str'
test 'toText(num)', (t) ->
obj = 123
_t = objelity.toText(obj)
t.is _t, '123'
test 'toText(undefined)', (t) ->
obj = undefined
_t = objelity.toText(obj)
t.is _t, 'undefined'
test 'toText(null)', (t) ->
obj = null
_t = objelity.toText(obj)
t.is _t, 'null'
test 'toText(true)', (t) ->
obj = true
_t = objelity.toText(obj)
t.is _t, 'true'
test 'toText(NaN)', (t) ->
obj = NaN
_t = objelity.toText(obj)
t.is _t, 'NaN'
test 'rejectObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.rejectObject obj, (val, path, index, object) ->
return val % 2 is 0
t.deepEqual newObj, {
aaa:
bbb:
ccc: 1
eee:
fff: 3
}
test 'rejectObject(obj, array)', (t) ->
obj =
a: 1
b: 2
c: 3
t.deepEqual objelity.rejectObject(obj, ['b']), {a:1, c:3}
test 'rejectObject(obj, nestedArray)', (t) ->
obj =
a:
aa: 11
bb: 22
b: 2
c: 3
t.deepEqual objelity.rejectObject(obj, ['a']), {b:2, c:3}
t.deepEqual objelity.rejectObject(obj, ['a.b','c']), {a:{aa:11}, b:2}
test 'filterObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
newObj = objelity.filterObject obj, (val, path, index, object) ->
return val % 2 is 0
t.deepEqual newObj, {
aaa:
bbb:
ddd: 2
eee:
ggg: 4
}
test 'filterObject(obj, array)', (t) ->
obj =
a: 1
b: 2
c: 3
t.deepEqual objelity.filterObject(obj, ['a','c']), {a:1, c:3}
test 'filterObject(obj, nestedArray)', (t) ->
obj =
a:
aa: 11
bb: 22
b: 2
c: 3
t.deepEqual objelity.filterObject(obj, ['a','c']), {a:{aa:11, bb:22}, c:3}
t.deepEqual objelity.filterObject(obj, ['a.b','c']), {a:{bb:22}, c:3}
test 'to string of deep keys', (t) ->
obj =
str: 'string1'
num: 123
arr:[
true,
false
undefined
]
o:
sym: Symbol("foo")
nil: null
fn: (-> false)
newObj = objelity.toStringOfDeepKeys(obj)
t.deepEqual newObj,{
str: 'string1'
num: 123
arr:[
true
false
'[object Undefined]'
]
o:
sym: 'Symbol(foo)'
nil: '[object Null]'
fn: "function () {\n return false;\n }"
}
getObject = ->
{
num: 123
str: 'string'
bool1: true
bool2: false
nul: null
und: undefined
arr: ['a','r','r']
buf: new Buffer('')
fn: -> true
gfn: -> yield 0
args: arguments
obcr: Object.create(null)
date: new Date(Date.UTC(2018,9,15))
reg: /foo/
newreg: new RegExp('foo')
err: new Error('unknown error')
symbol: Symbol('str')
map: new Map([['a',1],['b',2]])
weakMap: new WeakMap()
set: new Set([1,2,'3'])
weakSet: new WeakSet()
int8Array: new Int8Array([1,9876543210,-9876543210])
uint8Array: new Uint8Array([1,9876543210,-9876543210])
uint8ClampedArray: new Uint8ClampedArray([1,9876543210,-9876543210])
int16Array: new Int16Array([1,9876543210,-9876543210])
uint16Array: new Uint16Array([1,9876543210,-9876543210])
int32Array: new Int32Array([1,9876543210,-9876543210])
uint32Array: new Uint32Array([1,9876543210,-9876543210])
float32Array: new Float32Array([1,9876543210,-9876543210])
float64Array: new Float64Array([1,9876543210,-9876543210])
nan: 0/0
}
test 'stringify diff', (t) ->
a = objelity.stringify(getObject(999),null,2)
aa = JSON.parse(a)
c = JSON.stringify(getObject(999),null,2)
cc = JSON.parse(c)
t.notDeepEqual aa,cc
t.snapshot a
t.snapshot c
test 'stringify primitive', (t) ->
t.is objelity.stringify('str'), '"str"'
t.is objelity.stringify(123), '123'
t.is objelity.stringify(true), 'true'
t.is objelity.stringify(false), 'false'
t.is objelity.stringify(null), 'null'
t.is objelity.stringify(undefined), '"[object Undefined] undefined"'
t.is objelity.stringify(NaN), '"[object Number] NaN"'
t.is objelity.stringify([1,2,3]), '[1,2,3]'
test 'stringify readme', (t) ->
obj =
undefined: undefined
function: -> true
generator: -> yield 0
RegExp: /foo/
newReg: new RegExp('foo')
err: new Error('unknown error')
# symbol: Symbol('str')
# map: new Map([['a',1],['b',2]])
# weakMap: new WeakMap()
# set: new Set([1,2,'3'])
# weakSet: new WeakSet()
NaN: 0/0
a = objelity.stringify(obj,null,2)
aa = JSON.parse(a)
c = JSON.stringify(obj,null,2)
cc = JSON.parse(c)
t.snapshot aa
t.snapshot cc
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
path.includes('aaa')
t.deepEqual res,1
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
val % 2 is 0
t.deepEqual res,2
test 'pickValue(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickValue obj, (val, path, index, object) ->
/fff|ggg/.test(path)
t.deepEqual res,3
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
path.includes('aaa')
t.deepEqual res,{aaa:{bbb:{ccc:1}}}
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
val % 2 is 0
t.deepEqual res,{aaa:{bbb:{ddd:2}}}
test 'pickObject(obj, fn)', (t) ->
obj =
aaa:
bbb:
ccc: 1
ddd: 2
eee:
fff: 3
ggg: 4
res = objelity.pickObject obj, (val, path, index, object) ->
/fff|ggg/.test(path)
t.deepEqual res,{aaa:{eee:{fff:3}}} |
[
{
"context": "riter buf, types\n writer.write 'custom', { a: 'HELLOWORLD' }\n writer.rawBuffer().should.eql new Buffer [",
"end": 7011,
"score": 0.6452469229698181,
"start": 7001,
"tag": "NAME",
"value": "HELLOWORLD"
}
] | test/writer.spec.coffee | vickvu/bison-types | 0 | should = require 'should'
sinon = require 'sinon'
preCompile = require "#{SRC}/preCompile"
Writer = require "#{SRC}/writer"
typeHelper = require "#{SRC}/type-helper"
describe 'Bison Writer', ->
beforeEach ->
sinon.spy typeHelper, 'getTypeInfo'
afterEach ->
typeHelper.getTypeInfo.restore()
it 'should create a writer with a default options', ->
buf = new Buffer 8
writer = new Writer buf
writer.buffer.bigEndian.should.eql false
writer.buffer.getOffset().should.eql 0
writer.buffer.noAssert.should.eql true
it 'should create a writer with a specified offset', ->
buf = new Buffer 8
writer = new Writer buf, null, {offset:4}
writer.buffer.getOffset().should.eql 4
it 'should create a writer with a specified endian-ness', ->
buf = new Buffer 8
writer = new Writer buf, null, {bigEndian:true}
writer.buffer.bigEndian.should.eql true
it 'should create a writer with a specified value for noAssert', ->
buf = new Buffer 8
writer = new Writer buf, null, {noAssert:false}
writer.buffer.noAssert.should.eql false
it 'should write a UInt8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8', 5
writer.rawBuffer().should.eql new Buffer [ 0x05 ]
it 'should write a UInt16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', 513
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02 ]
it 'should write a UInt32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', 67305985
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should write a UInt64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '578437695752307201'
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 ]
it 'should write max UInt8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8', 255
writer.rawBuffer().should.eql new Buffer [0xFF]
it 'should write max UInt16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', 65535
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF]
it 'should write max UInt32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', 4294967295
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF, 0xFF, 0xFF]
it 'should write max UInt64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '18446744073709551615'
writer.rawBuffer().should.eql new Buffer [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ]
it 'should write Int8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'int8', -1
writer.rawBuffer().should.eql new Buffer [0xFF]
it 'should write Int16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', -1
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF]
it 'should write Int32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', -1
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF, 0xFF, 0xFF]
it 'should write Int64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '-1'
writer.rawBuffer().should.eql new Buffer [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ]
it 'should write Bool', ->
buf = new Buffer 5
writer = new Writer buf
# falsy
writer.write 'bool', false
writer.write 'bool', 0
# truthy
writer.write 'bool', true
writer.write 'bool', 1
writer.write 'bool', 'hi'
writer.rawBuffer().should.eql new Buffer [ 0x00, 0x00, 0x01, 0x01, 0x01 ]
it 'should write string', ->
buf = new Buffer 5
writer = new Writer buf
writer.write 'utf-8', 'HELLO'
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F]
it 'should be able to write bytes', ->
buf = new Buffer 5
writer = new Writer buf
writer.write 'bytes', [0x48, 0x45, 0x4C, 0x4C, 0x4F]
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F]
it 'should be able to define a simple type', ->
buf = new Buffer 1
writer = new Writer buf, preCompile {'my-simple-type': 'uint8'}
writer.write 'my-simple-type', 5
writer.rawBuffer().should.eql new Buffer [0x05]
it 'should be able to define a complex type', ->
buf = new Buffer 1
types = preCompile
complex:
_write: (val, multiplier) -> @buffer.writeUInt8 val*multiplier
writer = new Writer buf, types
writer.write 'complex', 1, 5
writer.rawBuffer().should.eql new Buffer [0x05]
it 'should be able to define a custom type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'uint8'}
{d: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: 3, d: 4 }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to skip', ->
buf = new Buffer 4
buf.fill 0
types = preCompile
custom: [
{a: 'uint8'}
{b: 'skip(2)'}
{c: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', {a: 1, c: 4}
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x00, 0x00, 0x04 ]
it 'should be able to define a custom embedded type', ->
buf = new Buffer 3
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
d: 'uint8'
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03 ]
it 'should be able to define a custom complex embedded type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
{d: 'uint8'}
{e: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3, e:4} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to define a custom complex embedded type within an embedded type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
{d: 'uint8'}
{e: 'super-embedded-type'}
]
'super-embedded-type': [
f: 'uint8'
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3, e: {f:4}} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to write a string of a certain length', ->
buf = new Buffer 10
buf.fill 0
types = preCompile
custom: [
a: 'utf-8(5)'
]
writer = new Writer buf, types
writer.write 'custom', { a: 'HELLOWORLD' }
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00] #Only writes hello
it 'should be able to specify a parameter', ->
buf = new Buffer 2
types = preCompile
divide:
_write: (val, divider) -> @buffer.writeUInt8(val / divider)
custom: [
{a: 'uint8'}
{b: 'divide(4)'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 2, b: 12 }
writer.rawBuffer().should.eql new Buffer [ 0x02, 0x03 ]
it 'should be able to use previously resolved value', ->
buf = new Buffer 2
types = preCompile
divide:
_write: (val, divider) -> @buffer.writeUInt8(val / divider)
custom: [
{a: 'uint8'}
{b: 'divide(a)'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 2, b: 6 }
writer.rawBuffer().should.eql new Buffer [ 0x02, 0x03 ]
it 'should be able to write an array', ->
buf = new Buffer 4
types = preCompile
object: [
c: 'uint8'
]
custom: [
{a: 'uint8'}
{b: 'object[a]'}
]
writer = new Writer buf, types
writer.write 'custom',
a: 3,
b: [
{c:1},
{c:2},
{c:3}
]
writer.rawBuffer().should.eql new Buffer [ 0x03, 0x01, 0x02, 0x03 ]
it 'should only write specified amount in array', ->
buf = new Buffer 5
buf.fill 0
types = preCompile
object: [
c: 'uint8'
]
custom: [
b: 'object[3]'
]
writer = new Writer buf, types
writer.write 'custom',
b: [
{c:1},
{c:2},
{c:3},
{c:4}
]
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x00, 0x00 ] #Doesn't write last 2 values
it 'should write a UInt8 with an override value', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8=3', 5
writer.rawBuffer().should.eql new Buffer [ 0x03 ]
it 'should be able to write an array of type that is defined with _write function', ->
buf = new Buffer 3
writer = new Writer buf
writer.write 'uint8[3]', [1,2,3]
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03 ]
it 'should be able to write array and size', ->
buf = new Buffer 4
buf.fill 0
types = preCompile
custom: [
{a: 'uint8=b.length'}
{b: 'uint8[b.length]'}
]
writer = new Writer buf, types
writer.write 'custom', {b: [1,2,3]}
writer.rawBuffer().should.eql new Buffer [ 0x03, 0x01, 0x02, 0x03 ]
it 'should only create type definition once per type', ->
buf = new Buffer 2
buf.fill 0
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', {a: 1, b: 2}
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02]
typeHelper.getTypeInfo.withArgs('uint8').callCount.should.eql 1
| 40882 | should = require 'should'
sinon = require 'sinon'
preCompile = require "#{SRC}/preCompile"
Writer = require "#{SRC}/writer"
typeHelper = require "#{SRC}/type-helper"
describe 'Bison Writer', ->
beforeEach ->
sinon.spy typeHelper, 'getTypeInfo'
afterEach ->
typeHelper.getTypeInfo.restore()
it 'should create a writer with a default options', ->
buf = new Buffer 8
writer = new Writer buf
writer.buffer.bigEndian.should.eql false
writer.buffer.getOffset().should.eql 0
writer.buffer.noAssert.should.eql true
it 'should create a writer with a specified offset', ->
buf = new Buffer 8
writer = new Writer buf, null, {offset:4}
writer.buffer.getOffset().should.eql 4
it 'should create a writer with a specified endian-ness', ->
buf = new Buffer 8
writer = new Writer buf, null, {bigEndian:true}
writer.buffer.bigEndian.should.eql true
it 'should create a writer with a specified value for noAssert', ->
buf = new Buffer 8
writer = new Writer buf, null, {noAssert:false}
writer.buffer.noAssert.should.eql false
it 'should write a UInt8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8', 5
writer.rawBuffer().should.eql new Buffer [ 0x05 ]
it 'should write a UInt16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', 513
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02 ]
it 'should write a UInt32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', 67305985
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should write a UInt64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '578437695752307201'
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 ]
it 'should write max UInt8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8', 255
writer.rawBuffer().should.eql new Buffer [0xFF]
it 'should write max UInt16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', 65535
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF]
it 'should write max UInt32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', 4294967295
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF, 0xFF, 0xFF]
it 'should write max UInt64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '18446744073709551615'
writer.rawBuffer().should.eql new Buffer [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ]
it 'should write Int8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'int8', -1
writer.rawBuffer().should.eql new Buffer [0xFF]
it 'should write Int16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', -1
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF]
it 'should write Int32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', -1
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF, 0xFF, 0xFF]
it 'should write Int64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '-1'
writer.rawBuffer().should.eql new Buffer [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ]
it 'should write Bool', ->
buf = new Buffer 5
writer = new Writer buf
# falsy
writer.write 'bool', false
writer.write 'bool', 0
# truthy
writer.write 'bool', true
writer.write 'bool', 1
writer.write 'bool', 'hi'
writer.rawBuffer().should.eql new Buffer [ 0x00, 0x00, 0x01, 0x01, 0x01 ]
it 'should write string', ->
buf = new Buffer 5
writer = new Writer buf
writer.write 'utf-8', 'HELLO'
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F]
it 'should be able to write bytes', ->
buf = new Buffer 5
writer = new Writer buf
writer.write 'bytes', [0x48, 0x45, 0x4C, 0x4C, 0x4F]
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F]
it 'should be able to define a simple type', ->
buf = new Buffer 1
writer = new Writer buf, preCompile {'my-simple-type': 'uint8'}
writer.write 'my-simple-type', 5
writer.rawBuffer().should.eql new Buffer [0x05]
it 'should be able to define a complex type', ->
buf = new Buffer 1
types = preCompile
complex:
_write: (val, multiplier) -> @buffer.writeUInt8 val*multiplier
writer = new Writer buf, types
writer.write 'complex', 1, 5
writer.rawBuffer().should.eql new Buffer [0x05]
it 'should be able to define a custom type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'uint8'}
{d: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: 3, d: 4 }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to skip', ->
buf = new Buffer 4
buf.fill 0
types = preCompile
custom: [
{a: 'uint8'}
{b: 'skip(2)'}
{c: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', {a: 1, c: 4}
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x00, 0x00, 0x04 ]
it 'should be able to define a custom embedded type', ->
buf = new Buffer 3
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
d: 'uint8'
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03 ]
it 'should be able to define a custom complex embedded type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
{d: 'uint8'}
{e: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3, e:4} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to define a custom complex embedded type within an embedded type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
{d: 'uint8'}
{e: 'super-embedded-type'}
]
'super-embedded-type': [
f: 'uint8'
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3, e: {f:4}} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to write a string of a certain length', ->
buf = new Buffer 10
buf.fill 0
types = preCompile
custom: [
a: 'utf-8(5)'
]
writer = new Writer buf, types
writer.write 'custom', { a: '<NAME>' }
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00] #Only writes hello
it 'should be able to specify a parameter', ->
buf = new Buffer 2
types = preCompile
divide:
_write: (val, divider) -> @buffer.writeUInt8(val / divider)
custom: [
{a: 'uint8'}
{b: 'divide(4)'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 2, b: 12 }
writer.rawBuffer().should.eql new Buffer [ 0x02, 0x03 ]
it 'should be able to use previously resolved value', ->
buf = new Buffer 2
types = preCompile
divide:
_write: (val, divider) -> @buffer.writeUInt8(val / divider)
custom: [
{a: 'uint8'}
{b: 'divide(a)'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 2, b: 6 }
writer.rawBuffer().should.eql new Buffer [ 0x02, 0x03 ]
it 'should be able to write an array', ->
buf = new Buffer 4
types = preCompile
object: [
c: 'uint8'
]
custom: [
{a: 'uint8'}
{b: 'object[a]'}
]
writer = new Writer buf, types
writer.write 'custom',
a: 3,
b: [
{c:1},
{c:2},
{c:3}
]
writer.rawBuffer().should.eql new Buffer [ 0x03, 0x01, 0x02, 0x03 ]
it 'should only write specified amount in array', ->
buf = new Buffer 5
buf.fill 0
types = preCompile
object: [
c: 'uint8'
]
custom: [
b: 'object[3]'
]
writer = new Writer buf, types
writer.write 'custom',
b: [
{c:1},
{c:2},
{c:3},
{c:4}
]
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x00, 0x00 ] #Doesn't write last 2 values
it 'should write a UInt8 with an override value', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8=3', 5
writer.rawBuffer().should.eql new Buffer [ 0x03 ]
it 'should be able to write an array of type that is defined with _write function', ->
buf = new Buffer 3
writer = new Writer buf
writer.write 'uint8[3]', [1,2,3]
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03 ]
it 'should be able to write array and size', ->
buf = new Buffer 4
buf.fill 0
types = preCompile
custom: [
{a: 'uint8=b.length'}
{b: 'uint8[b.length]'}
]
writer = new Writer buf, types
writer.write 'custom', {b: [1,2,3]}
writer.rawBuffer().should.eql new Buffer [ 0x03, 0x01, 0x02, 0x03 ]
it 'should only create type definition once per type', ->
buf = new Buffer 2
buf.fill 0
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', {a: 1, b: 2}
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02]
typeHelper.getTypeInfo.withArgs('uint8').callCount.should.eql 1
| true | should = require 'should'
sinon = require 'sinon'
preCompile = require "#{SRC}/preCompile"
Writer = require "#{SRC}/writer"
typeHelper = require "#{SRC}/type-helper"
describe 'Bison Writer', ->
beforeEach ->
sinon.spy typeHelper, 'getTypeInfo'
afterEach ->
typeHelper.getTypeInfo.restore()
it 'should create a writer with a default options', ->
buf = new Buffer 8
writer = new Writer buf
writer.buffer.bigEndian.should.eql false
writer.buffer.getOffset().should.eql 0
writer.buffer.noAssert.should.eql true
it 'should create a writer with a specified offset', ->
buf = new Buffer 8
writer = new Writer buf, null, {offset:4}
writer.buffer.getOffset().should.eql 4
it 'should create a writer with a specified endian-ness', ->
buf = new Buffer 8
writer = new Writer buf, null, {bigEndian:true}
writer.buffer.bigEndian.should.eql true
it 'should create a writer with a specified value for noAssert', ->
buf = new Buffer 8
writer = new Writer buf, null, {noAssert:false}
writer.buffer.noAssert.should.eql false
it 'should write a UInt8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8', 5
writer.rawBuffer().should.eql new Buffer [ 0x05 ]
it 'should write a UInt16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', 513
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02 ]
it 'should write a UInt32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', 67305985
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should write a UInt64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '578437695752307201'
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 ]
it 'should write max UInt8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8', 255
writer.rawBuffer().should.eql new Buffer [0xFF]
it 'should write max UInt16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', 65535
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF]
it 'should write max UInt32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', 4294967295
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF, 0xFF, 0xFF]
it 'should write max UInt64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '18446744073709551615'
writer.rawBuffer().should.eql new Buffer [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ]
it 'should write Int8', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'int8', -1
writer.rawBuffer().should.eql new Buffer [0xFF]
it 'should write Int16', ->
buf = new Buffer 2
writer = new Writer buf
writer.write 'uint16', -1
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF]
it 'should write Int32', ->
buf = new Buffer 4
writer = new Writer buf
writer.write 'uint32', -1
writer.rawBuffer().should.eql new Buffer [0xFF, 0xFF, 0xFF, 0xFF]
it 'should write Int64', ->
buf = new Buffer 8
writer = new Writer buf
writer.write 'uint64', '-1'
writer.rawBuffer().should.eql new Buffer [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF ]
it 'should write Bool', ->
buf = new Buffer 5
writer = new Writer buf
# falsy
writer.write 'bool', false
writer.write 'bool', 0
# truthy
writer.write 'bool', true
writer.write 'bool', 1
writer.write 'bool', 'hi'
writer.rawBuffer().should.eql new Buffer [ 0x00, 0x00, 0x01, 0x01, 0x01 ]
it 'should write string', ->
buf = new Buffer 5
writer = new Writer buf
writer.write 'utf-8', 'HELLO'
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F]
it 'should be able to write bytes', ->
buf = new Buffer 5
writer = new Writer buf
writer.write 'bytes', [0x48, 0x45, 0x4C, 0x4C, 0x4F]
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F]
it 'should be able to define a simple type', ->
buf = new Buffer 1
writer = new Writer buf, preCompile {'my-simple-type': 'uint8'}
writer.write 'my-simple-type', 5
writer.rawBuffer().should.eql new Buffer [0x05]
it 'should be able to define a complex type', ->
buf = new Buffer 1
types = preCompile
complex:
_write: (val, multiplier) -> @buffer.writeUInt8 val*multiplier
writer = new Writer buf, types
writer.write 'complex', 1, 5
writer.rawBuffer().should.eql new Buffer [0x05]
it 'should be able to define a custom type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'uint8'}
{d: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: 3, d: 4 }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to skip', ->
buf = new Buffer 4
buf.fill 0
types = preCompile
custom: [
{a: 'uint8'}
{b: 'skip(2)'}
{c: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', {a: 1, c: 4}
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x00, 0x00, 0x04 ]
it 'should be able to define a custom embedded type', ->
buf = new Buffer 3
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
d: 'uint8'
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03 ]
it 'should be able to define a custom complex embedded type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
{d: 'uint8'}
{e: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3, e:4} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to define a custom complex embedded type within an embedded type', ->
buf = new Buffer 4
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
{c: 'embedded-type'}
]
'embedded-type': [
{d: 'uint8'}
{e: 'super-embedded-type'}
]
'super-embedded-type': [
f: 'uint8'
]
writer = new Writer buf, types
writer.write 'custom', { a: 1, b: 2, c: {d: 3, e: {f:4}} }
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x04 ]
it 'should be able to write a string of a certain length', ->
buf = new Buffer 10
buf.fill 0
types = preCompile
custom: [
a: 'utf-8(5)'
]
writer = new Writer buf, types
writer.write 'custom', { a: 'PI:NAME:<NAME>END_PI' }
writer.rawBuffer().should.eql new Buffer [0x48, 0x45, 0x4C, 0x4C, 0x4F, 0x00, 0x00, 0x00, 0x00, 0x00] #Only writes hello
it 'should be able to specify a parameter', ->
buf = new Buffer 2
types = preCompile
divide:
_write: (val, divider) -> @buffer.writeUInt8(val / divider)
custom: [
{a: 'uint8'}
{b: 'divide(4)'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 2, b: 12 }
writer.rawBuffer().should.eql new Buffer [ 0x02, 0x03 ]
it 'should be able to use previously resolved value', ->
buf = new Buffer 2
types = preCompile
divide:
_write: (val, divider) -> @buffer.writeUInt8(val / divider)
custom: [
{a: 'uint8'}
{b: 'divide(a)'}
]
writer = new Writer buf, types
writer.write 'custom', { a: 2, b: 6 }
writer.rawBuffer().should.eql new Buffer [ 0x02, 0x03 ]
it 'should be able to write an array', ->
buf = new Buffer 4
types = preCompile
object: [
c: 'uint8'
]
custom: [
{a: 'uint8'}
{b: 'object[a]'}
]
writer = new Writer buf, types
writer.write 'custom',
a: 3,
b: [
{c:1},
{c:2},
{c:3}
]
writer.rawBuffer().should.eql new Buffer [ 0x03, 0x01, 0x02, 0x03 ]
it 'should only write specified amount in array', ->
buf = new Buffer 5
buf.fill 0
types = preCompile
object: [
c: 'uint8'
]
custom: [
b: 'object[3]'
]
writer = new Writer buf, types
writer.write 'custom',
b: [
{c:1},
{c:2},
{c:3},
{c:4}
]
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03, 0x00, 0x00 ] #Doesn't write last 2 values
it 'should write a UInt8 with an override value', ->
buf = new Buffer 1
writer = new Writer buf
writer.write 'uint8=3', 5
writer.rawBuffer().should.eql new Buffer [ 0x03 ]
it 'should be able to write an array of type that is defined with _write function', ->
buf = new Buffer 3
writer = new Writer buf
writer.write 'uint8[3]', [1,2,3]
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02, 0x03 ]
it 'should be able to write array and size', ->
buf = new Buffer 4
buf.fill 0
types = preCompile
custom: [
{a: 'uint8=b.length'}
{b: 'uint8[b.length]'}
]
writer = new Writer buf, types
writer.write 'custom', {b: [1,2,3]}
writer.rawBuffer().should.eql new Buffer [ 0x03, 0x01, 0x02, 0x03 ]
it 'should only create type definition once per type', ->
buf = new Buffer 2
buf.fill 0
types = preCompile
custom: [
{a: 'uint8'}
{b: 'uint8'}
]
writer = new Writer buf, types
writer.write 'custom', {a: 1, b: 2}
writer.rawBuffer().should.eql new Buffer [ 0x01, 0x02]
typeHelper.getTypeInfo.withArgs('uint8').callCount.should.eql 1
|
[
{
"context": "ets (completions) for Atom\n# Originally created by Renato \"Hii\" Garcia\n'.source.pwn, .source.inc':\n 'CA_Init",
"end": 75,
"score": 0.9967004656791687,
"start": 69,
"tag": "NAME",
"value": "Renato"
},
{
"context": "letions) for Atom\n# Originally created by Renato \"Hii\" Garcia\n'.source.pwn, .source.inc':\n 'CA_Init':\n ",
"end": 80,
"score": 0.8709292411804199,
"start": 77,
"tag": "NAME",
"value": "Hii"
},
{
"context": "ons) for Atom\n# Originally created by Renato \"Hii\" Garcia\n'.source.pwn, .source.inc':\n 'CA_Init':\n 'pre",
"end": 88,
"score": 0.9997565150260925,
"start": 82,
"tag": "NAME",
"value": "Garcia"
},
{
"context": "zeof players})'\n 'description': 'Function from: ColAndreas'\n 'descriptionMoreURL': 'http://forum.sa-mp.co",
"end": 8128,
"score": 0.9687692523002625,
"start": 8118,
"tag": "NAME",
"value": "ColAndreas"
},
{
"context": "dist = 300.0})'\n 'description': 'Function from: ColAndreas'\n 'descriptionMoreURL': 'http://forum.sa-mp.co",
"end": 8582,
"score": 0.9609892964363098,
"start": 8572,
"tag": "NAME",
"value": "ColAndreas"
},
{
"context": "ance = 300.0})'\n 'description': 'Function from: ColAndreas'\n 'descriptionMoreURL': 'http://forum.sa-mp.co",
"end": 8931,
"score": 0.9747828841209412,
"start": 8921,
"tag": "NAME",
"value": "ColAndreas"
}
] | snippets/ColAndreas.cson | Wuzi/language-pawn | 4 | # ColAndreas snippets (completions) for Atom
# Originally created by Renato "Hii" Garcia
'.source.pwn, .source.inc':
'CA_Init':
'prefix': 'CA_Init'
'body': 'CA_Init()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBuilding':
'prefix': 'CA_RemoveBuilding'
'body': 'CA_RemoveBuilding(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLine':
'prefix': 'CA_RayCastLine'
'body': 'CA_RayCastLine(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineID':
'prefix': 'CA_RayCastLineID'
'body': 'CA_RayCastLineID(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineExtraID':
'prefix': 'CA_RayCastLineExtraID'
'body': 'CA_RayCastLineExtraID(${1:type}, ${2:Float:StartX}, ${3:Float:StartY}, ${4:Float:StartZ}, ${5:Float:EndX}, ${6:Float:EndY}, ${7:Float:EndZ}, ${8:&Float:x}, ${9:&Float:y}, ${10:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastMultiLine':
'prefix': 'CA_RayCastMultiLine'
'body': 'CA_RayCastMultiLine(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:Float:retx[]}, ${8:Float:rety[]}, ${9:Float:retz[]}, ${10:Float:retdist[]}, ${11:ModelIDs[]}, ${12:size = sizeof(retx})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineAngle':
'prefix': 'CA_RayCastLineAngle'
'body': 'CA_RayCastLineAngle(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastReflectionVector':
'prefix': 'CA_RayCastReflectionVector'
'body': 'CA_RayCastReflectionVector(${1:Float:startx}, ${2:Float:starty}, ${3:Float:startz}, ${4:Float:endx}, ${5:Float:endy}, ${6:Float:endz}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:nx}, ${11:&Float:ny}, ${12:&Float:nz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineNormal':
'prefix': 'CA_RayCastLineNormal'
'body': 'CA_RayCastLineNormal(${1:Float:startx}, ${2:Float:starty}, ${3:Float:startz}, ${4:Float:endx}, ${5:Float:endy}, ${6:Float:endz}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:nx}, ${11:&Float:ny}, ${12:&Float:nz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_ContactTest':
'prefix': 'CA_ContactTest'
'body': 'CA_ContactTest(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_EulerToQuat':
'prefix': 'CA_EulerToQuat'
'body': 'CA_EulerToQuat(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:x}, ${5:&Float:y}, ${6:&Float:z}, ${7:&Float:w})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_QuatToEuler':
'prefix': 'CA_QuatToEuler'
'body': 'CA_QuatToEuler(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:w}, ${5:&Float:rx}, ${6:&Float:ry}, ${7:&Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetModelBoundingSphere':
'prefix': 'CA_GetModelBoundingSphere'
'body': 'CA_GetModelBoundingSphere(${1:modelid}, ${2:&Float:offx}, ${3:&Float:offy}, ${4:&Float:offz}, ${5:&Float:radius})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetModelBoundingBox':
'prefix': 'CA_GetModelBoundingBox'
'body': 'CA_GetModelBoundingBox(${1:modelid}, ${2:&Float:minx}, ${3:&Float:miny}, ${4:&Float:minz}, ${5:&Float:maxx}, ${6:&Float:maxy}, ${7:&Float:maxz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectExtraID':
'prefix': 'CA_SetObjectExtraID'
'body': 'CA_SetObjectExtraID(${1:index}, ${2:type}, ${3:data})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetObjectExtraID':
'prefix': 'CA_GetObjectExtraID'
'body': 'CA_GetObjectExtraID(${1:index}, ${2:type})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineEx':
'prefix': 'CA_RayCastLineEx'
'body': 'CA_RayCastLineEx(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz}, ${13:&Float:rw}, ${14:&Float:cx}, ${15:&Float:cy}, ${16:&Float:cz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineAngleEx':
'prefix': 'CA_RayCastLineAngleEx'
'body': 'CA_RayCastLineAngleEx(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz}, ${13:&Float:ocx}, ${14:&Float:ocy}, ${15:&Float:ocz}, ${16:&Float:orx}, ${17:&Float:ory}, ${18:&Float:orz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject':
'prefix': 'CA_CreateObject'
'body': 'CA_CreateObject(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:bool:add = false})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyObject':
'prefix': 'CA_DestroyObject'
'body': 'CA_DestroyObject(${1:index})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectPos':
'prefix': 'CA_SetObjectPos'
'body': 'CA_SetObjectPos(${1:index}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectRot':
'prefix': 'CA_SetObjectRot'
'body': 'CA_SetObjectRot(${1:index}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObjectEx_SC':
'prefix': 'CA_CreateDynamicObjectEx_SC'
'body': 'CA_CreateDynamicObjectEx_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 0.0}, ${9:Float:streamdistance = 200.0}, ${10:worlds[] = { -1 }}, ${11:interiors[] = { -1 }}, ${12:players[] = { -1 }}, ${13:maxworlds = sizeof worlds}, ${14:maxinteriors = sizeof interiors}, ${15:maxplayers = sizeof players})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObject_SC':
'prefix': 'CA_CreateDynamicObject_SC'
'body': 'CA_CreateDynamicObject_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:vw = -1}, ${9:interior = -1}, ${10:playerid = -1}, ${11:Float:streamdist = 300.0}, ${12:Float:drawdist = 300.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject_SC':
'prefix': 'CA_CreateObject_SC'
'body': 'CA_CreateObject_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 300.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObjectEx_DC':
'prefix': 'CA_CreateDynamicObjectEx_DC'
'body': 'CA_CreateDynamicObjectEx_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 0.0}, ${9:Float:streamdistance = 200.0}, ${10:worlds[] = { -1 }}, ${11:interiors[] = { -1 }}, ${12:players[] = { -1 }}, ${13:maxworlds = sizeof worlds}, ${14:maxinteriors = sizeof interiors}, ${15:maxplayers = sizeof players})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObject_DC':
'prefix': 'CA_CreateDynamicObject_DC'
'body': 'CA_CreateDynamicObject_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:vw = -1}, ${9:interior = -1}, ${10:playerid = -1}, ${11:Float:streamdist = 300.0}, ${12:Float:drawdist = 300.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject_DC':
'prefix': 'CA_CreateObject_DC'
'body': 'CA_CreateObject_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 300.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyObject_DC':
'prefix': 'CA_DestroyObject_DC'
'body': 'CA_DestroyObject_DC(${1:index})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectPos_DC':
'prefix': 'CA_SetObjectPos_DC'
'body': 'CA_SetObjectPos_DC(${1:index}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectRot_DC':
'prefix': 'CA_SetObjectRot_DC'
'body': 'CA_SetObjectRot_DC(${1:index}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyAllObjects_DC':
'prefix': 'CA_DestroyAllObjects_DC'
'body': 'CA_DestroyAllObjects_DC()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_FindZ_For2DCoord':
'prefix': 'CA_FindZ_For2DCoord'
'body': 'CA_FindZ_For2DCoord(${1:Float:x}, ${2:Float:y}, ${3:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastExplode':
'prefix': 'CA_RayCastExplode'
'body': 'CA_RayCastExplode(${1:Float:cX}, ${2:Float:cY}, ${3:Float:cZ}, ${4:Float:Radius}, ${5:Float:intensity = 20.0}, ${6:Float:collisions[][3]})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerOnSurface':
'prefix': 'CA_IsPlayerOnSurface'
'body': 'CA_IsPlayerOnSurface(${1:playerid}, ${2:Float:tolerance=1.5})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBarriers':
'prefix': 'CA_RemoveBarriers'
'body': 'CA_RemoveBarriers()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBreakableBuildings':
'prefix': 'CA_RemoveBreakableBuildings'
'body': 'CA_RemoveBreakableBuildings()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerInWater':
'prefix': 'CA_IsPlayerInWater'
'body': 'CA_IsPlayerInWater(${1:playerid}, ${2:&Float:depth}, ${3:&Float:playerdepth})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerNearWater':
'prefix': 'CA_IsPlayerNearWater'
'body': 'CA_IsPlayerNearWater(${1:playerid}, ${2:Float:dist=3.0}, ${3:Float:height=3.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerFacingWater':
'prefix': 'CA_IsPlayerFacingWater'
'body': 'CA_IsPlayerFacingWater(${1:playerid}, ${2:Float:dist=3.0}, ${3:Float:height=3.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerBlocked':
'prefix': 'CA_IsPlayerBlocked'
'body': 'CA_IsPlayerBlocked(${1:playerid}, ${2:Float:dist=1.5}, ${3:Float:height=0.5})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetRoomHeight':
'prefix': 'CA_GetRoomHeight'
'body': 'CA_GetRoomHeight(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetRoomCenter':
'prefix': 'CA_GetRoomCenter'
'body': 'CA_GetRoomCenter(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:&Float:m_x}, ${5:&Float:m_y})'
'leftLabel': 'Float'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
| 49093 | # ColAndreas snippets (completions) for Atom
# Originally created by <NAME> "<NAME>" <NAME>
'.source.pwn, .source.inc':
'CA_Init':
'prefix': 'CA_Init'
'body': 'CA_Init()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBuilding':
'prefix': 'CA_RemoveBuilding'
'body': 'CA_RemoveBuilding(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLine':
'prefix': 'CA_RayCastLine'
'body': 'CA_RayCastLine(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineID':
'prefix': 'CA_RayCastLineID'
'body': 'CA_RayCastLineID(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineExtraID':
'prefix': 'CA_RayCastLineExtraID'
'body': 'CA_RayCastLineExtraID(${1:type}, ${2:Float:StartX}, ${3:Float:StartY}, ${4:Float:StartZ}, ${5:Float:EndX}, ${6:Float:EndY}, ${7:Float:EndZ}, ${8:&Float:x}, ${9:&Float:y}, ${10:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastMultiLine':
'prefix': 'CA_RayCastMultiLine'
'body': 'CA_RayCastMultiLine(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:Float:retx[]}, ${8:Float:rety[]}, ${9:Float:retz[]}, ${10:Float:retdist[]}, ${11:ModelIDs[]}, ${12:size = sizeof(retx})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineAngle':
'prefix': 'CA_RayCastLineAngle'
'body': 'CA_RayCastLineAngle(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastReflectionVector':
'prefix': 'CA_RayCastReflectionVector'
'body': 'CA_RayCastReflectionVector(${1:Float:startx}, ${2:Float:starty}, ${3:Float:startz}, ${4:Float:endx}, ${5:Float:endy}, ${6:Float:endz}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:nx}, ${11:&Float:ny}, ${12:&Float:nz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineNormal':
'prefix': 'CA_RayCastLineNormal'
'body': 'CA_RayCastLineNormal(${1:Float:startx}, ${2:Float:starty}, ${3:Float:startz}, ${4:Float:endx}, ${5:Float:endy}, ${6:Float:endz}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:nx}, ${11:&Float:ny}, ${12:&Float:nz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_ContactTest':
'prefix': 'CA_ContactTest'
'body': 'CA_ContactTest(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_EulerToQuat':
'prefix': 'CA_EulerToQuat'
'body': 'CA_EulerToQuat(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:x}, ${5:&Float:y}, ${6:&Float:z}, ${7:&Float:w})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_QuatToEuler':
'prefix': 'CA_QuatToEuler'
'body': 'CA_QuatToEuler(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:w}, ${5:&Float:rx}, ${6:&Float:ry}, ${7:&Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetModelBoundingSphere':
'prefix': 'CA_GetModelBoundingSphere'
'body': 'CA_GetModelBoundingSphere(${1:modelid}, ${2:&Float:offx}, ${3:&Float:offy}, ${4:&Float:offz}, ${5:&Float:radius})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetModelBoundingBox':
'prefix': 'CA_GetModelBoundingBox'
'body': 'CA_GetModelBoundingBox(${1:modelid}, ${2:&Float:minx}, ${3:&Float:miny}, ${4:&Float:minz}, ${5:&Float:maxx}, ${6:&Float:maxy}, ${7:&Float:maxz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectExtraID':
'prefix': 'CA_SetObjectExtraID'
'body': 'CA_SetObjectExtraID(${1:index}, ${2:type}, ${3:data})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetObjectExtraID':
'prefix': 'CA_GetObjectExtraID'
'body': 'CA_GetObjectExtraID(${1:index}, ${2:type})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineEx':
'prefix': 'CA_RayCastLineEx'
'body': 'CA_RayCastLineEx(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz}, ${13:&Float:rw}, ${14:&Float:cx}, ${15:&Float:cy}, ${16:&Float:cz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineAngleEx':
'prefix': 'CA_RayCastLineAngleEx'
'body': 'CA_RayCastLineAngleEx(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz}, ${13:&Float:ocx}, ${14:&Float:ocy}, ${15:&Float:ocz}, ${16:&Float:orx}, ${17:&Float:ory}, ${18:&Float:orz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject':
'prefix': 'CA_CreateObject'
'body': 'CA_CreateObject(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:bool:add = false})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyObject':
'prefix': 'CA_DestroyObject'
'body': 'CA_DestroyObject(${1:index})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectPos':
'prefix': 'CA_SetObjectPos'
'body': 'CA_SetObjectPos(${1:index}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectRot':
'prefix': 'CA_SetObjectRot'
'body': 'CA_SetObjectRot(${1:index}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObjectEx_SC':
'prefix': 'CA_CreateDynamicObjectEx_SC'
'body': 'CA_CreateDynamicObjectEx_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 0.0}, ${9:Float:streamdistance = 200.0}, ${10:worlds[] = { -1 }}, ${11:interiors[] = { -1 }}, ${12:players[] = { -1 }}, ${13:maxworlds = sizeof worlds}, ${14:maxinteriors = sizeof interiors}, ${15:maxplayers = sizeof players})'
'description': 'Function from: <NAME>'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObject_SC':
'prefix': 'CA_CreateDynamicObject_SC'
'body': 'CA_CreateDynamicObject_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:vw = -1}, ${9:interior = -1}, ${10:playerid = -1}, ${11:Float:streamdist = 300.0}, ${12:Float:drawdist = 300.0})'
'description': 'Function from: <NAME>'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject_SC':
'prefix': 'CA_CreateObject_SC'
'body': 'CA_CreateObject_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 300.0})'
'description': 'Function from: <NAME>'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObjectEx_DC':
'prefix': 'CA_CreateDynamicObjectEx_DC'
'body': 'CA_CreateDynamicObjectEx_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 0.0}, ${9:Float:streamdistance = 200.0}, ${10:worlds[] = { -1 }}, ${11:interiors[] = { -1 }}, ${12:players[] = { -1 }}, ${13:maxworlds = sizeof worlds}, ${14:maxinteriors = sizeof interiors}, ${15:maxplayers = sizeof players})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObject_DC':
'prefix': 'CA_CreateDynamicObject_DC'
'body': 'CA_CreateDynamicObject_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:vw = -1}, ${9:interior = -1}, ${10:playerid = -1}, ${11:Float:streamdist = 300.0}, ${12:Float:drawdist = 300.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject_DC':
'prefix': 'CA_CreateObject_DC'
'body': 'CA_CreateObject_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 300.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyObject_DC':
'prefix': 'CA_DestroyObject_DC'
'body': 'CA_DestroyObject_DC(${1:index})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectPos_DC':
'prefix': 'CA_SetObjectPos_DC'
'body': 'CA_SetObjectPos_DC(${1:index}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectRot_DC':
'prefix': 'CA_SetObjectRot_DC'
'body': 'CA_SetObjectRot_DC(${1:index}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyAllObjects_DC':
'prefix': 'CA_DestroyAllObjects_DC'
'body': 'CA_DestroyAllObjects_DC()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_FindZ_For2DCoord':
'prefix': 'CA_FindZ_For2DCoord'
'body': 'CA_FindZ_For2DCoord(${1:Float:x}, ${2:Float:y}, ${3:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastExplode':
'prefix': 'CA_RayCastExplode'
'body': 'CA_RayCastExplode(${1:Float:cX}, ${2:Float:cY}, ${3:Float:cZ}, ${4:Float:Radius}, ${5:Float:intensity = 20.0}, ${6:Float:collisions[][3]})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerOnSurface':
'prefix': 'CA_IsPlayerOnSurface'
'body': 'CA_IsPlayerOnSurface(${1:playerid}, ${2:Float:tolerance=1.5})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBarriers':
'prefix': 'CA_RemoveBarriers'
'body': 'CA_RemoveBarriers()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBreakableBuildings':
'prefix': 'CA_RemoveBreakableBuildings'
'body': 'CA_RemoveBreakableBuildings()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerInWater':
'prefix': 'CA_IsPlayerInWater'
'body': 'CA_IsPlayerInWater(${1:playerid}, ${2:&Float:depth}, ${3:&Float:playerdepth})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerNearWater':
'prefix': 'CA_IsPlayerNearWater'
'body': 'CA_IsPlayerNearWater(${1:playerid}, ${2:Float:dist=3.0}, ${3:Float:height=3.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerFacingWater':
'prefix': 'CA_IsPlayerFacingWater'
'body': 'CA_IsPlayerFacingWater(${1:playerid}, ${2:Float:dist=3.0}, ${3:Float:height=3.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerBlocked':
'prefix': 'CA_IsPlayerBlocked'
'body': 'CA_IsPlayerBlocked(${1:playerid}, ${2:Float:dist=1.5}, ${3:Float:height=0.5})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetRoomHeight':
'prefix': 'CA_GetRoomHeight'
'body': 'CA_GetRoomHeight(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetRoomCenter':
'prefix': 'CA_GetRoomCenter'
'body': 'CA_GetRoomCenter(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:&Float:m_x}, ${5:&Float:m_y})'
'leftLabel': 'Float'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
| true | # ColAndreas snippets (completions) for Atom
# Originally created by PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI
'.source.pwn, .source.inc':
'CA_Init':
'prefix': 'CA_Init'
'body': 'CA_Init()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBuilding':
'prefix': 'CA_RemoveBuilding'
'body': 'CA_RemoveBuilding(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:radius})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLine':
'prefix': 'CA_RayCastLine'
'body': 'CA_RayCastLine(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineID':
'prefix': 'CA_RayCastLineID'
'body': 'CA_RayCastLineID(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineExtraID':
'prefix': 'CA_RayCastLineExtraID'
'body': 'CA_RayCastLineExtraID(${1:type}, ${2:Float:StartX}, ${3:Float:StartY}, ${4:Float:StartZ}, ${5:Float:EndX}, ${6:Float:EndY}, ${7:Float:EndZ}, ${8:&Float:x}, ${9:&Float:y}, ${10:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastMultiLine':
'prefix': 'CA_RayCastMultiLine'
'body': 'CA_RayCastMultiLine(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:Float:retx[]}, ${8:Float:rety[]}, ${9:Float:retz[]}, ${10:Float:retdist[]}, ${11:ModelIDs[]}, ${12:size = sizeof(retx})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineAngle':
'prefix': 'CA_RayCastLineAngle'
'body': 'CA_RayCastLineAngle(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastReflectionVector':
'prefix': 'CA_RayCastReflectionVector'
'body': 'CA_RayCastReflectionVector(${1:Float:startx}, ${2:Float:starty}, ${3:Float:startz}, ${4:Float:endx}, ${5:Float:endy}, ${6:Float:endz}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:nx}, ${11:&Float:ny}, ${12:&Float:nz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineNormal':
'prefix': 'CA_RayCastLineNormal'
'body': 'CA_RayCastLineNormal(${1:Float:startx}, ${2:Float:starty}, ${3:Float:startz}, ${4:Float:endx}, ${5:Float:endy}, ${6:Float:endz}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:nx}, ${11:&Float:ny}, ${12:&Float:nz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_ContactTest':
'prefix': 'CA_ContactTest'
'body': 'CA_ContactTest(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_EulerToQuat':
'prefix': 'CA_EulerToQuat'
'body': 'CA_EulerToQuat(${1:Float:rx}, ${2:Float:ry}, ${3:Float:rz}, ${4:&Float:x}, ${5:&Float:y}, ${6:&Float:z}, ${7:&Float:w})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_QuatToEuler':
'prefix': 'CA_QuatToEuler'
'body': 'CA_QuatToEuler(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:Float:w}, ${5:&Float:rx}, ${6:&Float:ry}, ${7:&Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetModelBoundingSphere':
'prefix': 'CA_GetModelBoundingSphere'
'body': 'CA_GetModelBoundingSphere(${1:modelid}, ${2:&Float:offx}, ${3:&Float:offy}, ${4:&Float:offz}, ${5:&Float:radius})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetModelBoundingBox':
'prefix': 'CA_GetModelBoundingBox'
'body': 'CA_GetModelBoundingBox(${1:modelid}, ${2:&Float:minx}, ${3:&Float:miny}, ${4:&Float:minz}, ${5:&Float:maxx}, ${6:&Float:maxy}, ${7:&Float:maxz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectExtraID':
'prefix': 'CA_SetObjectExtraID'
'body': 'CA_SetObjectExtraID(${1:index}, ${2:type}, ${3:data})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetObjectExtraID':
'prefix': 'CA_GetObjectExtraID'
'body': 'CA_GetObjectExtraID(${1:index}, ${2:type})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineEx':
'prefix': 'CA_RayCastLineEx'
'body': 'CA_RayCastLineEx(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz}, ${13:&Float:rw}, ${14:&Float:cx}, ${15:&Float:cy}, ${16:&Float:cz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastLineAngleEx':
'prefix': 'CA_RayCastLineAngleEx'
'body': 'CA_RayCastLineAngleEx(${1:Float:StartX}, ${2:Float:StartY}, ${3:Float:StartZ}, ${4:Float:EndX}, ${5:Float:EndY}, ${6:Float:EndZ}, ${7:&Float:x}, ${8:&Float:y}, ${9:&Float:z}, ${10:&Float:rx}, ${11:&Float:ry}, ${12:&Float:rz}, ${13:&Float:ocx}, ${14:&Float:ocy}, ${15:&Float:ocz}, ${16:&Float:orx}, ${17:&Float:ory}, ${18:&Float:orz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject':
'prefix': 'CA_CreateObject'
'body': 'CA_CreateObject(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:bool:add = false})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyObject':
'prefix': 'CA_DestroyObject'
'body': 'CA_DestroyObject(${1:index})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectPos':
'prefix': 'CA_SetObjectPos'
'body': 'CA_SetObjectPos(${1:index}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectRot':
'prefix': 'CA_SetObjectRot'
'body': 'CA_SetObjectRot(${1:index}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObjectEx_SC':
'prefix': 'CA_CreateDynamicObjectEx_SC'
'body': 'CA_CreateDynamicObjectEx_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 0.0}, ${9:Float:streamdistance = 200.0}, ${10:worlds[] = { -1 }}, ${11:interiors[] = { -1 }}, ${12:players[] = { -1 }}, ${13:maxworlds = sizeof worlds}, ${14:maxinteriors = sizeof interiors}, ${15:maxplayers = sizeof players})'
'description': 'Function from: PI:NAME:<NAME>END_PI'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObject_SC':
'prefix': 'CA_CreateDynamicObject_SC'
'body': 'CA_CreateDynamicObject_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:vw = -1}, ${9:interior = -1}, ${10:playerid = -1}, ${11:Float:streamdist = 300.0}, ${12:Float:drawdist = 300.0})'
'description': 'Function from: PI:NAME:<NAME>END_PI'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject_SC':
'prefix': 'CA_CreateObject_SC'
'body': 'CA_CreateObject_SC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 300.0})'
'description': 'Function from: PI:NAME:<NAME>END_PI'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObjectEx_DC':
'prefix': 'CA_CreateDynamicObjectEx_DC'
'body': 'CA_CreateDynamicObjectEx_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 0.0}, ${9:Float:streamdistance = 200.0}, ${10:worlds[] = { -1 }}, ${11:interiors[] = { -1 }}, ${12:players[] = { -1 }}, ${13:maxworlds = sizeof worlds}, ${14:maxinteriors = sizeof interiors}, ${15:maxplayers = sizeof players})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateDynamicObject_DC':
'prefix': 'CA_CreateDynamicObject_DC'
'body': 'CA_CreateDynamicObject_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:vw = -1}, ${9:interior = -1}, ${10:playerid = -1}, ${11:Float:streamdist = 300.0}, ${12:Float:drawdist = 300.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_CreateObject_DC':
'prefix': 'CA_CreateObject_DC'
'body': 'CA_CreateObject_DC(${1:modelid}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z}, ${5:Float:rx}, ${6:Float:ry}, ${7:Float:rz}, ${8:Float:drawdistance = 300.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyObject_DC':
'prefix': 'CA_DestroyObject_DC'
'body': 'CA_DestroyObject_DC(${1:index})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectPos_DC':
'prefix': 'CA_SetObjectPos_DC'
'body': 'CA_SetObjectPos_DC(${1:index}, ${2:Float:x}, ${3:Float:y}, ${4:Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_SetObjectRot_DC':
'prefix': 'CA_SetObjectRot_DC'
'body': 'CA_SetObjectRot_DC(${1:index}, ${2:Float:rx}, ${3:Float:ry}, ${4:Float:rz})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_DestroyAllObjects_DC':
'prefix': 'CA_DestroyAllObjects_DC'
'body': 'CA_DestroyAllObjects_DC()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_FindZ_For2DCoord':
'prefix': 'CA_FindZ_For2DCoord'
'body': 'CA_FindZ_For2DCoord(${1:Float:x}, ${2:Float:y}, ${3:&Float:z})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RayCastExplode':
'prefix': 'CA_RayCastExplode'
'body': 'CA_RayCastExplode(${1:Float:cX}, ${2:Float:cY}, ${3:Float:cZ}, ${4:Float:Radius}, ${5:Float:intensity = 20.0}, ${6:Float:collisions[][3]})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerOnSurface':
'prefix': 'CA_IsPlayerOnSurface'
'body': 'CA_IsPlayerOnSurface(${1:playerid}, ${2:Float:tolerance=1.5})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBarriers':
'prefix': 'CA_RemoveBarriers'
'body': 'CA_RemoveBarriers()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_RemoveBreakableBuildings':
'prefix': 'CA_RemoveBreakableBuildings'
'body': 'CA_RemoveBreakableBuildings()'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerInWater':
'prefix': 'CA_IsPlayerInWater'
'body': 'CA_IsPlayerInWater(${1:playerid}, ${2:&Float:depth}, ${3:&Float:playerdepth})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerNearWater':
'prefix': 'CA_IsPlayerNearWater'
'body': 'CA_IsPlayerNearWater(${1:playerid}, ${2:Float:dist=3.0}, ${3:Float:height=3.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerFacingWater':
'prefix': 'CA_IsPlayerFacingWater'
'body': 'CA_IsPlayerFacingWater(${1:playerid}, ${2:Float:dist=3.0}, ${3:Float:height=3.0})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_IsPlayerBlocked':
'prefix': 'CA_IsPlayerBlocked'
'body': 'CA_IsPlayerBlocked(${1:playerid}, ${2:Float:dist=1.5}, ${3:Float:height=0.5})'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetRoomHeight':
'prefix': 'CA_GetRoomHeight'
'body': 'CA_GetRoomHeight(${1:Float:x}, ${2:Float:y}, ${3:Float:z})'
'leftLabel': 'Float'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
'CA_GetRoomCenter':
'prefix': 'CA_GetRoomCenter'
'body': 'CA_GetRoomCenter(${1:Float:x}, ${2:Float:y}, ${3:Float:z}, ${4:&Float:m_x}, ${5:&Float:m_y})'
'leftLabel': 'Float'
'description': 'Function from: ColAndreas'
'descriptionMoreURL': 'http://forum.sa-mp.com/showthread.php?t=586068'
|
[
{
"context": "d).\n\njct project API spec doc:\nhttps://github.com/antleaf/jct-project/blob/master/api/spec.md\n\nalgorithm sp",
"end": 1005,
"score": 0.9949502944946289,
"start": 998,
"tag": "USERNAME",
"value": "antleaf"
},
{
"context": "ool. Service provided by Cottage Labs LLP. Contact us@cottagelabs.com'\n\nAPI.add 'service/jct/calculate', get: () -> ret",
"end": 3691,
"score": 0.9999300241470337,
"start": 3673,
"tag": "EMAIL",
"value": "us@cottagelabs.com"
},
{
"context": "e new API log codes spec, \n # https://github.com/CottageLabs/jct/blob/feature/api_codes/markdown/apidocs.md#pe",
"end": 22024,
"score": 0.9982321858406067,
"start": 22013,
"tag": "USERNAME",
"value": "CottageLabs"
},
{
"context": "agreements data from sheets \n# https://github.com/antleaf/jct-project/blob/master/ta/public_data.md\n# only ",
"end": 22520,
"score": 0.9989922046661377,
"start": 22513,
"tag": "USERNAME",
"value": "antleaf"
},
{
"context": "lf-archiving prohibited list\n# https://github.com/antleaf/jct-project/issues/406\n# If journal in list, sa c",
"end": 30641,
"score": 0.9995766878128052,
"start": 30634,
"tag": "USERNAME",
"value": "antleaf"
},
{
"context": " issn.exact:\"') + '\")'\n # https://github.com/antleaf/jct-project/issues/406 no qualification needed if",
"end": 36123,
"score": 0.9982337951660156,
"start": 36116,
"tag": "USERNAME",
"value": "antleaf"
},
{
"context": "entionAt is in past - active - https://github.com/antleaf/jct-project/issues/437\n if fndr.retentio",
"end": 41206,
"score": 0.9992486238479614,
"start": 41199,
"tag": "USERNAME",
"value": "antleaf"
},
{
"context": " # 26032021, as per https://github.com/antleaf/jct-project/issues/380\n # rights reten",
"end": 41401,
"score": 0.9993946552276611,
"start": 41394,
"tag": "USERNAME",
"value": "antleaf"
},
{
"context": "ers: {'User-Agent': 'Journal Checker Tool; mailto: jct@cottagelabs.zendesk.com'}}\n total = res.data.message['total-result",
"end": 48845,
"score": 0.9999297857284546,
"start": 48818,
"tag": "EMAIL",
"value": "jct@cottagelabs.zendesk.com"
},
{
"context": "PI.service.jct.feedback name: 'unknowns', email: 'jct@cottagelabs.com', subject: 'JCT system reporting unknowns', feedb",
"end": 58133,
"score": 0.9999305009841919,
"start": 58114,
"tag": "EMAIL",
"value": "jct@cottagelabs.com"
},
{
"context": "mail.indexOf('.') isnt -1 then params.email else 'nobody@cottagelabs.com'\n subject: params.subject ? params.feedback.",
"end": 58711,
"score": 0.9999082684516907,
"start": 58689,
"tag": "EMAIL",
"value": "nobody@cottagelabs.com"
},
{
"context": "ain: ms.domain, apiKey: ms.apikey\n opts.from ?= 'jct@cottagelabs.com' # ms.from ? \n opts.to ?= 'jct@cottagelabs.zende",
"end": 61576,
"score": 0.9999220371246338,
"start": 61557,
"tag": "EMAIL",
"value": "jct@cottagelabs.com"
},
{
"context": " 'jct@cottagelabs.com' # ms.from ? \n opts.to ?= 'jct@cottagelabs.zendesk.com' # ms.to ? \n opts.to = opts.to.join(',') if ",
"end": 61628,
"score": 0.999897837638855,
"start": 61605,
"tag": "EMAIL",
"value": "jct@cottagelabs.zendesk"
},
{
"context": " ms.from ? \n opts.to ?= 'jct@cottagelabs.zendesk.com' # ms.to ? \n opts.to = opts.to.join(',') if type",
"end": 61632,
"score": 0.9987964034080505,
"start": 61629,
"tag": "EMAIL",
"value": "com"
},
{
"context": "bscriber to Jisc TA) 03kk7td41\n funder: 'Wellcome'\n 'expected outcome': 'Researcher can publis",
"end": 63786,
"score": 0.5828205347061157,
"start": 63782,
"tag": "NAME",
"value": "come"
},
{
"context": " or Wiley agreement) 03czfpz43\n funder: 'Wellcome'\n 'expected outcome': 'Researcher can publis",
"end": 64332,
"score": 0.642004668712616,
"start": 64328,
"tag": "NAME",
"value": "come"
},
{
"context": "iversity of Cape Town' # 03p74gp79\n funder: 'Bill & Melinda Gates Foundation' # Bill & Melinda Gate",
"end": 66540,
"score": 0.9740902185440063,
"start": 66536,
"tag": "NAME",
"value": "Bill"
},
{
"context": "ty of Cape Town' # 03p74gp79\n funder: 'Bill & Melinda Gates Foundation' # Bill & Melinda Gates Foundation billmelindagat",
"end": 66567,
"score": 0.9422047734260559,
"start": 66543,
"tag": "NAME",
"value": "Melinda Gates Foundation"
},
{
"context": "iversity of Cape Town' # 03p74gp79\n funder: 'SAMRC'\n 'expected outcome': 'Researcher can publis",
"end": 67186,
"score": 0.9801691770553589,
"start": 67181,
"tag": "USERNAME",
"value": "SAMRC"
},
{
"context": "iversity of Amsterdam' # 04dkp9463\n funder: 'NWO'\n 'expected outcome': 'Research can publish ",
"end": 67672,
"score": 0.8251580595970154,
"start": 67669,
"tag": "USERNAME",
"value": "NWO"
},
{
"context": "'University of Vienna' # 03prydq77\n funder: 'FWF'\n 'expected outcome': 'No routes to complian",
"end": 68331,
"score": 0.9075489044189453,
"start": 68328,
"tag": "USERNAME",
"value": "FWF"
}
] | server/service/jct/api.coffee | CottageLabs/jct_api | 1 | import moment from 'moment'
import mailgun from 'mailgun-js'
import fs from 'fs'
import tar from 'tar'
import Future from 'fibers/future'
import { Random } from 'meteor/random'
import unidecode from 'unidecode'
import csvtojson from 'csvtojson'
import stream from 'stream'
'''
The JCT API was a plugin for the noddy API stack, however it has since been
separated out to a standalone app. It has the smallest amount of noddy code that
it required, to keep it simple for future maintenance as a separate project.
It is possible that the old noddy codebase may have useful parts for future
development though, so consider having a look at it when new requirements come up.
This API defines the routes needed to support the JCT UIs, and the admin feed-ins
from sheets, and collates source data from DOAJ and OAB systems, as well as other
services run within the leviathan noddy API stack (such as the academic search
capabilities it already had).
jct project API spec doc:
https://github.com/antleaf/jct-project/blob/master/api/spec.md
algorithm spec docs:
https://docs.google.com/document/d/1-jdDMg7uxJAJd0r1P7MbavjDi1r261clTXAv_CFMwVE/edit?ts=5efb583f
https://docs.google.com/spreadsheets/d/11tR_vXJ7AnS_3m1_OSR3Guuyw7jgwPgh3ETgsIX0ltU/edit#gid=105475641
# Expected result examples: https://docs.google.com/document/d/1AZX_m8EAlnqnGWUYDjKmUsaIxnUh3EOuut9kZKO3d78/edit
given a journal, funder(s), and institution(s), tell if they are compliant or not
journal meets general JCT plan S compliance by meeting certain criteria
or journal can be applying to be in DOAJ if not in there yet
or journal can be in transformative journals list (which will be provided by plan S). If it IS in the list, it IS compliant
institutions could be any, and need to be tied to transformative agreements (which could be with larger umbrella orgs)
or an institutional affiliation to a transformative agreement could make a journal suitable
funders will be a list given to us by JCT detailing their particular requirements - in future this may alter whether or not the journal is acceptable to the funder
'''
# define the necessary collections - institution is defined global so a separate script was able to initialise it
# where devislive is true, the live indexes are actually reading from the dev ones. This is handy for
# datasets that are the same, such as institutions, journals, and transformative agreements
# but compliance and unknown should be unique as they could have different results on dev or live depending on code changes
# to do alterations to code on dev that may change how institutions, journals, or agreements are constructed, comment out the devislive setting
# NOTE: doing this would mean live would not have recent data to read from, so after this code change is deployed to live
# it should be followed by manually triggering a full import on live
# (for convenience the settings have initially been set up to only run import on dev as well, to make the most
# of the dev machine and minimise any potential memory or CPU intense work on the live machine - see the settings.json file for this config)
@jct_institution = new API.collection {index:"jct", type:"institution", devislive: true}
jct_journal = new API.collection {index:"jct", type:"journal"}
jct_agreement = new API.collection {index:"jct", type:"agreement"}
jct_compliance = new API.collection {index:"jct", type:"compliance"}
jct_unknown = new API.collection {index:"jct", type:"unknown"}
# define endpoints that the JCT requires (to be served at a dedicated domain)
API.add 'service/jct', get: () -> return 'cOAlition S Journal Checker Tool. Service provided by Cottage Labs LLP. Contact us@cottagelabs.com'
API.add 'service/jct/calculate', get: () -> return API.service.jct.calculate this.queryParams
API.add 'service/jct/suggest/:which', get: () -> return API.service.jct.suggest[this.urlParams.which] undefined, this.queryParams.from, this.queryParams.size
API.add 'service/jct/suggest/:which/:ac', get: () -> return API.service.jct.suggest[this.urlParams.which] this.urlParams.ac, this.queryParams.from, this.queryParams.size
API.add 'service/jct/ta',
get: () ->
if this.queryParams.issn or this.queryParams.journal
res = API.service.jct.ta this.queryParams.issn ? this.queryParams.journal, this.queryParams.institution ? this.queryParams.ror
ret = []
for r in (if not _.isArray(res) then [res] else res)
if r.compliant is 'yes'
ret.push issn: r.issn, ror: r.ror, id: log[0].result.split(' - ')[1]
return if ret.length then ret else 404
else
return jct_agreement.search this.queryParams
API.add 'service/jct/ta/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.ta.import this.queryParams.mail), 1
return true
API.add 'service/jct/sa_prohibited',
get: () ->
return API.service.jct.sa_prohibited this.queryParams.issn
API.add 'service/jct/sa_prohibited/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.sa_prohibited undefined, true), 1
return true
API.add 'service/jct/retention',
get: () ->
return API.service.jct.retention this.queryParams.issn
API.add 'service/jct/retention/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.retention undefined, true), 1
return true
API.add 'service/jct/tj', get: () -> return jct_journal.search this.queryParams, {restrict: [{exists: {field: 'tj'}}]}
API.add 'service/jct/tj/:issn',
get: () ->
res = API.service.jct.tj this.urlParams.issn
return if res?.compliant isnt 'yes' then 404 else issn: this.urlParams.issn, transformative_journal: true
API.add 'service/jct/tj/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.tj undefined, true), 1
return true
API.add 'service/jct/funder', get: () -> return API.service.jct.funders undefined, this.queryParams.refresh
API.add 'service/jct/funder/:iid', get: () -> return API.service.jct.funders this.urlParams.iid
API.add 'service/jct/feedback',
get: () -> return API.service.jct.feedback this.queryParams
post: () -> return API.service.jct.feedback this.bodyParams
API.add 'service/jct/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.import this.queryParams.refresh), 1
return true
API.add 'service/jct/unknown', get: () -> return jct_unknown.search this.queryParams
API.add 'service/jct/unknown/:start/:end',
get: () ->
csv = false
if typeof this.urlParams.start is 'string' and this.urlParams.start.indexOf('.csv') isnt -1
this.urlParams.start = this.urlParams.start.replace('.csv','')
csv = true
else if typeof this.urlParams.end is 'string' and this.urlParams.end.indexOf('.csv') isnt -1
this.urlParams.end = this.urlParams.end.replace('.csv','')
csv = true
res = []
if typeof this.urlParams.start in ['number','string'] or typeof this.urlParams.end in ['number','string']
q = if typeof this.urlParams.start in ['number','string'] then 'createdAt:>=' + this.urlParams.start else ''
if typeof this.urlParams.end in ['number','string']
q += ' AND ' if q isnt ''
q += 'createdAt:<' + this.urlParams.end
else
q = '*'
for un in unks = jct_unknown.fetch q
params = un._id.split '_'
res.push route: un.route, issn: params[1], funder: params[0], ror: params[2], log: un.log
if csv
fn = 'JCT_export_' + this.urlParams.start + (if this.urlParams.end then '_' + this.urlParams.end else '') + ".csv"
this.response.writeHead(200, {'Content-disposition': "attachment; filename=" + fn, 'Content-type': 'text/csv; charset=UTF-8', 'Content-Encoding': 'UTF-8'})
this.response.end API.service.jct.csv res
else
return res
API.add 'service/jct/journal', get: () -> return jct_journal.search this.queryParams
API.add 'service/jct/institution', get: () -> return jct_institution.search this.queryParams
API.add 'service/jct/compliance', get: () -> return jct_compliance.search this.queryParams
# the results that have already been calculated. These used to get used to re-serve as a
# faster cached result, but uncertainties over agreement on how long to cache stuff made
# this unnecessarily complex, so these are only stored as a history now.
API.add 'service/jct/test', get: () -> return API.service.jct.test this.queryParams
_jct_clean = (str) ->
pure = /[!-/:-@[-`{-~¡-©«-¬®-±´¶-¸»¿×÷˂-˅˒-˟˥-˫˭˯-˿͵;΄-΅·϶҂՚-՟։-֊־׀׃׆׳-״؆-؏؛؞-؟٪-٭۔۩۽-۾܀-܍߶-߹।-॥॰৲-৳৺૱୰௳-௺౿ೱ-ೲ൹෴฿๏๚-๛༁-༗༚-༟༴༶༸༺-༽྅྾-࿅࿇-࿌࿎-࿔၊-၏႞-႟჻፠-፨᎐-᎙᙭-᙮᚛-᚜᛫-᛭᜵-᜶។-៖៘-៛᠀-᠊᥀᥄-᥅᧞-᧿᨞-᨟᭚-᭪᭴-᭼᰻-᰿᱾-᱿᾽᾿-῁῍-῏῝-῟῭-`´-῾\u2000-\u206e⁺-⁾₊-₎₠-₵℀-℁℃-℆℈-℉℔№-℘℞-℣℥℧℩℮℺-℻⅀-⅄⅊-⅍⅏←-⏧␀-␦⑀-⑊⒜-ⓩ─-⚝⚠-⚼⛀-⛃✁-✄✆-✉✌-✧✩-❋❍❏-❒❖❘-❞❡-❵➔➘-➯➱-➾⟀-⟊⟌⟐-⭌⭐-⭔⳥-⳪⳹-⳼⳾-⳿⸀-\u2e7e⺀-⺙⺛-⻳⼀-⿕⿰-⿻\u3000-〿゛-゜゠・㆐-㆑㆖-㆟㇀-㇣㈀-㈞㈪-㉃㉐㉠-㉿㊊-㊰㋀-㋾㌀-㏿䷀-䷿꒐-꓆꘍-꘏꙳꙾꜀-꜖꜠-꜡꞉-꞊꠨-꠫꡴-꡷꣎-꣏꤮-꤯꥟꩜-꩟﬩﴾-﴿﷼-﷽︐-︙︰-﹒﹔-﹦﹨-﹫!-/:-@[-`{-・¢-₩│-○-�]|\ud800[\udd00-\udd02\udd37-\udd3f\udd79-\udd89\udd90-\udd9b\uddd0-\uddfc\udf9f\udfd0]|\ud802[\udd1f\udd3f\ude50-\ude58]|\ud809[\udc00-\udc7e]|\ud834[\udc00-\udcf5\udd00-\udd26\udd29-\udd64\udd6a-\udd6c\udd83-\udd84\udd8c-\udda9\uddae-\udddd\ude00-\ude41\ude45\udf00-\udf56]|\ud835[\udec1\udedb\udefb\udf15\udf35\udf4f\udf6f\udf89\udfa9\udfc3]|\ud83c[\udc00-\udc2b\udc30-\udc93]/g;
str = str.replace(pure, ' ')
return str.toLowerCase().replace(/ +/g,' ').trim()
# and now define the methods
API.service ?= {}
API.service.jct = {}
API.service.jct.suggest = {}
API.service.jct.suggest.funder = (str, from, size) ->
res = []
for f in API.service.jct.funders()
matches = true
if str isnt f.id
for s in (if str then str.toLowerCase().split(' ') else [])
if s not in ['of','the','and'] and f.funder.toLowerCase().indexOf(s) is -1
matches = false
res.push({title: f.funder, id: f.id}) if matches
return total: res.length, data: res
API.service.jct.suggest.institution = (str, from, size) ->
# TODO add an import method from wikidata or ROR, and have the usual import routine check for changes on a suitable schedule
if typeof str is 'string' and str.length is 9 and rec = jct_institution.get str
delete rec[x] for x in ['createdAt', 'created_date', '_id', 'description', 'values', 'wid']
return total: 1, data: [rec]
else
q = {query: {filtered: {query: {}, filter: {bool: {should: []}}}}, size: size}
q.from = from if from?
if str
str = _jct_clean(str).replace(/the /gi,'')
qry = (if str.indexOf(' ') is -1 then 'id:' + str + '* OR ' else '') + '(title:' + str.replace(/ /g,' AND title:') + '*) OR (alternate:' + str.replace(/ /g,' AND alternate:') + '*) OR (description:' + str.replace(/ /g,' AND description:') + '*) OR (values:' + str.replace(/ /g,' AND values:') + '*)'
q.query.filtered.query.query_string = {query: qry}
else
q.query.filtered.query.match_all = {}
res = jct_institution.search q
unis = []
starts = []
extra = []
for rec in res?.hits?.hits ? []
delete rec._source[x] for x in ['createdAt', 'created_date', '_id', 'description', 'values', 'wid']
if str
if rec._source.title.toLowerCase().indexOf('universit') isnt -1
unis.push rec._source
else if _jct_clean(rec._source.title).replace('the ','').replace('university ','').replace('of ','').startsWith(str.replace('the ','').replace('university ','').replace('of ',''))
starts.push rec._source
else if str.indexOf(' ') is -1 or unidecode(str) isnt str # allow matches on more random characters that may be matching elsewhere in the data but not in the actual title
extra.push rec._source
else
extra.push rec._source
ret = total: res?.hits?.total ? 0, data: _.union unis.sort((a, b) -> return a.title.length - b.title.length), starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
if ret.data.length < 10
seen = []
seen.push(sr.id) for sr in ret.data
q = {query: {filtered: {query: {}, filter: {bool: {should: []}}}}, size: size}
q.from = from if from?
if str
str = _jct_clean(str).replace(/the /gi,'')
q.query.filtered.query.query_string = {query: (if str.indexOf(' ') is -1 then 'ror.exact:"' + str + '" OR ' else '') + '(institution:' + str.replace(/ /g,' AND institution:') + '*)'}
else
q.query.filtered.query.query_string = {query: 'ror:*'}
res = jct_agreement.search q
if res?.hits?.total
ret.total += res.hits.total
unis = []
starts = []
extra = []
for rec in res?.hits?.hits ? []
if rec._source.ror not in seen
rc = {title: rec._source.institution, id: rec._source.ror, ta: true}
if str
if rc.title.toLowerCase().indexOf('universit') isnt -1
unis.push rc
else if _jct_clean(rc.title).replace('the ','').replace('university ','').replace('of ','').startsWith(str.replace('the ','').replace('university ','').replace('of ',''))
starts.push rc
else if rec._source.ror.indexOf(str) is 0 and unidecode(str) isnt str # allow matches on more random characters that may be matching elsewhere in the data but not in the actual title
extra.push rc
else
extra.push rc
ret.data = _.union ret.data, _.union unis.sort((a, b) -> return a.title.length - b.title.length), starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
return ret
API.service.jct.suggest.journal = (str, from, size) ->
q = {query: {filtered: {query: {query_string: {query: 'issn:* AND NOT discontinued:true AND NOT dois:0'}}, filter: {bool: {should: []}}}}, size: size, _source: {includes: ['title','issn','publisher','src']}}
q.from = from if from?
if str and str.replace(/\-/g,'').length
if str.indexOf(' ') is -1
if str.indexOf('-') isnt -1 and str.length is 9
q.query.filtered.query.query_string.query = 'issn.exact:"' + str + '" AND NOT discontinued:true AND NOT dois:0'
else
q.query.filtered.query.query_string.query = 'NOT discontinued:true AND NOT dois:0 AND ('
if str.indexOf('-') isnt -1
q.query.filtered.query.query_string.query += '(issn:"' + str.replace('-','" AND issn:') + '*)'
else
q.query.filtered.query.query_string.query += 'issn:' + str + '*'
q.query.filtered.query.query_string.query += ' OR title:"' + str + '" OR title:' + str + '* OR title:' + str + '~)'
else
str = _jct_clean str
q.query.filtered.query.query_string.query = 'issn:* AND NOT discontinued:true AND NOT dois:0 AND (title:"' + str + '" OR '
q.query.filtered.query.query_string.query += (if str.indexOf(' ') is -1 then 'title:' + str + '*' else '(title:' + str.replace(/ /g,'~ AND title:') + '*)') + ')'
res = jct_journal.search q
starts = []
extra = []
for rec in res?.hits?.hits ? []
if not str or JSON.stringify(rec._source.issn).indexOf(str) isnt -1 or _jct_clean(rec._source.title).startsWith(str)
starts.push rec._source
else
extra.push rec._source
rec._source.id = rec._source.issn[0]
return total: res?.hits?.total ? 0, data: _.union starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
API.service.jct.calculate = (params={}, refresh, checks=['sa', 'doaj', 'ta', 'tj'], retention=true, sa_prohibition=true) ->
# given funder(s), journal(s), institution(s), find out if compliant or not
# note could be given lists of each - if so, calculate all and return a list
if params.issn
params.journal = params.issn
delete params.issn
if params.ror
params.institution = params.ror
delete params.ror
refresh ?= params.refresh if params.refresh?
if params.checks?
checks = if typeof params.checks is 'string' then params.checks.split(',') else params.checks
retention = params.retention if params.retention?
res =
request:
started: Date.now()
ended: undefined
took: undefined
journal: []
funder: []
institution: []
checks: checks
retention: retention
compliant: false
cache: true
results: []
return res if not params.journal
issnsets = {}
for p in ['funder','journal','institution']
params[p] = params[p].toString() if typeof params[p] is 'number'
params[p] = params[p].split(',') if typeof params[p] is 'string'
params[p] ?= []
for v in params[p]
if sg = API.service.jct.suggest[p] v
if sg.data and sg.data.length
ad = sg.data[0]
res.request[p].push {id: ad.id, title: ad.title, issn: ad.issn, publisher: ad.publisher}
issnsets[v] ?= ad.issn if p is 'journal' and _.isArray(ad.issn) and ad.issn.length
res.request[p].push({id: v}) if not sg?.data
rq = Random.id() # random ID to store with the cached results, to measure number of unique requests that aggregate multiple sets of entities
checked = 0
_check = (funder, journal, institution) ->
hascompliant = false
allcached = true
_results = []
cr = sa: ('sa' in checks), doaj: ('doaj' in checks), ta: ('ta' in checks), tj: ('tj' in checks)
_ck = (which) ->
allcached = false
Meteor.setTimeout () ->
if which is 'sa'
rs = API.service.jct.sa (issnsets[journal] ? journal), (if institution? then institution else undefined), funder, retention, sa_prohibition
else
rs = API.service.jct[which] (issnsets[journal] ? journal), (if institution? and which is 'ta' then institution else undefined)
if rs
for r in (if _.isArray(rs) then rs else [rs])
hascompliant = true if r.compliant is 'yes'
if r.compliant is 'unknown'
API.service.jct.unknown r, funder, journal, institution
_results.push r
cr[which] = Date.now()
, 1
for c in checks
_ck(c) if cr[c]
while cr.sa is true or cr.doaj is true or cr.ta is true or cr.tj is true
future = new Future()
Meteor.setTimeout (() -> future.return()), 100
future.wait()
res.compliant = true if hascompliant
delete res.cache if not allcached
# store a new set of results every time without removing old ones, to keep track of incoming request amounts
jct_compliance.insert journal: journal, funder: funder, institution: institution, retention: retention, rq: rq, checks: checks, compliant: hascompliant, cache: allcached, results: _results
res.results.push(rs) for rs in _results
checked += 1
combos = [] # make a list of all possible valid combos of params
for j in (if params.journal and params.journal.length then params.journal else [undefined])
cm = journal: j
for f in (if params.funder and params.funder.length then params.funder else [undefined]) # does funder have any effect? - probably not right now, so the check will treat them the same
cm = _.clone cm
cm.funder = f
for i in (if params.institution and params.institution.length then params.institution else [undefined])
cm = _.clone cm
cm.institution = i
combos.push cm
console.log 'Calculating for:'
console.log combos
# start an async check for every combo
_prl = (combo) -> Meteor.setTimeout (() -> _check combo.funder, combo.journal, combo.institution), 1
for c in combos
if c.institution isnt undefined or c.funder isnt undefined or c.journal isnt undefined
_prl c
else
checked += 1
while checked isnt combos.length
future = new Future()
Meteor.setTimeout (() -> future.return()), 100
future.wait()
res.request.ended = Date.now()
res.request.took = res.request.ended - res.request.started
return res
# For a TA to be in force, an agreement record for the the ISSN and also one for
# the ROR mus be found, and the current date must be after those record start dates
# and before those record end dates. A journal and institution could be in more than
# one TA at a time - return all cases where both journal and institution are in the
# same TA
API.service.jct.ta = (issn, ror) ->
issn = issn.split(',') if typeof issn is 'string'
tas = []
qr = ''
if issn
qr += 'issn.exact:"' + issn.join('" OR issn.exact:"') + '"'
if ror
qr += ' OR ' if qr isnt ''
if typeof ror is 'string' and ror.indexOf(',') isnt -1
ror = ror.split(',')
qr += 'ror.exact:"' + ror.join('" OR ror.exact:"') + '"'
else
qr += 'ror.exact:"' + ror + '"'
res =
route: 'ta'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: ror
log: []
# what if start or end dates do not exist, but at least one of them does? Must they all exist?
journals = {}
institutions = {}
count = 0
jct_agreement.each qr, (rec) -> # how many could this be? If many, will it be fast enough?
count += 1
if rec.issn?
journals[rec.rid] = rec
else if rec.ror?
institutions[rec.rid] = rec
agreements = {}
for j of journals
if institutions[j]?
allow = true # avoid possibly duplicate TAs
agreements[j] ?= {}
for isn in (if typeof journals[j].issn is 'string' then [journals[j].issn] else journals[j].issn)
agreements[j][isn] ?= []
if institutions[j].ror not in agreements[j][isn]
agreements[j][isn].push institutions[j].ror
else
allow = false
if allow
rs = _.clone res
rs.compliant = 'yes'
rs.qualifications = if journals[j].corresponding_authors or institutions[j].corresponding_authors then [{corresponding_authors: {}}] else []
rs.log.push code: 'TA.Exists'
tas.push rs
if tas.length is 0
res.compliant = 'no'
res.log.push code: 'TA.NoTA'
tas.push res
return if tas.length is 1 then tas[0] else tas
# NOTE there are more log codes to use in the new API log codes spec,
# https://github.com/CottageLabs/jct/blob/feature/api_codes/markdown/apidocs.md#per-route-response-data
# TA.NotAcive - TA.Active - TA.Unknown - TA.NonCompliant - TA.Compliant
# but it is not known how these could be used here, as all TAs in the system appear to be active - anything with an end date in the past is not imported
# and there is no way to identify plan S compliant / not compliant unknown from the current algorithm spec
# import transformative agreements data from sheets
# https://github.com/antleaf/jct-project/blob/master/ta/public_data.md
# only validated agreements will be exposed at the following sheet
# https://docs.google.com/spreadsheets/d/e/2PACX-1vStezELi7qnKcyE8OiO2OYx2kqQDOnNsDX1JfAsK487n2uB_Dve5iDTwhUFfJ7eFPDhEjkfhXhqVTGw/pub?gid=1130349201&single=true&output=csv
# get the "Data URL" - if it's a valid URL, and the End Date is after current date, get the csv from it
API.service.jct.ta.import = (mail=true) ->
bads = []
records = []
res = sheets: 0, ready: 0, processed:0, records: 0, failed: []
console.log 'Starting ta import'
batch = []
bissns = [] # track ones going into the batch
for ov in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vStezELi7qnKcyE8OiO2OYx2kqQDOnNsDX1JfAsK487n2uB_Dve5iDTwhUFfJ7eFPDhEjkfhXhqVTGw/pub?gid=1130349201&single=true&output=csv'
res.sheets += 1
if typeof ov?['Data URL'] is 'string' and ov['Data URL'].trim().indexOf('http') is 0 and ov?['End Date']? and moment(ov['End Date'].trim(), 'YYYY-MM-DD').valueOf() > Date.now()
res.ready += 1
src = ov['Data URL'].trim()
console.log res
future = new Future()
Meteor.setTimeout (() -> future.return()), 1000 # wait 1s so don't instantly send 200 requests to google
future.wait()
_src = (src, ov) ->
Meteor.setTimeout () ->
console.log src
try
for rec in API.service.jct.csv2json src
for e of rec # get rid of empty things
delete rec[e] if not rec[e]
ri = {}
for ik in ['Institution Name', 'ROR ID', 'Institution First Seen', 'Institution Last Seen']
ri[ik] = rec[ik]
delete rec[ik]
if not _.isEmpty(ri) and not ri['Institution Last Seen'] # if these are present then it is too late to use this agreement
ri[k] = ov[k] for k of ov
# pick out records relevant to institution type
ri.rid = (if ri['ESAC ID'] then ri['ESAC ID'].trim() else '') + (if ri['ESAC ID'] and ri['Relationship'] then '_' + ri['Relationship'].trim() else '') # are these sufficient to be unique?
ri.institution = ri['Institution Name'].trim() if ri['Institution Name']
ri.ror = ri['ROR ID'].split('/').pop().trim() if ri['ROR ID']?
ri.corresponding_authors = true if ri['C/A Only'].trim().toLowerCase() is 'yes'
res.records += 1
records.push(ri) if ri.institution and ri.ror
if not _.isEmpty(rec) and not rec['Journal Last Seen']
rec[k] = ov[k] for k of ov
rec.rid = (if rec['ESAC ID'] then rec['ESAC ID'].trim() else '') + (if rec['ESAC ID'] and rec['Relationship'] then '_' + rec['Relationship'].trim() else '') # are these sufficient to be unique?
rec.issn = []
bad = false
for ik in ['ISSN (Print)','ISSN (Online)']
for isp in (if typeof rec[ik] is 'string' then rec[ik].split(',') else [])
if not isp? or typeof isp isnt 'string' or isp.indexOf('-') is -1 or isp.split('-').length > 2 or isp.length < 5
bads.push issn: isp, esac: rec['ESAC ID'], rid: rec.rid, src: src
bad = true
else if typeof isp is 'string'
nisp = isp.toUpperCase().trim().replace(/ /g, '')
rec.issn.push(nisp) if nisp.length and nisp not in rec.issn
rec.journal = rec['Journal Name'].trim() if rec['Journal Name']?
rec.corresponding_authors = true if rec['C/A Only'].trim().toLowerCase() is 'yes'
res.records += 1
if not bad and rec.journal and rec.issn.length
if exists = jct_journal.find 'issn.exact:"' + rec.issn.join('" OR issn.exact:"') + '"'
for ei in exists.issn
# don't take in ISSNs from TAs because we know they've been incorrect
rec.issn.push(ei) if typeof ei is 'string' and ei.length and ei not in rec.issn
else
inbi = false
# but if no record at all, not much choice so may as well accept
for ri in rec.issn
if ri in bissns
inbi = true
else
bissns.push ri
if not inbi
batch.push issn: rec.issn, title: rec.journal, ta: true
records.push rec
catch
console.log src + ' FAILED'
res.failed.push src
res.processed += 1
, 1
_src src, ov
while res.sheets isnt res.processed
future = new Future()
Meteor.setTimeout (() -> future.return()), 5000 # wait 5s repeatedly until all sheets are done
future.wait()
console.log 'TA sheets still processing, ' + (res.sheets - res.processed)
if records.length
console.log 'Removing and reloading ' + records.length + ' agreements'
jct_agreement.remove '*'
jct_agreement.insert records
res.extracted = records.length
if batch.length
jct_journal.insert batch
batch = []
if mail
API.service.jct.mail
subject: 'JCT TA import complete'
text: JSON.stringify res, '', 2
if bads.length
API.service.jct.mail
subject: 'JCT TA import found ' + bads.length + ' bad ISSNs'
text: bads.length + ' bad ISSNs listed in attached file'
attachment: bads
filename: 'bad_issns.csv'
return res
# import transformative journals data, which should indicate if the journal IS
# transformative or just in the list for tracking (to be transformative means to
# have submitted to the list with the appropriate responses)
# fields called pissn and eissn will contain ISSNs to check against
# check if an issn is in the transformative journals list (to be provided by plan S)
API.service.jct.tj = (issn, refresh) ->
if refresh
console.log 'Starting tj import'
recs = API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vT2SPOjVU4CKhP7FHOgaf0aRsjSOt-ApwLOy44swojTDFsWlZAIZViC0gdbmxJaEWxdJSnUmNoAnoo9/pub?gid=0&single=true&output=csv'
console.log 'Retrieved ' + recs.length + ' tj records from sheet'
for rec in recs
tj = {}
try tj.title = rec['Journal Title'].trim() if rec['Journal Title']
tj.issn ?= []
tj.issn.push(rec['ISSN (Print)'].trim().toUpperCase()) if typeof rec['ISSN (Print)'] is 'string' and rec['ISSN (Print)'].length
tj.issn.push(rec['e-ISSN (Online/Web)'].trim().toUpperCase()) if typeof rec['e-ISSN (Online/Web)'] is 'string' and rec['e-ISSN (Online/Web)'].length
if tj.issn and tj.issn.length
if exists = jct_journal.find 'issn.exact:"' + tj.issn.join('" OR issn.exact:"') + '"'
upd = {}
# don't trust incoming ISSNs from sheets because data provided by third parties has been seen to be wrong
#for isn in tj.issn
# if isn not in exists.issn
# upd.issn ?= []
# upd.issn.push isn
upd.tj = true if exists.tj isnt true
if JSON.stringify(upd) isnt '{}'
jct_journal.update exists._id, upd
else
tj.tj = true
jct_journal.insert tj
issn = issn.split(',') if typeof issn is 'string'
if issn and issn.length
res =
route: 'tj'
compliant: 'unknown'
qualifications: undefined
issn: issn
log: []
if exists = jct_journal.find 'tj:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.compliant = 'yes'
res.log.push code: 'TJ.Exists'
else
res.compliant = 'no'
res.log.push code: 'TJ.NoTJ'
return res
# TODO note there are two more codes in the new API log code spec,
# TJ.NonCompliant - TJ.Compliant
# but there is as yet no way to determine those so they are not used here yet.
else
return jct_journal.count 'tj:true'
# Import and check for Self-archiving prohibited list
# https://github.com/antleaf/jct-project/issues/406
# If journal in list, sa check not compliant
API.service.jct.sa_prohibited = (issn, refresh) ->
# check the sa prohibited data source first, to check if retained is false
# If retained is false, SA check is not compliant.
# will be a list of journals by ISSN
if refresh
counter = 0
for rt in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQ0EEMZTikcQZV28BiCL4huv-r0RnHiDrU08j3W1fyERNasoJYuAZek5G3oQH1TUKmf_X-yC5SiHaBM/pub?gid=0&single=true&output=csv'
counter += 1
console.log('sa prohibited import ' + counter) if counter % 20 is 0
rt.journal = rt['Journal Title'].trim() if typeof rt['Journal Title'] is 'string'
rt.issn = []
rt.issn.push(rt['ISSN (print)'].trim().toUpperCase()) if typeof rt['ISSN (print)'] is 'string' and rt['ISSN (print)'].length
rt.issn.push(rt['ISSN (electronic)'].trim().toUpperCase()) if typeof rt['ISSN (electronic)'] is 'string' and rt['ISSN (electronic)'].length
rt.publisher = rt.Publisher.trim() if typeof rt.Publisher is 'string'
if rt.issn.length
if exists = jct_journal.find 'issn.exact:"' + rt.issn.join('" OR issn.exact:"') + '"'
upd = {}
upd.issn ?= []
for isn in rt.issn
if isn not in exists.issn
upd.issn.push isn
upd.sa_prohibited = true if exists.sa_prohibited isnt true
upd.retention = rt
if JSON.stringify(upd) isnt '{}'
for en in exists.issn
upd.issn.push(en) if typeof en is 'string' and en.length and en not in upd.issn
jct_journal.update exists._id, upd
else
rec = sa_prohibited: true, retention: rt, issn: rt.issn, publisher: rt.publisher, title: rt.journal
jct_journal.insert rec
console.log('Imported ' + counter)
if issn
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'self_archiving'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: undefined
funder: undefined
log: []
if exists = jct_journal.find 'sa_prohibited:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.log.push code: 'SA.RRException'
res.compliant = 'no'
else
res.log.push code: 'SA.RRNoException'
return res
else
return jct_journal.count 'sa_prohibited:true'
# what are these qualifications relevant to? TAs?
# there is no funder qualification done now, due to retention policy change decision at ened of October 2020. May be added again later.
# rights_retention_author_advice -
# rights_retention_funder_implementation - the journal does not have an SA policy and the funder has a rights retention policy that starts in the future.
# There should be one record of this per funder that meets the conditions, and the following qualification specific data is requried:
# funder: <funder name>
# date: <date policy comes into force (YYYY-MM-DD)
# funder implementation ones are handled directly in the calculate stage at the moment
API.service.jct.retention = (issn, refresh) ->
# check the rights retention data source once it exists if the record is not in OAB
# for now this is a fallback to something that is not in OAB
# will be a list of journals by ISSN and a number 1,2,3,4,5
if refresh
counter = 0
for rt in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vTm6sDI16Kin3baNWaAiMUfGdMEUEGXy0LRvSDnvAQTWDN_exlYGyv4gnstGKdv3rXshjSa7AUWtAc5/pub?gid=0&single=true&output=csv'
counter += 1
console.log('Retention import ' + counter) if counter % 20 is 0
rt.journal = rt['Journal Name'].trim() if typeof rt['Journal Name'] is 'string'
rt.issn = []
rt.issn.push(rt['ISSN (print)'].trim().toUpperCase()) if typeof rt['ISSN (print)'] is 'string' and rt['ISSN (print)'].length
rt.issn.push(rt['ISSN (online)'].trim().toUpperCase()) if typeof rt['ISSN (online)'] is 'string' and rt['ISSN (online)'].length
rt.position = if typeof rt.Position is 'number' then rt.Position else parseInt rt.Position.trim()
rt.publisher = rt.Publisher.trim() if typeof rt.Publisher is 'string'
if rt.issn.length
if exists = jct_journal.find 'issn.exact:"' + rt.issn.join('" OR issn.exact:"') + '"'
upd = {}
upd.issn ?= []
for isn in rt.issn
if isn not in exists.issn
upd.issn.push isn
upd.retained = true if exists.retained isnt true
upd.retention = rt
if JSON.stringify(upd) isnt '{}'
for en in exists.issn
upd.issn.push(en) if typeof en is 'string' and en.length and en not in upd.issn
jct_journal.update exists._id, upd
else
rec = retained: true, retention: rt, issn: rt.issn, publisher: rt.publisher, title: rt.journal
jct_journal.insert rec
console.log('Imported ' + counter)
if issn
issn = [issn] if typeof issn is 'string'
res =
route: 'retention' # this is actually only used as a subset of OAB permission self_archiving so far
compliant: 'yes' # if not present then compliant but with author and funder quals - so what are the default funder quals?
qualifications: [{'rights_retention_author_advice': ''}]
issn: issn
log: []
if exists = jct_journal.find 'retained:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
# https://github.com/antleaf/jct-project/issues/406 no qualification needed if retained is true. Position not used.
delete res.qualifications
res.log.push code: 'SA.Compliant'
else
# new log code algo states there should be an SA.Unknown, but given we default to
# compliant at the moment, I don't see a way to achieve that, so set as Compliant for now
res.log.push(code: 'SA.Compliant') if res.log.length is 0
return res
else
return jct_journal.count 'retained:true'
API.service.jct.permission = (issn, institution) ->
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'self_archiving'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: institution
funder: undefined
log: []
try
permsurl = 'https://api.openaccessbutton.org/permissions?meta=false&issn=' + (if typeof issn is 'string' then issn else issn.join(',')) + (if typeof institution is 'string' then '&ror=' + institution else if institution? and Array.isArray(institution) and institution.length then '&ror=' + institution.join(',') else '')
perms = HTTP.call('GET', permsurl, {timeout:3000}).data
if perms.best_permission?
res.compliant = 'no' # set to no until a successful route through is found
pb = perms.best_permission
res.log.push code: 'SA.InOAB'
lc = false
pbls = [] # have to do these now even if can't archive, because needed for new API code algo values
for l in pb.licences ? []
pbls.push l.type
if lc is false and l.type.toLowerCase().replace(/\-/g,'').replace(/ /g,'') in ['ccby','ccbysa','cc0','ccbynd']
lc = l.type # set the first but have to keep going for new API codes algo
if pb.can_archive
if 'postprint' in pb.versions or 'publisher pdf' in pb.versions or 'acceptedVersion' in pb.versions or 'publishedVersion' in pb.versions
# and Embargo is zero
if typeof pb.embargo_months is 'string'
try pb.embargo_months = parseInt pb.embargo_months
if typeof pb.embargo_months isnt 'number' or pb.embargo_months is 0
if lc
res.log.push code: 'SA.OABCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
res.compliant = 'yes'
else if not pb.licences? or pb.licences.length is 0
res.log.push code: 'SA.OABIncomplete', parameters: missing: ['licences']
res.compliant = 'unknown'
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.NotInOAB'
catch
# Fixme: if we don't get an answer then we don't have the info, but this may not be strictly what we want.
res.log.push code: 'SA.OABIncomplete', parameters: missing: ['licences']
res.compliant = 'unknown'
return res
# Calculate self archiving check. It combines, sa_prohibited, OA.works permission and rr checks
API.service.jct.sa = (journal, institution, funder, retention=true, sa_prohibition=true) ->
# Get SA prohibition
if journal and sa_prohibition
res_sa = API.service.jct.sa_prohibited journal, undefined
if res_sa and res_sa.compliant is 'no'
return res_sa
# Get OA.Works permission
rs = API.service.jct.permission journal, institution
# merge the qualifications and logs from SA prohibition into OA.Works permission
rs.qualifications ?= []
if res_sa.qualifications? and res_sa.qualifications.length
for q in (if _.isArray(res_sa.qualifications) then res_sa.qualifications else [res_sa.qualifications])
rs.qualifications.push(q)
rs.log ?= []
if res_sa.log? and res_sa.log.length
for l in (if _.isArray(res_sa.log) then res_sa.log else [res_sa.log])
rs.log.push(l)
# check for retention
if rs
_rtn = {}
for r in (if _.isArray(rs) then rs else [rs])
if r.compliant isnt 'yes' and retention
# only check retention if the funder allows it - and only if there IS a funder
# funder allows if their rights retention date
if journal and funder? and fndr = API.service.jct.funders funder
r.funder = funder
# 1609459200000 = Wed Sep 25 52971
# if fndr.retentionAt? and (fndr.retentionAt is 1609459200000 or fndr.retentionAt >= Date.now())
# if retentionAt is in past - active - https://github.com/antleaf/jct-project/issues/437
if fndr.retentionAt? and fndr.retentionAt < Date.now()
r.log.push code: 'SA.FunderRRActive'
# 26032021, as per https://github.com/antleaf/jct-project/issues/380
# rights retention qualification disabled
#r.qualifications ?= []
#r.qualifications.push 'rights_retention_funder_implementation': funder: funder, date: moment(fndr.retentionAt).format 'YYYY-MM-DD'
# retention is a special case on permissions, done this way so can be easily disabled for testing
_rtn[journal] ?= API.service.jct.retention journal
r.compliant = _rtn[journal].compliant
r.log.push(lg) for lg in _rtn[journal].log
if _rtn[journal].qualifications? and _rtn[journal].qualifications.length
r.qualifications ?= []
r.qualifications.push(ql) for ql in _rtn[journal].qualifications
else
r.log.push code: 'SA.FunderRRNotActive'
return rs
API.service.jct.doaj = (issn) ->
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'fully_oa'
compliant: 'unknown'
qualifications: undefined
issn: issn
log: []
if issn
if ind = jct_journal.find 'indoaj:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.log.push code: 'FullOA.InDOAJ'
db = ind.doaj.bibjson
# Publishing License bibjson.license[].type bibjson.license[].type CC BY, CC BY SA, CC0 CC BY ND
pl = false
lics = []
if db.license? and db.license.length
for bl in db.license
if typeof bl?.type is 'string'
if bl.type.toLowerCase().trim().replace(/ /g,'').replace(/-/g,'') in ['ccby','ccbysa','cc0','ccbynd']
pl = bl.type if pl is false # only the first suitable one
lics.push bl.type # but have to keep going and record them all now for new API code returns values
if not db.license?
res.log.push code: 'FullOA.Unknown', parameters: missing: ['license']
else if pl
res.log.push code: 'FullOA.Compliant', parameters: licence: lics
res.compliant = 'yes'
else
res.log.push code: 'FullOA.NonCompliant', parameters: licence: lics
res.compliant = 'no'
# extra parts used to go here, but have been removed due to algorithm simplification.
else
res.log.push code: 'FullOA.NotInDOAJ'
res.compliant = 'no'
if res.compliant isnt 'yes'
# check if there is an open application for the journal to join DOAJ, if it wasn't already there
if pfd = jct_journal.find 'doajinprogress:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
if true # if an application, has to have applied within 6 months
res.log.push code: 'FullOA.InProgressDOAJ'
res.compliant = 'yes'
res.qualifications = [{doaj_under_review: {}}]
else
res.log.push code: 'FullOA.NotInProgressDOAJ' # there is actually an application, but it is too old
res.compliant = 'no'
else
res.log.push code: 'FullOA.NotInProgressDOAJ' # there is no application, so still may or may not be compliant
return res
# https://www.coalition-s.org/plan-s-funders-implementation/
_funders = []
_last_funders = Date.now()
API.service.jct.funders = (id, refresh) ->
if refresh or _funders.length is 0 or _last_funders > (Date.now() - 604800000) # if older than a week
_last_funders = Date.now()
_funders = []
for r in API.service.jct.table2json 'https://www.coalition-s.org/plan-s-funders-implementation/'
rec =
funder: r['cOAlition S organisation (funder)']
launch: r['Launch date for implementing Plan S-aligned OA policy']
application: r['Application of Plan S principles ']
retention: r['Rights Retention Strategy Implementation']
try rec.funder = rec.funder.replace('&','&')
for k of rec
if rec[k]?
rec[k] = rec[k].trim()
if rec[k].indexOf('<a') isnt -1
rec.url ?= []
rec.url.push rec[k].split('href')[1].split('=')[1].split('"')[1]
rec[k] = (rec[k].split('<')[0] + rec[k].split('>')[1].split('<')[0] + rec[k].split('>').pop()).trim()
else
delete rec[k]
if rec.retention
if rec.retention.indexOf('Note:') isnt -1
rec.notes ?= []
rec.notes.push rec.retention.split('Note:')[1].replace(')','').trim()
rec.retention = rec.retention.split('Note:')[0].replace('(','').trim()
rec.retentionAt = moment('01012021','DDMMYYYY').valueOf() if rec.retention.toLowerCase().indexOf('early adopter') isnt -1
try rec.startAt = moment(rec.launch, 'Do MMMM YYYY').valueOf()
delete rec.startAt if JSON.stringify(rec.startAt) is 'null'
if not rec.startAt? and rec.launch?
rec.notes ?= []
rec.notes.push rec.launch
try rec.id = rec.funder.toLowerCase().replace(/[^a-z0-9]/g,'')
_funders.push(rec) if rec.id?
if id?
for e in _funders
if e.id is id
return e
return _funders
API.service.jct.journals = {}
API.service.jct.journals.import = (refresh) ->
# first see if DOAJ file has updated - if so, do a full journal import
# doaj only updates their journal dump once a week so calling journal import
# won't actually do anything if the dump file name has not changed since last run
# or if a refresh is called
fldr = '/tmp/jct_doaj' + (if API.settings.dev then '_dev' else '') + '/'
if not fs.existsSync fldr
fs.mkdirSync fldr
ret = false
prev = false
current = false
fs.writeFileSync fldr + 'doaj.tar', HTTP.call('GET', 'https://doaj.org/public-data-dump/journal', {npmRequestOptions:{encoding:null}}).content
tar.extract file: fldr + 'doaj.tar', cwd: fldr, sync: true # extracted doaj dump folders end 2020-10-01
console.log 'got DOAJ journals dump'
for f in fs.readdirSync fldr # readdir alphasorts, so if more than one in tmp then last one will be newest
if f.indexOf('doaj_journal_data') isnt -1
if prev
try fs.unlinkSync fldr + prev + '/journal_batch_1.json'
try fs.rmdirSync fldr + prev
prev = current
current = f
if current and (prev or refresh)
console.log 'DOAJ journal dump ' + current + ' is suitable for ingest, getting crossref first'
# get everything from crossref
removed = false
total = 0
counter = 0
batch = []
while total is 0 or counter < total
if batch.length >= 10000 or (removed and batch.length >= 5000)
if not removed
# makes a shorter period of lack of records to query
# there will still be a period of 5 to 10 minutes where not all journals will be present
# but, since imports only occur once a day to every few days depending on settings, and
# responses should be cached at cloudflare anyway, this should not affect anyone as long as
# imports are not often run during UK/US business hours
jct_journal.remove '*'
console.log 'Removing old journal records'
future = new Future()
Meteor.setTimeout (() -> future.return()), 10000
future.wait()
removed = true
console.log 'Importing crossref ' + counter
jct_journal.insert batch
batch = []
try
url = 'https://api.crossref.org/journals?offset=' + counter + '&rows=' + 1000
console.log 'getting from crossref journals ' + url
res = HTTP.call 'GET', url, {headers: {'User-Agent': 'Journal Checker Tool; mailto: jct@cottagelabs.zendesk.com'}}
total = res.data.message['total-results'] if total is 0
for rec in res.data.message.items
if rec.ISSN and rec.ISSN.length and typeof rec.ISSN[0] is 'string'
rec.crossref = true
rec.issn = []
for i in rec.ISSN
rec.issn.push(i) if typeof i is 'string' and i.length and i not in rec.issn
rec.dois = rec.counts?['total-dois']
if rec.breakdowns?['dois-by-issued-year']?
rec.years = []
for yr in rec.breakdowns['dois-by-issued-year']
rec.years.push(yr[0]) if yr.length is 2 and yr[0] not in rec.years
rec.years.sort()
if not rec.years? or not rec.years.length or not rec.dois
rec.discontinued = true
else
thisyear = new Date().getFullYear()
if thisyear not in rec.years and (thisyear-1) not in rec.years and (thisyear-2) not in rec.years and (thisyear-3) not in rec.years
rec.discontinued = true
batch.push rec
counter += 1000
catch err
future = new Future()
Meteor.setTimeout (() -> future.return()), 2000 # wait 2s on probable crossref downtime
future.wait()
if batch.length
jct_journal.insert batch
batch = []
# then load the DOAJ data from the file (crossref takes priority because it has better metadata for spotting discontinuations)
# only about 20% of the ~15k are not already in crossref, so do updates then bulk load the new ones
console.log 'Importing from DOAJ journal dump ' + current
imports = 0
for rec in JSON.parse fs.readFileSync fldr + current + '/journal_batch_1.json'
imports += 1
console.log('DOAJ dump import ' + imports) if imports % 1000 is 0
qr = if typeof rec.bibjson.pissn is 'string' then 'issn.exact:"' + rec.bibjson.pissn + '"' else ''
if typeof rec.bibjson.eissn is 'string'
qr += ' OR ' if qr isnt ''
qr += 'issn.exact:"' + rec.bibjson.eissn + '"'
if exists = jct_journal.find qr
upd = doaj: rec
upd.indoaj = true
upd.discontinued = true if rec.bibjson.discontinued_date or rec.bibjson.is_replaced_by
upd.issn = [] # DOAJ ISSN data overrides crossref because we've seen errors in crossref that are correct in DOAJ such as 1474-9728
upd.issn.push(rec.bibjson.pissn.toUpperCase()) if typeof rec.bibjson.pissn is 'string' and rec.bibjson.pissn.length and rec.bibjson.pissn.toUpperCase() not in upd.issn
upd.issn.push(rec.bibjson.eissn.toUpperCase()) if typeof rec.bibjson.eissn is 'string' and rec.bibjson.eissn.length and rec.bibjson.eissn.toUpperCase() not in upd.issn
jct_journal.update exists._id, upd
else
nr = doaj: rec, indoaj: true
nr.title ?= rec.bibjson.title
nr.publisher ?= rec.bibjson.publisher.name if rec.bibjson.publisher?.name?
nr.discontinued = true if rec.bibjson.discontinued_date or rec.bibjson.is_replaced_by
nr.issn ?= []
nr.issn.push(rec.bibjson.pissn.toUpperCase()) if typeof rec.bibjson.pissn is 'string' and rec.bibjson.pissn.toUpperCase() not in nr.issn
nr.issn.push(rec.bibjson.eissn.toUpperCase()) if typeof rec.bibjson.eissn is 'string' and rec.bibjson.eissn.toUpperCase() not in nr.issn
batch.push nr
if batch.length
jct_journal.insert batch
batch = []
# get new doaj inprogress data if the journals load processed some doaj
# journals (otherwise we're between the week-long period when doaj doesn't update)
# and if doaj did update, load them into the catalogue too - there's only a few hundred so can check them for crossref dups too
r = HTTP.call 'GET', 'https://doaj.org/jct/inprogress?api_key=' + API.settings.service.jct.doaj.apikey
console.log 'Loading DOAJ inprogress records'
inpc = 0
for rec in JSON.parse r.content
inpc += 1
console.log('DOAJ inprogress ' + inpc) if inpc % 100 is 0
issns = []
issns.push(rec.pissn.toUpperCase()) if typeof rec.pissn is 'string' and rec.pissn.length
issns.push(rec.eissn.toUpperCase()) if typeof rec.eissn is 'string' and rec.eissn.length
if exists = jct_journal.find 'issn.exact:"' + issns.join('" OR issn.exact:"') + '"'
if not exists.indoaj # no point adding an application if already in doaj, which should be impossible, but check anyway
upd = doajinprogress: true, doajprogress: rec
nissns = []
for isn in issns
nissns.push(isn) if isn not in nissns and isn not in exists.issn
if nissns.length
upd.issn = _.union exists.issn, nissns
jct_journal.update exists._id, upd
else
console.log 'DOAJ in progress application already in DOAJ for ' + issns.join(', ')
else
nr = doajprogress: rec, issn: issns, doajinprogress: true
batch.push nr
if batch.length
jct_journal.insert batch
batch = []
return jct_journal.count()
else
return 0
# when importing TJ or TA data, add any journals not yet known about
API.service.jct.import = (refresh) ->
res = previously: jct_journal.count(), presently: undefined, started: Date.now()
res.newest = jct_agreement.find '*', true
if refresh or res.newest?.createdAt < Date.now()-86400000
# run all imports necessary for up to date data
console.log 'Starting JCT imports'
console.log 'Starting journals import'
res.journals = API.service.jct.journals.import refresh # takes about 10 mins depending how crossref is feeling
console.log 'JCT journals imported ' + res.journals
console.log 'Starting TJs import'
res.tj = API.service.jct.tj undefined, true
console.log 'JCT import TJs complete'
console.log 'Starting sa prohibited data import'
res.retention = API.service.jct.sa_prohibited undefined, true
console.log 'JCT import sa prohibited data complete'
console.log 'Starting retention data import'
res.retention = API.service.jct.retention undefined, true
console.log 'JCT import retention data complete'
console.log 'Starting funder data import'
res.funders = API.service.jct.funders undefined, true
res.funders = res.funders.length if _.isArray res.funders
console.log 'JCT import funders complete'
console.log 'Starting TAs data import'
res.ta = API.service.jct.ta.import false # this is the slowest, takes about twenty minutes
console.log 'JCT import TAs complete'
# check the mappings on jct_journal, jct_agreement, any others that get used and changed during import
# include a warning in the email if they seem far out of sync
# and include the previously and presently count, they should not be too different
res.presently = jct_journal.count()
res.ended = Date.now()
res.took = res.ended - res.started
res.minutes = Math.ceil res.took/60000
if res.mapped = JSON.stringify(jct_journal.mapping()).indexOf('dynamic_templates') isnt -1
res.mapped = JSON.stringify(jct_agreement.mapping()).indexOf('dynamic_templates') isnt -1
API.service.jct.mail
subject: 'JCT import complete'
text: JSON.stringify res, '', 2
return res
_jct_import = () ->
try API.service.jct.funders undefined, true # get the funders at startup
if API.settings.service?.jct?.import isnt false # so defaults to run if not set to false in settings
console.log 'Setting up a daily import check which will run an import if it is a Saturday'
# if later updates are made to run this on a cluster again, make sure that only one server runs this (e.g. use the import setting above where necessary)
Meteor.setInterval () ->
today = new Date()
if today.getDay() is 6 # if today is a Saturday run an import
console.log 'Starting Saturday import'
API.service.jct.import()
, 86400000
Meteor.setTimeout _jct_import, 5000
API.service.jct.unknown = (res, funder, journal, institution, send) ->
if res?
# it may not be worth saving these seperately if compliance result caching is on, but for now will keep them
r = _.clone res
r._id = (funder ? '') + '_' + (journal ? '') + '_' + (institution ? '') # overwrite dups
r.counter = 1
if ls = jct_unknown.get r._id
r.lastsend = ls.lastsend
r.counter += ls.counter ? 0
try jct_unknown.insert r
cnt = jct_unknown.count()
if send
try
cnt = 0
start = false
end = false
if typeof send isnt 'boolean'
start = send
q = 'createdAt:>' + send
else if lf = jct_unknown.find 'lastsend:*', {sort: {lastsend: {order: 'desc'}}}
start = lf.lastsend
q = 'createdAt:>' + lf.lastsend
else
q = '*'
last = false
for un in jct_unknown.fetch q, {newest: false}
start = un.createdAt if start is false
end = un.createdAt
last = un
cnt += 1
if last isnt false
jct_unknown.update last._id, lastsend: Date.now()
durl = 'https://' + (if API.settings.dev then 'api.jct.cottagelabs.com' else 'api.journalcheckertool.org') + '/unknown/' + start + '/' + end + '.csv'
API.service.jct.feedback name: 'unknowns', email: 'jct@cottagelabs.com', subject: 'JCT system reporting unknowns', feedback: durl
return cnt
Meteor.setTimeout (() -> API.service.jct.unknown(undefined, undefined, undefined, undefined, true)), 86400000 # send once a day
API.service.jct.feedback = (params={}) ->
if typeof params.name is 'string' and typeof params.email is 'string' and typeof params.feedback is 'string' and (not params.context? or typeof params.context is 'object')
API.service.jct.mail
from: if params.email.indexOf('@') isnt -1 and params.email.indexOf('.') isnt -1 then params.email else 'nobody@cottagelabs.com'
subject: params.subject ? params.feedback.substring(0,100) + if params.feedback.length > 100 then '...' else ''
text: (if API.settings.dev then '(dev)\n\n' else '') + params.feedback + '\n\n' + (if params.subject then '' else JSON.stringify params, '', 2)
return true
else
return false
API.service.jct.csv = (rows) ->
if Array.isArray(rows) and rows.length
header = ''
fields = []
for r in rows
for k of r
if k not in fields
fields.push k
header += ',' if header isnt ''
header += '"' + k.replace(/\"/g, '') + '"'
res = ''
for rr in rows
res += '\n' if res isnt ''
ln = ''
for f in fields
ln += ',' if ln isnt ''
ln += '"' + JSON.stringify(rr[f] ? '').replace(/\"/g, '') + '"'
res += ln
return header + '\n' + res
else
return ''
API.service.jct.csv2json = Async.wrap (content, callback) ->
content = HTTP.call('GET', content).content if content.indexOf('http') is 0
csvtojson().fromString(content).then (result) -> return callback null, result
API.service.jct.table2json = (content) ->
content = HTTP.call('GET', content).content if content.indexOf('http') is 0 # TODO need to try this without puppeteer
if content.indexOf('<table') isnt -1
content = '<table' + content.split('<table')[1]
else if content.indexOf('<TABLE') isnt -1
content = '<TABLE' + content.split('<TABLE')[1]
if content.indexOf('</table') isnt -1
content = content.split('</table')[0] + '</table>'
else if content.indexOf('</TABLE') isnt -1
content = content.split('</TABLE')[1] + '</TABLE>'
content = content.replace(/\r?\n|\r/g,'')
ths = content.match(/<th.*?<\/th/gi)
headers = []
results = []
if ths?
for h in ths
str = h.replace(/<th.*?>/i,'').replace(/<\/th.*?/i,'').replace(/<.*?>/gi,'').replace(/\s\s+/g,' ').trim()
str = 'UNKNOWN' if str.replace(/ /g,'').length is 0
headers.push str
for r in content.split('<tr')
if r.toLowerCase().indexOf('<th') is -1
result = {}
row = r.replace(/.*?>/i,'').replace(/<\/tr.*?/i,'')
vals = row.match(/<td.*?<\/td/gi)
keycounter = 0
for d of vals
val = vals[d].replace(/<.*?>/gi,'').replace('</td','')
if headers.length > keycounter
result[headers[keycounter]] = val
keycounter += 1
if vals[d].toLowerCase().indexOf('colspan') isnt -1
try
keycounter += parseInt(vals[d].toLowerCase().split('colspan')[1].split('>')[0].replace(/[^0-9]/,''))-1
delete result.UNKNOWN if result.UNKNOWN?
if not _.isEmpty result
results.push result
return results
API.service.jct.mail = (opts) ->
ms = API.settings.mail ? {} # need domain and apikey
mailer = mailgun domain: ms.domain, apiKey: ms.apikey
opts.from ?= 'jct@cottagelabs.com' # ms.from ?
opts.to ?= 'jct@cottagelabs.zendesk.com' # ms.to ?
opts.to = opts.to.join(',') if typeof opts.to is 'object'
#try HTTP.call 'POST', 'https://api.mailgun.net/v3/' + ms.domain + '/messages', {params:opts, auth:'api:'+ms.apikey}
# opts.attachment can be a string which is assumed to be a filename to attach, or a Buffer
# https://www.npmjs.com/package/mailgun-js
if typeof opts.attachment is 'object'
if opts.filename
fn = opts.filename
delete opts.filename
else
fn = 'data.csv'
att = API.service.jct.csv opts.attachment
opts.attachment = new mailer.Attachment filename: fn, contentType: 'text/csv', data: Buffer.from att, 'utf8'
console.log 'Sending mail to ' + opts.to
mailer.messages().send opts
return true
API.service.jct.test = (params={}) ->
# A series of queries based on journals, with existing knowledge of their policies.
# To test TJ and Rights retention elements of the algorithm some made up information is included,
# this is marked with [1]. Not all queries test all the compliance routes (in particular rights retention).
# Expected JCT Outcome, is what the outcome should be based on reading the information within journal, institution and funder data.
# Actual JCT Outcome is what was obtained by walking through the algorithm under the assumption that
# the publicly available information is within the JCT data sources.
params.refresh = true
params.sa_prohibition = true if not params.sa_prohibition?
params.test = params.tests if params.tests?
params.test = params.test.toString() if typeof params.test is 'number'
if typeof params.test is 'string'
ns = 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'
for n in ['10','1','2','3','4','5','6','7','8','9']
params.test = params.test.replace n, ns[n]
params.test = params.test.split ','
res = pass: true, fails: [], results: []
queries =
one: # Query 1
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc TA)
institution: 'Cardiff University' # (subscriber to Jisc TA) 03kk7td41
funder: 'Wellcome'
'expected outcome': 'Researcher can publish via gold open access route or via TA'
qualification: 'Researcher must be corresponding author to be eligible for TA'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('corresponding_authors') isnt -1
two: # Query 2
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc TA)
institution: 'Emory University' # (no TA or Wiley agreement) 03czfpz43
funder: 'Wellcome'
'expected outcome': 'Researcher can publish via gold open access route'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).split('"fully_oa"')[1].split('"issn"')[0].indexOf('"yes"') isnt -1
three: # Query 3
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc & VSNU TAs)
institution: ['Emory University', 'Cardiff University', 'Utrecht University'] # 03czfpz43,03kk7td41,04pp8hn57 (Emory has no TA or Wiley account, Cardiff is subscriber to Jisc TA, Utrecht is subscriber to VSNU TA which expires prior to 1 Jan 2021)
funder: ['Wellcome', 'NWO']
'expected outcome': 'For Cardiff: Researcher can publish via gold open access route or via TA (Qualification: Researcher must be corresponding author to be eligible for TA). For Emory and Utrecht: Researcher can publish via gold open access route'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
if rs.indexOf('TA.Exists') isnt -1
return rs.split('"fully_oa"')[1].split('"issn"')[0].indexOf('"yes"') isnt -1
return false
four: # Query 4
journal: 'Proceedings of the Royal Society B' # (subscription journal published by Royal Society, AAM can be shared CC BY no embargo, UK Jisc Read Publish Deal)
institution: 'Rothamsted Research' # (subscribe to Read Publish Deal) 0347fy350
funder: 'European Commission' # EC
'expected outcome': 'Researcher can self-archive or publish via Read Publish Deal'
qualification: 'Research must be corresponding author to be eligible for Read Publish Deal'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
return rs.indexOf('corresponding_authors') isnt -1 and rs.indexOf('TA.Exists') isnt -1
return false
five: # Query 5
journal: 'Proceedings of the Royal Society B' # (subscription journal published by Royal Society, AAM can be shared CC BY no embargo, UK Jisc Read Publish Deal)
institution: 'University of Cape Town' # 03p74gp79
funder: 'Bill & Melinda Gates Foundation' # Bill & Melinda Gates Foundation billmelindagatesfoundation
'expected outcome': 'Researcher can self-archive'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
for rs in r.results
if rs.route is 'self_archiving' and rs.compliant is 'yes'
return true
return false
six: # Query 6
journal: '1477-9129' # Development (published by Company of Biologists, not the other one, hence done by ISSN) # (Transformative Journal, AAM 12 month embargo) 0951-1991
institution: 'University of Cape Town' # 03p74gp79
funder: 'SAMRC'
'expected outcome': 'Researcher can publish via payment of APC (Transformative Journal)'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('TJ.Exists') isnt -1
seven: # Query 7
journal: 'Brill Research Perspectives in Law and Religion' # (Subscription Journal, VSNU Read Publish Agreement, AAM can be shared CC BY-NC no embargo)
institution: 'University of Amsterdam' # 04dkp9463
funder: 'NWO'
'expected outcome': 'Research can publish via the Transformative Agreement'
qualification: 'Researcher must be corresponding author to take advantage of the TA.'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
return rs.indexOf('corresponding_authors') isnt -1 and rs.indexOf('TA.Exists') isnt -1
return false
eight: # Query 8
journal: 'Migration and Society' # (Subscribe to Open, CC BY, CC BY-ND and CC BY-NC-ND licences available but currently only CC BY-NC-ND in DOAJ)
institution: 'University of Vienna' # 03prydq77
funder: 'FWF'
'expected outcome': 'No routes to compliance'
'actual outcome': 'As expected' # this is not possible because everything is currently compliant due to rights retention
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
nine: # Query 9
journal: 'Folia Historica Cracoviensia' # (fully oa, in DOAJ, CC BY-NC-ND)
institution: ['University of Warsaw', 'University of Ljubljana'] # 039bjqg32,05njb9z20
funder: ['NCN']
'expected outcome': 'No route to compliance.' # this is impossible due to rights retention
'actual outcome': 'As expected'
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
ten: # Query 10
journal: 'Journal of Clinical Investigation' # (subscription for front end material, research articles: publication fee, no embargo, CC BY licence where required by funders, not in DOAJ, Option 5 Rights Retention Policy [1])
institution: 'University of Vienna' # 03prydq77
funder: 'FWF'
'expected outcome': 'Researcher can publish via standard publication route'
'actual outcome': 'Researcher cannot publish in this journal and comply with funders OA policy' # as there is no rights retention this is impossible so it does succeed
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
for q of queries
if not params.test? or q in params.test
qr = queries[q]
ans = query: q
ans.pass = false
ans.inputs = queries[q]
ans.discovered = issn: [], funder: [], ror: []
for k in ['journal','institution','funder']
for j in (if typeof qr[k] is 'string' then [qr[k]] else qr[k])
try
ans.discovered[if k is 'journal' then 'issn' else if k is 'institution' then 'ror' else 'funder'].push API.service.jct.suggest[k](j).data[0].id
catch
console.log k, j
ans.result = API.service.jct.calculate {funder: ans.discovered.funder, issn: ans.discovered.issn, ror: ans.discovered.ror}, params.refresh, params.checks, params.retention, params.sa_prohibition
ans.pass = queries[q].test ans.result
if ans.pass isnt true
res.pass = false
res.fails.push q
res.results.push ans
delete res.fails if not res.fails.length
return res
| 222780 | import moment from 'moment'
import mailgun from 'mailgun-js'
import fs from 'fs'
import tar from 'tar'
import Future from 'fibers/future'
import { Random } from 'meteor/random'
import unidecode from 'unidecode'
import csvtojson from 'csvtojson'
import stream from 'stream'
'''
The JCT API was a plugin for the noddy API stack, however it has since been
separated out to a standalone app. It has the smallest amount of noddy code that
it required, to keep it simple for future maintenance as a separate project.
It is possible that the old noddy codebase may have useful parts for future
development though, so consider having a look at it when new requirements come up.
This API defines the routes needed to support the JCT UIs, and the admin feed-ins
from sheets, and collates source data from DOAJ and OAB systems, as well as other
services run within the leviathan noddy API stack (such as the academic search
capabilities it already had).
jct project API spec doc:
https://github.com/antleaf/jct-project/blob/master/api/spec.md
algorithm spec docs:
https://docs.google.com/document/d/1-jdDMg7uxJAJd0r1P7MbavjDi1r261clTXAv_CFMwVE/edit?ts=5efb583f
https://docs.google.com/spreadsheets/d/11tR_vXJ7AnS_3m1_OSR3Guuyw7jgwPgh3ETgsIX0ltU/edit#gid=105475641
# Expected result examples: https://docs.google.com/document/d/1AZX_m8EAlnqnGWUYDjKmUsaIxnUh3EOuut9kZKO3d78/edit
given a journal, funder(s), and institution(s), tell if they are compliant or not
journal meets general JCT plan S compliance by meeting certain criteria
or journal can be applying to be in DOAJ if not in there yet
or journal can be in transformative journals list (which will be provided by plan S). If it IS in the list, it IS compliant
institutions could be any, and need to be tied to transformative agreements (which could be with larger umbrella orgs)
or an institutional affiliation to a transformative agreement could make a journal suitable
funders will be a list given to us by JCT detailing their particular requirements - in future this may alter whether or not the journal is acceptable to the funder
'''
# define the necessary collections - institution is defined global so a separate script was able to initialise it
# where devislive is true, the live indexes are actually reading from the dev ones. This is handy for
# datasets that are the same, such as institutions, journals, and transformative agreements
# but compliance and unknown should be unique as they could have different results on dev or live depending on code changes
# to do alterations to code on dev that may change how institutions, journals, or agreements are constructed, comment out the devislive setting
# NOTE: doing this would mean live would not have recent data to read from, so after this code change is deployed to live
# it should be followed by manually triggering a full import on live
# (for convenience the settings have initially been set up to only run import on dev as well, to make the most
# of the dev machine and minimise any potential memory or CPU intense work on the live machine - see the settings.json file for this config)
@jct_institution = new API.collection {index:"jct", type:"institution", devislive: true}
jct_journal = new API.collection {index:"jct", type:"journal"}
jct_agreement = new API.collection {index:"jct", type:"agreement"}
jct_compliance = new API.collection {index:"jct", type:"compliance"}
jct_unknown = new API.collection {index:"jct", type:"unknown"}
# define endpoints that the JCT requires (to be served at a dedicated domain)
API.add 'service/jct', get: () -> return 'cOAlition S Journal Checker Tool. Service provided by Cottage Labs LLP. Contact <EMAIL>'
API.add 'service/jct/calculate', get: () -> return API.service.jct.calculate this.queryParams
API.add 'service/jct/suggest/:which', get: () -> return API.service.jct.suggest[this.urlParams.which] undefined, this.queryParams.from, this.queryParams.size
API.add 'service/jct/suggest/:which/:ac', get: () -> return API.service.jct.suggest[this.urlParams.which] this.urlParams.ac, this.queryParams.from, this.queryParams.size
API.add 'service/jct/ta',
get: () ->
if this.queryParams.issn or this.queryParams.journal
res = API.service.jct.ta this.queryParams.issn ? this.queryParams.journal, this.queryParams.institution ? this.queryParams.ror
ret = []
for r in (if not _.isArray(res) then [res] else res)
if r.compliant is 'yes'
ret.push issn: r.issn, ror: r.ror, id: log[0].result.split(' - ')[1]
return if ret.length then ret else 404
else
return jct_agreement.search this.queryParams
API.add 'service/jct/ta/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.ta.import this.queryParams.mail), 1
return true
API.add 'service/jct/sa_prohibited',
get: () ->
return API.service.jct.sa_prohibited this.queryParams.issn
API.add 'service/jct/sa_prohibited/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.sa_prohibited undefined, true), 1
return true
API.add 'service/jct/retention',
get: () ->
return API.service.jct.retention this.queryParams.issn
API.add 'service/jct/retention/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.retention undefined, true), 1
return true
API.add 'service/jct/tj', get: () -> return jct_journal.search this.queryParams, {restrict: [{exists: {field: 'tj'}}]}
API.add 'service/jct/tj/:issn',
get: () ->
res = API.service.jct.tj this.urlParams.issn
return if res?.compliant isnt 'yes' then 404 else issn: this.urlParams.issn, transformative_journal: true
API.add 'service/jct/tj/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.tj undefined, true), 1
return true
API.add 'service/jct/funder', get: () -> return API.service.jct.funders undefined, this.queryParams.refresh
API.add 'service/jct/funder/:iid', get: () -> return API.service.jct.funders this.urlParams.iid
API.add 'service/jct/feedback',
get: () -> return API.service.jct.feedback this.queryParams
post: () -> return API.service.jct.feedback this.bodyParams
API.add 'service/jct/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.import this.queryParams.refresh), 1
return true
API.add 'service/jct/unknown', get: () -> return jct_unknown.search this.queryParams
API.add 'service/jct/unknown/:start/:end',
get: () ->
csv = false
if typeof this.urlParams.start is 'string' and this.urlParams.start.indexOf('.csv') isnt -1
this.urlParams.start = this.urlParams.start.replace('.csv','')
csv = true
else if typeof this.urlParams.end is 'string' and this.urlParams.end.indexOf('.csv') isnt -1
this.urlParams.end = this.urlParams.end.replace('.csv','')
csv = true
res = []
if typeof this.urlParams.start in ['number','string'] or typeof this.urlParams.end in ['number','string']
q = if typeof this.urlParams.start in ['number','string'] then 'createdAt:>=' + this.urlParams.start else ''
if typeof this.urlParams.end in ['number','string']
q += ' AND ' if q isnt ''
q += 'createdAt:<' + this.urlParams.end
else
q = '*'
for un in unks = jct_unknown.fetch q
params = un._id.split '_'
res.push route: un.route, issn: params[1], funder: params[0], ror: params[2], log: un.log
if csv
fn = 'JCT_export_' + this.urlParams.start + (if this.urlParams.end then '_' + this.urlParams.end else '') + ".csv"
this.response.writeHead(200, {'Content-disposition': "attachment; filename=" + fn, 'Content-type': 'text/csv; charset=UTF-8', 'Content-Encoding': 'UTF-8'})
this.response.end API.service.jct.csv res
else
return res
API.add 'service/jct/journal', get: () -> return jct_journal.search this.queryParams
API.add 'service/jct/institution', get: () -> return jct_institution.search this.queryParams
API.add 'service/jct/compliance', get: () -> return jct_compliance.search this.queryParams
# the results that have already been calculated. These used to get used to re-serve as a
# faster cached result, but uncertainties over agreement on how long to cache stuff made
# this unnecessarily complex, so these are only stored as a history now.
API.add 'service/jct/test', get: () -> return API.service.jct.test this.queryParams
_jct_clean = (str) ->
pure = /[!-/:-@[-`{-~¡-©«-¬®-±´¶-¸»¿×÷˂-˅˒-˟˥-˫˭˯-˿͵;΄-΅·϶҂՚-՟։-֊־׀׃׆׳-״؆-؏؛؞-؟٪-٭۔۩۽-۾܀-܍߶-߹।-॥॰৲-৳৺૱୰௳-௺౿ೱ-ೲ൹෴฿๏๚-๛༁-༗༚-༟༴༶༸༺-༽྅྾-࿅࿇-࿌࿎-࿔၊-၏႞-႟჻፠-፨᎐-᎙᙭-᙮᚛-᚜᛫-᛭᜵-᜶។-៖៘-៛᠀-᠊᥀᥄-᥅᧞-᧿᨞-᨟᭚-᭪᭴-᭼᰻-᰿᱾-᱿᾽᾿-῁῍-῏῝-῟῭-`´-῾\u2000-\u206e⁺-⁾₊-₎₠-₵℀-℁℃-℆℈-℉℔№-℘℞-℣℥℧℩℮℺-℻⅀-⅄⅊-⅍⅏←-⏧␀-␦⑀-⑊⒜-ⓩ─-⚝⚠-⚼⛀-⛃✁-✄✆-✉✌-✧✩-❋❍❏-❒❖❘-❞❡-❵➔➘-➯➱-➾⟀-⟊⟌⟐-⭌⭐-⭔⳥-⳪⳹-⳼⳾-⳿⸀-\u2e7e⺀-⺙⺛-⻳⼀-⿕⿰-⿻\u3000-〿゛-゜゠・㆐-㆑㆖-㆟㇀-㇣㈀-㈞㈪-㉃㉐㉠-㉿㊊-㊰㋀-㋾㌀-㏿䷀-䷿꒐-꓆꘍-꘏꙳꙾꜀-꜖꜠-꜡꞉-꞊꠨-꠫꡴-꡷꣎-꣏꤮-꤯꥟꩜-꩟﬩﴾-﴿﷼-﷽︐-︙︰-﹒﹔-﹦﹨-﹫!-/:-@[-`{-・¢-₩│-○-�]|\ud800[\udd00-\udd02\udd37-\udd3f\udd79-\udd89\udd90-\udd9b\uddd0-\uddfc\udf9f\udfd0]|\ud802[\udd1f\udd3f\ude50-\ude58]|\ud809[\udc00-\udc7e]|\ud834[\udc00-\udcf5\udd00-\udd26\udd29-\udd64\udd6a-\udd6c\udd83-\udd84\udd8c-\udda9\uddae-\udddd\ude00-\ude41\ude45\udf00-\udf56]|\ud835[\udec1\udedb\udefb\udf15\udf35\udf4f\udf6f\udf89\udfa9\udfc3]|\ud83c[\udc00-\udc2b\udc30-\udc93]/g;
str = str.replace(pure, ' ')
return str.toLowerCase().replace(/ +/g,' ').trim()
# and now define the methods
API.service ?= {}
API.service.jct = {}
API.service.jct.suggest = {}
API.service.jct.suggest.funder = (str, from, size) ->
res = []
for f in API.service.jct.funders()
matches = true
if str isnt f.id
for s in (if str then str.toLowerCase().split(' ') else [])
if s not in ['of','the','and'] and f.funder.toLowerCase().indexOf(s) is -1
matches = false
res.push({title: f.funder, id: f.id}) if matches
return total: res.length, data: res
API.service.jct.suggest.institution = (str, from, size) ->
# TODO add an import method from wikidata or ROR, and have the usual import routine check for changes on a suitable schedule
if typeof str is 'string' and str.length is 9 and rec = jct_institution.get str
delete rec[x] for x in ['createdAt', 'created_date', '_id', 'description', 'values', 'wid']
return total: 1, data: [rec]
else
q = {query: {filtered: {query: {}, filter: {bool: {should: []}}}}, size: size}
q.from = from if from?
if str
str = _jct_clean(str).replace(/the /gi,'')
qry = (if str.indexOf(' ') is -1 then 'id:' + str + '* OR ' else '') + '(title:' + str.replace(/ /g,' AND title:') + '*) OR (alternate:' + str.replace(/ /g,' AND alternate:') + '*) OR (description:' + str.replace(/ /g,' AND description:') + '*) OR (values:' + str.replace(/ /g,' AND values:') + '*)'
q.query.filtered.query.query_string = {query: qry}
else
q.query.filtered.query.match_all = {}
res = jct_institution.search q
unis = []
starts = []
extra = []
for rec in res?.hits?.hits ? []
delete rec._source[x] for x in ['createdAt', 'created_date', '_id', 'description', 'values', 'wid']
if str
if rec._source.title.toLowerCase().indexOf('universit') isnt -1
unis.push rec._source
else if _jct_clean(rec._source.title).replace('the ','').replace('university ','').replace('of ','').startsWith(str.replace('the ','').replace('university ','').replace('of ',''))
starts.push rec._source
else if str.indexOf(' ') is -1 or unidecode(str) isnt str # allow matches on more random characters that may be matching elsewhere in the data but not in the actual title
extra.push rec._source
else
extra.push rec._source
ret = total: res?.hits?.total ? 0, data: _.union unis.sort((a, b) -> return a.title.length - b.title.length), starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
if ret.data.length < 10
seen = []
seen.push(sr.id) for sr in ret.data
q = {query: {filtered: {query: {}, filter: {bool: {should: []}}}}, size: size}
q.from = from if from?
if str
str = _jct_clean(str).replace(/the /gi,'')
q.query.filtered.query.query_string = {query: (if str.indexOf(' ') is -1 then 'ror.exact:"' + str + '" OR ' else '') + '(institution:' + str.replace(/ /g,' AND institution:') + '*)'}
else
q.query.filtered.query.query_string = {query: 'ror:*'}
res = jct_agreement.search q
if res?.hits?.total
ret.total += res.hits.total
unis = []
starts = []
extra = []
for rec in res?.hits?.hits ? []
if rec._source.ror not in seen
rc = {title: rec._source.institution, id: rec._source.ror, ta: true}
if str
if rc.title.toLowerCase().indexOf('universit') isnt -1
unis.push rc
else if _jct_clean(rc.title).replace('the ','').replace('university ','').replace('of ','').startsWith(str.replace('the ','').replace('university ','').replace('of ',''))
starts.push rc
else if rec._source.ror.indexOf(str) is 0 and unidecode(str) isnt str # allow matches on more random characters that may be matching elsewhere in the data but not in the actual title
extra.push rc
else
extra.push rc
ret.data = _.union ret.data, _.union unis.sort((a, b) -> return a.title.length - b.title.length), starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
return ret
API.service.jct.suggest.journal = (str, from, size) ->
q = {query: {filtered: {query: {query_string: {query: 'issn:* AND NOT discontinued:true AND NOT dois:0'}}, filter: {bool: {should: []}}}}, size: size, _source: {includes: ['title','issn','publisher','src']}}
q.from = from if from?
if str and str.replace(/\-/g,'').length
if str.indexOf(' ') is -1
if str.indexOf('-') isnt -1 and str.length is 9
q.query.filtered.query.query_string.query = 'issn.exact:"' + str + '" AND NOT discontinued:true AND NOT dois:0'
else
q.query.filtered.query.query_string.query = 'NOT discontinued:true AND NOT dois:0 AND ('
if str.indexOf('-') isnt -1
q.query.filtered.query.query_string.query += '(issn:"' + str.replace('-','" AND issn:') + '*)'
else
q.query.filtered.query.query_string.query += 'issn:' + str + '*'
q.query.filtered.query.query_string.query += ' OR title:"' + str + '" OR title:' + str + '* OR title:' + str + '~)'
else
str = _jct_clean str
q.query.filtered.query.query_string.query = 'issn:* AND NOT discontinued:true AND NOT dois:0 AND (title:"' + str + '" OR '
q.query.filtered.query.query_string.query += (if str.indexOf(' ') is -1 then 'title:' + str + '*' else '(title:' + str.replace(/ /g,'~ AND title:') + '*)') + ')'
res = jct_journal.search q
starts = []
extra = []
for rec in res?.hits?.hits ? []
if not str or JSON.stringify(rec._source.issn).indexOf(str) isnt -1 or _jct_clean(rec._source.title).startsWith(str)
starts.push rec._source
else
extra.push rec._source
rec._source.id = rec._source.issn[0]
return total: res?.hits?.total ? 0, data: _.union starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
API.service.jct.calculate = (params={}, refresh, checks=['sa', 'doaj', 'ta', 'tj'], retention=true, sa_prohibition=true) ->
# given funder(s), journal(s), institution(s), find out if compliant or not
# note could be given lists of each - if so, calculate all and return a list
if params.issn
params.journal = params.issn
delete params.issn
if params.ror
params.institution = params.ror
delete params.ror
refresh ?= params.refresh if params.refresh?
if params.checks?
checks = if typeof params.checks is 'string' then params.checks.split(',') else params.checks
retention = params.retention if params.retention?
res =
request:
started: Date.now()
ended: undefined
took: undefined
journal: []
funder: []
institution: []
checks: checks
retention: retention
compliant: false
cache: true
results: []
return res if not params.journal
issnsets = {}
for p in ['funder','journal','institution']
params[p] = params[p].toString() if typeof params[p] is 'number'
params[p] = params[p].split(',') if typeof params[p] is 'string'
params[p] ?= []
for v in params[p]
if sg = API.service.jct.suggest[p] v
if sg.data and sg.data.length
ad = sg.data[0]
res.request[p].push {id: ad.id, title: ad.title, issn: ad.issn, publisher: ad.publisher}
issnsets[v] ?= ad.issn if p is 'journal' and _.isArray(ad.issn) and ad.issn.length
res.request[p].push({id: v}) if not sg?.data
rq = Random.id() # random ID to store with the cached results, to measure number of unique requests that aggregate multiple sets of entities
checked = 0
_check = (funder, journal, institution) ->
hascompliant = false
allcached = true
_results = []
cr = sa: ('sa' in checks), doaj: ('doaj' in checks), ta: ('ta' in checks), tj: ('tj' in checks)
_ck = (which) ->
allcached = false
Meteor.setTimeout () ->
if which is 'sa'
rs = API.service.jct.sa (issnsets[journal] ? journal), (if institution? then institution else undefined), funder, retention, sa_prohibition
else
rs = API.service.jct[which] (issnsets[journal] ? journal), (if institution? and which is 'ta' then institution else undefined)
if rs
for r in (if _.isArray(rs) then rs else [rs])
hascompliant = true if r.compliant is 'yes'
if r.compliant is 'unknown'
API.service.jct.unknown r, funder, journal, institution
_results.push r
cr[which] = Date.now()
, 1
for c in checks
_ck(c) if cr[c]
while cr.sa is true or cr.doaj is true or cr.ta is true or cr.tj is true
future = new Future()
Meteor.setTimeout (() -> future.return()), 100
future.wait()
res.compliant = true if hascompliant
delete res.cache if not allcached
# store a new set of results every time without removing old ones, to keep track of incoming request amounts
jct_compliance.insert journal: journal, funder: funder, institution: institution, retention: retention, rq: rq, checks: checks, compliant: hascompliant, cache: allcached, results: _results
res.results.push(rs) for rs in _results
checked += 1
combos = [] # make a list of all possible valid combos of params
for j in (if params.journal and params.journal.length then params.journal else [undefined])
cm = journal: j
for f in (if params.funder and params.funder.length then params.funder else [undefined]) # does funder have any effect? - probably not right now, so the check will treat them the same
cm = _.clone cm
cm.funder = f
for i in (if params.institution and params.institution.length then params.institution else [undefined])
cm = _.clone cm
cm.institution = i
combos.push cm
console.log 'Calculating for:'
console.log combos
# start an async check for every combo
_prl = (combo) -> Meteor.setTimeout (() -> _check combo.funder, combo.journal, combo.institution), 1
for c in combos
if c.institution isnt undefined or c.funder isnt undefined or c.journal isnt undefined
_prl c
else
checked += 1
while checked isnt combos.length
future = new Future()
Meteor.setTimeout (() -> future.return()), 100
future.wait()
res.request.ended = Date.now()
res.request.took = res.request.ended - res.request.started
return res
# For a TA to be in force, an agreement record for the the ISSN and also one for
# the ROR mus be found, and the current date must be after those record start dates
# and before those record end dates. A journal and institution could be in more than
# one TA at a time - return all cases where both journal and institution are in the
# same TA
API.service.jct.ta = (issn, ror) ->
issn = issn.split(',') if typeof issn is 'string'
tas = []
qr = ''
if issn
qr += 'issn.exact:"' + issn.join('" OR issn.exact:"') + '"'
if ror
qr += ' OR ' if qr isnt ''
if typeof ror is 'string' and ror.indexOf(',') isnt -1
ror = ror.split(',')
qr += 'ror.exact:"' + ror.join('" OR ror.exact:"') + '"'
else
qr += 'ror.exact:"' + ror + '"'
res =
route: 'ta'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: ror
log: []
# what if start or end dates do not exist, but at least one of them does? Must they all exist?
journals = {}
institutions = {}
count = 0
jct_agreement.each qr, (rec) -> # how many could this be? If many, will it be fast enough?
count += 1
if rec.issn?
journals[rec.rid] = rec
else if rec.ror?
institutions[rec.rid] = rec
agreements = {}
for j of journals
if institutions[j]?
allow = true # avoid possibly duplicate TAs
agreements[j] ?= {}
for isn in (if typeof journals[j].issn is 'string' then [journals[j].issn] else journals[j].issn)
agreements[j][isn] ?= []
if institutions[j].ror not in agreements[j][isn]
agreements[j][isn].push institutions[j].ror
else
allow = false
if allow
rs = _.clone res
rs.compliant = 'yes'
rs.qualifications = if journals[j].corresponding_authors or institutions[j].corresponding_authors then [{corresponding_authors: {}}] else []
rs.log.push code: 'TA.Exists'
tas.push rs
if tas.length is 0
res.compliant = 'no'
res.log.push code: 'TA.NoTA'
tas.push res
return if tas.length is 1 then tas[0] else tas
# NOTE there are more log codes to use in the new API log codes spec,
# https://github.com/CottageLabs/jct/blob/feature/api_codes/markdown/apidocs.md#per-route-response-data
# TA.NotAcive - TA.Active - TA.Unknown - TA.NonCompliant - TA.Compliant
# but it is not known how these could be used here, as all TAs in the system appear to be active - anything with an end date in the past is not imported
# and there is no way to identify plan S compliant / not compliant unknown from the current algorithm spec
# import transformative agreements data from sheets
# https://github.com/antleaf/jct-project/blob/master/ta/public_data.md
# only validated agreements will be exposed at the following sheet
# https://docs.google.com/spreadsheets/d/e/2PACX-1vStezELi7qnKcyE8OiO2OYx2kqQDOnNsDX1JfAsK487n2uB_Dve5iDTwhUFfJ7eFPDhEjkfhXhqVTGw/pub?gid=1130349201&single=true&output=csv
# get the "Data URL" - if it's a valid URL, and the End Date is after current date, get the csv from it
API.service.jct.ta.import = (mail=true) ->
bads = []
records = []
res = sheets: 0, ready: 0, processed:0, records: 0, failed: []
console.log 'Starting ta import'
batch = []
bissns = [] # track ones going into the batch
for ov in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vStezELi7qnKcyE8OiO2OYx2kqQDOnNsDX1JfAsK487n2uB_Dve5iDTwhUFfJ7eFPDhEjkfhXhqVTGw/pub?gid=1130349201&single=true&output=csv'
res.sheets += 1
if typeof ov?['Data URL'] is 'string' and ov['Data URL'].trim().indexOf('http') is 0 and ov?['End Date']? and moment(ov['End Date'].trim(), 'YYYY-MM-DD').valueOf() > Date.now()
res.ready += 1
src = ov['Data URL'].trim()
console.log res
future = new Future()
Meteor.setTimeout (() -> future.return()), 1000 # wait 1s so don't instantly send 200 requests to google
future.wait()
_src = (src, ov) ->
Meteor.setTimeout () ->
console.log src
try
for rec in API.service.jct.csv2json src
for e of rec # get rid of empty things
delete rec[e] if not rec[e]
ri = {}
for ik in ['Institution Name', 'ROR ID', 'Institution First Seen', 'Institution Last Seen']
ri[ik] = rec[ik]
delete rec[ik]
if not _.isEmpty(ri) and not ri['Institution Last Seen'] # if these are present then it is too late to use this agreement
ri[k] = ov[k] for k of ov
# pick out records relevant to institution type
ri.rid = (if ri['ESAC ID'] then ri['ESAC ID'].trim() else '') + (if ri['ESAC ID'] and ri['Relationship'] then '_' + ri['Relationship'].trim() else '') # are these sufficient to be unique?
ri.institution = ri['Institution Name'].trim() if ri['Institution Name']
ri.ror = ri['ROR ID'].split('/').pop().trim() if ri['ROR ID']?
ri.corresponding_authors = true if ri['C/A Only'].trim().toLowerCase() is 'yes'
res.records += 1
records.push(ri) if ri.institution and ri.ror
if not _.isEmpty(rec) and not rec['Journal Last Seen']
rec[k] = ov[k] for k of ov
rec.rid = (if rec['ESAC ID'] then rec['ESAC ID'].trim() else '') + (if rec['ESAC ID'] and rec['Relationship'] then '_' + rec['Relationship'].trim() else '') # are these sufficient to be unique?
rec.issn = []
bad = false
for ik in ['ISSN (Print)','ISSN (Online)']
for isp in (if typeof rec[ik] is 'string' then rec[ik].split(',') else [])
if not isp? or typeof isp isnt 'string' or isp.indexOf('-') is -1 or isp.split('-').length > 2 or isp.length < 5
bads.push issn: isp, esac: rec['ESAC ID'], rid: rec.rid, src: src
bad = true
else if typeof isp is 'string'
nisp = isp.toUpperCase().trim().replace(/ /g, '')
rec.issn.push(nisp) if nisp.length and nisp not in rec.issn
rec.journal = rec['Journal Name'].trim() if rec['Journal Name']?
rec.corresponding_authors = true if rec['C/A Only'].trim().toLowerCase() is 'yes'
res.records += 1
if not bad and rec.journal and rec.issn.length
if exists = jct_journal.find 'issn.exact:"' + rec.issn.join('" OR issn.exact:"') + '"'
for ei in exists.issn
# don't take in ISSNs from TAs because we know they've been incorrect
rec.issn.push(ei) if typeof ei is 'string' and ei.length and ei not in rec.issn
else
inbi = false
# but if no record at all, not much choice so may as well accept
for ri in rec.issn
if ri in bissns
inbi = true
else
bissns.push ri
if not inbi
batch.push issn: rec.issn, title: rec.journal, ta: true
records.push rec
catch
console.log src + ' FAILED'
res.failed.push src
res.processed += 1
, 1
_src src, ov
while res.sheets isnt res.processed
future = new Future()
Meteor.setTimeout (() -> future.return()), 5000 # wait 5s repeatedly until all sheets are done
future.wait()
console.log 'TA sheets still processing, ' + (res.sheets - res.processed)
if records.length
console.log 'Removing and reloading ' + records.length + ' agreements'
jct_agreement.remove '*'
jct_agreement.insert records
res.extracted = records.length
if batch.length
jct_journal.insert batch
batch = []
if mail
API.service.jct.mail
subject: 'JCT TA import complete'
text: JSON.stringify res, '', 2
if bads.length
API.service.jct.mail
subject: 'JCT TA import found ' + bads.length + ' bad ISSNs'
text: bads.length + ' bad ISSNs listed in attached file'
attachment: bads
filename: 'bad_issns.csv'
return res
# import transformative journals data, which should indicate if the journal IS
# transformative or just in the list for tracking (to be transformative means to
# have submitted to the list with the appropriate responses)
# fields called pissn and eissn will contain ISSNs to check against
# check if an issn is in the transformative journals list (to be provided by plan S)
API.service.jct.tj = (issn, refresh) ->
if refresh
console.log 'Starting tj import'
recs = API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vT2SPOjVU4CKhP7FHOgaf0aRsjSOt-ApwLOy44swojTDFsWlZAIZViC0gdbmxJaEWxdJSnUmNoAnoo9/pub?gid=0&single=true&output=csv'
console.log 'Retrieved ' + recs.length + ' tj records from sheet'
for rec in recs
tj = {}
try tj.title = rec['Journal Title'].trim() if rec['Journal Title']
tj.issn ?= []
tj.issn.push(rec['ISSN (Print)'].trim().toUpperCase()) if typeof rec['ISSN (Print)'] is 'string' and rec['ISSN (Print)'].length
tj.issn.push(rec['e-ISSN (Online/Web)'].trim().toUpperCase()) if typeof rec['e-ISSN (Online/Web)'] is 'string' and rec['e-ISSN (Online/Web)'].length
if tj.issn and tj.issn.length
if exists = jct_journal.find 'issn.exact:"' + tj.issn.join('" OR issn.exact:"') + '"'
upd = {}
# don't trust incoming ISSNs from sheets because data provided by third parties has been seen to be wrong
#for isn in tj.issn
# if isn not in exists.issn
# upd.issn ?= []
# upd.issn.push isn
upd.tj = true if exists.tj isnt true
if JSON.stringify(upd) isnt '{}'
jct_journal.update exists._id, upd
else
tj.tj = true
jct_journal.insert tj
issn = issn.split(',') if typeof issn is 'string'
if issn and issn.length
res =
route: 'tj'
compliant: 'unknown'
qualifications: undefined
issn: issn
log: []
if exists = jct_journal.find 'tj:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.compliant = 'yes'
res.log.push code: 'TJ.Exists'
else
res.compliant = 'no'
res.log.push code: 'TJ.NoTJ'
return res
# TODO note there are two more codes in the new API log code spec,
# TJ.NonCompliant - TJ.Compliant
# but there is as yet no way to determine those so they are not used here yet.
else
return jct_journal.count 'tj:true'
# Import and check for Self-archiving prohibited list
# https://github.com/antleaf/jct-project/issues/406
# If journal in list, sa check not compliant
API.service.jct.sa_prohibited = (issn, refresh) ->
# check the sa prohibited data source first, to check if retained is false
# If retained is false, SA check is not compliant.
# will be a list of journals by ISSN
if refresh
counter = 0
for rt in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQ0EEMZTikcQZV28BiCL4huv-r0RnHiDrU08j3W1fyERNasoJYuAZek5G3oQH1TUKmf_X-yC5SiHaBM/pub?gid=0&single=true&output=csv'
counter += 1
console.log('sa prohibited import ' + counter) if counter % 20 is 0
rt.journal = rt['Journal Title'].trim() if typeof rt['Journal Title'] is 'string'
rt.issn = []
rt.issn.push(rt['ISSN (print)'].trim().toUpperCase()) if typeof rt['ISSN (print)'] is 'string' and rt['ISSN (print)'].length
rt.issn.push(rt['ISSN (electronic)'].trim().toUpperCase()) if typeof rt['ISSN (electronic)'] is 'string' and rt['ISSN (electronic)'].length
rt.publisher = rt.Publisher.trim() if typeof rt.Publisher is 'string'
if rt.issn.length
if exists = jct_journal.find 'issn.exact:"' + rt.issn.join('" OR issn.exact:"') + '"'
upd = {}
upd.issn ?= []
for isn in rt.issn
if isn not in exists.issn
upd.issn.push isn
upd.sa_prohibited = true if exists.sa_prohibited isnt true
upd.retention = rt
if JSON.stringify(upd) isnt '{}'
for en in exists.issn
upd.issn.push(en) if typeof en is 'string' and en.length and en not in upd.issn
jct_journal.update exists._id, upd
else
rec = sa_prohibited: true, retention: rt, issn: rt.issn, publisher: rt.publisher, title: rt.journal
jct_journal.insert rec
console.log('Imported ' + counter)
if issn
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'self_archiving'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: undefined
funder: undefined
log: []
if exists = jct_journal.find 'sa_prohibited:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.log.push code: 'SA.RRException'
res.compliant = 'no'
else
res.log.push code: 'SA.RRNoException'
return res
else
return jct_journal.count 'sa_prohibited:true'
# what are these qualifications relevant to? TAs?
# there is no funder qualification done now, due to retention policy change decision at ened of October 2020. May be added again later.
# rights_retention_author_advice -
# rights_retention_funder_implementation - the journal does not have an SA policy and the funder has a rights retention policy that starts in the future.
# There should be one record of this per funder that meets the conditions, and the following qualification specific data is requried:
# funder: <funder name>
# date: <date policy comes into force (YYYY-MM-DD)
# funder implementation ones are handled directly in the calculate stage at the moment
API.service.jct.retention = (issn, refresh) ->
# check the rights retention data source once it exists if the record is not in OAB
# for now this is a fallback to something that is not in OAB
# will be a list of journals by ISSN and a number 1,2,3,4,5
if refresh
counter = 0
for rt in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vTm6sDI16Kin3baNWaAiMUfGdMEUEGXy0LRvSDnvAQTWDN_exlYGyv4gnstGKdv3rXshjSa7AUWtAc5/pub?gid=0&single=true&output=csv'
counter += 1
console.log('Retention import ' + counter) if counter % 20 is 0
rt.journal = rt['Journal Name'].trim() if typeof rt['Journal Name'] is 'string'
rt.issn = []
rt.issn.push(rt['ISSN (print)'].trim().toUpperCase()) if typeof rt['ISSN (print)'] is 'string' and rt['ISSN (print)'].length
rt.issn.push(rt['ISSN (online)'].trim().toUpperCase()) if typeof rt['ISSN (online)'] is 'string' and rt['ISSN (online)'].length
rt.position = if typeof rt.Position is 'number' then rt.Position else parseInt rt.Position.trim()
rt.publisher = rt.Publisher.trim() if typeof rt.Publisher is 'string'
if rt.issn.length
if exists = jct_journal.find 'issn.exact:"' + rt.issn.join('" OR issn.exact:"') + '"'
upd = {}
upd.issn ?= []
for isn in rt.issn
if isn not in exists.issn
upd.issn.push isn
upd.retained = true if exists.retained isnt true
upd.retention = rt
if JSON.stringify(upd) isnt '{}'
for en in exists.issn
upd.issn.push(en) if typeof en is 'string' and en.length and en not in upd.issn
jct_journal.update exists._id, upd
else
rec = retained: true, retention: rt, issn: rt.issn, publisher: rt.publisher, title: rt.journal
jct_journal.insert rec
console.log('Imported ' + counter)
if issn
issn = [issn] if typeof issn is 'string'
res =
route: 'retention' # this is actually only used as a subset of OAB permission self_archiving so far
compliant: 'yes' # if not present then compliant but with author and funder quals - so what are the default funder quals?
qualifications: [{'rights_retention_author_advice': ''}]
issn: issn
log: []
if exists = jct_journal.find 'retained:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
# https://github.com/antleaf/jct-project/issues/406 no qualification needed if retained is true. Position not used.
delete res.qualifications
res.log.push code: 'SA.Compliant'
else
# new log code algo states there should be an SA.Unknown, but given we default to
# compliant at the moment, I don't see a way to achieve that, so set as Compliant for now
res.log.push(code: 'SA.Compliant') if res.log.length is 0
return res
else
return jct_journal.count 'retained:true'
API.service.jct.permission = (issn, institution) ->
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'self_archiving'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: institution
funder: undefined
log: []
try
permsurl = 'https://api.openaccessbutton.org/permissions?meta=false&issn=' + (if typeof issn is 'string' then issn else issn.join(',')) + (if typeof institution is 'string' then '&ror=' + institution else if institution? and Array.isArray(institution) and institution.length then '&ror=' + institution.join(',') else '')
perms = HTTP.call('GET', permsurl, {timeout:3000}).data
if perms.best_permission?
res.compliant = 'no' # set to no until a successful route through is found
pb = perms.best_permission
res.log.push code: 'SA.InOAB'
lc = false
pbls = [] # have to do these now even if can't archive, because needed for new API code algo values
for l in pb.licences ? []
pbls.push l.type
if lc is false and l.type.toLowerCase().replace(/\-/g,'').replace(/ /g,'') in ['ccby','ccbysa','cc0','ccbynd']
lc = l.type # set the first but have to keep going for new API codes algo
if pb.can_archive
if 'postprint' in pb.versions or 'publisher pdf' in pb.versions or 'acceptedVersion' in pb.versions or 'publishedVersion' in pb.versions
# and Embargo is zero
if typeof pb.embargo_months is 'string'
try pb.embargo_months = parseInt pb.embargo_months
if typeof pb.embargo_months isnt 'number' or pb.embargo_months is 0
if lc
res.log.push code: 'SA.OABCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
res.compliant = 'yes'
else if not pb.licences? or pb.licences.length is 0
res.log.push code: 'SA.OABIncomplete', parameters: missing: ['licences']
res.compliant = 'unknown'
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.NotInOAB'
catch
# Fixme: if we don't get an answer then we don't have the info, but this may not be strictly what we want.
res.log.push code: 'SA.OABIncomplete', parameters: missing: ['licences']
res.compliant = 'unknown'
return res
# Calculate self archiving check. It combines, sa_prohibited, OA.works permission and rr checks
API.service.jct.sa = (journal, institution, funder, retention=true, sa_prohibition=true) ->
# Get SA prohibition
if journal and sa_prohibition
res_sa = API.service.jct.sa_prohibited journal, undefined
if res_sa and res_sa.compliant is 'no'
return res_sa
# Get OA.Works permission
rs = API.service.jct.permission journal, institution
# merge the qualifications and logs from SA prohibition into OA.Works permission
rs.qualifications ?= []
if res_sa.qualifications? and res_sa.qualifications.length
for q in (if _.isArray(res_sa.qualifications) then res_sa.qualifications else [res_sa.qualifications])
rs.qualifications.push(q)
rs.log ?= []
if res_sa.log? and res_sa.log.length
for l in (if _.isArray(res_sa.log) then res_sa.log else [res_sa.log])
rs.log.push(l)
# check for retention
if rs
_rtn = {}
for r in (if _.isArray(rs) then rs else [rs])
if r.compliant isnt 'yes' and retention
# only check retention if the funder allows it - and only if there IS a funder
# funder allows if their rights retention date
if journal and funder? and fndr = API.service.jct.funders funder
r.funder = funder
# 1609459200000 = Wed Sep 25 52971
# if fndr.retentionAt? and (fndr.retentionAt is 1609459200000 or fndr.retentionAt >= Date.now())
# if retentionAt is in past - active - https://github.com/antleaf/jct-project/issues/437
if fndr.retentionAt? and fndr.retentionAt < Date.now()
r.log.push code: 'SA.FunderRRActive'
# 26032021, as per https://github.com/antleaf/jct-project/issues/380
# rights retention qualification disabled
#r.qualifications ?= []
#r.qualifications.push 'rights_retention_funder_implementation': funder: funder, date: moment(fndr.retentionAt).format 'YYYY-MM-DD'
# retention is a special case on permissions, done this way so can be easily disabled for testing
_rtn[journal] ?= API.service.jct.retention journal
r.compliant = _rtn[journal].compliant
r.log.push(lg) for lg in _rtn[journal].log
if _rtn[journal].qualifications? and _rtn[journal].qualifications.length
r.qualifications ?= []
r.qualifications.push(ql) for ql in _rtn[journal].qualifications
else
r.log.push code: 'SA.FunderRRNotActive'
return rs
API.service.jct.doaj = (issn) ->
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'fully_oa'
compliant: 'unknown'
qualifications: undefined
issn: issn
log: []
if issn
if ind = jct_journal.find 'indoaj:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.log.push code: 'FullOA.InDOAJ'
db = ind.doaj.bibjson
# Publishing License bibjson.license[].type bibjson.license[].type CC BY, CC BY SA, CC0 CC BY ND
pl = false
lics = []
if db.license? and db.license.length
for bl in db.license
if typeof bl?.type is 'string'
if bl.type.toLowerCase().trim().replace(/ /g,'').replace(/-/g,'') in ['ccby','ccbysa','cc0','ccbynd']
pl = bl.type if pl is false # only the first suitable one
lics.push bl.type # but have to keep going and record them all now for new API code returns values
if not db.license?
res.log.push code: 'FullOA.Unknown', parameters: missing: ['license']
else if pl
res.log.push code: 'FullOA.Compliant', parameters: licence: lics
res.compliant = 'yes'
else
res.log.push code: 'FullOA.NonCompliant', parameters: licence: lics
res.compliant = 'no'
# extra parts used to go here, but have been removed due to algorithm simplification.
else
res.log.push code: 'FullOA.NotInDOAJ'
res.compliant = 'no'
if res.compliant isnt 'yes'
# check if there is an open application for the journal to join DOAJ, if it wasn't already there
if pfd = jct_journal.find 'doajinprogress:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
if true # if an application, has to have applied within 6 months
res.log.push code: 'FullOA.InProgressDOAJ'
res.compliant = 'yes'
res.qualifications = [{doaj_under_review: {}}]
else
res.log.push code: 'FullOA.NotInProgressDOAJ' # there is actually an application, but it is too old
res.compliant = 'no'
else
res.log.push code: 'FullOA.NotInProgressDOAJ' # there is no application, so still may or may not be compliant
return res
# https://www.coalition-s.org/plan-s-funders-implementation/
_funders = []
_last_funders = Date.now()
API.service.jct.funders = (id, refresh) ->
if refresh or _funders.length is 0 or _last_funders > (Date.now() - 604800000) # if older than a week
_last_funders = Date.now()
_funders = []
for r in API.service.jct.table2json 'https://www.coalition-s.org/plan-s-funders-implementation/'
rec =
funder: r['cOAlition S organisation (funder)']
launch: r['Launch date for implementing Plan S-aligned OA policy']
application: r['Application of Plan S principles ']
retention: r['Rights Retention Strategy Implementation']
try rec.funder = rec.funder.replace('&','&')
for k of rec
if rec[k]?
rec[k] = rec[k].trim()
if rec[k].indexOf('<a') isnt -1
rec.url ?= []
rec.url.push rec[k].split('href')[1].split('=')[1].split('"')[1]
rec[k] = (rec[k].split('<')[0] + rec[k].split('>')[1].split('<')[0] + rec[k].split('>').pop()).trim()
else
delete rec[k]
if rec.retention
if rec.retention.indexOf('Note:') isnt -1
rec.notes ?= []
rec.notes.push rec.retention.split('Note:')[1].replace(')','').trim()
rec.retention = rec.retention.split('Note:')[0].replace('(','').trim()
rec.retentionAt = moment('01012021','DDMMYYYY').valueOf() if rec.retention.toLowerCase().indexOf('early adopter') isnt -1
try rec.startAt = moment(rec.launch, 'Do MMMM YYYY').valueOf()
delete rec.startAt if JSON.stringify(rec.startAt) is 'null'
if not rec.startAt? and rec.launch?
rec.notes ?= []
rec.notes.push rec.launch
try rec.id = rec.funder.toLowerCase().replace(/[^a-z0-9]/g,'')
_funders.push(rec) if rec.id?
if id?
for e in _funders
if e.id is id
return e
return _funders
API.service.jct.journals = {}
API.service.jct.journals.import = (refresh) ->
# first see if DOAJ file has updated - if so, do a full journal import
# doaj only updates their journal dump once a week so calling journal import
# won't actually do anything if the dump file name has not changed since last run
# or if a refresh is called
fldr = '/tmp/jct_doaj' + (if API.settings.dev then '_dev' else '') + '/'
if not fs.existsSync fldr
fs.mkdirSync fldr
ret = false
prev = false
current = false
fs.writeFileSync fldr + 'doaj.tar', HTTP.call('GET', 'https://doaj.org/public-data-dump/journal', {npmRequestOptions:{encoding:null}}).content
tar.extract file: fldr + 'doaj.tar', cwd: fldr, sync: true # extracted doaj dump folders end 2020-10-01
console.log 'got DOAJ journals dump'
for f in fs.readdirSync fldr # readdir alphasorts, so if more than one in tmp then last one will be newest
if f.indexOf('doaj_journal_data') isnt -1
if prev
try fs.unlinkSync fldr + prev + '/journal_batch_1.json'
try fs.rmdirSync fldr + prev
prev = current
current = f
if current and (prev or refresh)
console.log 'DOAJ journal dump ' + current + ' is suitable for ingest, getting crossref first'
# get everything from crossref
removed = false
total = 0
counter = 0
batch = []
while total is 0 or counter < total
if batch.length >= 10000 or (removed and batch.length >= 5000)
if not removed
# makes a shorter period of lack of records to query
# there will still be a period of 5 to 10 minutes where not all journals will be present
# but, since imports only occur once a day to every few days depending on settings, and
# responses should be cached at cloudflare anyway, this should not affect anyone as long as
# imports are not often run during UK/US business hours
jct_journal.remove '*'
console.log 'Removing old journal records'
future = new Future()
Meteor.setTimeout (() -> future.return()), 10000
future.wait()
removed = true
console.log 'Importing crossref ' + counter
jct_journal.insert batch
batch = []
try
url = 'https://api.crossref.org/journals?offset=' + counter + '&rows=' + 1000
console.log 'getting from crossref journals ' + url
res = HTTP.call 'GET', url, {headers: {'User-Agent': 'Journal Checker Tool; mailto: <EMAIL>'}}
total = res.data.message['total-results'] if total is 0
for rec in res.data.message.items
if rec.ISSN and rec.ISSN.length and typeof rec.ISSN[0] is 'string'
rec.crossref = true
rec.issn = []
for i in rec.ISSN
rec.issn.push(i) if typeof i is 'string' and i.length and i not in rec.issn
rec.dois = rec.counts?['total-dois']
if rec.breakdowns?['dois-by-issued-year']?
rec.years = []
for yr in rec.breakdowns['dois-by-issued-year']
rec.years.push(yr[0]) if yr.length is 2 and yr[0] not in rec.years
rec.years.sort()
if not rec.years? or not rec.years.length or not rec.dois
rec.discontinued = true
else
thisyear = new Date().getFullYear()
if thisyear not in rec.years and (thisyear-1) not in rec.years and (thisyear-2) not in rec.years and (thisyear-3) not in rec.years
rec.discontinued = true
batch.push rec
counter += 1000
catch err
future = new Future()
Meteor.setTimeout (() -> future.return()), 2000 # wait 2s on probable crossref downtime
future.wait()
if batch.length
jct_journal.insert batch
batch = []
# then load the DOAJ data from the file (crossref takes priority because it has better metadata for spotting discontinuations)
# only about 20% of the ~15k are not already in crossref, so do updates then bulk load the new ones
console.log 'Importing from DOAJ journal dump ' + current
imports = 0
for rec in JSON.parse fs.readFileSync fldr + current + '/journal_batch_1.json'
imports += 1
console.log('DOAJ dump import ' + imports) if imports % 1000 is 0
qr = if typeof rec.bibjson.pissn is 'string' then 'issn.exact:"' + rec.bibjson.pissn + '"' else ''
if typeof rec.bibjson.eissn is 'string'
qr += ' OR ' if qr isnt ''
qr += 'issn.exact:"' + rec.bibjson.eissn + '"'
if exists = jct_journal.find qr
upd = doaj: rec
upd.indoaj = true
upd.discontinued = true if rec.bibjson.discontinued_date or rec.bibjson.is_replaced_by
upd.issn = [] # DOAJ ISSN data overrides crossref because we've seen errors in crossref that are correct in DOAJ such as 1474-9728
upd.issn.push(rec.bibjson.pissn.toUpperCase()) if typeof rec.bibjson.pissn is 'string' and rec.bibjson.pissn.length and rec.bibjson.pissn.toUpperCase() not in upd.issn
upd.issn.push(rec.bibjson.eissn.toUpperCase()) if typeof rec.bibjson.eissn is 'string' and rec.bibjson.eissn.length and rec.bibjson.eissn.toUpperCase() not in upd.issn
jct_journal.update exists._id, upd
else
nr = doaj: rec, indoaj: true
nr.title ?= rec.bibjson.title
nr.publisher ?= rec.bibjson.publisher.name if rec.bibjson.publisher?.name?
nr.discontinued = true if rec.bibjson.discontinued_date or rec.bibjson.is_replaced_by
nr.issn ?= []
nr.issn.push(rec.bibjson.pissn.toUpperCase()) if typeof rec.bibjson.pissn is 'string' and rec.bibjson.pissn.toUpperCase() not in nr.issn
nr.issn.push(rec.bibjson.eissn.toUpperCase()) if typeof rec.bibjson.eissn is 'string' and rec.bibjson.eissn.toUpperCase() not in nr.issn
batch.push nr
if batch.length
jct_journal.insert batch
batch = []
# get new doaj inprogress data if the journals load processed some doaj
# journals (otherwise we're between the week-long period when doaj doesn't update)
# and if doaj did update, load them into the catalogue too - there's only a few hundred so can check them for crossref dups too
r = HTTP.call 'GET', 'https://doaj.org/jct/inprogress?api_key=' + API.settings.service.jct.doaj.apikey
console.log 'Loading DOAJ inprogress records'
inpc = 0
for rec in JSON.parse r.content
inpc += 1
console.log('DOAJ inprogress ' + inpc) if inpc % 100 is 0
issns = []
issns.push(rec.pissn.toUpperCase()) if typeof rec.pissn is 'string' and rec.pissn.length
issns.push(rec.eissn.toUpperCase()) if typeof rec.eissn is 'string' and rec.eissn.length
if exists = jct_journal.find 'issn.exact:"' + issns.join('" OR issn.exact:"') + '"'
if not exists.indoaj # no point adding an application if already in doaj, which should be impossible, but check anyway
upd = doajinprogress: true, doajprogress: rec
nissns = []
for isn in issns
nissns.push(isn) if isn not in nissns and isn not in exists.issn
if nissns.length
upd.issn = _.union exists.issn, nissns
jct_journal.update exists._id, upd
else
console.log 'DOAJ in progress application already in DOAJ for ' + issns.join(', ')
else
nr = doajprogress: rec, issn: issns, doajinprogress: true
batch.push nr
if batch.length
jct_journal.insert batch
batch = []
return jct_journal.count()
else
return 0
# when importing TJ or TA data, add any journals not yet known about
API.service.jct.import = (refresh) ->
res = previously: jct_journal.count(), presently: undefined, started: Date.now()
res.newest = jct_agreement.find '*', true
if refresh or res.newest?.createdAt < Date.now()-86400000
# run all imports necessary for up to date data
console.log 'Starting JCT imports'
console.log 'Starting journals import'
res.journals = API.service.jct.journals.import refresh # takes about 10 mins depending how crossref is feeling
console.log 'JCT journals imported ' + res.journals
console.log 'Starting TJs import'
res.tj = API.service.jct.tj undefined, true
console.log 'JCT import TJs complete'
console.log 'Starting sa prohibited data import'
res.retention = API.service.jct.sa_prohibited undefined, true
console.log 'JCT import sa prohibited data complete'
console.log 'Starting retention data import'
res.retention = API.service.jct.retention undefined, true
console.log 'JCT import retention data complete'
console.log 'Starting funder data import'
res.funders = API.service.jct.funders undefined, true
res.funders = res.funders.length if _.isArray res.funders
console.log 'JCT import funders complete'
console.log 'Starting TAs data import'
res.ta = API.service.jct.ta.import false # this is the slowest, takes about twenty minutes
console.log 'JCT import TAs complete'
# check the mappings on jct_journal, jct_agreement, any others that get used and changed during import
# include a warning in the email if they seem far out of sync
# and include the previously and presently count, they should not be too different
res.presently = jct_journal.count()
res.ended = Date.now()
res.took = res.ended - res.started
res.minutes = Math.ceil res.took/60000
if res.mapped = JSON.stringify(jct_journal.mapping()).indexOf('dynamic_templates') isnt -1
res.mapped = JSON.stringify(jct_agreement.mapping()).indexOf('dynamic_templates') isnt -1
API.service.jct.mail
subject: 'JCT import complete'
text: JSON.stringify res, '', 2
return res
_jct_import = () ->
try API.service.jct.funders undefined, true # get the funders at startup
if API.settings.service?.jct?.import isnt false # so defaults to run if not set to false in settings
console.log 'Setting up a daily import check which will run an import if it is a Saturday'
# if later updates are made to run this on a cluster again, make sure that only one server runs this (e.g. use the import setting above where necessary)
Meteor.setInterval () ->
today = new Date()
if today.getDay() is 6 # if today is a Saturday run an import
console.log 'Starting Saturday import'
API.service.jct.import()
, 86400000
Meteor.setTimeout _jct_import, 5000
API.service.jct.unknown = (res, funder, journal, institution, send) ->
if res?
# it may not be worth saving these seperately if compliance result caching is on, but for now will keep them
r = _.clone res
r._id = (funder ? '') + '_' + (journal ? '') + '_' + (institution ? '') # overwrite dups
r.counter = 1
if ls = jct_unknown.get r._id
r.lastsend = ls.lastsend
r.counter += ls.counter ? 0
try jct_unknown.insert r
cnt = jct_unknown.count()
if send
try
cnt = 0
start = false
end = false
if typeof send isnt 'boolean'
start = send
q = 'createdAt:>' + send
else if lf = jct_unknown.find 'lastsend:*', {sort: {lastsend: {order: 'desc'}}}
start = lf.lastsend
q = 'createdAt:>' + lf.lastsend
else
q = '*'
last = false
for un in jct_unknown.fetch q, {newest: false}
start = un.createdAt if start is false
end = un.createdAt
last = un
cnt += 1
if last isnt false
jct_unknown.update last._id, lastsend: Date.now()
durl = 'https://' + (if API.settings.dev then 'api.jct.cottagelabs.com' else 'api.journalcheckertool.org') + '/unknown/' + start + '/' + end + '.csv'
API.service.jct.feedback name: 'unknowns', email: '<EMAIL>', subject: 'JCT system reporting unknowns', feedback: durl
return cnt
Meteor.setTimeout (() -> API.service.jct.unknown(undefined, undefined, undefined, undefined, true)), 86400000 # send once a day
API.service.jct.feedback = (params={}) ->
if typeof params.name is 'string' and typeof params.email is 'string' and typeof params.feedback is 'string' and (not params.context? or typeof params.context is 'object')
API.service.jct.mail
from: if params.email.indexOf('@') isnt -1 and params.email.indexOf('.') isnt -1 then params.email else '<EMAIL>'
subject: params.subject ? params.feedback.substring(0,100) + if params.feedback.length > 100 then '...' else ''
text: (if API.settings.dev then '(dev)\n\n' else '') + params.feedback + '\n\n' + (if params.subject then '' else JSON.stringify params, '', 2)
return true
else
return false
API.service.jct.csv = (rows) ->
if Array.isArray(rows) and rows.length
header = ''
fields = []
for r in rows
for k of r
if k not in fields
fields.push k
header += ',' if header isnt ''
header += '"' + k.replace(/\"/g, '') + '"'
res = ''
for rr in rows
res += '\n' if res isnt ''
ln = ''
for f in fields
ln += ',' if ln isnt ''
ln += '"' + JSON.stringify(rr[f] ? '').replace(/\"/g, '') + '"'
res += ln
return header + '\n' + res
else
return ''
API.service.jct.csv2json = Async.wrap (content, callback) ->
content = HTTP.call('GET', content).content if content.indexOf('http') is 0
csvtojson().fromString(content).then (result) -> return callback null, result
API.service.jct.table2json = (content) ->
content = HTTP.call('GET', content).content if content.indexOf('http') is 0 # TODO need to try this without puppeteer
if content.indexOf('<table') isnt -1
content = '<table' + content.split('<table')[1]
else if content.indexOf('<TABLE') isnt -1
content = '<TABLE' + content.split('<TABLE')[1]
if content.indexOf('</table') isnt -1
content = content.split('</table')[0] + '</table>'
else if content.indexOf('</TABLE') isnt -1
content = content.split('</TABLE')[1] + '</TABLE>'
content = content.replace(/\r?\n|\r/g,'')
ths = content.match(/<th.*?<\/th/gi)
headers = []
results = []
if ths?
for h in ths
str = h.replace(/<th.*?>/i,'').replace(/<\/th.*?/i,'').replace(/<.*?>/gi,'').replace(/\s\s+/g,' ').trim()
str = 'UNKNOWN' if str.replace(/ /g,'').length is 0
headers.push str
for r in content.split('<tr')
if r.toLowerCase().indexOf('<th') is -1
result = {}
row = r.replace(/.*?>/i,'').replace(/<\/tr.*?/i,'')
vals = row.match(/<td.*?<\/td/gi)
keycounter = 0
for d of vals
val = vals[d].replace(/<.*?>/gi,'').replace('</td','')
if headers.length > keycounter
result[headers[keycounter]] = val
keycounter += 1
if vals[d].toLowerCase().indexOf('colspan') isnt -1
try
keycounter += parseInt(vals[d].toLowerCase().split('colspan')[1].split('>')[0].replace(/[^0-9]/,''))-1
delete result.UNKNOWN if result.UNKNOWN?
if not _.isEmpty result
results.push result
return results
API.service.jct.mail = (opts) ->
ms = API.settings.mail ? {} # need domain and apikey
mailer = mailgun domain: ms.domain, apiKey: ms.apikey
opts.from ?= '<EMAIL>' # ms.from ?
opts.to ?= '<EMAIL>.<EMAIL>' # ms.to ?
opts.to = opts.to.join(',') if typeof opts.to is 'object'
#try HTTP.call 'POST', 'https://api.mailgun.net/v3/' + ms.domain + '/messages', {params:opts, auth:'api:'+ms.apikey}
# opts.attachment can be a string which is assumed to be a filename to attach, or a Buffer
# https://www.npmjs.com/package/mailgun-js
if typeof opts.attachment is 'object'
if opts.filename
fn = opts.filename
delete opts.filename
else
fn = 'data.csv'
att = API.service.jct.csv opts.attachment
opts.attachment = new mailer.Attachment filename: fn, contentType: 'text/csv', data: Buffer.from att, 'utf8'
console.log 'Sending mail to ' + opts.to
mailer.messages().send opts
return true
API.service.jct.test = (params={}) ->
# A series of queries based on journals, with existing knowledge of their policies.
# To test TJ and Rights retention elements of the algorithm some made up information is included,
# this is marked with [1]. Not all queries test all the compliance routes (in particular rights retention).
# Expected JCT Outcome, is what the outcome should be based on reading the information within journal, institution and funder data.
# Actual JCT Outcome is what was obtained by walking through the algorithm under the assumption that
# the publicly available information is within the JCT data sources.
params.refresh = true
params.sa_prohibition = true if not params.sa_prohibition?
params.test = params.tests if params.tests?
params.test = params.test.toString() if typeof params.test is 'number'
if typeof params.test is 'string'
ns = 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'
for n in ['10','1','2','3','4','5','6','7','8','9']
params.test = params.test.replace n, ns[n]
params.test = params.test.split ','
res = pass: true, fails: [], results: []
queries =
one: # Query 1
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc TA)
institution: 'Cardiff University' # (subscriber to Jisc TA) 03kk7td41
funder: 'Well<NAME>'
'expected outcome': 'Researcher can publish via gold open access route or via TA'
qualification: 'Researcher must be corresponding author to be eligible for TA'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('corresponding_authors') isnt -1
two: # Query 2
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc TA)
institution: 'Emory University' # (no TA or Wiley agreement) 03czfpz43
funder: 'Well<NAME>'
'expected outcome': 'Researcher can publish via gold open access route'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).split('"fully_oa"')[1].split('"issn"')[0].indexOf('"yes"') isnt -1
three: # Query 3
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc & VSNU TAs)
institution: ['Emory University', 'Cardiff University', 'Utrecht University'] # 03czfpz43,03kk7td41,04pp8hn57 (Emory has no TA or Wiley account, Cardiff is subscriber to Jisc TA, Utrecht is subscriber to VSNU TA which expires prior to 1 Jan 2021)
funder: ['Wellcome', 'NWO']
'expected outcome': 'For Cardiff: Researcher can publish via gold open access route or via TA (Qualification: Researcher must be corresponding author to be eligible for TA). For Emory and Utrecht: Researcher can publish via gold open access route'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
if rs.indexOf('TA.Exists') isnt -1
return rs.split('"fully_oa"')[1].split('"issn"')[0].indexOf('"yes"') isnt -1
return false
four: # Query 4
journal: 'Proceedings of the Royal Society B' # (subscription journal published by Royal Society, AAM can be shared CC BY no embargo, UK Jisc Read Publish Deal)
institution: 'Rothamsted Research' # (subscribe to Read Publish Deal) 0347fy350
funder: 'European Commission' # EC
'expected outcome': 'Researcher can self-archive or publish via Read Publish Deal'
qualification: 'Research must be corresponding author to be eligible for Read Publish Deal'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
return rs.indexOf('corresponding_authors') isnt -1 and rs.indexOf('TA.Exists') isnt -1
return false
five: # Query 5
journal: 'Proceedings of the Royal Society B' # (subscription journal published by Royal Society, AAM can be shared CC BY no embargo, UK Jisc Read Publish Deal)
institution: 'University of Cape Town' # 03p74gp79
funder: '<NAME> & <NAME>' # Bill & Melinda Gates Foundation billmelindagatesfoundation
'expected outcome': 'Researcher can self-archive'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
for rs in r.results
if rs.route is 'self_archiving' and rs.compliant is 'yes'
return true
return false
six: # Query 6
journal: '1477-9129' # Development (published by Company of Biologists, not the other one, hence done by ISSN) # (Transformative Journal, AAM 12 month embargo) 0951-1991
institution: 'University of Cape Town' # 03p74gp79
funder: 'SAMRC'
'expected outcome': 'Researcher can publish via payment of APC (Transformative Journal)'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('TJ.Exists') isnt -1
seven: # Query 7
journal: 'Brill Research Perspectives in Law and Religion' # (Subscription Journal, VSNU Read Publish Agreement, AAM can be shared CC BY-NC no embargo)
institution: 'University of Amsterdam' # 04dkp9463
funder: 'NWO'
'expected outcome': 'Research can publish via the Transformative Agreement'
qualification: 'Researcher must be corresponding author to take advantage of the TA.'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
return rs.indexOf('corresponding_authors') isnt -1 and rs.indexOf('TA.Exists') isnt -1
return false
eight: # Query 8
journal: 'Migration and Society' # (Subscribe to Open, CC BY, CC BY-ND and CC BY-NC-ND licences available but currently only CC BY-NC-ND in DOAJ)
institution: 'University of Vienna' # 03prydq77
funder: 'FWF'
'expected outcome': 'No routes to compliance'
'actual outcome': 'As expected' # this is not possible because everything is currently compliant due to rights retention
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
nine: # Query 9
journal: 'Folia Historica Cracoviensia' # (fully oa, in DOAJ, CC BY-NC-ND)
institution: ['University of Warsaw', 'University of Ljubljana'] # 039bjqg32,05njb9z20
funder: ['NCN']
'expected outcome': 'No route to compliance.' # this is impossible due to rights retention
'actual outcome': 'As expected'
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
ten: # Query 10
journal: 'Journal of Clinical Investigation' # (subscription for front end material, research articles: publication fee, no embargo, CC BY licence where required by funders, not in DOAJ, Option 5 Rights Retention Policy [1])
institution: 'University of Vienna' # 03prydq77
funder: 'FWF'
'expected outcome': 'Researcher can publish via standard publication route'
'actual outcome': 'Researcher cannot publish in this journal and comply with funders OA policy' # as there is no rights retention this is impossible so it does succeed
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
for q of queries
if not params.test? or q in params.test
qr = queries[q]
ans = query: q
ans.pass = false
ans.inputs = queries[q]
ans.discovered = issn: [], funder: [], ror: []
for k in ['journal','institution','funder']
for j in (if typeof qr[k] is 'string' then [qr[k]] else qr[k])
try
ans.discovered[if k is 'journal' then 'issn' else if k is 'institution' then 'ror' else 'funder'].push API.service.jct.suggest[k](j).data[0].id
catch
console.log k, j
ans.result = API.service.jct.calculate {funder: ans.discovered.funder, issn: ans.discovered.issn, ror: ans.discovered.ror}, params.refresh, params.checks, params.retention, params.sa_prohibition
ans.pass = queries[q].test ans.result
if ans.pass isnt true
res.pass = false
res.fails.push q
res.results.push ans
delete res.fails if not res.fails.length
return res
| true | import moment from 'moment'
import mailgun from 'mailgun-js'
import fs from 'fs'
import tar from 'tar'
import Future from 'fibers/future'
import { Random } from 'meteor/random'
import unidecode from 'unidecode'
import csvtojson from 'csvtojson'
import stream from 'stream'
'''
The JCT API was a plugin for the noddy API stack, however it has since been
separated out to a standalone app. It has the smallest amount of noddy code that
it required, to keep it simple for future maintenance as a separate project.
It is possible that the old noddy codebase may have useful parts for future
development though, so consider having a look at it when new requirements come up.
This API defines the routes needed to support the JCT UIs, and the admin feed-ins
from sheets, and collates source data from DOAJ and OAB systems, as well as other
services run within the leviathan noddy API stack (such as the academic search
capabilities it already had).
jct project API spec doc:
https://github.com/antleaf/jct-project/blob/master/api/spec.md
algorithm spec docs:
https://docs.google.com/document/d/1-jdDMg7uxJAJd0r1P7MbavjDi1r261clTXAv_CFMwVE/edit?ts=5efb583f
https://docs.google.com/spreadsheets/d/11tR_vXJ7AnS_3m1_OSR3Guuyw7jgwPgh3ETgsIX0ltU/edit#gid=105475641
# Expected result examples: https://docs.google.com/document/d/1AZX_m8EAlnqnGWUYDjKmUsaIxnUh3EOuut9kZKO3d78/edit
given a journal, funder(s), and institution(s), tell if they are compliant or not
journal meets general JCT plan S compliance by meeting certain criteria
or journal can be applying to be in DOAJ if not in there yet
or journal can be in transformative journals list (which will be provided by plan S). If it IS in the list, it IS compliant
institutions could be any, and need to be tied to transformative agreements (which could be with larger umbrella orgs)
or an institutional affiliation to a transformative agreement could make a journal suitable
funders will be a list given to us by JCT detailing their particular requirements - in future this may alter whether or not the journal is acceptable to the funder
'''
# define the necessary collections - institution is defined global so a separate script was able to initialise it
# where devislive is true, the live indexes are actually reading from the dev ones. This is handy for
# datasets that are the same, such as institutions, journals, and transformative agreements
# but compliance and unknown should be unique as they could have different results on dev or live depending on code changes
# to do alterations to code on dev that may change how institutions, journals, or agreements are constructed, comment out the devislive setting
# NOTE: doing this would mean live would not have recent data to read from, so after this code change is deployed to live
# it should be followed by manually triggering a full import on live
# (for convenience the settings have initially been set up to only run import on dev as well, to make the most
# of the dev machine and minimise any potential memory or CPU intense work on the live machine - see the settings.json file for this config)
@jct_institution = new API.collection {index:"jct", type:"institution", devislive: true}
jct_journal = new API.collection {index:"jct", type:"journal"}
jct_agreement = new API.collection {index:"jct", type:"agreement"}
jct_compliance = new API.collection {index:"jct", type:"compliance"}
jct_unknown = new API.collection {index:"jct", type:"unknown"}
# define endpoints that the JCT requires (to be served at a dedicated domain)
API.add 'service/jct', get: () -> return 'cOAlition S Journal Checker Tool. Service provided by Cottage Labs LLP. Contact PI:EMAIL:<EMAIL>END_PI'
API.add 'service/jct/calculate', get: () -> return API.service.jct.calculate this.queryParams
API.add 'service/jct/suggest/:which', get: () -> return API.service.jct.suggest[this.urlParams.which] undefined, this.queryParams.from, this.queryParams.size
API.add 'service/jct/suggest/:which/:ac', get: () -> return API.service.jct.suggest[this.urlParams.which] this.urlParams.ac, this.queryParams.from, this.queryParams.size
API.add 'service/jct/ta',
get: () ->
if this.queryParams.issn or this.queryParams.journal
res = API.service.jct.ta this.queryParams.issn ? this.queryParams.journal, this.queryParams.institution ? this.queryParams.ror
ret = []
for r in (if not _.isArray(res) then [res] else res)
if r.compliant is 'yes'
ret.push issn: r.issn, ror: r.ror, id: log[0].result.split(' - ')[1]
return if ret.length then ret else 404
else
return jct_agreement.search this.queryParams
API.add 'service/jct/ta/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.ta.import this.queryParams.mail), 1
return true
API.add 'service/jct/sa_prohibited',
get: () ->
return API.service.jct.sa_prohibited this.queryParams.issn
API.add 'service/jct/sa_prohibited/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.sa_prohibited undefined, true), 1
return true
API.add 'service/jct/retention',
get: () ->
return API.service.jct.retention this.queryParams.issn
API.add 'service/jct/retention/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.retention undefined, true), 1
return true
API.add 'service/jct/tj', get: () -> return jct_journal.search this.queryParams, {restrict: [{exists: {field: 'tj'}}]}
API.add 'service/jct/tj/:issn',
get: () ->
res = API.service.jct.tj this.urlParams.issn
return if res?.compliant isnt 'yes' then 404 else issn: this.urlParams.issn, transformative_journal: true
API.add 'service/jct/tj/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.tj undefined, true), 1
return true
API.add 'service/jct/funder', get: () -> return API.service.jct.funders undefined, this.queryParams.refresh
API.add 'service/jct/funder/:iid', get: () -> return API.service.jct.funders this.urlParams.iid
API.add 'service/jct/feedback',
get: () -> return API.service.jct.feedback this.queryParams
post: () -> return API.service.jct.feedback this.bodyParams
API.add 'service/jct/import',
get: () ->
Meteor.setTimeout (() => API.service.jct.import this.queryParams.refresh), 1
return true
API.add 'service/jct/unknown', get: () -> return jct_unknown.search this.queryParams
API.add 'service/jct/unknown/:start/:end',
get: () ->
csv = false
if typeof this.urlParams.start is 'string' and this.urlParams.start.indexOf('.csv') isnt -1
this.urlParams.start = this.urlParams.start.replace('.csv','')
csv = true
else if typeof this.urlParams.end is 'string' and this.urlParams.end.indexOf('.csv') isnt -1
this.urlParams.end = this.urlParams.end.replace('.csv','')
csv = true
res = []
if typeof this.urlParams.start in ['number','string'] or typeof this.urlParams.end in ['number','string']
q = if typeof this.urlParams.start in ['number','string'] then 'createdAt:>=' + this.urlParams.start else ''
if typeof this.urlParams.end in ['number','string']
q += ' AND ' if q isnt ''
q += 'createdAt:<' + this.urlParams.end
else
q = '*'
for un in unks = jct_unknown.fetch q
params = un._id.split '_'
res.push route: un.route, issn: params[1], funder: params[0], ror: params[2], log: un.log
if csv
fn = 'JCT_export_' + this.urlParams.start + (if this.urlParams.end then '_' + this.urlParams.end else '') + ".csv"
this.response.writeHead(200, {'Content-disposition': "attachment; filename=" + fn, 'Content-type': 'text/csv; charset=UTF-8', 'Content-Encoding': 'UTF-8'})
this.response.end API.service.jct.csv res
else
return res
API.add 'service/jct/journal', get: () -> return jct_journal.search this.queryParams
API.add 'service/jct/institution', get: () -> return jct_institution.search this.queryParams
API.add 'service/jct/compliance', get: () -> return jct_compliance.search this.queryParams
# the results that have already been calculated. These used to get used to re-serve as a
# faster cached result, but uncertainties over agreement on how long to cache stuff made
# this unnecessarily complex, so these are only stored as a history now.
API.add 'service/jct/test', get: () -> return API.service.jct.test this.queryParams
_jct_clean = (str) ->
pure = /[!-/:-@[-`{-~¡-©«-¬®-±´¶-¸»¿×÷˂-˅˒-˟˥-˫˭˯-˿͵;΄-΅·϶҂՚-՟։-֊־׀׃׆׳-״؆-؏؛؞-؟٪-٭۔۩۽-۾܀-܍߶-߹।-॥॰৲-৳৺૱୰௳-௺౿ೱ-ೲ൹෴฿๏๚-๛༁-༗༚-༟༴༶༸༺-༽྅྾-࿅࿇-࿌࿎-࿔၊-၏႞-႟჻፠-፨᎐-᎙᙭-᙮᚛-᚜᛫-᛭᜵-᜶។-៖៘-៛᠀-᠊᥀᥄-᥅᧞-᧿᨞-᨟᭚-᭪᭴-᭼᰻-᰿᱾-᱿᾽᾿-῁῍-῏῝-῟῭-`´-῾\u2000-\u206e⁺-⁾₊-₎₠-₵℀-℁℃-℆℈-℉℔№-℘℞-℣℥℧℩℮℺-℻⅀-⅄⅊-⅍⅏←-⏧␀-␦⑀-⑊⒜-ⓩ─-⚝⚠-⚼⛀-⛃✁-✄✆-✉✌-✧✩-❋❍❏-❒❖❘-❞❡-❵➔➘-➯➱-➾⟀-⟊⟌⟐-⭌⭐-⭔⳥-⳪⳹-⳼⳾-⳿⸀-\u2e7e⺀-⺙⺛-⻳⼀-⿕⿰-⿻\u3000-〿゛-゜゠・㆐-㆑㆖-㆟㇀-㇣㈀-㈞㈪-㉃㉐㉠-㉿㊊-㊰㋀-㋾㌀-㏿䷀-䷿꒐-꓆꘍-꘏꙳꙾꜀-꜖꜠-꜡꞉-꞊꠨-꠫꡴-꡷꣎-꣏꤮-꤯꥟꩜-꩟﬩﴾-﴿﷼-﷽︐-︙︰-﹒﹔-﹦﹨-﹫!-/:-@[-`{-・¢-₩│-○-�]|\ud800[\udd00-\udd02\udd37-\udd3f\udd79-\udd89\udd90-\udd9b\uddd0-\uddfc\udf9f\udfd0]|\ud802[\udd1f\udd3f\ude50-\ude58]|\ud809[\udc00-\udc7e]|\ud834[\udc00-\udcf5\udd00-\udd26\udd29-\udd64\udd6a-\udd6c\udd83-\udd84\udd8c-\udda9\uddae-\udddd\ude00-\ude41\ude45\udf00-\udf56]|\ud835[\udec1\udedb\udefb\udf15\udf35\udf4f\udf6f\udf89\udfa9\udfc3]|\ud83c[\udc00-\udc2b\udc30-\udc93]/g;
str = str.replace(pure, ' ')
return str.toLowerCase().replace(/ +/g,' ').trim()
# and now define the methods
API.service ?= {}
API.service.jct = {}
API.service.jct.suggest = {}
API.service.jct.suggest.funder = (str, from, size) ->
res = []
for f in API.service.jct.funders()
matches = true
if str isnt f.id
for s in (if str then str.toLowerCase().split(' ') else [])
if s not in ['of','the','and'] and f.funder.toLowerCase().indexOf(s) is -1
matches = false
res.push({title: f.funder, id: f.id}) if matches
return total: res.length, data: res
API.service.jct.suggest.institution = (str, from, size) ->
# TODO add an import method from wikidata or ROR, and have the usual import routine check for changes on a suitable schedule
if typeof str is 'string' and str.length is 9 and rec = jct_institution.get str
delete rec[x] for x in ['createdAt', 'created_date', '_id', 'description', 'values', 'wid']
return total: 1, data: [rec]
else
q = {query: {filtered: {query: {}, filter: {bool: {should: []}}}}, size: size}
q.from = from if from?
if str
str = _jct_clean(str).replace(/the /gi,'')
qry = (if str.indexOf(' ') is -1 then 'id:' + str + '* OR ' else '') + '(title:' + str.replace(/ /g,' AND title:') + '*) OR (alternate:' + str.replace(/ /g,' AND alternate:') + '*) OR (description:' + str.replace(/ /g,' AND description:') + '*) OR (values:' + str.replace(/ /g,' AND values:') + '*)'
q.query.filtered.query.query_string = {query: qry}
else
q.query.filtered.query.match_all = {}
res = jct_institution.search q
unis = []
starts = []
extra = []
for rec in res?.hits?.hits ? []
delete rec._source[x] for x in ['createdAt', 'created_date', '_id', 'description', 'values', 'wid']
if str
if rec._source.title.toLowerCase().indexOf('universit') isnt -1
unis.push rec._source
else if _jct_clean(rec._source.title).replace('the ','').replace('university ','').replace('of ','').startsWith(str.replace('the ','').replace('university ','').replace('of ',''))
starts.push rec._source
else if str.indexOf(' ') is -1 or unidecode(str) isnt str # allow matches on more random characters that may be matching elsewhere in the data but not in the actual title
extra.push rec._source
else
extra.push rec._source
ret = total: res?.hits?.total ? 0, data: _.union unis.sort((a, b) -> return a.title.length - b.title.length), starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
if ret.data.length < 10
seen = []
seen.push(sr.id) for sr in ret.data
q = {query: {filtered: {query: {}, filter: {bool: {should: []}}}}, size: size}
q.from = from if from?
if str
str = _jct_clean(str).replace(/the /gi,'')
q.query.filtered.query.query_string = {query: (if str.indexOf(' ') is -1 then 'ror.exact:"' + str + '" OR ' else '') + '(institution:' + str.replace(/ /g,' AND institution:') + '*)'}
else
q.query.filtered.query.query_string = {query: 'ror:*'}
res = jct_agreement.search q
if res?.hits?.total
ret.total += res.hits.total
unis = []
starts = []
extra = []
for rec in res?.hits?.hits ? []
if rec._source.ror not in seen
rc = {title: rec._source.institution, id: rec._source.ror, ta: true}
if str
if rc.title.toLowerCase().indexOf('universit') isnt -1
unis.push rc
else if _jct_clean(rc.title).replace('the ','').replace('university ','').replace('of ','').startsWith(str.replace('the ','').replace('university ','').replace('of ',''))
starts.push rc
else if rec._source.ror.indexOf(str) is 0 and unidecode(str) isnt str # allow matches on more random characters that may be matching elsewhere in the data but not in the actual title
extra.push rc
else
extra.push rc
ret.data = _.union ret.data, _.union unis.sort((a, b) -> return a.title.length - b.title.length), starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
return ret
API.service.jct.suggest.journal = (str, from, size) ->
q = {query: {filtered: {query: {query_string: {query: 'issn:* AND NOT discontinued:true AND NOT dois:0'}}, filter: {bool: {should: []}}}}, size: size, _source: {includes: ['title','issn','publisher','src']}}
q.from = from if from?
if str and str.replace(/\-/g,'').length
if str.indexOf(' ') is -1
if str.indexOf('-') isnt -1 and str.length is 9
q.query.filtered.query.query_string.query = 'issn.exact:"' + str + '" AND NOT discontinued:true AND NOT dois:0'
else
q.query.filtered.query.query_string.query = 'NOT discontinued:true AND NOT dois:0 AND ('
if str.indexOf('-') isnt -1
q.query.filtered.query.query_string.query += '(issn:"' + str.replace('-','" AND issn:') + '*)'
else
q.query.filtered.query.query_string.query += 'issn:' + str + '*'
q.query.filtered.query.query_string.query += ' OR title:"' + str + '" OR title:' + str + '* OR title:' + str + '~)'
else
str = _jct_clean str
q.query.filtered.query.query_string.query = 'issn:* AND NOT discontinued:true AND NOT dois:0 AND (title:"' + str + '" OR '
q.query.filtered.query.query_string.query += (if str.indexOf(' ') is -1 then 'title:' + str + '*' else '(title:' + str.replace(/ /g,'~ AND title:') + '*)') + ')'
res = jct_journal.search q
starts = []
extra = []
for rec in res?.hits?.hits ? []
if not str or JSON.stringify(rec._source.issn).indexOf(str) isnt -1 or _jct_clean(rec._source.title).startsWith(str)
starts.push rec._source
else
extra.push rec._source
rec._source.id = rec._source.issn[0]
return total: res?.hits?.total ? 0, data: _.union starts.sort((a, b) -> return a.title.length - b.title.length), extra.sort((a, b) -> return a.title.length - b.title.length)
API.service.jct.calculate = (params={}, refresh, checks=['sa', 'doaj', 'ta', 'tj'], retention=true, sa_prohibition=true) ->
# given funder(s), journal(s), institution(s), find out if compliant or not
# note could be given lists of each - if so, calculate all and return a list
if params.issn
params.journal = params.issn
delete params.issn
if params.ror
params.institution = params.ror
delete params.ror
refresh ?= params.refresh if params.refresh?
if params.checks?
checks = if typeof params.checks is 'string' then params.checks.split(',') else params.checks
retention = params.retention if params.retention?
res =
request:
started: Date.now()
ended: undefined
took: undefined
journal: []
funder: []
institution: []
checks: checks
retention: retention
compliant: false
cache: true
results: []
return res if not params.journal
issnsets = {}
for p in ['funder','journal','institution']
params[p] = params[p].toString() if typeof params[p] is 'number'
params[p] = params[p].split(',') if typeof params[p] is 'string'
params[p] ?= []
for v in params[p]
if sg = API.service.jct.suggest[p] v
if sg.data and sg.data.length
ad = sg.data[0]
res.request[p].push {id: ad.id, title: ad.title, issn: ad.issn, publisher: ad.publisher}
issnsets[v] ?= ad.issn if p is 'journal' and _.isArray(ad.issn) and ad.issn.length
res.request[p].push({id: v}) if not sg?.data
rq = Random.id() # random ID to store with the cached results, to measure number of unique requests that aggregate multiple sets of entities
checked = 0
_check = (funder, journal, institution) ->
hascompliant = false
allcached = true
_results = []
cr = sa: ('sa' in checks), doaj: ('doaj' in checks), ta: ('ta' in checks), tj: ('tj' in checks)
_ck = (which) ->
allcached = false
Meteor.setTimeout () ->
if which is 'sa'
rs = API.service.jct.sa (issnsets[journal] ? journal), (if institution? then institution else undefined), funder, retention, sa_prohibition
else
rs = API.service.jct[which] (issnsets[journal] ? journal), (if institution? and which is 'ta' then institution else undefined)
if rs
for r in (if _.isArray(rs) then rs else [rs])
hascompliant = true if r.compliant is 'yes'
if r.compliant is 'unknown'
API.service.jct.unknown r, funder, journal, institution
_results.push r
cr[which] = Date.now()
, 1
for c in checks
_ck(c) if cr[c]
while cr.sa is true or cr.doaj is true or cr.ta is true or cr.tj is true
future = new Future()
Meteor.setTimeout (() -> future.return()), 100
future.wait()
res.compliant = true if hascompliant
delete res.cache if not allcached
# store a new set of results every time without removing old ones, to keep track of incoming request amounts
jct_compliance.insert journal: journal, funder: funder, institution: institution, retention: retention, rq: rq, checks: checks, compliant: hascompliant, cache: allcached, results: _results
res.results.push(rs) for rs in _results
checked += 1
combos = [] # make a list of all possible valid combos of params
for j in (if params.journal and params.journal.length then params.journal else [undefined])
cm = journal: j
for f in (if params.funder and params.funder.length then params.funder else [undefined]) # does funder have any effect? - probably not right now, so the check will treat them the same
cm = _.clone cm
cm.funder = f
for i in (if params.institution and params.institution.length then params.institution else [undefined])
cm = _.clone cm
cm.institution = i
combos.push cm
console.log 'Calculating for:'
console.log combos
# start an async check for every combo
_prl = (combo) -> Meteor.setTimeout (() -> _check combo.funder, combo.journal, combo.institution), 1
for c in combos
if c.institution isnt undefined or c.funder isnt undefined or c.journal isnt undefined
_prl c
else
checked += 1
while checked isnt combos.length
future = new Future()
Meteor.setTimeout (() -> future.return()), 100
future.wait()
res.request.ended = Date.now()
res.request.took = res.request.ended - res.request.started
return res
# For a TA to be in force, an agreement record for the the ISSN and also one for
# the ROR mus be found, and the current date must be after those record start dates
# and before those record end dates. A journal and institution could be in more than
# one TA at a time - return all cases where both journal and institution are in the
# same TA
API.service.jct.ta = (issn, ror) ->
issn = issn.split(',') if typeof issn is 'string'
tas = []
qr = ''
if issn
qr += 'issn.exact:"' + issn.join('" OR issn.exact:"') + '"'
if ror
qr += ' OR ' if qr isnt ''
if typeof ror is 'string' and ror.indexOf(',') isnt -1
ror = ror.split(',')
qr += 'ror.exact:"' + ror.join('" OR ror.exact:"') + '"'
else
qr += 'ror.exact:"' + ror + '"'
res =
route: 'ta'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: ror
log: []
# what if start or end dates do not exist, but at least one of them does? Must they all exist?
journals = {}
institutions = {}
count = 0
jct_agreement.each qr, (rec) -> # how many could this be? If many, will it be fast enough?
count += 1
if rec.issn?
journals[rec.rid] = rec
else if rec.ror?
institutions[rec.rid] = rec
agreements = {}
for j of journals
if institutions[j]?
allow = true # avoid possibly duplicate TAs
agreements[j] ?= {}
for isn in (if typeof journals[j].issn is 'string' then [journals[j].issn] else journals[j].issn)
agreements[j][isn] ?= []
if institutions[j].ror not in agreements[j][isn]
agreements[j][isn].push institutions[j].ror
else
allow = false
if allow
rs = _.clone res
rs.compliant = 'yes'
rs.qualifications = if journals[j].corresponding_authors or institutions[j].corresponding_authors then [{corresponding_authors: {}}] else []
rs.log.push code: 'TA.Exists'
tas.push rs
if tas.length is 0
res.compliant = 'no'
res.log.push code: 'TA.NoTA'
tas.push res
return if tas.length is 1 then tas[0] else tas
# NOTE there are more log codes to use in the new API log codes spec,
# https://github.com/CottageLabs/jct/blob/feature/api_codes/markdown/apidocs.md#per-route-response-data
# TA.NotAcive - TA.Active - TA.Unknown - TA.NonCompliant - TA.Compliant
# but it is not known how these could be used here, as all TAs in the system appear to be active - anything with an end date in the past is not imported
# and there is no way to identify plan S compliant / not compliant unknown from the current algorithm spec
# import transformative agreements data from sheets
# https://github.com/antleaf/jct-project/blob/master/ta/public_data.md
# only validated agreements will be exposed at the following sheet
# https://docs.google.com/spreadsheets/d/e/2PACX-1vStezELi7qnKcyE8OiO2OYx2kqQDOnNsDX1JfAsK487n2uB_Dve5iDTwhUFfJ7eFPDhEjkfhXhqVTGw/pub?gid=1130349201&single=true&output=csv
# get the "Data URL" - if it's a valid URL, and the End Date is after current date, get the csv from it
API.service.jct.ta.import = (mail=true) ->
bads = []
records = []
res = sheets: 0, ready: 0, processed:0, records: 0, failed: []
console.log 'Starting ta import'
batch = []
bissns = [] # track ones going into the batch
for ov in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vStezELi7qnKcyE8OiO2OYx2kqQDOnNsDX1JfAsK487n2uB_Dve5iDTwhUFfJ7eFPDhEjkfhXhqVTGw/pub?gid=1130349201&single=true&output=csv'
res.sheets += 1
if typeof ov?['Data URL'] is 'string' and ov['Data URL'].trim().indexOf('http') is 0 and ov?['End Date']? and moment(ov['End Date'].trim(), 'YYYY-MM-DD').valueOf() > Date.now()
res.ready += 1
src = ov['Data URL'].trim()
console.log res
future = new Future()
Meteor.setTimeout (() -> future.return()), 1000 # wait 1s so don't instantly send 200 requests to google
future.wait()
_src = (src, ov) ->
Meteor.setTimeout () ->
console.log src
try
for rec in API.service.jct.csv2json src
for e of rec # get rid of empty things
delete rec[e] if not rec[e]
ri = {}
for ik in ['Institution Name', 'ROR ID', 'Institution First Seen', 'Institution Last Seen']
ri[ik] = rec[ik]
delete rec[ik]
if not _.isEmpty(ri) and not ri['Institution Last Seen'] # if these are present then it is too late to use this agreement
ri[k] = ov[k] for k of ov
# pick out records relevant to institution type
ri.rid = (if ri['ESAC ID'] then ri['ESAC ID'].trim() else '') + (if ri['ESAC ID'] and ri['Relationship'] then '_' + ri['Relationship'].trim() else '') # are these sufficient to be unique?
ri.institution = ri['Institution Name'].trim() if ri['Institution Name']
ri.ror = ri['ROR ID'].split('/').pop().trim() if ri['ROR ID']?
ri.corresponding_authors = true if ri['C/A Only'].trim().toLowerCase() is 'yes'
res.records += 1
records.push(ri) if ri.institution and ri.ror
if not _.isEmpty(rec) and not rec['Journal Last Seen']
rec[k] = ov[k] for k of ov
rec.rid = (if rec['ESAC ID'] then rec['ESAC ID'].trim() else '') + (if rec['ESAC ID'] and rec['Relationship'] then '_' + rec['Relationship'].trim() else '') # are these sufficient to be unique?
rec.issn = []
bad = false
for ik in ['ISSN (Print)','ISSN (Online)']
for isp in (if typeof rec[ik] is 'string' then rec[ik].split(',') else [])
if not isp? or typeof isp isnt 'string' or isp.indexOf('-') is -1 or isp.split('-').length > 2 or isp.length < 5
bads.push issn: isp, esac: rec['ESAC ID'], rid: rec.rid, src: src
bad = true
else if typeof isp is 'string'
nisp = isp.toUpperCase().trim().replace(/ /g, '')
rec.issn.push(nisp) if nisp.length and nisp not in rec.issn
rec.journal = rec['Journal Name'].trim() if rec['Journal Name']?
rec.corresponding_authors = true if rec['C/A Only'].trim().toLowerCase() is 'yes'
res.records += 1
if not bad and rec.journal and rec.issn.length
if exists = jct_journal.find 'issn.exact:"' + rec.issn.join('" OR issn.exact:"') + '"'
for ei in exists.issn
# don't take in ISSNs from TAs because we know they've been incorrect
rec.issn.push(ei) if typeof ei is 'string' and ei.length and ei not in rec.issn
else
inbi = false
# but if no record at all, not much choice so may as well accept
for ri in rec.issn
if ri in bissns
inbi = true
else
bissns.push ri
if not inbi
batch.push issn: rec.issn, title: rec.journal, ta: true
records.push rec
catch
console.log src + ' FAILED'
res.failed.push src
res.processed += 1
, 1
_src src, ov
while res.sheets isnt res.processed
future = new Future()
Meteor.setTimeout (() -> future.return()), 5000 # wait 5s repeatedly until all sheets are done
future.wait()
console.log 'TA sheets still processing, ' + (res.sheets - res.processed)
if records.length
console.log 'Removing and reloading ' + records.length + ' agreements'
jct_agreement.remove '*'
jct_agreement.insert records
res.extracted = records.length
if batch.length
jct_journal.insert batch
batch = []
if mail
API.service.jct.mail
subject: 'JCT TA import complete'
text: JSON.stringify res, '', 2
if bads.length
API.service.jct.mail
subject: 'JCT TA import found ' + bads.length + ' bad ISSNs'
text: bads.length + ' bad ISSNs listed in attached file'
attachment: bads
filename: 'bad_issns.csv'
return res
# import transformative journals data, which should indicate if the journal IS
# transformative or just in the list for tracking (to be transformative means to
# have submitted to the list with the appropriate responses)
# fields called pissn and eissn will contain ISSNs to check against
# check if an issn is in the transformative journals list (to be provided by plan S)
API.service.jct.tj = (issn, refresh) ->
if refresh
console.log 'Starting tj import'
recs = API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vT2SPOjVU4CKhP7FHOgaf0aRsjSOt-ApwLOy44swojTDFsWlZAIZViC0gdbmxJaEWxdJSnUmNoAnoo9/pub?gid=0&single=true&output=csv'
console.log 'Retrieved ' + recs.length + ' tj records from sheet'
for rec in recs
tj = {}
try tj.title = rec['Journal Title'].trim() if rec['Journal Title']
tj.issn ?= []
tj.issn.push(rec['ISSN (Print)'].trim().toUpperCase()) if typeof rec['ISSN (Print)'] is 'string' and rec['ISSN (Print)'].length
tj.issn.push(rec['e-ISSN (Online/Web)'].trim().toUpperCase()) if typeof rec['e-ISSN (Online/Web)'] is 'string' and rec['e-ISSN (Online/Web)'].length
if tj.issn and tj.issn.length
if exists = jct_journal.find 'issn.exact:"' + tj.issn.join('" OR issn.exact:"') + '"'
upd = {}
# don't trust incoming ISSNs from sheets because data provided by third parties has been seen to be wrong
#for isn in tj.issn
# if isn not in exists.issn
# upd.issn ?= []
# upd.issn.push isn
upd.tj = true if exists.tj isnt true
if JSON.stringify(upd) isnt '{}'
jct_journal.update exists._id, upd
else
tj.tj = true
jct_journal.insert tj
issn = issn.split(',') if typeof issn is 'string'
if issn and issn.length
res =
route: 'tj'
compliant: 'unknown'
qualifications: undefined
issn: issn
log: []
if exists = jct_journal.find 'tj:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.compliant = 'yes'
res.log.push code: 'TJ.Exists'
else
res.compliant = 'no'
res.log.push code: 'TJ.NoTJ'
return res
# TODO note there are two more codes in the new API log code spec,
# TJ.NonCompliant - TJ.Compliant
# but there is as yet no way to determine those so they are not used here yet.
else
return jct_journal.count 'tj:true'
# Import and check for Self-archiving prohibited list
# https://github.com/antleaf/jct-project/issues/406
# If journal in list, sa check not compliant
API.service.jct.sa_prohibited = (issn, refresh) ->
# check the sa prohibited data source first, to check if retained is false
# If retained is false, SA check is not compliant.
# will be a list of journals by ISSN
if refresh
counter = 0
for rt in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQ0EEMZTikcQZV28BiCL4huv-r0RnHiDrU08j3W1fyERNasoJYuAZek5G3oQH1TUKmf_X-yC5SiHaBM/pub?gid=0&single=true&output=csv'
counter += 1
console.log('sa prohibited import ' + counter) if counter % 20 is 0
rt.journal = rt['Journal Title'].trim() if typeof rt['Journal Title'] is 'string'
rt.issn = []
rt.issn.push(rt['ISSN (print)'].trim().toUpperCase()) if typeof rt['ISSN (print)'] is 'string' and rt['ISSN (print)'].length
rt.issn.push(rt['ISSN (electronic)'].trim().toUpperCase()) if typeof rt['ISSN (electronic)'] is 'string' and rt['ISSN (electronic)'].length
rt.publisher = rt.Publisher.trim() if typeof rt.Publisher is 'string'
if rt.issn.length
if exists = jct_journal.find 'issn.exact:"' + rt.issn.join('" OR issn.exact:"') + '"'
upd = {}
upd.issn ?= []
for isn in rt.issn
if isn not in exists.issn
upd.issn.push isn
upd.sa_prohibited = true if exists.sa_prohibited isnt true
upd.retention = rt
if JSON.stringify(upd) isnt '{}'
for en in exists.issn
upd.issn.push(en) if typeof en is 'string' and en.length and en not in upd.issn
jct_journal.update exists._id, upd
else
rec = sa_prohibited: true, retention: rt, issn: rt.issn, publisher: rt.publisher, title: rt.journal
jct_journal.insert rec
console.log('Imported ' + counter)
if issn
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'self_archiving'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: undefined
funder: undefined
log: []
if exists = jct_journal.find 'sa_prohibited:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.log.push code: 'SA.RRException'
res.compliant = 'no'
else
res.log.push code: 'SA.RRNoException'
return res
else
return jct_journal.count 'sa_prohibited:true'
# what are these qualifications relevant to? TAs?
# there is no funder qualification done now, due to retention policy change decision at ened of October 2020. May be added again later.
# rights_retention_author_advice -
# rights_retention_funder_implementation - the journal does not have an SA policy and the funder has a rights retention policy that starts in the future.
# There should be one record of this per funder that meets the conditions, and the following qualification specific data is requried:
# funder: <funder name>
# date: <date policy comes into force (YYYY-MM-DD)
# funder implementation ones are handled directly in the calculate stage at the moment
API.service.jct.retention = (issn, refresh) ->
# check the rights retention data source once it exists if the record is not in OAB
# for now this is a fallback to something that is not in OAB
# will be a list of journals by ISSN and a number 1,2,3,4,5
if refresh
counter = 0
for rt in API.service.jct.csv2json 'https://docs.google.com/spreadsheets/d/e/2PACX-1vTm6sDI16Kin3baNWaAiMUfGdMEUEGXy0LRvSDnvAQTWDN_exlYGyv4gnstGKdv3rXshjSa7AUWtAc5/pub?gid=0&single=true&output=csv'
counter += 1
console.log('Retention import ' + counter) if counter % 20 is 0
rt.journal = rt['Journal Name'].trim() if typeof rt['Journal Name'] is 'string'
rt.issn = []
rt.issn.push(rt['ISSN (print)'].trim().toUpperCase()) if typeof rt['ISSN (print)'] is 'string' and rt['ISSN (print)'].length
rt.issn.push(rt['ISSN (online)'].trim().toUpperCase()) if typeof rt['ISSN (online)'] is 'string' and rt['ISSN (online)'].length
rt.position = if typeof rt.Position is 'number' then rt.Position else parseInt rt.Position.trim()
rt.publisher = rt.Publisher.trim() if typeof rt.Publisher is 'string'
if rt.issn.length
if exists = jct_journal.find 'issn.exact:"' + rt.issn.join('" OR issn.exact:"') + '"'
upd = {}
upd.issn ?= []
for isn in rt.issn
if isn not in exists.issn
upd.issn.push isn
upd.retained = true if exists.retained isnt true
upd.retention = rt
if JSON.stringify(upd) isnt '{}'
for en in exists.issn
upd.issn.push(en) if typeof en is 'string' and en.length and en not in upd.issn
jct_journal.update exists._id, upd
else
rec = retained: true, retention: rt, issn: rt.issn, publisher: rt.publisher, title: rt.journal
jct_journal.insert rec
console.log('Imported ' + counter)
if issn
issn = [issn] if typeof issn is 'string'
res =
route: 'retention' # this is actually only used as a subset of OAB permission self_archiving so far
compliant: 'yes' # if not present then compliant but with author and funder quals - so what are the default funder quals?
qualifications: [{'rights_retention_author_advice': ''}]
issn: issn
log: []
if exists = jct_journal.find 'retained:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
# https://github.com/antleaf/jct-project/issues/406 no qualification needed if retained is true. Position not used.
delete res.qualifications
res.log.push code: 'SA.Compliant'
else
# new log code algo states there should be an SA.Unknown, but given we default to
# compliant at the moment, I don't see a way to achieve that, so set as Compliant for now
res.log.push(code: 'SA.Compliant') if res.log.length is 0
return res
else
return jct_journal.count 'retained:true'
API.service.jct.permission = (issn, institution) ->
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'self_archiving'
compliant: 'unknown'
qualifications: undefined
issn: issn
ror: institution
funder: undefined
log: []
try
permsurl = 'https://api.openaccessbutton.org/permissions?meta=false&issn=' + (if typeof issn is 'string' then issn else issn.join(',')) + (if typeof institution is 'string' then '&ror=' + institution else if institution? and Array.isArray(institution) and institution.length then '&ror=' + institution.join(',') else '')
perms = HTTP.call('GET', permsurl, {timeout:3000}).data
if perms.best_permission?
res.compliant = 'no' # set to no until a successful route through is found
pb = perms.best_permission
res.log.push code: 'SA.InOAB'
lc = false
pbls = [] # have to do these now even if can't archive, because needed for new API code algo values
for l in pb.licences ? []
pbls.push l.type
if lc is false and l.type.toLowerCase().replace(/\-/g,'').replace(/ /g,'') in ['ccby','ccbysa','cc0','ccbynd']
lc = l.type # set the first but have to keep going for new API codes algo
if pb.can_archive
if 'postprint' in pb.versions or 'publisher pdf' in pb.versions or 'acceptedVersion' in pb.versions or 'publishedVersion' in pb.versions
# and Embargo is zero
if typeof pb.embargo_months is 'string'
try pb.embargo_months = parseInt pb.embargo_months
if typeof pb.embargo_months isnt 'number' or pb.embargo_months is 0
if lc
res.log.push code: 'SA.OABCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
res.compliant = 'yes'
else if not pb.licences? or pb.licences.length is 0
res.log.push code: 'SA.OABIncomplete', parameters: missing: ['licences']
res.compliant = 'unknown'
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.OABNonCompliant', parameters: licence: pbls, embargo: (if pb.embargo_months? then [pb.embargo_months] else undefined), version: pb.versions
else
res.log.push code: 'SA.NotInOAB'
catch
# Fixme: if we don't get an answer then we don't have the info, but this may not be strictly what we want.
res.log.push code: 'SA.OABIncomplete', parameters: missing: ['licences']
res.compliant = 'unknown'
return res
# Calculate self archiving check. It combines, sa_prohibited, OA.works permission and rr checks
API.service.jct.sa = (journal, institution, funder, retention=true, sa_prohibition=true) ->
# Get SA prohibition
if journal and sa_prohibition
res_sa = API.service.jct.sa_prohibited journal, undefined
if res_sa and res_sa.compliant is 'no'
return res_sa
# Get OA.Works permission
rs = API.service.jct.permission journal, institution
# merge the qualifications and logs from SA prohibition into OA.Works permission
rs.qualifications ?= []
if res_sa.qualifications? and res_sa.qualifications.length
for q in (if _.isArray(res_sa.qualifications) then res_sa.qualifications else [res_sa.qualifications])
rs.qualifications.push(q)
rs.log ?= []
if res_sa.log? and res_sa.log.length
for l in (if _.isArray(res_sa.log) then res_sa.log else [res_sa.log])
rs.log.push(l)
# check for retention
if rs
_rtn = {}
for r in (if _.isArray(rs) then rs else [rs])
if r.compliant isnt 'yes' and retention
# only check retention if the funder allows it - and only if there IS a funder
# funder allows if their rights retention date
if journal and funder? and fndr = API.service.jct.funders funder
r.funder = funder
# 1609459200000 = Wed Sep 25 52971
# if fndr.retentionAt? and (fndr.retentionAt is 1609459200000 or fndr.retentionAt >= Date.now())
# if retentionAt is in past - active - https://github.com/antleaf/jct-project/issues/437
if fndr.retentionAt? and fndr.retentionAt < Date.now()
r.log.push code: 'SA.FunderRRActive'
# 26032021, as per https://github.com/antleaf/jct-project/issues/380
# rights retention qualification disabled
#r.qualifications ?= []
#r.qualifications.push 'rights_retention_funder_implementation': funder: funder, date: moment(fndr.retentionAt).format 'YYYY-MM-DD'
# retention is a special case on permissions, done this way so can be easily disabled for testing
_rtn[journal] ?= API.service.jct.retention journal
r.compliant = _rtn[journal].compliant
r.log.push(lg) for lg in _rtn[journal].log
if _rtn[journal].qualifications? and _rtn[journal].qualifications.length
r.qualifications ?= []
r.qualifications.push(ql) for ql in _rtn[journal].qualifications
else
r.log.push code: 'SA.FunderRRNotActive'
return rs
API.service.jct.doaj = (issn) ->
issn = issn.split(',') if typeof issn is 'string'
res =
route: 'fully_oa'
compliant: 'unknown'
qualifications: undefined
issn: issn
log: []
if issn
if ind = jct_journal.find 'indoaj:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
res.log.push code: 'FullOA.InDOAJ'
db = ind.doaj.bibjson
# Publishing License bibjson.license[].type bibjson.license[].type CC BY, CC BY SA, CC0 CC BY ND
pl = false
lics = []
if db.license? and db.license.length
for bl in db.license
if typeof bl?.type is 'string'
if bl.type.toLowerCase().trim().replace(/ /g,'').replace(/-/g,'') in ['ccby','ccbysa','cc0','ccbynd']
pl = bl.type if pl is false # only the first suitable one
lics.push bl.type # but have to keep going and record them all now for new API code returns values
if not db.license?
res.log.push code: 'FullOA.Unknown', parameters: missing: ['license']
else if pl
res.log.push code: 'FullOA.Compliant', parameters: licence: lics
res.compliant = 'yes'
else
res.log.push code: 'FullOA.NonCompliant', parameters: licence: lics
res.compliant = 'no'
# extra parts used to go here, but have been removed due to algorithm simplification.
else
res.log.push code: 'FullOA.NotInDOAJ'
res.compliant = 'no'
if res.compliant isnt 'yes'
# check if there is an open application for the journal to join DOAJ, if it wasn't already there
if pfd = jct_journal.find 'doajinprogress:true AND (issn.exact:"' + issn.join('" OR issn.exact:"') + '")'
if true # if an application, has to have applied within 6 months
res.log.push code: 'FullOA.InProgressDOAJ'
res.compliant = 'yes'
res.qualifications = [{doaj_under_review: {}}]
else
res.log.push code: 'FullOA.NotInProgressDOAJ' # there is actually an application, but it is too old
res.compliant = 'no'
else
res.log.push code: 'FullOA.NotInProgressDOAJ' # there is no application, so still may or may not be compliant
return res
# https://www.coalition-s.org/plan-s-funders-implementation/
_funders = []
_last_funders = Date.now()
API.service.jct.funders = (id, refresh) ->
if refresh or _funders.length is 0 or _last_funders > (Date.now() - 604800000) # if older than a week
_last_funders = Date.now()
_funders = []
for r in API.service.jct.table2json 'https://www.coalition-s.org/plan-s-funders-implementation/'
rec =
funder: r['cOAlition S organisation (funder)']
launch: r['Launch date for implementing Plan S-aligned OA policy']
application: r['Application of Plan S principles ']
retention: r['Rights Retention Strategy Implementation']
try rec.funder = rec.funder.replace('&','&')
for k of rec
if rec[k]?
rec[k] = rec[k].trim()
if rec[k].indexOf('<a') isnt -1
rec.url ?= []
rec.url.push rec[k].split('href')[1].split('=')[1].split('"')[1]
rec[k] = (rec[k].split('<')[0] + rec[k].split('>')[1].split('<')[0] + rec[k].split('>').pop()).trim()
else
delete rec[k]
if rec.retention
if rec.retention.indexOf('Note:') isnt -1
rec.notes ?= []
rec.notes.push rec.retention.split('Note:')[1].replace(')','').trim()
rec.retention = rec.retention.split('Note:')[0].replace('(','').trim()
rec.retentionAt = moment('01012021','DDMMYYYY').valueOf() if rec.retention.toLowerCase().indexOf('early adopter') isnt -1
try rec.startAt = moment(rec.launch, 'Do MMMM YYYY').valueOf()
delete rec.startAt if JSON.stringify(rec.startAt) is 'null'
if not rec.startAt? and rec.launch?
rec.notes ?= []
rec.notes.push rec.launch
try rec.id = rec.funder.toLowerCase().replace(/[^a-z0-9]/g,'')
_funders.push(rec) if rec.id?
if id?
for e in _funders
if e.id is id
return e
return _funders
API.service.jct.journals = {}
API.service.jct.journals.import = (refresh) ->
# first see if DOAJ file has updated - if so, do a full journal import
# doaj only updates their journal dump once a week so calling journal import
# won't actually do anything if the dump file name has not changed since last run
# or if a refresh is called
fldr = '/tmp/jct_doaj' + (if API.settings.dev then '_dev' else '') + '/'
if not fs.existsSync fldr
fs.mkdirSync fldr
ret = false
prev = false
current = false
fs.writeFileSync fldr + 'doaj.tar', HTTP.call('GET', 'https://doaj.org/public-data-dump/journal', {npmRequestOptions:{encoding:null}}).content
tar.extract file: fldr + 'doaj.tar', cwd: fldr, sync: true # extracted doaj dump folders end 2020-10-01
console.log 'got DOAJ journals dump'
for f in fs.readdirSync fldr # readdir alphasorts, so if more than one in tmp then last one will be newest
if f.indexOf('doaj_journal_data') isnt -1
if prev
try fs.unlinkSync fldr + prev + '/journal_batch_1.json'
try fs.rmdirSync fldr + prev
prev = current
current = f
if current and (prev or refresh)
console.log 'DOAJ journal dump ' + current + ' is suitable for ingest, getting crossref first'
# get everything from crossref
removed = false
total = 0
counter = 0
batch = []
while total is 0 or counter < total
if batch.length >= 10000 or (removed and batch.length >= 5000)
if not removed
# makes a shorter period of lack of records to query
# there will still be a period of 5 to 10 minutes where not all journals will be present
# but, since imports only occur once a day to every few days depending on settings, and
# responses should be cached at cloudflare anyway, this should not affect anyone as long as
# imports are not often run during UK/US business hours
jct_journal.remove '*'
console.log 'Removing old journal records'
future = new Future()
Meteor.setTimeout (() -> future.return()), 10000
future.wait()
removed = true
console.log 'Importing crossref ' + counter
jct_journal.insert batch
batch = []
try
url = 'https://api.crossref.org/journals?offset=' + counter + '&rows=' + 1000
console.log 'getting from crossref journals ' + url
res = HTTP.call 'GET', url, {headers: {'User-Agent': 'Journal Checker Tool; mailto: PI:EMAIL:<EMAIL>END_PI'}}
total = res.data.message['total-results'] if total is 0
for rec in res.data.message.items
if rec.ISSN and rec.ISSN.length and typeof rec.ISSN[0] is 'string'
rec.crossref = true
rec.issn = []
for i in rec.ISSN
rec.issn.push(i) if typeof i is 'string' and i.length and i not in rec.issn
rec.dois = rec.counts?['total-dois']
if rec.breakdowns?['dois-by-issued-year']?
rec.years = []
for yr in rec.breakdowns['dois-by-issued-year']
rec.years.push(yr[0]) if yr.length is 2 and yr[0] not in rec.years
rec.years.sort()
if not rec.years? or not rec.years.length or not rec.dois
rec.discontinued = true
else
thisyear = new Date().getFullYear()
if thisyear not in rec.years and (thisyear-1) not in rec.years and (thisyear-2) not in rec.years and (thisyear-3) not in rec.years
rec.discontinued = true
batch.push rec
counter += 1000
catch err
future = new Future()
Meteor.setTimeout (() -> future.return()), 2000 # wait 2s on probable crossref downtime
future.wait()
if batch.length
jct_journal.insert batch
batch = []
# then load the DOAJ data from the file (crossref takes priority because it has better metadata for spotting discontinuations)
# only about 20% of the ~15k are not already in crossref, so do updates then bulk load the new ones
console.log 'Importing from DOAJ journal dump ' + current
imports = 0
for rec in JSON.parse fs.readFileSync fldr + current + '/journal_batch_1.json'
imports += 1
console.log('DOAJ dump import ' + imports) if imports % 1000 is 0
qr = if typeof rec.bibjson.pissn is 'string' then 'issn.exact:"' + rec.bibjson.pissn + '"' else ''
if typeof rec.bibjson.eissn is 'string'
qr += ' OR ' if qr isnt ''
qr += 'issn.exact:"' + rec.bibjson.eissn + '"'
if exists = jct_journal.find qr
upd = doaj: rec
upd.indoaj = true
upd.discontinued = true if rec.bibjson.discontinued_date or rec.bibjson.is_replaced_by
upd.issn = [] # DOAJ ISSN data overrides crossref because we've seen errors in crossref that are correct in DOAJ such as 1474-9728
upd.issn.push(rec.bibjson.pissn.toUpperCase()) if typeof rec.bibjson.pissn is 'string' and rec.bibjson.pissn.length and rec.bibjson.pissn.toUpperCase() not in upd.issn
upd.issn.push(rec.bibjson.eissn.toUpperCase()) if typeof rec.bibjson.eissn is 'string' and rec.bibjson.eissn.length and rec.bibjson.eissn.toUpperCase() not in upd.issn
jct_journal.update exists._id, upd
else
nr = doaj: rec, indoaj: true
nr.title ?= rec.bibjson.title
nr.publisher ?= rec.bibjson.publisher.name if rec.bibjson.publisher?.name?
nr.discontinued = true if rec.bibjson.discontinued_date or rec.bibjson.is_replaced_by
nr.issn ?= []
nr.issn.push(rec.bibjson.pissn.toUpperCase()) if typeof rec.bibjson.pissn is 'string' and rec.bibjson.pissn.toUpperCase() not in nr.issn
nr.issn.push(rec.bibjson.eissn.toUpperCase()) if typeof rec.bibjson.eissn is 'string' and rec.bibjson.eissn.toUpperCase() not in nr.issn
batch.push nr
if batch.length
jct_journal.insert batch
batch = []
# get new doaj inprogress data if the journals load processed some doaj
# journals (otherwise we're between the week-long period when doaj doesn't update)
# and if doaj did update, load them into the catalogue too - there's only a few hundred so can check them for crossref dups too
r = HTTP.call 'GET', 'https://doaj.org/jct/inprogress?api_key=' + API.settings.service.jct.doaj.apikey
console.log 'Loading DOAJ inprogress records'
inpc = 0
for rec in JSON.parse r.content
inpc += 1
console.log('DOAJ inprogress ' + inpc) if inpc % 100 is 0
issns = []
issns.push(rec.pissn.toUpperCase()) if typeof rec.pissn is 'string' and rec.pissn.length
issns.push(rec.eissn.toUpperCase()) if typeof rec.eissn is 'string' and rec.eissn.length
if exists = jct_journal.find 'issn.exact:"' + issns.join('" OR issn.exact:"') + '"'
if not exists.indoaj # no point adding an application if already in doaj, which should be impossible, but check anyway
upd = doajinprogress: true, doajprogress: rec
nissns = []
for isn in issns
nissns.push(isn) if isn not in nissns and isn not in exists.issn
if nissns.length
upd.issn = _.union exists.issn, nissns
jct_journal.update exists._id, upd
else
console.log 'DOAJ in progress application already in DOAJ for ' + issns.join(', ')
else
nr = doajprogress: rec, issn: issns, doajinprogress: true
batch.push nr
if batch.length
jct_journal.insert batch
batch = []
return jct_journal.count()
else
return 0
# when importing TJ or TA data, add any journals not yet known about
API.service.jct.import = (refresh) ->
res = previously: jct_journal.count(), presently: undefined, started: Date.now()
res.newest = jct_agreement.find '*', true
if refresh or res.newest?.createdAt < Date.now()-86400000
# run all imports necessary for up to date data
console.log 'Starting JCT imports'
console.log 'Starting journals import'
res.journals = API.service.jct.journals.import refresh # takes about 10 mins depending how crossref is feeling
console.log 'JCT journals imported ' + res.journals
console.log 'Starting TJs import'
res.tj = API.service.jct.tj undefined, true
console.log 'JCT import TJs complete'
console.log 'Starting sa prohibited data import'
res.retention = API.service.jct.sa_prohibited undefined, true
console.log 'JCT import sa prohibited data complete'
console.log 'Starting retention data import'
res.retention = API.service.jct.retention undefined, true
console.log 'JCT import retention data complete'
console.log 'Starting funder data import'
res.funders = API.service.jct.funders undefined, true
res.funders = res.funders.length if _.isArray res.funders
console.log 'JCT import funders complete'
console.log 'Starting TAs data import'
res.ta = API.service.jct.ta.import false # this is the slowest, takes about twenty minutes
console.log 'JCT import TAs complete'
# check the mappings on jct_journal, jct_agreement, any others that get used and changed during import
# include a warning in the email if they seem far out of sync
# and include the previously and presently count, they should not be too different
res.presently = jct_journal.count()
res.ended = Date.now()
res.took = res.ended - res.started
res.minutes = Math.ceil res.took/60000
if res.mapped = JSON.stringify(jct_journal.mapping()).indexOf('dynamic_templates') isnt -1
res.mapped = JSON.stringify(jct_agreement.mapping()).indexOf('dynamic_templates') isnt -1
API.service.jct.mail
subject: 'JCT import complete'
text: JSON.stringify res, '', 2
return res
_jct_import = () ->
try API.service.jct.funders undefined, true # get the funders at startup
if API.settings.service?.jct?.import isnt false # so defaults to run if not set to false in settings
console.log 'Setting up a daily import check which will run an import if it is a Saturday'
# if later updates are made to run this on a cluster again, make sure that only one server runs this (e.g. use the import setting above where necessary)
Meteor.setInterval () ->
today = new Date()
if today.getDay() is 6 # if today is a Saturday run an import
console.log 'Starting Saturday import'
API.service.jct.import()
, 86400000
Meteor.setTimeout _jct_import, 5000
API.service.jct.unknown = (res, funder, journal, institution, send) ->
if res?
# it may not be worth saving these seperately if compliance result caching is on, but for now will keep them
r = _.clone res
r._id = (funder ? '') + '_' + (journal ? '') + '_' + (institution ? '') # overwrite dups
r.counter = 1
if ls = jct_unknown.get r._id
r.lastsend = ls.lastsend
r.counter += ls.counter ? 0
try jct_unknown.insert r
cnt = jct_unknown.count()
if send
try
cnt = 0
start = false
end = false
if typeof send isnt 'boolean'
start = send
q = 'createdAt:>' + send
else if lf = jct_unknown.find 'lastsend:*', {sort: {lastsend: {order: 'desc'}}}
start = lf.lastsend
q = 'createdAt:>' + lf.lastsend
else
q = '*'
last = false
for un in jct_unknown.fetch q, {newest: false}
start = un.createdAt if start is false
end = un.createdAt
last = un
cnt += 1
if last isnt false
jct_unknown.update last._id, lastsend: Date.now()
durl = 'https://' + (if API.settings.dev then 'api.jct.cottagelabs.com' else 'api.journalcheckertool.org') + '/unknown/' + start + '/' + end + '.csv'
API.service.jct.feedback name: 'unknowns', email: 'PI:EMAIL:<EMAIL>END_PI', subject: 'JCT system reporting unknowns', feedback: durl
return cnt
Meteor.setTimeout (() -> API.service.jct.unknown(undefined, undefined, undefined, undefined, true)), 86400000 # send once a day
API.service.jct.feedback = (params={}) ->
if typeof params.name is 'string' and typeof params.email is 'string' and typeof params.feedback is 'string' and (not params.context? or typeof params.context is 'object')
API.service.jct.mail
from: if params.email.indexOf('@') isnt -1 and params.email.indexOf('.') isnt -1 then params.email else 'PI:EMAIL:<EMAIL>END_PI'
subject: params.subject ? params.feedback.substring(0,100) + if params.feedback.length > 100 then '...' else ''
text: (if API.settings.dev then '(dev)\n\n' else '') + params.feedback + '\n\n' + (if params.subject then '' else JSON.stringify params, '', 2)
return true
else
return false
API.service.jct.csv = (rows) ->
if Array.isArray(rows) and rows.length
header = ''
fields = []
for r in rows
for k of r
if k not in fields
fields.push k
header += ',' if header isnt ''
header += '"' + k.replace(/\"/g, '') + '"'
res = ''
for rr in rows
res += '\n' if res isnt ''
ln = ''
for f in fields
ln += ',' if ln isnt ''
ln += '"' + JSON.stringify(rr[f] ? '').replace(/\"/g, '') + '"'
res += ln
return header + '\n' + res
else
return ''
API.service.jct.csv2json = Async.wrap (content, callback) ->
content = HTTP.call('GET', content).content if content.indexOf('http') is 0
csvtojson().fromString(content).then (result) -> return callback null, result
API.service.jct.table2json = (content) ->
content = HTTP.call('GET', content).content if content.indexOf('http') is 0 # TODO need to try this without puppeteer
if content.indexOf('<table') isnt -1
content = '<table' + content.split('<table')[1]
else if content.indexOf('<TABLE') isnt -1
content = '<TABLE' + content.split('<TABLE')[1]
if content.indexOf('</table') isnt -1
content = content.split('</table')[0] + '</table>'
else if content.indexOf('</TABLE') isnt -1
content = content.split('</TABLE')[1] + '</TABLE>'
content = content.replace(/\r?\n|\r/g,'')
ths = content.match(/<th.*?<\/th/gi)
headers = []
results = []
if ths?
for h in ths
str = h.replace(/<th.*?>/i,'').replace(/<\/th.*?/i,'').replace(/<.*?>/gi,'').replace(/\s\s+/g,' ').trim()
str = 'UNKNOWN' if str.replace(/ /g,'').length is 0
headers.push str
for r in content.split('<tr')
if r.toLowerCase().indexOf('<th') is -1
result = {}
row = r.replace(/.*?>/i,'').replace(/<\/tr.*?/i,'')
vals = row.match(/<td.*?<\/td/gi)
keycounter = 0
for d of vals
val = vals[d].replace(/<.*?>/gi,'').replace('</td','')
if headers.length > keycounter
result[headers[keycounter]] = val
keycounter += 1
if vals[d].toLowerCase().indexOf('colspan') isnt -1
try
keycounter += parseInt(vals[d].toLowerCase().split('colspan')[1].split('>')[0].replace(/[^0-9]/,''))-1
delete result.UNKNOWN if result.UNKNOWN?
if not _.isEmpty result
results.push result
return results
API.service.jct.mail = (opts) ->
ms = API.settings.mail ? {} # need domain and apikey
mailer = mailgun domain: ms.domain, apiKey: ms.apikey
opts.from ?= 'PI:EMAIL:<EMAIL>END_PI' # ms.from ?
opts.to ?= 'PI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI' # ms.to ?
opts.to = opts.to.join(',') if typeof opts.to is 'object'
#try HTTP.call 'POST', 'https://api.mailgun.net/v3/' + ms.domain + '/messages', {params:opts, auth:'api:'+ms.apikey}
# opts.attachment can be a string which is assumed to be a filename to attach, or a Buffer
# https://www.npmjs.com/package/mailgun-js
if typeof opts.attachment is 'object'
if opts.filename
fn = opts.filename
delete opts.filename
else
fn = 'data.csv'
att = API.service.jct.csv opts.attachment
opts.attachment = new mailer.Attachment filename: fn, contentType: 'text/csv', data: Buffer.from att, 'utf8'
console.log 'Sending mail to ' + opts.to
mailer.messages().send opts
return true
API.service.jct.test = (params={}) ->
# A series of queries based on journals, with existing knowledge of their policies.
# To test TJ and Rights retention elements of the algorithm some made up information is included,
# this is marked with [1]. Not all queries test all the compliance routes (in particular rights retention).
# Expected JCT Outcome, is what the outcome should be based on reading the information within journal, institution and funder data.
# Actual JCT Outcome is what was obtained by walking through the algorithm under the assumption that
# the publicly available information is within the JCT data sources.
params.refresh = true
params.sa_prohibition = true if not params.sa_prohibition?
params.test = params.tests if params.tests?
params.test = params.test.toString() if typeof params.test is 'number'
if typeof params.test is 'string'
ns = 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten'
for n in ['10','1','2','3','4','5','6','7','8','9']
params.test = params.test.replace n, ns[n]
params.test = params.test.split ','
res = pass: true, fails: [], results: []
queries =
one: # Query 1
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc TA)
institution: 'Cardiff University' # (subscriber to Jisc TA) 03kk7td41
funder: 'WellPI:NAME:<NAME>END_PI'
'expected outcome': 'Researcher can publish via gold open access route or via TA'
qualification: 'Researcher must be corresponding author to be eligible for TA'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('corresponding_authors') isnt -1
two: # Query 2
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc TA)
institution: 'Emory University' # (no TA or Wiley agreement) 03czfpz43
funder: 'WellPI:NAME:<NAME>END_PI'
'expected outcome': 'Researcher can publish via gold open access route'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).split('"fully_oa"')[1].split('"issn"')[0].indexOf('"yes"') isnt -1
three: # Query 3
journal: 'Aging Cell' # (published by Wiley, fully OA, in DOAJ, CC BY, included within UK Jisc & VSNU TAs)
institution: ['Emory University', 'Cardiff University', 'Utrecht University'] # 03czfpz43,03kk7td41,04pp8hn57 (Emory has no TA or Wiley account, Cardiff is subscriber to Jisc TA, Utrecht is subscriber to VSNU TA which expires prior to 1 Jan 2021)
funder: ['Wellcome', 'NWO']
'expected outcome': 'For Cardiff: Researcher can publish via gold open access route or via TA (Qualification: Researcher must be corresponding author to be eligible for TA). For Emory and Utrecht: Researcher can publish via gold open access route'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
if rs.indexOf('TA.Exists') isnt -1
return rs.split('"fully_oa"')[1].split('"issn"')[0].indexOf('"yes"') isnt -1
return false
four: # Query 4
journal: 'Proceedings of the Royal Society B' # (subscription journal published by Royal Society, AAM can be shared CC BY no embargo, UK Jisc Read Publish Deal)
institution: 'Rothamsted Research' # (subscribe to Read Publish Deal) 0347fy350
funder: 'European Commission' # EC
'expected outcome': 'Researcher can self-archive or publish via Read Publish Deal'
qualification: 'Research must be corresponding author to be eligible for Read Publish Deal'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
return rs.indexOf('corresponding_authors') isnt -1 and rs.indexOf('TA.Exists') isnt -1
return false
five: # Query 5
journal: 'Proceedings of the Royal Society B' # (subscription journal published by Royal Society, AAM can be shared CC BY no embargo, UK Jisc Read Publish Deal)
institution: 'University of Cape Town' # 03p74gp79
funder: 'PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI' # Bill & Melinda Gates Foundation billmelindagatesfoundation
'expected outcome': 'Researcher can self-archive'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
for rs in r.results
if rs.route is 'self_archiving' and rs.compliant is 'yes'
return true
return false
six: # Query 6
journal: '1477-9129' # Development (published by Company of Biologists, not the other one, hence done by ISSN) # (Transformative Journal, AAM 12 month embargo) 0951-1991
institution: 'University of Cape Town' # 03p74gp79
funder: 'SAMRC'
'expected outcome': 'Researcher can publish via payment of APC (Transformative Journal)'
'actual outcome': 'As expected'
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('TJ.Exists') isnt -1
seven: # Query 7
journal: 'Brill Research Perspectives in Law and Religion' # (Subscription Journal, VSNU Read Publish Agreement, AAM can be shared CC BY-NC no embargo)
institution: 'University of Amsterdam' # 04dkp9463
funder: 'NWO'
'expected outcome': 'Research can publish via the Transformative Agreement'
qualification: 'Researcher must be corresponding author to take advantage of the TA.'
'actual outcome': 'As expected'
test: (r) ->
if r.compliant
rs = JSON.stringify r.results
return rs.indexOf('corresponding_authors') isnt -1 and rs.indexOf('TA.Exists') isnt -1
return false
eight: # Query 8
journal: 'Migration and Society' # (Subscribe to Open, CC BY, CC BY-ND and CC BY-NC-ND licences available but currently only CC BY-NC-ND in DOAJ)
institution: 'University of Vienna' # 03prydq77
funder: 'FWF'
'expected outcome': 'No routes to compliance'
'actual outcome': 'As expected' # this is not possible because everything is currently compliant due to rights retention
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
nine: # Query 9
journal: 'Folia Historica Cracoviensia' # (fully oa, in DOAJ, CC BY-NC-ND)
institution: ['University of Warsaw', 'University of Ljubljana'] # 039bjqg32,05njb9z20
funder: ['NCN']
'expected outcome': 'No route to compliance.' # this is impossible due to rights retention
'actual outcome': 'As expected'
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
ten: # Query 10
journal: 'Journal of Clinical Investigation' # (subscription for front end material, research articles: publication fee, no embargo, CC BY licence where required by funders, not in DOAJ, Option 5 Rights Retention Policy [1])
institution: 'University of Vienna' # 03prydq77
funder: 'FWF'
'expected outcome': 'Researcher can publish via standard publication route'
'actual outcome': 'Researcher cannot publish in this journal and comply with funders OA policy' # as there is no rights retention this is impossible so it does succeed
#test: (r) -> return not r.compliant
test: (r) -> return r.compliant and JSON.stringify(r.results).indexOf('SA.Compliant') isnt -1
for q of queries
if not params.test? or q in params.test
qr = queries[q]
ans = query: q
ans.pass = false
ans.inputs = queries[q]
ans.discovered = issn: [], funder: [], ror: []
for k in ['journal','institution','funder']
for j in (if typeof qr[k] is 'string' then [qr[k]] else qr[k])
try
ans.discovered[if k is 'journal' then 'issn' else if k is 'institution' then 'ror' else 'funder'].push API.service.jct.suggest[k](j).data[0].id
catch
console.log k, j
ans.result = API.service.jct.calculate {funder: ans.discovered.funder, issn: ans.discovered.issn, ror: ans.discovered.ror}, params.refresh, params.checks, params.retention, params.sa_prohibition
ans.pass = queries[q].test ans.result
if ans.pass isnt true
res.pass = false
res.fails.push q
res.results.push ans
delete res.fails if not res.fails.length
return res
|
[
{
"context": "& Debt\"\nlocation: \"Newcastle\"\nphase: \"beta\"\nsro: \"Charu Gorasia\"\nservice_man: \"Gary Wainwright \"\nphase_history:\n ",
"end": 213,
"score": 0.9999032020568848,
"start": 200,
"tag": "NAME",
"value": "Charu Gorasia"
},
{
"context": "\nphase: \"beta\"\nsro: \"Charu Gorasia\"\nservice_man: \"Gary Wainwright \"\nphase_history:\n discovery: [\n {\n label",
"end": 244,
"score": 0.9999006390571594,
"start": 229,
"tag": "NAME",
"value": "Gary Wainwright"
}
] | app/data/projects/report-benefit-fraud.cson | tsmorgan/dwp-ux-work | 0 | id: 19
name: "Report benefit fraud"
description: "Lets users report someone they suspect is claiming benefits they aren't entitled to."
theme: "Fraud & Debt"
location: "Newcastle"
phase: "beta"
sro: "Charu Gorasia"
service_man: "Gary Wainwright "
phase_history:
discovery: [
{
label: "Completed"
date: "April 2015"
}
]
alpha: [
{
label: "Completed"
date: "September 2015"
}
]
beta: [
{
label: "Started"
date: "October 2015"
}
{
label: "Private beta Started"
date: "March 2016"
}
{
label: "Public beta predicted"
date: "October 2016"
}
]
priority: "Top"
prototype: "https://still-ocean-5673.herokuapp.com/start-page/" | 164671 | id: 19
name: "Report benefit fraud"
description: "Lets users report someone they suspect is claiming benefits they aren't entitled to."
theme: "Fraud & Debt"
location: "Newcastle"
phase: "beta"
sro: "<NAME>"
service_man: "<NAME> "
phase_history:
discovery: [
{
label: "Completed"
date: "April 2015"
}
]
alpha: [
{
label: "Completed"
date: "September 2015"
}
]
beta: [
{
label: "Started"
date: "October 2015"
}
{
label: "Private beta Started"
date: "March 2016"
}
{
label: "Public beta predicted"
date: "October 2016"
}
]
priority: "Top"
prototype: "https://still-ocean-5673.herokuapp.com/start-page/" | true | id: 19
name: "Report benefit fraud"
description: "Lets users report someone they suspect is claiming benefits they aren't entitled to."
theme: "Fraud & Debt"
location: "Newcastle"
phase: "beta"
sro: "PI:NAME:<NAME>END_PI"
service_man: "PI:NAME:<NAME>END_PI "
phase_history:
discovery: [
{
label: "Completed"
date: "April 2015"
}
]
alpha: [
{
label: "Completed"
date: "September 2015"
}
]
beta: [
{
label: "Started"
date: "October 2015"
}
{
label: "Private beta Started"
date: "March 2016"
}
{
label: "Public beta predicted"
date: "October 2016"
}
]
priority: "Top"
prototype: "https://still-ocean-5673.herokuapp.com/start-page/" |
[
{
"context": "plementation\n# ```\n# <script>window.exampleKey = 'geometry'</script>\nmodule.exports =\nclass Surface\n\n ### P",
"end": 507,
"score": 0.8712874054908752,
"start": 499,
"tag": "KEY",
"value": "geometry"
}
] | src/geom/mixins/surface.coffee | abe33/agt | 1 | # Public: Every closed geometry should have the properties of a surface.
#
# These properties are:
#
# - **Acreage** - A `Surface` object can express its surface in px<sup>2</sup>.
# - **Inclusiveness** - A `Surface` object can `contains` other geometries
# inside the bounds of its shape. It also can returns coordinates inside
# its shape randomly.
#
# ```coffeescript
# class DummySurface
# @include agt.geom.Surface
#
# # Your surface implementation
# ```
# <script>window.exampleKey = 'geometry'</script>
module.exports =
class Surface
### Public ###
# Abstract: Returns the surface of the geometry in px<sup>2</sup>.
#
# Returns a {Number}.
acreage: -> null
# Abstract: Returns a random [Point]{agt.geom.Point} with coordinates
# inside the geometry shape.
#
# <script>drawGeometry(exampleKey, {surface: true})</script>
#
# Returns a [Point]{agt.geom.Point}.
randomPointInSurface: -> null
# Abstract: Tests if the passed-in coordinates are inside the geometry shape.
#
# <script>drawGeometry(exampleKey, {contains: true})</script>
#
# x - Either a {Number} for the x coordinate or a [Point]{agt.geom.Point}.
# y - A {Number} for the y coordinate, used when a {Number} was passed for
# the x coordinate as well.
#
# Returns a {Boolean}.
contains: (x, y) -> null
# Tests if the passed-in geometry is completely contained inside the
# current geometry shape.
#
# <script>drawContainsGeometry(exampleKey)</script>
#
# geometry - The [Geometry]{agt.geom.Geometry} to test.
#
# Returns a {Boolean}.
containsGeometry: (geometry) ->
geometry.points().every (point) => @contains point
| 610 | # Public: Every closed geometry should have the properties of a surface.
#
# These properties are:
#
# - **Acreage** - A `Surface` object can express its surface in px<sup>2</sup>.
# - **Inclusiveness** - A `Surface` object can `contains` other geometries
# inside the bounds of its shape. It also can returns coordinates inside
# its shape randomly.
#
# ```coffeescript
# class DummySurface
# @include agt.geom.Surface
#
# # Your surface implementation
# ```
# <script>window.exampleKey = '<KEY>'</script>
module.exports =
class Surface
### Public ###
# Abstract: Returns the surface of the geometry in px<sup>2</sup>.
#
# Returns a {Number}.
acreage: -> null
# Abstract: Returns a random [Point]{agt.geom.Point} with coordinates
# inside the geometry shape.
#
# <script>drawGeometry(exampleKey, {surface: true})</script>
#
# Returns a [Point]{agt.geom.Point}.
randomPointInSurface: -> null
# Abstract: Tests if the passed-in coordinates are inside the geometry shape.
#
# <script>drawGeometry(exampleKey, {contains: true})</script>
#
# x - Either a {Number} for the x coordinate or a [Point]{agt.geom.Point}.
# y - A {Number} for the y coordinate, used when a {Number} was passed for
# the x coordinate as well.
#
# Returns a {Boolean}.
contains: (x, y) -> null
# Tests if the passed-in geometry is completely contained inside the
# current geometry shape.
#
# <script>drawContainsGeometry(exampleKey)</script>
#
# geometry - The [Geometry]{agt.geom.Geometry} to test.
#
# Returns a {Boolean}.
containsGeometry: (geometry) ->
geometry.points().every (point) => @contains point
| true | # Public: Every closed geometry should have the properties of a surface.
#
# These properties are:
#
# - **Acreage** - A `Surface` object can express its surface in px<sup>2</sup>.
# - **Inclusiveness** - A `Surface` object can `contains` other geometries
# inside the bounds of its shape. It also can returns coordinates inside
# its shape randomly.
#
# ```coffeescript
# class DummySurface
# @include agt.geom.Surface
#
# # Your surface implementation
# ```
# <script>window.exampleKey = 'PI:KEY:<KEY>END_PI'</script>
module.exports =
class Surface
### Public ###
# Abstract: Returns the surface of the geometry in px<sup>2</sup>.
#
# Returns a {Number}.
acreage: -> null
# Abstract: Returns a random [Point]{agt.geom.Point} with coordinates
# inside the geometry shape.
#
# <script>drawGeometry(exampleKey, {surface: true})</script>
#
# Returns a [Point]{agt.geom.Point}.
randomPointInSurface: -> null
# Abstract: Tests if the passed-in coordinates are inside the geometry shape.
#
# <script>drawGeometry(exampleKey, {contains: true})</script>
#
# x - Either a {Number} for the x coordinate or a [Point]{agt.geom.Point}.
# y - A {Number} for the y coordinate, used when a {Number} was passed for
# the x coordinate as well.
#
# Returns a {Boolean}.
contains: (x, y) -> null
# Tests if the passed-in geometry is completely contained inside the
# current geometry shape.
#
# <script>drawContainsGeometry(exampleKey)</script>
#
# geometry - The [Geometry]{agt.geom.Geometry} to test.
#
# Returns a {Boolean}.
containsGeometry: (geometry) ->
geometry.points().every (point) => @contains point
|
[
{
"context": "atever'\n query:\n access_token: 'whatever'\n res = {}\n next = sinon.spy (error) ->",
"end": 857,
"score": 0.6826906800270081,
"start": 851,
"tag": "KEY",
"value": "atever"
},
{
"context": "ation: {}\n query:\n access_token: 'whatever'\n body:\n access_token: 'wha",
"end": 1443,
"score": 0.4049184024333954,
"start": 1441,
"tag": "PASSWORD",
"value": "wh"
},
{
"context": "ion: {}\n query:\n access_token: 'whatever'\n body:\n access_token: 'whatever'",
"end": 1449,
"score": 0.7766383290290833,
"start": 1443,
"tag": "KEY",
"value": "atever"
},
{
"context": "'whatever'\n body:\n access_token: 'whatever'\n res = {}\n next = sinon.spy (err",
"end": 1492,
"score": 0.47616109251976013,
"start": 1490,
"tag": "PASSWORD",
"value": "wh"
},
{
"context": "hatever'\n body:\n access_token: 'whatever'\n res = {}\n next = sinon.spy (error) ->",
"end": 1498,
"score": 0.7121027708053589,
"start": 1492,
"tag": "KEY",
"value": "atever"
},
{
"context": "'whatever'\n body:\n access_token: 'whatever'\n res = {}\n next = sinon.spy (err",
"end": 2146,
"score": 0.5786666870117188,
"start": 2144,
"tag": "PASSWORD",
"value": "wh"
},
{
"context": "hatever'\n body:\n access_token: 'whatever'\n res = {}\n next = sinon.spy (error) ->",
"end": 2152,
"score": 0.7840468883514404,
"start": 2146,
"tag": "KEY",
"value": "atever"
},
{
"context": "eaders: {}\n body:\n access_token: 'whatever'\n res = {}\n next = sinon.spy (error) ->",
"end": 2768,
"score": 0.6487183570861816,
"start": 2760,
"tag": "KEY",
"value": "whatever"
},
{
"context": "ion: {}\n query:\n access_token: 'whatever'\n res = {}\n next = sinon.spy (error) ->",
"end": 3789,
"score": 0.8487620949745178,
"start": 3783,
"tag": "KEY",
"value": "atever"
},
{
"context": "rlencoded'\n body:\n access_token: 'whatever'\n res = {}\n next = sinon.spy (error) ->",
"end": 4313,
"score": 0.8744170069694519,
"start": 4305,
"tag": "PASSWORD",
"value": "whatever"
}
] | test/unit/oidc/getBearerToken.coffee | Zacaria/connect | 0 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
chai.use sinonChai
chai.should()
getBearerToken = require '../../../oidc/getBearerToken'
describe 'Get Bearer Token', ->
{req,res,next,err} = {}
describe 'with no token present', ->
before (done) ->
req = { headers: {}, authorization: {} }
res = {}
next = sinon.spy (error) ->
done()
getBearerToken(req, res, next)
it 'should not set token on the request', ->
expect(req.bearer).to.be.undefined
it 'should continue', ->
expect(err).to.be.undefined
describe 'with authorization header and query parameter', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
query:
access_token: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with query parameter and request body parameter', ->
before (done) ->
req =
authorization: {}
query:
access_token: 'whatever'
body:
access_token: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with authorization header and request body parameter', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
body:
access_token: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with request body parameter and invalid content type', ->
before (done) ->
req =
authorization: {}
headers: {}
body:
access_token: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Invalid content-type'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with valid (parsed) authorization header', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
describe 'with query parameter', ->
before (done) ->
req =
authorization: {}
query:
access_token: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
describe 'with request body parameter', ->
before (done) ->
req =
authorization: {}
headers:
'content-type': 'application/x-www-form-urlencoded'
body:
access_token: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
| 65047 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
chai.use sinonChai
chai.should()
getBearerToken = require '../../../oidc/getBearerToken'
describe 'Get Bearer Token', ->
{req,res,next,err} = {}
describe 'with no token present', ->
before (done) ->
req = { headers: {}, authorization: {} }
res = {}
next = sinon.spy (error) ->
done()
getBearerToken(req, res, next)
it 'should not set token on the request', ->
expect(req.bearer).to.be.undefined
it 'should continue', ->
expect(err).to.be.undefined
describe 'with authorization header and query parameter', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
query:
access_token: 'wh<KEY>'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with query parameter and request body parameter', ->
before (done) ->
req =
authorization: {}
query:
access_token: '<PASSWORD> <KEY>'
body:
access_token: '<PASSWORD> <KEY>'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with authorization header and request body parameter', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
body:
access_token: '<PASSWORD> <KEY>'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with request body parameter and invalid content type', ->
before (done) ->
req =
authorization: {}
headers: {}
body:
access_token: '<KEY>'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Invalid content-type'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with valid (parsed) authorization header', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
describe 'with query parameter', ->
before (done) ->
req =
authorization: {}
query:
access_token: 'wh<KEY>'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
describe 'with request body parameter', ->
before (done) ->
req =
authorization: {}
headers:
'content-type': 'application/x-www-form-urlencoded'
body:
access_token: '<KEY>'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
| true | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
chai.use sinonChai
chai.should()
getBearerToken = require '../../../oidc/getBearerToken'
describe 'Get Bearer Token', ->
{req,res,next,err} = {}
describe 'with no token present', ->
before (done) ->
req = { headers: {}, authorization: {} }
res = {}
next = sinon.spy (error) ->
done()
getBearerToken(req, res, next)
it 'should not set token on the request', ->
expect(req.bearer).to.be.undefined
it 'should continue', ->
expect(err).to.be.undefined
describe 'with authorization header and query parameter', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
query:
access_token: 'whPI:KEY:<KEY>END_PI'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with query parameter and request body parameter', ->
before (done) ->
req =
authorization: {}
query:
access_token: 'PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI'
body:
access_token: 'PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with authorization header and request body parameter', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
body:
access_token: 'PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Multiple authentication methods'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with request body parameter and invalid content type', ->
before (done) ->
req =
authorization: {}
headers: {}
body:
access_token: 'PI:KEY:<KEY>END_PI'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should provide an error', ->
err.error.should.equal 'invalid_request'
it 'should provide an error description', ->
err.error_description.should.equal 'Invalid content-type'
it 'should provide a status code', ->
err.statusCode.should.equal 400
describe 'with valid (parsed) authorization header', ->
before (done) ->
req =
authorization:
scheme: 'bearer'
credentials: 'whatever'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
describe 'with query parameter', ->
before (done) ->
req =
authorization: {}
query:
access_token: 'whPI:KEY:<KEY>END_PI'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
describe 'with request body parameter', ->
before (done) ->
req =
authorization: {}
headers:
'content-type': 'application/x-www-form-urlencoded'
body:
access_token: 'PI:PASSWORD:<KEY>END_PI'
res = {}
next = sinon.spy (error) ->
err = error
done()
getBearerToken(req, res, next)
it 'should set token on the request', ->
req.bearer.should.equal 'whatever'
it 'should continue', ->
next.firstCall.args.length.should.equal 0
|
[
{
"context": "ould.be.above 2\n rows[0].key.should.eql 'test_scanner_get_startRow_11'\n rows[0].column.should.eql 'node_column",
"end": 2147,
"score": 0.9185751080513,
"start": 2119,
"tag": "KEY",
"value": "test_scanner_get_startRow_11"
},
{
"context": "column_family:'\n rows[1].key.should.eql 'test_scanner_get_startRow_111'\n rows[1].column.should.eql 'node_column",
"end": 2270,
"score": 0.9102345108985901,
"start": 2241,
"tag": "KEY",
"value": "test_scanner_get_startRow_111"
},
{
"context": "_table')\n .row()\n .put [\n { key:'test_scanner_get_startEndRow_1', column:'node_column_fa",
"end": 2508,
"score": 0.6028165817260742,
"start": 2503,
"tag": "KEY",
"value": "test_"
},
{
"context": " .row()\n .put [\n { key:'test_scanner_get_startEndRow_1', column:'node_column_family:', $:'v 1.3' }\n ",
"end": 2532,
"score": 0.654279351234436,
"start": 2516,
"tag": "KEY",
"value": "get_startEndRow_"
},
{
"context": "'node_column_family:', $:'v 1.3' }\n { key:'test_scanner_get_startEndRow_11', column:'node_column_f",
"end": 2598,
"score": 0.5264929533004761,
"start": 2593,
"tag": "KEY",
"value": "test_"
},
{
"context": "_family:', $:'v 1.3' }\n { key:'test_scanner_get_startEndRow_11', column:'node_column_family:', $:'v 1.1' }\n ",
"end": 2624,
"score": 0.622921884059906,
"start": 2606,
"tag": "KEY",
"value": "get_startEndRow_11"
},
{
"context": "'node_column_family:', $:'v 1.1' }\n { key:'test_scanner_get_startEndRow_111', column:'node_column_",
"end": 2689,
"score": 0.5723521709442139,
"start": 2684,
"tag": "KEY",
"value": "test_"
},
{
"context": "_family:', $:'v 1.1' }\n { key:'test_scanner_get_startEndRow_111', column:'node_column_family:', $:'v 1.2' }\n ",
"end": 2716,
"score": 0.6652659177780151,
"start": 2697,
"tag": "KEY",
"value": "get_startEndRow_111"
},
{
"context": "'node_column_family:', $:'v 1.2' }\n { key:'test_scanner_get_startEndRow_2', column:'node_column_f",
"end": 2780,
"score": 0.5298740267753601,
"start": 2776,
"tag": "KEY",
"value": "test"
},
{
"context": "_family:', $:'v 1.2' }\n { key:'test_scanner_get_startEndRow_2', column:'node_column_family:', $:'v",
"end": 2793,
"score": 0.6527897715568542,
"start": 2789,
"tag": "KEY",
"value": "get_"
},
{
"context": "'v 1.2' }\n { key:'test_scanner_get_startEndRow_2', column:'node_column_family:', $:'v 2.2' }\n ",
"end": 2805,
"score": 0.5731094479560852,
"start": 2801,
"tag": "KEY",
"value": "Row_"
},
{
"context": "th.should.eql 2\n rows[0].key.should.eql 'test_scanner_get_startEndRow_11'\n rows[0].column.should.eql 'node_column",
"end": 3548,
"score": 0.9761024117469788,
"start": 3517,
"tag": "KEY",
"value": "test_scanner_get_startEndRow_11"
},
{
"context": "column_family:'\n rows[1].key.should.eql 'test_scanner_get_startEndRow_111'\n rows[1].column.should.eql 'node_column",
"end": 3674,
"score": 0.9833475351333618,
"start": 3642,
"tag": "KEY",
"value": "test_scanner_get_startEndRow_111"
},
{
"context": "ode_column_family:c3', $:'v 3.3' }\n { key:'test_scanner_get_columns_3', column:'node_column_family:c4', $:'v 3.4' }\n ",
"end": 4889,
"score": 0.7984309792518616,
"start": 4863,
"tag": "KEY",
"value": "test_scanner_get_columns_3"
},
{
"context": "')\n .row()\n .put [\n { key:'test_scanner_get_startTime_1', column:'node_column_family:', timestamp: 118155",
"end": 7007,
"score": 0.8327706456184387,
"start": 6979,
"tag": "KEY",
"value": "test_scanner_get_startTime_1"
},
{
"context": "tamp: 1181558248913, $:'v 1.3' }\n { key:'test_scanner_get_startTime_11', column:'node_column_family:', timestamp: 118155",
"end": 7124,
"score": 0.8638792037963867,
"start": 7095,
"tag": "KEY",
"value": "test_scanner_get_startTime_11"
},
{
"context": "tamp: 1181558248913, $:'v 1.1' }\n { key:'test_scanner_get_startTime_111', column:'node_column_family:', timestamp: 118155",
"end": 7242,
"score": 0.8657939434051514,
"start": 7212,
"tag": "KEY",
"value": "test_scanner_get_startTime_111"
},
{
"context": "tamp: 1181558248913, $:'v 1.2' }\n { key:'test_scanner_get_startTime_2', column:'node_column_family:', timest",
"end": 7347,
"score": 0.7447523474693298,
"start": 7330,
"tag": "KEY",
"value": "test_scanner_get_"
},
{
"context": "1.2' }\n { key:'test_scanner_get_startTime_2', column:'node_column_family:', timestamp: 11815",
"end": 7356,
"score": 0.8895013928413391,
"start": 7356,
"tag": "KEY",
"value": ""
},
{
"context": " cells[0].key.should.eql 'test_scanner_get_startTime_1'\n cells[0].timestamp.sho",
"end": 8131,
"score": 0.5191605091094971,
"start": 8128,
"tag": "KEY",
"value": "get"
},
{
"context": "ells[0].key.should.eql 'test_scanner_get_startTime_1'\n cells[0].timestamp.should.eql 118",
"end": 8141,
"score": 0.5845568180084229,
"start": 8141,
"tag": "KEY",
"value": ""
},
{
"context": "1558248913\n cells[1].key.should.eql 'test_scanner_get_startTime_11'\n cells[1].timestamp.should.eql 1181",
"end": 8271,
"score": 0.9994643926620483,
"start": 8242,
"tag": "KEY",
"value": "test_scanner_get_startTime_11"
},
{
"context": "1558248913\n cells[2].key.should.eql 'test_scanner_get_startTime_111'\n cells[2].timestamp.should.eql 1181",
"end": 8400,
"score": 0.9995183348655701,
"start": 8370,
"tag": "KEY",
"value": "test_scanner_get_startTime_111"
},
{
"context": "a = for i in [0...1000] # 1000000\n { key: 'test_scanner_fetch_records_in_batch', column: \"node_column_family:#{i}\", $: 'v 1.3' }",
"end": 8649,
"score": 0.9995325207710266,
"start": 8614,
"tag": "KEY",
"value": "test_scanner_fetch_records_in_batch"
}
] | test/scanner.coffee | ripjar/node-hbase | 82 |
test = require './test'
describe 'scanner', ->
@timeout 0
it 'stream readable', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_stream_readable_1', column:'node_column_family:', $:'v 1.3' }
{ key:'test_scanner_stream_readable_11', column:'node_column_family:', $:'v 1.1' }
{ key:'test_scanner_stream_readable_111', column:'node_column_family:', $:'v 1.2' }
{ key:'test_scanner_stream_readable_2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
scanner = client
.table('node_table')
.scan
startRow: 'test_scanner_get_startRow_11'
maxVersions: 1
rows = []
scanner.on 'readable', ->
while chunk = scanner.read()
rows.push chunk
scanner.on 'error', (err) ->
next err
scanner.on 'end', ->
rows.length.should.be.above 2
next()
it 'Get startRow', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_get_startRow_1', column:'node_column_family:', $:'v 1.3' }
{ key:'test_scanner_get_startRow_11', column:'node_column_family:', $:'v 1.1' }
{ key:'test_scanner_get_startRow_111', column:'node_column_family:', $:'v 1.2' }
{ key:'test_scanner_get_startRow_2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_startRow_11'
maxVersions: 1
, (err, rows) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
rows.length.should.be.above 2
rows[0].key.should.eql 'test_scanner_get_startRow_11'
rows[0].column.should.eql 'node_column_family:'
rows[1].key.should.eql 'test_scanner_get_startRow_111'
rows[1].column.should.eql 'node_column_family:'
next()
it 'Get startRow and endRow', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_get_startEndRow_1', column:'node_column_family:', $:'v 1.3' }
{ key:'test_scanner_get_startEndRow_11', column:'node_column_family:', $:'v 1.1' }
{ key:'test_scanner_get_startEndRow_111', column:'node_column_family:', $:'v 1.2' }
{ key:'test_scanner_get_startEndRow_2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_startEndRow_11'
endRow: 'test_scanner_get_startEndRow_2'
maxVersions: 1
, (err, rows) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
rows.length.should.eql 2
rows[0].key.should.eql 'test_scanner_get_startEndRow_11'
rows[0].column.should.eql 'node_column_family:'
rows[1].key.should.eql 'test_scanner_get_startEndRow_111'
rows[1].column.should.eql 'node_column_family:'
next()
it 'Get columns', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_get_columns_1', column:'node_column_family:c1', $:'v 1.1' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c2', $:'v 1.2' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c3', $:'v 1.3' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c4', $:'v 1.4' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c1', $:'v 2.1' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c2', $:'v 2.2' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c3', $:'v 2.3' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c4', $:'v 2.4' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c1', $:'v 3.1' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c2', $:'v 3.2' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c3', $:'v 3.3' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c4', $:'v 3.4' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_columns_1'
endRow: 'test_scanner_get_columns_3'
maxVersions: 1
column: ['node_column_family:c4','node_column_family:c2']
, (err, rows) ->
return next err if err
rows.length.should.eql 4
keys = rows.map (row) -> row.key
keys.should.eql [ 'test_scanner_get_columns_1',
'test_scanner_get_columns_1',
'test_scanner_get_columns_2',
'test_scanner_get_columns_2' ]
columns = rows.map (row) -> row.column
columns.should.eql [ 'node_column_family:c2',
'node_column_family:c4',
'node_column_family:c2',
'node_column_family:c4' ]
next()
it 'Option maxVersions', (next) ->
test.client (err, client) ->
time = (new Date).getTime()
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+1, $:'v 1.1' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+2, $:'v 1.2' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+3, $:'v 1.3' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+4, $:'v 1.4' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_maxversions_1'
endRow: 'test_scanner_maxversions_11'
column: 'node_column_family:c'
maxVersions: 3
, (err, cells) ->
return next err if err
cells.length.should.eql 3
next()
it 'Get startTime and endTime', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_get_startTime_1', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.3' }
{ key:'test_scanner_get_startTime_11', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.1' }
{ key:'test_scanner_get_startTime_111', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.2' }
{ key:'test_scanner_get_startTime_2', column:'node_column_family:', timestamp: 1181558248914, $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startTime: 1181558248913
endTime: 1181558248914
maxVersions: 1
, (err, cells) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
cells.length.should.eql 3
cells[0].key.should.eql 'test_scanner_get_startTime_1'
cells[0].timestamp.should.eql 1181558248913
cells[1].key.should.eql 'test_scanner_get_startTime_11'
cells[1].timestamp.should.eql 1181558248913
cells[2].key.should.eql 'test_scanner_get_startTime_111'
cells[2].timestamp.should.eql 1181558248913
next()
it 'fetch records in batch', (next) ->
test.client (err, client) ->
data = for i in [0...1000] # 1000000
{ key: 'test_scanner_fetch_records_in_batch', column: "node_column_family:#{i}", $: 'v 1.3' }
count = init: 0, scan: 0, readable: 0, read: 0
client.on 'request', ({options}) ->
count.init++ if /^(^|\/rest)\/node_table\/scanner$/.test options.path
count.scan++ if /^(^|\/rest)\/node_table\/scanner\//.test options.path
client
.table('node_table')
.row()
.put data, (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_fetch_records_in_batch'
endRow: 'test_scanner_fetch_records_in_batch_'
maxVersions: 1
batch: 10
.on 'readable', ->
count.readable++
while record = @read()
count.read++
.on 'error', (err) ->
next err
.on 'end', ->
count.init.should.eql 1
count.scan.should.eql 102
# Node.js <10 = 1001, >10 = 101
count.readable.should.equalOneOf [101, 1001]
count.read.should.eql 1000
next()
| 179733 |
test = require './test'
describe 'scanner', ->
@timeout 0
it 'stream readable', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_stream_readable_1', column:'node_column_family:', $:'v 1.3' }
{ key:'test_scanner_stream_readable_11', column:'node_column_family:', $:'v 1.1' }
{ key:'test_scanner_stream_readable_111', column:'node_column_family:', $:'v 1.2' }
{ key:'test_scanner_stream_readable_2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
scanner = client
.table('node_table')
.scan
startRow: 'test_scanner_get_startRow_11'
maxVersions: 1
rows = []
scanner.on 'readable', ->
while chunk = scanner.read()
rows.push chunk
scanner.on 'error', (err) ->
next err
scanner.on 'end', ->
rows.length.should.be.above 2
next()
it 'Get startRow', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_get_startRow_1', column:'node_column_family:', $:'v 1.3' }
{ key:'test_scanner_get_startRow_11', column:'node_column_family:', $:'v 1.1' }
{ key:'test_scanner_get_startRow_111', column:'node_column_family:', $:'v 1.2' }
{ key:'test_scanner_get_startRow_2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_startRow_11'
maxVersions: 1
, (err, rows) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
rows.length.should.be.above 2
rows[0].key.should.eql '<KEY>'
rows[0].column.should.eql 'node_column_family:'
rows[1].key.should.eql '<KEY>'
rows[1].column.should.eql 'node_column_family:'
next()
it 'Get startRow and endRow', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'<KEY>scanner_<KEY>1', column:'node_column_family:', $:'v 1.3' }
{ key:'<KEY>scanner_<KEY>', column:'node_column_family:', $:'v 1.1' }
{ key:'<KEY>scanner_<KEY>', column:'node_column_family:', $:'v 1.2' }
{ key:'<KEY>_scanner_<KEY>startEnd<KEY>2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_startEndRow_11'
endRow: 'test_scanner_get_startEndRow_2'
maxVersions: 1
, (err, rows) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
rows.length.should.eql 2
rows[0].key.should.eql '<KEY>'
rows[0].column.should.eql 'node_column_family:'
rows[1].key.should.eql '<KEY>'
rows[1].column.should.eql 'node_column_family:'
next()
it 'Get columns', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_get_columns_1', column:'node_column_family:c1', $:'v 1.1' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c2', $:'v 1.2' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c3', $:'v 1.3' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c4', $:'v 1.4' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c1', $:'v 2.1' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c2', $:'v 2.2' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c3', $:'v 2.3' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c4', $:'v 2.4' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c1', $:'v 3.1' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c2', $:'v 3.2' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c3', $:'v 3.3' }
{ key:'<KEY>', column:'node_column_family:c4', $:'v 3.4' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_columns_1'
endRow: 'test_scanner_get_columns_3'
maxVersions: 1
column: ['node_column_family:c4','node_column_family:c2']
, (err, rows) ->
return next err if err
rows.length.should.eql 4
keys = rows.map (row) -> row.key
keys.should.eql [ 'test_scanner_get_columns_1',
'test_scanner_get_columns_1',
'test_scanner_get_columns_2',
'test_scanner_get_columns_2' ]
columns = rows.map (row) -> row.column
columns.should.eql [ 'node_column_family:c2',
'node_column_family:c4',
'node_column_family:c2',
'node_column_family:c4' ]
next()
it 'Option maxVersions', (next) ->
test.client (err, client) ->
time = (new Date).getTime()
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+1, $:'v 1.1' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+2, $:'v 1.2' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+3, $:'v 1.3' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+4, $:'v 1.4' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_maxversions_1'
endRow: 'test_scanner_maxversions_11'
column: 'node_column_family:c'
maxVersions: 3
, (err, cells) ->
return next err if err
cells.length.should.eql 3
next()
it 'Get startTime and endTime', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'<KEY>', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.3' }
{ key:'<KEY>', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.1' }
{ key:'<KEY>', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.2' }
{ key:'<KEY>startTime<KEY>_2', column:'node_column_family:', timestamp: 1181558248914, $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startTime: 1181558248913
endTime: 1181558248914
maxVersions: 1
, (err, cells) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
cells.length.should.eql 3
cells[0].key.should.eql 'test_scanner_<KEY>_startTime<KEY>_1'
cells[0].timestamp.should.eql 1181558248913
cells[1].key.should.eql '<KEY>'
cells[1].timestamp.should.eql 1181558248913
cells[2].key.should.eql '<KEY>'
cells[2].timestamp.should.eql 1181558248913
next()
it 'fetch records in batch', (next) ->
test.client (err, client) ->
data = for i in [0...1000] # 1000000
{ key: '<KEY>', column: "node_column_family:#{i}", $: 'v 1.3' }
count = init: 0, scan: 0, readable: 0, read: 0
client.on 'request', ({options}) ->
count.init++ if /^(^|\/rest)\/node_table\/scanner$/.test options.path
count.scan++ if /^(^|\/rest)\/node_table\/scanner\//.test options.path
client
.table('node_table')
.row()
.put data, (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_fetch_records_in_batch'
endRow: 'test_scanner_fetch_records_in_batch_'
maxVersions: 1
batch: 10
.on 'readable', ->
count.readable++
while record = @read()
count.read++
.on 'error', (err) ->
next err
.on 'end', ->
count.init.should.eql 1
count.scan.should.eql 102
# Node.js <10 = 1001, >10 = 101
count.readable.should.equalOneOf [101, 1001]
count.read.should.eql 1000
next()
| true |
test = require './test'
describe 'scanner', ->
@timeout 0
it 'stream readable', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_stream_readable_1', column:'node_column_family:', $:'v 1.3' }
{ key:'test_scanner_stream_readable_11', column:'node_column_family:', $:'v 1.1' }
{ key:'test_scanner_stream_readable_111', column:'node_column_family:', $:'v 1.2' }
{ key:'test_scanner_stream_readable_2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
scanner = client
.table('node_table')
.scan
startRow: 'test_scanner_get_startRow_11'
maxVersions: 1
rows = []
scanner.on 'readable', ->
while chunk = scanner.read()
rows.push chunk
scanner.on 'error', (err) ->
next err
scanner.on 'end', ->
rows.length.should.be.above 2
next()
it 'Get startRow', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_get_startRow_1', column:'node_column_family:', $:'v 1.3' }
{ key:'test_scanner_get_startRow_11', column:'node_column_family:', $:'v 1.1' }
{ key:'test_scanner_get_startRow_111', column:'node_column_family:', $:'v 1.2' }
{ key:'test_scanner_get_startRow_2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_startRow_11'
maxVersions: 1
, (err, rows) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
rows.length.should.be.above 2
rows[0].key.should.eql 'PI:KEY:<KEY>END_PI'
rows[0].column.should.eql 'node_column_family:'
rows[1].key.should.eql 'PI:KEY:<KEY>END_PI'
rows[1].column.should.eql 'node_column_family:'
next()
it 'Get startRow and endRow', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'PI:KEY:<KEY>END_PIscanner_PI:KEY:<KEY>END_PI1', column:'node_column_family:', $:'v 1.3' }
{ key:'PI:KEY:<KEY>END_PIscanner_PI:KEY:<KEY>END_PI', column:'node_column_family:', $:'v 1.1' }
{ key:'PI:KEY:<KEY>END_PIscanner_PI:KEY:<KEY>END_PI', column:'node_column_family:', $:'v 1.2' }
{ key:'PI:KEY:<KEY>END_PI_scanner_PI:KEY:<KEY>END_PIstartEndPI:KEY:<KEY>END_PI2', column:'node_column_family:', $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_startEndRow_11'
endRow: 'test_scanner_get_startEndRow_2'
maxVersions: 1
, (err, rows) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
rows.length.should.eql 2
rows[0].key.should.eql 'PI:KEY:<KEY>END_PI'
rows[0].column.should.eql 'node_column_family:'
rows[1].key.should.eql 'PI:KEY:<KEY>END_PI'
rows[1].column.should.eql 'node_column_family:'
next()
it 'Get columns', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_get_columns_1', column:'node_column_family:c1', $:'v 1.1' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c2', $:'v 1.2' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c3', $:'v 1.3' }
{ key:'test_scanner_get_columns_1', column:'node_column_family:c4', $:'v 1.4' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c1', $:'v 2.1' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c2', $:'v 2.2' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c3', $:'v 2.3' }
{ key:'test_scanner_get_columns_2', column:'node_column_family:c4', $:'v 2.4' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c1', $:'v 3.1' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c2', $:'v 3.2' }
{ key:'test_scanner_get_columns_3', column:'node_column_family:c3', $:'v 3.3' }
{ key:'PI:KEY:<KEY>END_PI', column:'node_column_family:c4', $:'v 3.4' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_get_columns_1'
endRow: 'test_scanner_get_columns_3'
maxVersions: 1
column: ['node_column_family:c4','node_column_family:c2']
, (err, rows) ->
return next err if err
rows.length.should.eql 4
keys = rows.map (row) -> row.key
keys.should.eql [ 'test_scanner_get_columns_1',
'test_scanner_get_columns_1',
'test_scanner_get_columns_2',
'test_scanner_get_columns_2' ]
columns = rows.map (row) -> row.column
columns.should.eql [ 'node_column_family:c2',
'node_column_family:c4',
'node_column_family:c2',
'node_column_family:c4' ]
next()
it 'Option maxVersions', (next) ->
test.client (err, client) ->
time = (new Date).getTime()
client
.table('node_table')
.row()
.put [
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+1, $:'v 1.1' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+2, $:'v 1.2' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+3, $:'v 1.3' }
{ key:'test_scanner_maxversions_1', column:'node_column_family:c', timestamp: time+4, $:'v 1.4' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_maxversions_1'
endRow: 'test_scanner_maxversions_11'
column: 'node_column_family:c'
maxVersions: 3
, (err, cells) ->
return next err if err
cells.length.should.eql 3
next()
it 'Get startTime and endTime', (next) ->
test.client (err, client) ->
client
.table('node_table')
.row()
.put [
{ key:'PI:KEY:<KEY>END_PI', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.3' }
{ key:'PI:KEY:<KEY>END_PI', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.1' }
{ key:'PI:KEY:<KEY>END_PI', column:'node_column_family:', timestamp: 1181558248913, $:'v 1.2' }
{ key:'PI:KEY:<KEY>END_PIstartTimePI:KEY:<KEY>END_PI_2', column:'node_column_family:', timestamp: 1181558248914, $:'v 2.2' }
], (err, success) ->
return next err if err
client
.table('node_table')
.scan
startTime: 1181558248913
endTime: 1181558248914
maxVersions: 1
, (err, cells) ->
return next err if err
# http:#brunodumon.wordpress.com/2010/02/17/building-indexes-using-hbase-mapping-strings-numbers-and-dates-onto-bytes/
# Technically, you would set the start row for the scanner to France
# and stop the scanning by using a RowFilter with a BinaryPrefixComparator
cells.length.should.eql 3
cells[0].key.should.eql 'test_scanner_PI:KEY:<KEY>END_PI_startTimePI:KEY:<KEY>END_PI_1'
cells[0].timestamp.should.eql 1181558248913
cells[1].key.should.eql 'PI:KEY:<KEY>END_PI'
cells[1].timestamp.should.eql 1181558248913
cells[2].key.should.eql 'PI:KEY:<KEY>END_PI'
cells[2].timestamp.should.eql 1181558248913
next()
it 'fetch records in batch', (next) ->
test.client (err, client) ->
data = for i in [0...1000] # 1000000
{ key: 'PI:KEY:<KEY>END_PI', column: "node_column_family:#{i}", $: 'v 1.3' }
count = init: 0, scan: 0, readable: 0, read: 0
client.on 'request', ({options}) ->
count.init++ if /^(^|\/rest)\/node_table\/scanner$/.test options.path
count.scan++ if /^(^|\/rest)\/node_table\/scanner\//.test options.path
client
.table('node_table')
.row()
.put data, (err, success) ->
return next err if err
client
.table('node_table')
.scan
startRow: 'test_scanner_fetch_records_in_batch'
endRow: 'test_scanner_fetch_records_in_batch_'
maxVersions: 1
batch: 10
.on 'readable', ->
count.readable++
while record = @read()
count.read++
.on 'error', (err) ->
next err
.on 'end', ->
count.init.should.eql 1
count.scan.should.eql 102
# Node.js <10 = 1001, >10 = 101
count.readable.should.equalOneOf [101, 1001]
count.read.should.eql 1000
next()
|
[
{
"context": "=\n\t\t\t\"code\": \"cliente-\" + Date.now()\n\t\t\t\"email\": \"rodrigoknascimento@gmail.com\"\n\t\t\t\"fullname\": \"Nome Sobrenome\"\n\t\t\t\"cpf\": \"22222",
"end": 1088,
"score": 0.9999138712882996,
"start": 1060,
"tag": "EMAIL",
"value": "rodrigoknascimento@gmail.com"
},
{
"context": "\": \"rodrigoknascimento@gmail.com\"\n\t\t\t\"fullname\": \"Nome Sobrenome\"\n\t\t\t\"cpf\": \"22222222222\"\n\t\t\t\"phone_area_code\": \"1",
"end": 1120,
"score": 0.999882698059082,
"start": 1106,
"tag": "NAME",
"value": "Nome Sobrenome"
},
{
"context": "ng_info\":\n\t\t\t\t\"credit_card\":\n\t\t\t\t\t\"holder_name\": \"Nome Completo\"\n\t\t\t\t\t\"number\": \"4111111111111111\"\n\t\t\t\t\t\"expirati",
"end": 1569,
"score": 0.9997116923332214,
"start": 1556,
"tag": "NAME",
"value": "Nome Completo"
}
] | server/payment.coffee | euajudo/web | 0 | tk = "#{process.env.MOIP_TOKEN}:#{process.env.MOIP_KEY}"
tk = new Buffer(tk).toString('base64')
headers =
Authorization: "Basic #{tk}"
"user-agent": 'Mozilla/4.0'
Meteor.methods
plan: ->
preferencesData = {
"notification": {
"webhook": {
"url": "https://euajudo.localtunnel.me/assinaturas"
},
"email": {
"merchant": {
"enabled": true
},
"customer": {
"enabled": true
}
}
}
}
preferencesResponse = HTTP.post 'https://sandbox.moip.com.br/assinaturas/v1/users/preferences',
data: preferencesData
headers: headers
# console.log 'preferencesResponse', preferencesResponse
planData =
"code": "plano-" + Date.now()
"name": "Plano Especial"
"amount": 100
"setup_fee": 0
"status": "ACTIVE"
"interval":
"length": 1
"unit": "MONTH"
planResponse = HTTP.post 'https://sandbox.moip.com.br/assinaturas/v1/plans',
data: planData
headers: headers
# console.log 'planResponse', planResponse
clientData =
"code": "cliente-" + Date.now()
"email": "rodrigoknascimento@gmail.com"
"fullname": "Nome Sobrenome"
"cpf": "22222222222"
"phone_area_code": "11"
"phone_number": "934343434"
"birthdate_day": "26"
"birthdate_month": "04"
"birthdate_year": "1980"
"address":
"street": "Rua Nome da Rua"
"number": "100"
"complement": "Casa"
"district": "Nome do Bairro"
"city": "São Paulo"
"state": "SP"
"country": "BRA"
"zipcode": "05015010"
"billing_info":
"credit_card":
"holder_name": "Nome Completo"
"number": "4111111111111111"
"expiration_month": "04"
"expiration_year": "15"
clientResponse = HTTP.post "https://sandbox.moip.com.br/assinaturas/v1/customers?new_vault=true",
data: clientData
headers: headers
# console.log 'clientResponse', clientResponse
subscriptionData =
"code": "assinatura-" + Date.now()
"amount": "100"
"plan" :
"code": planData.code
"customer":
"code": clientData.code
subscriptionResponse = HTTP.post "https://sandbox.moip.com.br/assinaturas/v1/subscriptions",
data: subscriptionData
headers: headers
# console.log 'subscriptionResponse', subscriptionResponse
| 150861 | tk = "#{process.env.MOIP_TOKEN}:#{process.env.MOIP_KEY}"
tk = new Buffer(tk).toString('base64')
headers =
Authorization: "Basic #{tk}"
"user-agent": 'Mozilla/4.0'
Meteor.methods
plan: ->
preferencesData = {
"notification": {
"webhook": {
"url": "https://euajudo.localtunnel.me/assinaturas"
},
"email": {
"merchant": {
"enabled": true
},
"customer": {
"enabled": true
}
}
}
}
preferencesResponse = HTTP.post 'https://sandbox.moip.com.br/assinaturas/v1/users/preferences',
data: preferencesData
headers: headers
# console.log 'preferencesResponse', preferencesResponse
planData =
"code": "plano-" + Date.now()
"name": "Plano Especial"
"amount": 100
"setup_fee": 0
"status": "ACTIVE"
"interval":
"length": 1
"unit": "MONTH"
planResponse = HTTP.post 'https://sandbox.moip.com.br/assinaturas/v1/plans',
data: planData
headers: headers
# console.log 'planResponse', planResponse
clientData =
"code": "cliente-" + Date.now()
"email": "<EMAIL>"
"fullname": "<NAME>"
"cpf": "22222222222"
"phone_area_code": "11"
"phone_number": "934343434"
"birthdate_day": "26"
"birthdate_month": "04"
"birthdate_year": "1980"
"address":
"street": "Rua Nome da Rua"
"number": "100"
"complement": "Casa"
"district": "Nome do Bairro"
"city": "São Paulo"
"state": "SP"
"country": "BRA"
"zipcode": "05015010"
"billing_info":
"credit_card":
"holder_name": "<NAME>"
"number": "4111111111111111"
"expiration_month": "04"
"expiration_year": "15"
clientResponse = HTTP.post "https://sandbox.moip.com.br/assinaturas/v1/customers?new_vault=true",
data: clientData
headers: headers
# console.log 'clientResponse', clientResponse
subscriptionData =
"code": "assinatura-" + Date.now()
"amount": "100"
"plan" :
"code": planData.code
"customer":
"code": clientData.code
subscriptionResponse = HTTP.post "https://sandbox.moip.com.br/assinaturas/v1/subscriptions",
data: subscriptionData
headers: headers
# console.log 'subscriptionResponse', subscriptionResponse
| true | tk = "#{process.env.MOIP_TOKEN}:#{process.env.MOIP_KEY}"
tk = new Buffer(tk).toString('base64')
headers =
Authorization: "Basic #{tk}"
"user-agent": 'Mozilla/4.0'
Meteor.methods
plan: ->
preferencesData = {
"notification": {
"webhook": {
"url": "https://euajudo.localtunnel.me/assinaturas"
},
"email": {
"merchant": {
"enabled": true
},
"customer": {
"enabled": true
}
}
}
}
preferencesResponse = HTTP.post 'https://sandbox.moip.com.br/assinaturas/v1/users/preferences',
data: preferencesData
headers: headers
# console.log 'preferencesResponse', preferencesResponse
planData =
"code": "plano-" + Date.now()
"name": "Plano Especial"
"amount": 100
"setup_fee": 0
"status": "ACTIVE"
"interval":
"length": 1
"unit": "MONTH"
planResponse = HTTP.post 'https://sandbox.moip.com.br/assinaturas/v1/plans',
data: planData
headers: headers
# console.log 'planResponse', planResponse
clientData =
"code": "cliente-" + Date.now()
"email": "PI:EMAIL:<EMAIL>END_PI"
"fullname": "PI:NAME:<NAME>END_PI"
"cpf": "22222222222"
"phone_area_code": "11"
"phone_number": "934343434"
"birthdate_day": "26"
"birthdate_month": "04"
"birthdate_year": "1980"
"address":
"street": "Rua Nome da Rua"
"number": "100"
"complement": "Casa"
"district": "Nome do Bairro"
"city": "São Paulo"
"state": "SP"
"country": "BRA"
"zipcode": "05015010"
"billing_info":
"credit_card":
"holder_name": "PI:NAME:<NAME>END_PI"
"number": "4111111111111111"
"expiration_month": "04"
"expiration_year": "15"
clientResponse = HTTP.post "https://sandbox.moip.com.br/assinaturas/v1/customers?new_vault=true",
data: clientData
headers: headers
# console.log 'clientResponse', clientResponse
subscriptionData =
"code": "assinatura-" + Date.now()
"amount": "100"
"plan" :
"code": planData.code
"customer":
"code": clientData.code
subscriptionResponse = HTTP.post "https://sandbox.moip.com.br/assinaturas/v1/subscriptions",
data: subscriptionData
headers: headers
# console.log 'subscriptionResponse', subscriptionResponse
|
[
{
"context": "\" }\n @m.on \"changed\", cb\n @m.set \"key\", 123\n (expect cb).to.have.been.called\n\n it \"d",
"end": 1711,
"score": 0.5801648497581482,
"start": 1709,
"tag": "KEY",
"value": "12"
}
] | plugins/spec/scaleApp.mvc.spec.coffee | flosse/scaleApp | 99 | require?("../../spec/nodeSetup")()
describe "mvc plugin", ->
before ->
if typeof(require) is "function"
@scaleApp = require "../../dist/scaleApp"
@plugin = require "../../dist/plugins/scaleApp.mvc"
else if window?
@scaleApp = window.scaleApp
@plugin = @scaleApp.plugins.mvc
@core = new @scaleApp.Core
@core.use(@plugin).boot()
describe "Model", ->
before -> @m = new @core.Model
it "takes an object as constructor parameter", ->
@m = new @core.Model { key: "value" }
(expect @m.key).to.equal "value"
it "does not override existing keys", ->
@m = new @core.Model { set: "value" }
(expect @m.set).not.to.equal "value"
(expect @m.set).to.be.a "function"
it "provides a on function", ->
(expect @m.on).to.be.a "function"
it "modifies a new value", ->
@m = new @core.Model { key: "value" }
@m.set "key", 123
@m.set "set", 123
#test chain
(@m.set "foo", "foo")
.set( "bar", "bar")
.set("a","b")
(expect @m.key).to.equal 123
(expect @m.get "key").to.equal 123
(expect @m.foo).to.equal "foo"
(expect @m.bar).to.equal "bar"
(expect @m.a).to.equal "b"
(expect @m.set).not.to.equal 123
it "modifies multiple values", ->
@m = new @core.Model { key: "value" }
@m.set { key:123, foo:"bar", num: 321 }
(expect @m.key).to.equal 123
(expect @m.get "key").to.equal 123
(expect @m.foo).to.equal "bar"
(expect @m.num).to.equal 321
it "publishes a 'changed' event", ->
cb = sinon.spy()
@m = new @core.Model { key: "value" }
@m.on "changed", cb
@m.set "key", 123
(expect cb).to.have.been.called
it "does not publishes a 'changed' event if the value is the same", ->
cb = sinon.spy()
@m = new @core.Model { key: "value" }
@m.on "changed", cb
@m.set "key", "value"
(expect cb).not.to.have.been.called
it "can serialized to JSON", ->
class M extends @core.Model
constructor: -> super { key: "value" }
foo: ->
bar: false
@m = new M
j = @m.toJSON()
(expect j.key).to.equal "value"
(expect j.foo).not.to.exist
(expect j.bar).not.to.exist
describe "View", ->
beforeEach ->
@m = new @core.Model { key: "value" }
@v = new @core.View
it "can take a model as constructor parameter", ->
v = new @core.View @m
(expect v.model).to.equal @m
v = new @core.View
(expect v.model).not.to.exist
it "renders the view when the model state changed and the model exists", ->
cb1 = sinon.spy()
cb2 = sinon.spy()
viewWithModel = new @core.View @m
viewWithoutModel = new @core.View
viewWithModel.render = cb1
viewWithoutModel.render = cb2
@m.set "key", "new value"
(expect cb1).to.have.been.called
(expect cb2).not.to.have.been.called
viewWithoutModel.setModel @m
@m.set "key", "an other val"
(expect cb2).to.have.been.called
describe "Controller", ->
beforeEach ->
@m = new @core.Model { key: "value" }
@v = new @core.View @m
it "holds a reference to the model and the view", ->
c = new @core.Controller @m, @v
(expect c.model).to.equal @m
(expect c.view).to.equal @v
| 114352 | require?("../../spec/nodeSetup")()
describe "mvc plugin", ->
before ->
if typeof(require) is "function"
@scaleApp = require "../../dist/scaleApp"
@plugin = require "../../dist/plugins/scaleApp.mvc"
else if window?
@scaleApp = window.scaleApp
@plugin = @scaleApp.plugins.mvc
@core = new @scaleApp.Core
@core.use(@plugin).boot()
describe "Model", ->
before -> @m = new @core.Model
it "takes an object as constructor parameter", ->
@m = new @core.Model { key: "value" }
(expect @m.key).to.equal "value"
it "does not override existing keys", ->
@m = new @core.Model { set: "value" }
(expect @m.set).not.to.equal "value"
(expect @m.set).to.be.a "function"
it "provides a on function", ->
(expect @m.on).to.be.a "function"
it "modifies a new value", ->
@m = new @core.Model { key: "value" }
@m.set "key", 123
@m.set "set", 123
#test chain
(@m.set "foo", "foo")
.set( "bar", "bar")
.set("a","b")
(expect @m.key).to.equal 123
(expect @m.get "key").to.equal 123
(expect @m.foo).to.equal "foo"
(expect @m.bar).to.equal "bar"
(expect @m.a).to.equal "b"
(expect @m.set).not.to.equal 123
it "modifies multiple values", ->
@m = new @core.Model { key: "value" }
@m.set { key:123, foo:"bar", num: 321 }
(expect @m.key).to.equal 123
(expect @m.get "key").to.equal 123
(expect @m.foo).to.equal "bar"
(expect @m.num).to.equal 321
it "publishes a 'changed' event", ->
cb = sinon.spy()
@m = new @core.Model { key: "value" }
@m.on "changed", cb
@m.set "key", <KEY>3
(expect cb).to.have.been.called
it "does not publishes a 'changed' event if the value is the same", ->
cb = sinon.spy()
@m = new @core.Model { key: "value" }
@m.on "changed", cb
@m.set "key", "value"
(expect cb).not.to.have.been.called
it "can serialized to JSON", ->
class M extends @core.Model
constructor: -> super { key: "value" }
foo: ->
bar: false
@m = new M
j = @m.toJSON()
(expect j.key).to.equal "value"
(expect j.foo).not.to.exist
(expect j.bar).not.to.exist
describe "View", ->
beforeEach ->
@m = new @core.Model { key: "value" }
@v = new @core.View
it "can take a model as constructor parameter", ->
v = new @core.View @m
(expect v.model).to.equal @m
v = new @core.View
(expect v.model).not.to.exist
it "renders the view when the model state changed and the model exists", ->
cb1 = sinon.spy()
cb2 = sinon.spy()
viewWithModel = new @core.View @m
viewWithoutModel = new @core.View
viewWithModel.render = cb1
viewWithoutModel.render = cb2
@m.set "key", "new value"
(expect cb1).to.have.been.called
(expect cb2).not.to.have.been.called
viewWithoutModel.setModel @m
@m.set "key", "an other val"
(expect cb2).to.have.been.called
describe "Controller", ->
beforeEach ->
@m = new @core.Model { key: "value" }
@v = new @core.View @m
it "holds a reference to the model and the view", ->
c = new @core.Controller @m, @v
(expect c.model).to.equal @m
(expect c.view).to.equal @v
| true | require?("../../spec/nodeSetup")()
describe "mvc plugin", ->
before ->
if typeof(require) is "function"
@scaleApp = require "../../dist/scaleApp"
@plugin = require "../../dist/plugins/scaleApp.mvc"
else if window?
@scaleApp = window.scaleApp
@plugin = @scaleApp.plugins.mvc
@core = new @scaleApp.Core
@core.use(@plugin).boot()
describe "Model", ->
before -> @m = new @core.Model
it "takes an object as constructor parameter", ->
@m = new @core.Model { key: "value" }
(expect @m.key).to.equal "value"
it "does not override existing keys", ->
@m = new @core.Model { set: "value" }
(expect @m.set).not.to.equal "value"
(expect @m.set).to.be.a "function"
it "provides a on function", ->
(expect @m.on).to.be.a "function"
it "modifies a new value", ->
@m = new @core.Model { key: "value" }
@m.set "key", 123
@m.set "set", 123
#test chain
(@m.set "foo", "foo")
.set( "bar", "bar")
.set("a","b")
(expect @m.key).to.equal 123
(expect @m.get "key").to.equal 123
(expect @m.foo).to.equal "foo"
(expect @m.bar).to.equal "bar"
(expect @m.a).to.equal "b"
(expect @m.set).not.to.equal 123
it "modifies multiple values", ->
@m = new @core.Model { key: "value" }
@m.set { key:123, foo:"bar", num: 321 }
(expect @m.key).to.equal 123
(expect @m.get "key").to.equal 123
(expect @m.foo).to.equal "bar"
(expect @m.num).to.equal 321
it "publishes a 'changed' event", ->
cb = sinon.spy()
@m = new @core.Model { key: "value" }
@m.on "changed", cb
@m.set "key", PI:KEY:<KEY>END_PI3
(expect cb).to.have.been.called
it "does not publishes a 'changed' event if the value is the same", ->
cb = sinon.spy()
@m = new @core.Model { key: "value" }
@m.on "changed", cb
@m.set "key", "value"
(expect cb).not.to.have.been.called
it "can serialized to JSON", ->
class M extends @core.Model
constructor: -> super { key: "value" }
foo: ->
bar: false
@m = new M
j = @m.toJSON()
(expect j.key).to.equal "value"
(expect j.foo).not.to.exist
(expect j.bar).not.to.exist
describe "View", ->
beforeEach ->
@m = new @core.Model { key: "value" }
@v = new @core.View
it "can take a model as constructor parameter", ->
v = new @core.View @m
(expect v.model).to.equal @m
v = new @core.View
(expect v.model).not.to.exist
it "renders the view when the model state changed and the model exists", ->
cb1 = sinon.spy()
cb2 = sinon.spy()
viewWithModel = new @core.View @m
viewWithoutModel = new @core.View
viewWithModel.render = cb1
viewWithoutModel.render = cb2
@m.set "key", "new value"
(expect cb1).to.have.been.called
(expect cb2).not.to.have.been.called
viewWithoutModel.setModel @m
@m.set "key", "an other val"
(expect cb2).to.have.been.called
describe "Controller", ->
beforeEach ->
@m = new @core.Model { key: "value" }
@v = new @core.View @m
it "holds a reference to the model and the view", ->
c = new @core.Controller @m, @v
(expect c.model).to.equal @m
(expect c.view).to.equal @v
|
[
{
"context": "ueKey> - assigns the issue to user\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nrequest = require 'request-b'\np",
"end": 292,
"score": 0.9997073411941528,
"start": 285,
"tag": "USERNAME",
"value": "bouzuya"
},
{
"context": "ssigns the issue to user\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nrequest = require 'request-b'\nparseConfig = re",
"end": 307,
"score": 0.9999179840087891,
"start": 294,
"tag": "EMAIL",
"value": "m@bouzuya.net"
},
{
"context": ", projectKey, issueNo, reviewer) ->\n issueKey = \"#{projectKey}-#{issueNo}\"\n githubUrl = null\n comment = null\n assig",
"end": 2038,
"score": 0.9972674250602722,
"start": 2012,
"tag": "KEY",
"value": "\"#{projectKey}-#{issueNo}\""
}
] | src/scripts/backlog-assign.coffee | bouzuya/hubot-backlog-assign | 0 | # Description
# A Hubot script that assigns the backlog issue to reviewer
#
# Configuration:
# HUBOT_BACKLOG_ASSIGN_SPACE_ID
# HUBOT_BACKLOG_ASSIGN_API_KEY
# HUBOT_BACKLOG_ASSIGN_USER_NAMES
#
# Commands:
# <user> review <issueKey> - assigns the issue to user
#
# Author:
# bouzuya <m@bouzuya.net>
#
request = require 'request-b'
parseConfig = require 'hubot-config'
module.exports = (robot) ->
config =
parseConfig 'backlog-assign',
spaceId: null
apiKey: null
userNames: '{}'
config.userNames = JSON.parse(config.userNames)
baseUrl = "https://#{config.spaceId}.backlog.jp"
getIssue = (issueKey) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/issues/#{issueKey}"
qs:
apiKey: config.apiKey
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
getGithubUrl = (issueKey) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/issues/#{issueKey}/comments"
qs:
apiKey: config.apiKey
order: 'desc'
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
.map (c) ->
c.content?.match(/(https:\/\/github\.com\/\S+)/)?[1]
.filter((m) -> m)[0]
getUser = (projectKey, name) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/projects/#{projectKey}/users"
qs:
apiKey: config.apiKey
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
users = JSON.parse(res.body)
users.filter((u) -> u.userId is name)[0]
updateIssue = ({ issueKey, assigneeId, comment }) ->
request
method: 'PATCH'
url: "#{baseUrl}/api/v2/issues/#{issueKey}"
qs:
apiKey: config.apiKey
form:
assigneeId: assigneeId
comment: comment
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
assign = (res, projectKey, issueNo, reviewer) ->
issueKey = "#{projectKey}-#{issueNo}"
githubUrl = null
comment = null
assigneeId = null
getIssue(issueKey)
.then (issue) ->
return res.send("""
#{issue.issueKey} #{issue.summary}
#{baseUrl}/view/#{issue.issueKey}
まだ処理中ですよ?
""") unless issue.status.id is 3
getGithubUrl(issueKey)
.then (g) ->
githubUrl = g
comment = """
レビューをおねがいします。
#{githubUrl}
"""
getUser projectKey, reviewer
.then (u) ->
assigneeId = u.id
.then ->
updateIssue { issueKey, assigneeId, comment }
.then (issue) ->
res.send """
#{issue.issueKey} #{issue.summary}
#{baseUrl}/view/#{issue.issueKey}
#{comment}
"""
.then null, (e) ->
res.robot.logger.error(e)
res.send 'hubot-backlog-assign: error'
robot.hear /^[@]?([^:,\s]+)[:,]?\s*(?:review ([a-zA-Z_]+)-(\d+)$)/, (res) ->
reviewerChatName = res.match[1]
projectKey = res.match[2]
issueNo = res.match[3]
reviewerName = config.userNames[reviewerChatName]
return res.send """
unknown user: #{reviewerChatName}
please set HUBOT_BACKLOG_ASSIGN_USER_NAMES.
HUBOT_BACKLOG_ASSIGN_USER_NAMES='{"#{reviewerChatName}":"<backlog name>"}'
""" unless reviewerName?
assign res, projectKey, issueNo, reviewerName
| 99551 | # Description
# A Hubot script that assigns the backlog issue to reviewer
#
# Configuration:
# HUBOT_BACKLOG_ASSIGN_SPACE_ID
# HUBOT_BACKLOG_ASSIGN_API_KEY
# HUBOT_BACKLOG_ASSIGN_USER_NAMES
#
# Commands:
# <user> review <issueKey> - assigns the issue to user
#
# Author:
# bouzuya <<EMAIL>>
#
request = require 'request-b'
parseConfig = require 'hubot-config'
module.exports = (robot) ->
config =
parseConfig 'backlog-assign',
spaceId: null
apiKey: null
userNames: '{}'
config.userNames = JSON.parse(config.userNames)
baseUrl = "https://#{config.spaceId}.backlog.jp"
getIssue = (issueKey) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/issues/#{issueKey}"
qs:
apiKey: config.apiKey
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
getGithubUrl = (issueKey) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/issues/#{issueKey}/comments"
qs:
apiKey: config.apiKey
order: 'desc'
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
.map (c) ->
c.content?.match(/(https:\/\/github\.com\/\S+)/)?[1]
.filter((m) -> m)[0]
getUser = (projectKey, name) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/projects/#{projectKey}/users"
qs:
apiKey: config.apiKey
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
users = JSON.parse(res.body)
users.filter((u) -> u.userId is name)[0]
updateIssue = ({ issueKey, assigneeId, comment }) ->
request
method: 'PATCH'
url: "#{baseUrl}/api/v2/issues/#{issueKey}"
qs:
apiKey: config.apiKey
form:
assigneeId: assigneeId
comment: comment
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
assign = (res, projectKey, issueNo, reviewer) ->
issueKey = <KEY>
githubUrl = null
comment = null
assigneeId = null
getIssue(issueKey)
.then (issue) ->
return res.send("""
#{issue.issueKey} #{issue.summary}
#{baseUrl}/view/#{issue.issueKey}
まだ処理中ですよ?
""") unless issue.status.id is 3
getGithubUrl(issueKey)
.then (g) ->
githubUrl = g
comment = """
レビューをおねがいします。
#{githubUrl}
"""
getUser projectKey, reviewer
.then (u) ->
assigneeId = u.id
.then ->
updateIssue { issueKey, assigneeId, comment }
.then (issue) ->
res.send """
#{issue.issueKey} #{issue.summary}
#{baseUrl}/view/#{issue.issueKey}
#{comment}
"""
.then null, (e) ->
res.robot.logger.error(e)
res.send 'hubot-backlog-assign: error'
robot.hear /^[@]?([^:,\s]+)[:,]?\s*(?:review ([a-zA-Z_]+)-(\d+)$)/, (res) ->
reviewerChatName = res.match[1]
projectKey = res.match[2]
issueNo = res.match[3]
reviewerName = config.userNames[reviewerChatName]
return res.send """
unknown user: #{reviewerChatName}
please set HUBOT_BACKLOG_ASSIGN_USER_NAMES.
HUBOT_BACKLOG_ASSIGN_USER_NAMES='{"#{reviewerChatName}":"<backlog name>"}'
""" unless reviewerName?
assign res, projectKey, issueNo, reviewerName
| true | # Description
# A Hubot script that assigns the backlog issue to reviewer
#
# Configuration:
# HUBOT_BACKLOG_ASSIGN_SPACE_ID
# HUBOT_BACKLOG_ASSIGN_API_KEY
# HUBOT_BACKLOG_ASSIGN_USER_NAMES
#
# Commands:
# <user> review <issueKey> - assigns the issue to user
#
# Author:
# bouzuya <PI:EMAIL:<EMAIL>END_PI>
#
request = require 'request-b'
parseConfig = require 'hubot-config'
module.exports = (robot) ->
config =
parseConfig 'backlog-assign',
spaceId: null
apiKey: null
userNames: '{}'
config.userNames = JSON.parse(config.userNames)
baseUrl = "https://#{config.spaceId}.backlog.jp"
getIssue = (issueKey) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/issues/#{issueKey}"
qs:
apiKey: config.apiKey
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
getGithubUrl = (issueKey) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/issues/#{issueKey}/comments"
qs:
apiKey: config.apiKey
order: 'desc'
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
.map (c) ->
c.content?.match(/(https:\/\/github\.com\/\S+)/)?[1]
.filter((m) -> m)[0]
getUser = (projectKey, name) ->
request
method: 'GET'
url: "#{baseUrl}/api/v2/projects/#{projectKey}/users"
qs:
apiKey: config.apiKey
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
users = JSON.parse(res.body)
users.filter((u) -> u.userId is name)[0]
updateIssue = ({ issueKey, assigneeId, comment }) ->
request
method: 'PATCH'
url: "#{baseUrl}/api/v2/issues/#{issueKey}"
qs:
apiKey: config.apiKey
form:
assigneeId: assigneeId
comment: comment
.then (res) ->
throw new Error(res.body) if res.statusCode >= 400
JSON.parse(res.body)
assign = (res, projectKey, issueNo, reviewer) ->
issueKey = PI:KEY:<KEY>END_PI
githubUrl = null
comment = null
assigneeId = null
getIssue(issueKey)
.then (issue) ->
return res.send("""
#{issue.issueKey} #{issue.summary}
#{baseUrl}/view/#{issue.issueKey}
まだ処理中ですよ?
""") unless issue.status.id is 3
getGithubUrl(issueKey)
.then (g) ->
githubUrl = g
comment = """
レビューをおねがいします。
#{githubUrl}
"""
getUser projectKey, reviewer
.then (u) ->
assigneeId = u.id
.then ->
updateIssue { issueKey, assigneeId, comment }
.then (issue) ->
res.send """
#{issue.issueKey} #{issue.summary}
#{baseUrl}/view/#{issue.issueKey}
#{comment}
"""
.then null, (e) ->
res.robot.logger.error(e)
res.send 'hubot-backlog-assign: error'
robot.hear /^[@]?([^:,\s]+)[:,]?\s*(?:review ([a-zA-Z_]+)-(\d+)$)/, (res) ->
reviewerChatName = res.match[1]
projectKey = res.match[2]
issueNo = res.match[3]
reviewerName = config.userNames[reviewerChatName]
return res.send """
unknown user: #{reviewerChatName}
please set HUBOT_BACKLOG_ASSIGN_USER_NAMES.
HUBOT_BACKLOG_ASSIGN_USER_NAMES='{"#{reviewerChatName}":"<backlog name>"}'
""" unless reviewerName?
assign res, projectKey, issueNo, reviewerName
|
[
{
"context": "# A simple extension to Xiaolin Wu's line drawing algorithm to draw thick l",
"end": 25,
"score": 0.7730218768119812,
"start": 24,
"tag": "NAME",
"value": "X"
},
{
"context": "# A simple extension to Xiaolin Wu's line drawing algorithm to draw thick lines.\n",
"end": 31,
"score": 0.5761699676513672,
"start": 27,
"tag": "NAME",
"value": "olin"
}
] | cs/thick-xiaolin-wu.coffee | jambolo/thick-xiaolin-wu | 0 | # A simple extension to Xiaolin Wu's line drawing algorithm to draw thick lines.
#
# Adapted from https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm
#
drawLine = (x0, y0, x1, y1, w, drawPixel) ->
# Ensure positive integer values for width
if w < 1
w = 1
# If drawing a dot, the call drawDot function
#if Math.abs(y1 - y0) < 1.0 && Math.abs(x1 - x0) < 1.0
# #drawDot (x0 + x1) / 2, (y0 + y1) / 2
# return
# steep means that m > 1
steep = Math.abs(y1 - y0) > Math.abs(x1 - x0)
# If steep, then x and y must be swapped because the width is fixed in the y direction and that won't work if
# dx < dy. Note that they are swapped again when plotting.
if steep
[x0, y0] = [y0, x0]
[x1, y1] = [y1, x1]
# Swap endpoints to ensure that dx > 0
if x0 > x1
[x0, x1] = [x1, x0]
[y0, y1] = [y1, y0]
dx = x1 - x0
dy = y1 - y0
gradient = if dx > 0 then dy / dx else 1.0
# Rotate w
w = w * Math.sqrt(1 + (gradient * gradient))
# Handle first endpoint
xend = Math.round(x0)
yend = y0 - (w - 1) * 0.5 + gradient * (xend - x0)
xgap = 1 - (x0 + 0.5 - xend)
xpxl1 = xend # this will be used in the main loop
ypxl1 = Math.floor(yend)
fpart = yend - Math.floor(yend)
rfpart = 1 - fpart
if steep
drawPixel ypxl1 , xpxl1, rfpart * xgap
drawPixel ypxl1 + i, xpxl1, 1 for i in [1...w]
drawPixel ypxl1 + w, xpxl1, fpart * xgap
else
drawPixel xpxl1, ypxl1 , rfpart * xgap
drawPixel xpxl1, ypxl1 + i, 1 for i in [1...w]
drawPixel xpxl1, ypxl1 + w, fpart * xgap
intery = yend + gradient # first y-intersection for the main loop
# Handle second endpoint
xend = Math.round(x1)
yend = y1 - (w - 1) * 0.5 + gradient * (xend - x1)
xgap = 1 - (x1 + 0.5 - xend)
xpxl2 = xend # this will be used in the main loop
ypxl2 = Math.floor(yend)
fpart = yend - Math.floor(yend)
rfpart = 1 - fpart
if steep
drawPixel ypxl2 , xpxl2, rfpart * xgap
drawPixel ypxl2 + i, xpxl2, 1 for i in [1...w]
drawPixel ypxl2 + w, xpxl2, fpart * xgap
else
drawPixel xpxl2, ypxl2 , rfpart * xgap
drawPixel xpxl2, ypxl2 + i, 1 for i in [1...w]
drawPixel xpxl2, ypxl2 + w, fpart * xgap
# main loop
if steep
for x in [xpxl1 + 1...xpxl2]
fpart = intery - Math.floor(intery)
rfpart = 1 - fpart
y = Math.floor(intery)
drawPixel y , x, rfpart
drawPixel y + i, x, 1 for i in [1...w]
drawPixel y + w, x, fpart
intery = intery + gradient
else
for x in [xpxl1 + 1...xpxl2]
fpart = intery - Math.floor(intery)
rfpart = 1 - fpart
y = Math.floor(intery)
drawPixel x, y , rfpart
drawPixel x, y + i, 1 for i in [1...w]
drawPixel x, y + w, fpart
intery = intery + gradient
return
| 104503 | # A simple extension to <NAME>ia<NAME> Wu's line drawing algorithm to draw thick lines.
#
# Adapted from https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm
#
drawLine = (x0, y0, x1, y1, w, drawPixel) ->
# Ensure positive integer values for width
if w < 1
w = 1
# If drawing a dot, the call drawDot function
#if Math.abs(y1 - y0) < 1.0 && Math.abs(x1 - x0) < 1.0
# #drawDot (x0 + x1) / 2, (y0 + y1) / 2
# return
# steep means that m > 1
steep = Math.abs(y1 - y0) > Math.abs(x1 - x0)
# If steep, then x and y must be swapped because the width is fixed in the y direction and that won't work if
# dx < dy. Note that they are swapped again when plotting.
if steep
[x0, y0] = [y0, x0]
[x1, y1] = [y1, x1]
# Swap endpoints to ensure that dx > 0
if x0 > x1
[x0, x1] = [x1, x0]
[y0, y1] = [y1, y0]
dx = x1 - x0
dy = y1 - y0
gradient = if dx > 0 then dy / dx else 1.0
# Rotate w
w = w * Math.sqrt(1 + (gradient * gradient))
# Handle first endpoint
xend = Math.round(x0)
yend = y0 - (w - 1) * 0.5 + gradient * (xend - x0)
xgap = 1 - (x0 + 0.5 - xend)
xpxl1 = xend # this will be used in the main loop
ypxl1 = Math.floor(yend)
fpart = yend - Math.floor(yend)
rfpart = 1 - fpart
if steep
drawPixel ypxl1 , xpxl1, rfpart * xgap
drawPixel ypxl1 + i, xpxl1, 1 for i in [1...w]
drawPixel ypxl1 + w, xpxl1, fpart * xgap
else
drawPixel xpxl1, ypxl1 , rfpart * xgap
drawPixel xpxl1, ypxl1 + i, 1 for i in [1...w]
drawPixel xpxl1, ypxl1 + w, fpart * xgap
intery = yend + gradient # first y-intersection for the main loop
# Handle second endpoint
xend = Math.round(x1)
yend = y1 - (w - 1) * 0.5 + gradient * (xend - x1)
xgap = 1 - (x1 + 0.5 - xend)
xpxl2 = xend # this will be used in the main loop
ypxl2 = Math.floor(yend)
fpart = yend - Math.floor(yend)
rfpart = 1 - fpart
if steep
drawPixel ypxl2 , xpxl2, rfpart * xgap
drawPixel ypxl2 + i, xpxl2, 1 for i in [1...w]
drawPixel ypxl2 + w, xpxl2, fpart * xgap
else
drawPixel xpxl2, ypxl2 , rfpart * xgap
drawPixel xpxl2, ypxl2 + i, 1 for i in [1...w]
drawPixel xpxl2, ypxl2 + w, fpart * xgap
# main loop
if steep
for x in [xpxl1 + 1...xpxl2]
fpart = intery - Math.floor(intery)
rfpart = 1 - fpart
y = Math.floor(intery)
drawPixel y , x, rfpart
drawPixel y + i, x, 1 for i in [1...w]
drawPixel y + w, x, fpart
intery = intery + gradient
else
for x in [xpxl1 + 1...xpxl2]
fpart = intery - Math.floor(intery)
rfpart = 1 - fpart
y = Math.floor(intery)
drawPixel x, y , rfpart
drawPixel x, y + i, 1 for i in [1...w]
drawPixel x, y + w, fpart
intery = intery + gradient
return
| true | # A simple extension to PI:NAME:<NAME>END_PIiaPI:NAME:<NAME>END_PI Wu's line drawing algorithm to draw thick lines.
#
# Adapted from https://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm
#
drawLine = (x0, y0, x1, y1, w, drawPixel) ->
# Ensure positive integer values for width
if w < 1
w = 1
# If drawing a dot, the call drawDot function
#if Math.abs(y1 - y0) < 1.0 && Math.abs(x1 - x0) < 1.0
# #drawDot (x0 + x1) / 2, (y0 + y1) / 2
# return
# steep means that m > 1
steep = Math.abs(y1 - y0) > Math.abs(x1 - x0)
# If steep, then x and y must be swapped because the width is fixed in the y direction and that won't work if
# dx < dy. Note that they are swapped again when plotting.
if steep
[x0, y0] = [y0, x0]
[x1, y1] = [y1, x1]
# Swap endpoints to ensure that dx > 0
if x0 > x1
[x0, x1] = [x1, x0]
[y0, y1] = [y1, y0]
dx = x1 - x0
dy = y1 - y0
gradient = if dx > 0 then dy / dx else 1.0
# Rotate w
w = w * Math.sqrt(1 + (gradient * gradient))
# Handle first endpoint
xend = Math.round(x0)
yend = y0 - (w - 1) * 0.5 + gradient * (xend - x0)
xgap = 1 - (x0 + 0.5 - xend)
xpxl1 = xend # this will be used in the main loop
ypxl1 = Math.floor(yend)
fpart = yend - Math.floor(yend)
rfpart = 1 - fpart
if steep
drawPixel ypxl1 , xpxl1, rfpart * xgap
drawPixel ypxl1 + i, xpxl1, 1 for i in [1...w]
drawPixel ypxl1 + w, xpxl1, fpart * xgap
else
drawPixel xpxl1, ypxl1 , rfpart * xgap
drawPixel xpxl1, ypxl1 + i, 1 for i in [1...w]
drawPixel xpxl1, ypxl1 + w, fpart * xgap
intery = yend + gradient # first y-intersection for the main loop
# Handle second endpoint
xend = Math.round(x1)
yend = y1 - (w - 1) * 0.5 + gradient * (xend - x1)
xgap = 1 - (x1 + 0.5 - xend)
xpxl2 = xend # this will be used in the main loop
ypxl2 = Math.floor(yend)
fpart = yend - Math.floor(yend)
rfpart = 1 - fpart
if steep
drawPixel ypxl2 , xpxl2, rfpart * xgap
drawPixel ypxl2 + i, xpxl2, 1 for i in [1...w]
drawPixel ypxl2 + w, xpxl2, fpart * xgap
else
drawPixel xpxl2, ypxl2 , rfpart * xgap
drawPixel xpxl2, ypxl2 + i, 1 for i in [1...w]
drawPixel xpxl2, ypxl2 + w, fpart * xgap
# main loop
if steep
for x in [xpxl1 + 1...xpxl2]
fpart = intery - Math.floor(intery)
rfpart = 1 - fpart
y = Math.floor(intery)
drawPixel y , x, rfpart
drawPixel y + i, x, 1 for i in [1...w]
drawPixel y + w, x, fpart
intery = intery + gradient
else
for x in [xpxl1 + 1...xpxl2]
fpart = intery - Math.floor(intery)
rfpart = 1 - fpart
y = Math.floor(intery)
drawPixel x, y , rfpart
drawPixel x, y + i, 1 for i in [1...w]
drawPixel x, y + w, fpart
intery = intery + gradient
return
|
[
{
"context": "ionController.doLogin {email:user.email, password: password}, req, res, next\n\t\t\t\t\telse\n\t\t\t\t\t\tres.sendStatus 2",
"end": 2138,
"score": 0.9979998469352722,
"start": 2130,
"tag": "PASSWORD",
"value": "password"
}
] | app/coffee/Features/PasswordReset/PasswordResetController.coffee | bowlofstew/web-sharelatex | 0 | PasswordResetHandler = require("./PasswordResetHandler")
RateLimiter = require("../../infrastructure/RateLimiter")
AuthenticationController = require("../Authentication/AuthenticationController")
UserGetter = require("../User/UserGetter")
UserSessionsManager = require("../User/UserSessionsManager")
logger = require "logger-sharelatex"
module.exports =
renderRequestResetForm: (req, res)->
logger.log "rendering request reset form"
res.render "user/passwordReset",
title:"reset_password"
requestReset: (req, res)->
email = req.body.email.trim().toLowerCase()
opts =
endpointName: "password_reset_rate_limit"
timeInterval: 60
subjectName: req.ip
throttle: 6
RateLimiter.addCount opts, (err, canContinue)->
if !canContinue
return res.send 500, { message: req.i18n.translate("rate_limit_hit_wait")}
PasswordResetHandler.generateAndEmailResetToken email, (err, exists)->
if err?
res.send 500, {message:err?.message}
else if exists
res.sendStatus 200
else
res.send 404, {message: req.i18n.translate("cant_find_email")}
renderSetPasswordForm: (req, res)->
if req.query.passwordResetToken?
req.session.resetToken = req.query.passwordResetToken
return res.redirect('/user/password/set')
if !req.session.resetToken?
return res.redirect('/user/password/reset')
res.render "user/setPassword",
title:"set_password"
passwordResetToken: req.session.resetToken
setNewUserPassword: (req, res, next)->
{passwordResetToken, password} = req.body
if !password? or password.length == 0 or !passwordResetToken? or passwordResetToken.length == 0
return res.sendStatus 400
delete req.session.resetToken
PasswordResetHandler.setNewUserPassword passwordResetToken?.trim(), password?.trim(), (err, found, user_id) ->
return next(err) if err?
if found
UserSessionsManager.revokeAllUserSessions {_id: user_id}, [], (err) ->
return next(err) if err?
if req.body.login_after
UserGetter.getUser user_id, {email: 1}, (err, user) ->
return next(err) if err?
AuthenticationController.doLogin {email:user.email, password: password}, req, res, next
else
res.sendStatus 200
else
res.sendStatus 404
| 29600 | PasswordResetHandler = require("./PasswordResetHandler")
RateLimiter = require("../../infrastructure/RateLimiter")
AuthenticationController = require("../Authentication/AuthenticationController")
UserGetter = require("../User/UserGetter")
UserSessionsManager = require("../User/UserSessionsManager")
logger = require "logger-sharelatex"
module.exports =
renderRequestResetForm: (req, res)->
logger.log "rendering request reset form"
res.render "user/passwordReset",
title:"reset_password"
requestReset: (req, res)->
email = req.body.email.trim().toLowerCase()
opts =
endpointName: "password_reset_rate_limit"
timeInterval: 60
subjectName: req.ip
throttle: 6
RateLimiter.addCount opts, (err, canContinue)->
if !canContinue
return res.send 500, { message: req.i18n.translate("rate_limit_hit_wait")}
PasswordResetHandler.generateAndEmailResetToken email, (err, exists)->
if err?
res.send 500, {message:err?.message}
else if exists
res.sendStatus 200
else
res.send 404, {message: req.i18n.translate("cant_find_email")}
renderSetPasswordForm: (req, res)->
if req.query.passwordResetToken?
req.session.resetToken = req.query.passwordResetToken
return res.redirect('/user/password/set')
if !req.session.resetToken?
return res.redirect('/user/password/reset')
res.render "user/setPassword",
title:"set_password"
passwordResetToken: req.session.resetToken
setNewUserPassword: (req, res, next)->
{passwordResetToken, password} = req.body
if !password? or password.length == 0 or !passwordResetToken? or passwordResetToken.length == 0
return res.sendStatus 400
delete req.session.resetToken
PasswordResetHandler.setNewUserPassword passwordResetToken?.trim(), password?.trim(), (err, found, user_id) ->
return next(err) if err?
if found
UserSessionsManager.revokeAllUserSessions {_id: user_id}, [], (err) ->
return next(err) if err?
if req.body.login_after
UserGetter.getUser user_id, {email: 1}, (err, user) ->
return next(err) if err?
AuthenticationController.doLogin {email:user.email, password: <PASSWORD>}, req, res, next
else
res.sendStatus 200
else
res.sendStatus 404
| true | PasswordResetHandler = require("./PasswordResetHandler")
RateLimiter = require("../../infrastructure/RateLimiter")
AuthenticationController = require("../Authentication/AuthenticationController")
UserGetter = require("../User/UserGetter")
UserSessionsManager = require("../User/UserSessionsManager")
logger = require "logger-sharelatex"
module.exports =
renderRequestResetForm: (req, res)->
logger.log "rendering request reset form"
res.render "user/passwordReset",
title:"reset_password"
requestReset: (req, res)->
email = req.body.email.trim().toLowerCase()
opts =
endpointName: "password_reset_rate_limit"
timeInterval: 60
subjectName: req.ip
throttle: 6
RateLimiter.addCount opts, (err, canContinue)->
if !canContinue
return res.send 500, { message: req.i18n.translate("rate_limit_hit_wait")}
PasswordResetHandler.generateAndEmailResetToken email, (err, exists)->
if err?
res.send 500, {message:err?.message}
else if exists
res.sendStatus 200
else
res.send 404, {message: req.i18n.translate("cant_find_email")}
renderSetPasswordForm: (req, res)->
if req.query.passwordResetToken?
req.session.resetToken = req.query.passwordResetToken
return res.redirect('/user/password/set')
if !req.session.resetToken?
return res.redirect('/user/password/reset')
res.render "user/setPassword",
title:"set_password"
passwordResetToken: req.session.resetToken
setNewUserPassword: (req, res, next)->
{passwordResetToken, password} = req.body
if !password? or password.length == 0 or !passwordResetToken? or passwordResetToken.length == 0
return res.sendStatus 400
delete req.session.resetToken
PasswordResetHandler.setNewUserPassword passwordResetToken?.trim(), password?.trim(), (err, found, user_id) ->
return next(err) if err?
if found
UserSessionsManager.revokeAllUserSessions {_id: user_id}, [], (err) ->
return next(err) if err?
if req.body.login_after
UserGetter.getUser user_id, {email: 1}, (err, user) ->
return next(err) if err?
AuthenticationController.doLogin {email:user.email, password: PI:PASSWORD:<PASSWORD>END_PI}, req, res, next
else
res.sendStatus 200
else
res.sendStatus 404
|
[
{
"context": "t-name'), name: element.data('name') }\n key = \"#{element.data('model')}:#{element.data('artist-name')};#{element.data('name')}\".toLo",
"end": 1571,
"score": 0.8410007953643799,
"start": 1535,
"tag": "KEY",
"value": "\"#{element.data('model')}:#{element."
},
{
"context": " key = \"#{element.data('model')}:#{element.data('artist-name')};#{element.data('name')}\".toLowerCase()\n window.spotify_player_list.resourceToIndex[",
"end": 1630,
"score": 0.889757513999939,
"start": 1577,
"tag": "KEY",
"value": "artist-name')};#{element.data('name')}\".toLowerCase()"
}
] | app/assets/javascripts/home_page_music/shared/spotify_player_list.js.coffee | home-page/home_page_music | 1 | class @SpotifyPlayerList
constructor: ->
window.spotify_player_list = {}
$(document.body).on "click", ".spotify_player_list_item_play_button", (event) ->
event.preventDefault()
model = $(this).parents('.spotify_player_list_item').data('model')
iframeHtml = if model == 'Track'
'<iframe src="https://embed.spotify.com/?uri=spotify:track:' + $(this).data('spotify-id') + '&view=coverart" frameborder="0" allowtransparency="true" width="300" height="80"></iframe>'
else
'<iframe src="https://embed.spotify.com/?uri=spotify:album:' + $(this).data('spotify-id') + '" frameborder="0" allowtransparency="true" width="300" height="380"></iframe>'
modalBodyHtml = """
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Play #{model}</h4>
</div>
<div class="modal-body" style="overflow-y:none;">
#{iframeHtml}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
"""
$('.modal-content').html(modalBodyHtml)
$('#modal').modal('show')
musicResources = { track: [], release: [] }
window.spotify_player_list.resourceToIndex = {}
$.each $('.spotify_player_list_item'), (index, element) =>
element = $(element)
resource = { artist_name: element.data('artist-name'), name: element.data('name') }
key = "#{element.data('model')}:#{element.data('artist-name')};#{element.data('name')}".toLowerCase()
window.spotify_player_list.resourceToIndex[key] = [] if window.spotify_player_list.resourceToIndex[key] == undefined
window.spotify_player_list.resourceToIndex[key].push index
if element.data('model') == 'Track'
musicResources['track'].push resource
else
musicResources['release'].push resource
@bulkRequest(musicResources, ['Track', 'Release'])
bulkRequest: (musicResources, models) ->
return if models.length == 0
model = null
resources = []
resources_count = 0
while resources_count == 0
model = models.shift()
window.spotify_player_list.model = model
window.spotify_player_list.models = models
resources = musicResources[model.toLowerCase()]
resources_count = resources.length
break if resources_count > 0
return if models.length == 0
data = {}
if model == 'Track'
data['tracks'] = resources
else
data['releases'] = resources
$.ajax(
url: "#{volontariatHost}/api/v1/music/#{model.toLowerCase()}s/bulk",
type: 'POST', dataType: 'json', data: data
).done((data) =>
$.each data, (index, element) =>
listItemIndexes = window.spotify_player_list.resourceToIndex["#{model}:#{element['artist_name']};#{element['name']}".toLowerCase()]
$.each listItemIndexes, (index, listItemIndex) =>
listItem = $('.spotify_player_list_item')[listItemIndex]
unless element['spotify_id'] == null
button = $(listItem).find('.spotify_player_list_item_play_icon')
$(button).data('spotify-id', element['spotify_id'])
$(button).addClass('spotify_player_list_item_play_button')
$(button).removeClass('hide')
$(listItem).find('.spotify_player_list_item_spinner').hide()
).fail((data) =>
$.each $('.spotify_player_list_item'), (index, element) =>
element = $(element)
if element.data('model') == window.spotify_player_list.model
listItemIndexes = window.spotify_player_list.resourceToIndex["#{model}:#{element.data('artist-name')};#{element.data('name')}".toLowerCase()]
$.each listItemIndexes, (index, listItemIndex) =>
listItem = $('.spotify_player_list_item')[listItemIndex]
$(listItem).find('.spotify_player_list_item_spinner').replace('<strong style="color:red;">Loading failed!</strong>')
).always((data) =>
@bulkRequest(musicResources, window.spotify_player_list.models) if models.length > 0
)
| 148184 | class @SpotifyPlayerList
constructor: ->
window.spotify_player_list = {}
$(document.body).on "click", ".spotify_player_list_item_play_button", (event) ->
event.preventDefault()
model = $(this).parents('.spotify_player_list_item').data('model')
iframeHtml = if model == 'Track'
'<iframe src="https://embed.spotify.com/?uri=spotify:track:' + $(this).data('spotify-id') + '&view=coverart" frameborder="0" allowtransparency="true" width="300" height="80"></iframe>'
else
'<iframe src="https://embed.spotify.com/?uri=spotify:album:' + $(this).data('spotify-id') + '" frameborder="0" allowtransparency="true" width="300" height="380"></iframe>'
modalBodyHtml = """
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Play #{model}</h4>
</div>
<div class="modal-body" style="overflow-y:none;">
#{iframeHtml}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
"""
$('.modal-content').html(modalBodyHtml)
$('#modal').modal('show')
musicResources = { track: [], release: [] }
window.spotify_player_list.resourceToIndex = {}
$.each $('.spotify_player_list_item'), (index, element) =>
element = $(element)
resource = { artist_name: element.data('artist-name'), name: element.data('name') }
key = <KEY>data('<KEY>
window.spotify_player_list.resourceToIndex[key] = [] if window.spotify_player_list.resourceToIndex[key] == undefined
window.spotify_player_list.resourceToIndex[key].push index
if element.data('model') == 'Track'
musicResources['track'].push resource
else
musicResources['release'].push resource
@bulkRequest(musicResources, ['Track', 'Release'])
bulkRequest: (musicResources, models) ->
return if models.length == 0
model = null
resources = []
resources_count = 0
while resources_count == 0
model = models.shift()
window.spotify_player_list.model = model
window.spotify_player_list.models = models
resources = musicResources[model.toLowerCase()]
resources_count = resources.length
break if resources_count > 0
return if models.length == 0
data = {}
if model == 'Track'
data['tracks'] = resources
else
data['releases'] = resources
$.ajax(
url: "#{volontariatHost}/api/v1/music/#{model.toLowerCase()}s/bulk",
type: 'POST', dataType: 'json', data: data
).done((data) =>
$.each data, (index, element) =>
listItemIndexes = window.spotify_player_list.resourceToIndex["#{model}:#{element['artist_name']};#{element['name']}".toLowerCase()]
$.each listItemIndexes, (index, listItemIndex) =>
listItem = $('.spotify_player_list_item')[listItemIndex]
unless element['spotify_id'] == null
button = $(listItem).find('.spotify_player_list_item_play_icon')
$(button).data('spotify-id', element['spotify_id'])
$(button).addClass('spotify_player_list_item_play_button')
$(button).removeClass('hide')
$(listItem).find('.spotify_player_list_item_spinner').hide()
).fail((data) =>
$.each $('.spotify_player_list_item'), (index, element) =>
element = $(element)
if element.data('model') == window.spotify_player_list.model
listItemIndexes = window.spotify_player_list.resourceToIndex["#{model}:#{element.data('artist-name')};#{element.data('name')}".toLowerCase()]
$.each listItemIndexes, (index, listItemIndex) =>
listItem = $('.spotify_player_list_item')[listItemIndex]
$(listItem).find('.spotify_player_list_item_spinner').replace('<strong style="color:red;">Loading failed!</strong>')
).always((data) =>
@bulkRequest(musicResources, window.spotify_player_list.models) if models.length > 0
)
| true | class @SpotifyPlayerList
constructor: ->
window.spotify_player_list = {}
$(document.body).on "click", ".spotify_player_list_item_play_button", (event) ->
event.preventDefault()
model = $(this).parents('.spotify_player_list_item').data('model')
iframeHtml = if model == 'Track'
'<iframe src="https://embed.spotify.com/?uri=spotify:track:' + $(this).data('spotify-id') + '&view=coverart" frameborder="0" allowtransparency="true" width="300" height="80"></iframe>'
else
'<iframe src="https://embed.spotify.com/?uri=spotify:album:' + $(this).data('spotify-id') + '" frameborder="0" allowtransparency="true" width="300" height="380"></iframe>'
modalBodyHtml = """
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Play #{model}</h4>
</div>
<div class="modal-body" style="overflow-y:none;">
#{iframeHtml}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
"""
$('.modal-content').html(modalBodyHtml)
$('#modal').modal('show')
musicResources = { track: [], release: [] }
window.spotify_player_list.resourceToIndex = {}
$.each $('.spotify_player_list_item'), (index, element) =>
element = $(element)
resource = { artist_name: element.data('artist-name'), name: element.data('name') }
key = PI:KEY:<KEY>END_PIdata('PI:KEY:<KEY>END_PI
window.spotify_player_list.resourceToIndex[key] = [] if window.spotify_player_list.resourceToIndex[key] == undefined
window.spotify_player_list.resourceToIndex[key].push index
if element.data('model') == 'Track'
musicResources['track'].push resource
else
musicResources['release'].push resource
@bulkRequest(musicResources, ['Track', 'Release'])
bulkRequest: (musicResources, models) ->
return if models.length == 0
model = null
resources = []
resources_count = 0
while resources_count == 0
model = models.shift()
window.spotify_player_list.model = model
window.spotify_player_list.models = models
resources = musicResources[model.toLowerCase()]
resources_count = resources.length
break if resources_count > 0
return if models.length == 0
data = {}
if model == 'Track'
data['tracks'] = resources
else
data['releases'] = resources
$.ajax(
url: "#{volontariatHost}/api/v1/music/#{model.toLowerCase()}s/bulk",
type: 'POST', dataType: 'json', data: data
).done((data) =>
$.each data, (index, element) =>
listItemIndexes = window.spotify_player_list.resourceToIndex["#{model}:#{element['artist_name']};#{element['name']}".toLowerCase()]
$.each listItemIndexes, (index, listItemIndex) =>
listItem = $('.spotify_player_list_item')[listItemIndex]
unless element['spotify_id'] == null
button = $(listItem).find('.spotify_player_list_item_play_icon')
$(button).data('spotify-id', element['spotify_id'])
$(button).addClass('spotify_player_list_item_play_button')
$(button).removeClass('hide')
$(listItem).find('.spotify_player_list_item_spinner').hide()
).fail((data) =>
$.each $('.spotify_player_list_item'), (index, element) =>
element = $(element)
if element.data('model') == window.spotify_player_list.model
listItemIndexes = window.spotify_player_list.resourceToIndex["#{model}:#{element.data('artist-name')};#{element.data('name')}".toLowerCase()]
$.each listItemIndexes, (index, listItemIndex) =>
listItem = $('.spotify_player_list_item')[listItemIndex]
$(listItem).find('.spotify_player_list_item_spinner').replace('<strong style="color:red;">Loading failed!</strong>')
).always((data) =>
@bulkRequest(musicResources, window.spotify_player_list.models) if models.length > 0
)
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9990485310554504,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/debugger/test-debugger-client.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.
# Make sure split messages go in.
# Make sure that if we get backed up, we still manage to get all the
# messages
addTest = (cb) ->
expectedConnections++
tests.push cb
return
doTest = (cb, done) ->
args = [
"--debug=" + debugPort
"-e"
script
]
nodeProcess = spawn(process.execPath, args)
nodeProcess.stdout.once "data", (c) ->
console.log ">>> new node process: %d", nodeProcess.pid
failed = true
try
process._debugProcess nodeProcess.pid
failed = false
finally
# At least TRY not to leave zombie procs if this fails.
nodeProcess.kill "SIGTERM" if failed
console.log ">>> starting debugger session"
return
didTryConnect = false
nodeProcess.stderr.setEncoding "utf8"
b = ""
nodeProcess.stderr.on "data", (data) ->
console.error "got stderr data %j", data
nodeProcess.stderr.resume()
b += data
if didTryConnect is false and b.match(/Debugger listening on port/)
# The timeout is here to expose a race in the bootstrap process.
# Without the early SIGUSR1 debug handler, it effectively results
# in an infinite ECONNREFUSED loop.
tryConnect = ->
# Wait for some data before trying to connect
c = new debug.Client()
console.error ">>> connecting..."
c.connect debug.port
c.on "break", (brk) ->
c.reqContinue ->
return
c.on "ready", ->
connectCount++
console.log "ready!"
cb c, ->
c.end()
c.on "end", ->
console.error ">>> killing node process %d\n\n", nodeProcess.pid
nodeProcess.kill()
done()
return
return
return
c.on "error", (err) ->
throw err if err.code isnt "ECONNREFUSED"
setTimeout tryConnect, 10
return
return
didTryConnect = true
setTimeout tryConnect, 100
return
return
run = ->
t = tests[0]
return unless t
doTest t, ->
tests.shift()
run()
return
return
process.env.NODE_DEBUGGER_TIMEOUT = 2000
common = require("../common")
assert = require("assert")
debug = require("_debugger")
debugPort = common.PORT + 1337
debug.port = debugPort
spawn = require("child_process").spawn
setTimeout(->
nodeProcess.kill "SIGTERM" if nodeProcess
throw new Error("timeout")return
, 10000).unref()
resCount = 0
p = new debug.Protocol()
p.onResponse = (res) ->
resCount++
return
p.execute "Type: connect\r\n" + "V8-Version: 3.0.4.1\r\n" + "Protocol-Version: 1\r\n" + "Embedding-Host: node v0.3.3-pre\r\n" + "Content-Length: 0\r\n\r\n"
assert.equal 1, resCount
parts = []
parts.push "Content-Length: 336\r\n"
assert.equal 21, parts[0].length
parts.push "\r\n"
assert.equal 2, parts[1].length
bodyLength = 0
parts.push "{\"seq\":12,\"type\":\"event\",\"event\":\"break\",\"body\":" + "{\"invocationText\":\"#<a Server>"
assert.equal 78, parts[2].length
bodyLength += parts[2].length
parts.push ".[anonymous](req=#<an IncomingMessage>, " + "res=#<a ServerResponse>)\",\"sourceLine\""
assert.equal 78, parts[3].length
bodyLength += parts[3].length
parts.push ":45,\"sourceColumn\":4,\"sourceLineText\":\" debugger;\"," + "\"script\":{\"id\":24,\"name\":\"/home/ryan/projects/node/" + "benchmark/http_simple.js\",\"lineOffset\":0,\"columnOffset\":0," + "\"lineCount\":98}}}"
assert.equal 180, parts[4].length
bodyLength += parts[4].length
assert.equal 336, bodyLength
i = 0
while i < parts.length
p.execute parts[i]
i++
assert.equal 2, resCount
d = "Content-Length: 466\r\n\r\n" + "{\"seq\":10,\"type\":\"event\",\"event\":\"afterCompile\",\"success\":true," + "\"body\":{\"script\":{\"handle\":1,\"type\":\"script\",\"name\":\"dns.js\"," + "\"id\":34,\"lineOffset\":0,\"columnOffset\":0,\"lineCount\":241," + "\"sourceStart\":\"(function (module, exports, require) {" + "var dns = process.binding('cares')" + ";\\nvar ne\",\"sourceLength\":6137,\"scriptType\":2,\"compilationType\":0," + "\"context\":{\"ref\":0},\"text\":\"dns.js (lines: 241)\"}},\"refs\":" + "[{\"handle\":0" + ",\"type\":\"context\",\"text\":\"#<a ContextMirror>\"}],\"running\":true}" + "Content-Length: 119\r\n\r\n" + "{\"seq\":11,\"type\":\"event\",\"event\":\"scriptCollected\",\"success\":true," + "\"body\":{\"script\":{\"id\":26}},\"refs\":[],\"running\":true}"
p.execute d
assert.equal 4, resCount
expectedConnections = 0
tests = []
addTest (client, done) ->
console.error "requesting version"
client.reqVersion (err, v) ->
assert.ok not err
console.log "version: %s", v
assert.equal process.versions.v8, v
done()
return
return
addTest (client, done) ->
console.error "requesting scripts"
client.reqScripts (err) ->
assert.ok not err
console.error "got %d scripts", Object.keys(client.scripts).length
foundMainScript = false
for k of client.scripts
script = client.scripts[k]
if script and script.name is "node.js"
foundMainScript = true
break
assert.ok foundMainScript
done()
return
return
addTest (client, done) ->
console.error "eval 2+2"
client.reqEval "2+2", (err, res) ->
console.error res
assert.ok not err
assert.equal "4", res.text
assert.equal 4, res.value
done()
return
return
connectCount = 0
script = "setTimeout(function () { console.log(\"blah\"); });" + "setInterval(function () {}, 1000000);"
nodeProcess = undefined
run()
process.on "exit", (code) ->
assert.equal expectedConnections, connectCount unless code
return
| 129187 | # 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.
# Make sure split messages go in.
# Make sure that if we get backed up, we still manage to get all the
# messages
addTest = (cb) ->
expectedConnections++
tests.push cb
return
doTest = (cb, done) ->
args = [
"--debug=" + debugPort
"-e"
script
]
nodeProcess = spawn(process.execPath, args)
nodeProcess.stdout.once "data", (c) ->
console.log ">>> new node process: %d", nodeProcess.pid
failed = true
try
process._debugProcess nodeProcess.pid
failed = false
finally
# At least TRY not to leave zombie procs if this fails.
nodeProcess.kill "SIGTERM" if failed
console.log ">>> starting debugger session"
return
didTryConnect = false
nodeProcess.stderr.setEncoding "utf8"
b = ""
nodeProcess.stderr.on "data", (data) ->
console.error "got stderr data %j", data
nodeProcess.stderr.resume()
b += data
if didTryConnect is false and b.match(/Debugger listening on port/)
# The timeout is here to expose a race in the bootstrap process.
# Without the early SIGUSR1 debug handler, it effectively results
# in an infinite ECONNREFUSED loop.
tryConnect = ->
# Wait for some data before trying to connect
c = new debug.Client()
console.error ">>> connecting..."
c.connect debug.port
c.on "break", (brk) ->
c.reqContinue ->
return
c.on "ready", ->
connectCount++
console.log "ready!"
cb c, ->
c.end()
c.on "end", ->
console.error ">>> killing node process %d\n\n", nodeProcess.pid
nodeProcess.kill()
done()
return
return
return
c.on "error", (err) ->
throw err if err.code isnt "ECONNREFUSED"
setTimeout tryConnect, 10
return
return
didTryConnect = true
setTimeout tryConnect, 100
return
return
run = ->
t = tests[0]
return unless t
doTest t, ->
tests.shift()
run()
return
return
process.env.NODE_DEBUGGER_TIMEOUT = 2000
common = require("../common")
assert = require("assert")
debug = require("_debugger")
debugPort = common.PORT + 1337
debug.port = debugPort
spawn = require("child_process").spawn
setTimeout(->
nodeProcess.kill "SIGTERM" if nodeProcess
throw new Error("timeout")return
, 10000).unref()
resCount = 0
p = new debug.Protocol()
p.onResponse = (res) ->
resCount++
return
p.execute "Type: connect\r\n" + "V8-Version: 3.0.4.1\r\n" + "Protocol-Version: 1\r\n" + "Embedding-Host: node v0.3.3-pre\r\n" + "Content-Length: 0\r\n\r\n"
assert.equal 1, resCount
parts = []
parts.push "Content-Length: 336\r\n"
assert.equal 21, parts[0].length
parts.push "\r\n"
assert.equal 2, parts[1].length
bodyLength = 0
parts.push "{\"seq\":12,\"type\":\"event\",\"event\":\"break\",\"body\":" + "{\"invocationText\":\"#<a Server>"
assert.equal 78, parts[2].length
bodyLength += parts[2].length
parts.push ".[anonymous](req=#<an IncomingMessage>, " + "res=#<a ServerResponse>)\",\"sourceLine\""
assert.equal 78, parts[3].length
bodyLength += parts[3].length
parts.push ":45,\"sourceColumn\":4,\"sourceLineText\":\" debugger;\"," + "\"script\":{\"id\":24,\"name\":\"/home/ryan/projects/node/" + "benchmark/http_simple.js\",\"lineOffset\":0,\"columnOffset\":0," + "\"lineCount\":98}}}"
assert.equal 180, parts[4].length
bodyLength += parts[4].length
assert.equal 336, bodyLength
i = 0
while i < parts.length
p.execute parts[i]
i++
assert.equal 2, resCount
d = "Content-Length: 466\r\n\r\n" + "{\"seq\":10,\"type\":\"event\",\"event\":\"afterCompile\",\"success\":true," + "\"body\":{\"script\":{\"handle\":1,\"type\":\"script\",\"name\":\"dns.js\"," + "\"id\":34,\"lineOffset\":0,\"columnOffset\":0,\"lineCount\":241," + "\"sourceStart\":\"(function (module, exports, require) {" + "var dns = process.binding('cares')" + ";\\nvar ne\",\"sourceLength\":6137,\"scriptType\":2,\"compilationType\":0," + "\"context\":{\"ref\":0},\"text\":\"dns.js (lines: 241)\"}},\"refs\":" + "[{\"handle\":0" + ",\"type\":\"context\",\"text\":\"#<a ContextMirror>\"}],\"running\":true}" + "Content-Length: 119\r\n\r\n" + "{\"seq\":11,\"type\":\"event\",\"event\":\"scriptCollected\",\"success\":true," + "\"body\":{\"script\":{\"id\":26}},\"refs\":[],\"running\":true}"
p.execute d
assert.equal 4, resCount
expectedConnections = 0
tests = []
addTest (client, done) ->
console.error "requesting version"
client.reqVersion (err, v) ->
assert.ok not err
console.log "version: %s", v
assert.equal process.versions.v8, v
done()
return
return
addTest (client, done) ->
console.error "requesting scripts"
client.reqScripts (err) ->
assert.ok not err
console.error "got %d scripts", Object.keys(client.scripts).length
foundMainScript = false
for k of client.scripts
script = client.scripts[k]
if script and script.name is "node.js"
foundMainScript = true
break
assert.ok foundMainScript
done()
return
return
addTest (client, done) ->
console.error "eval 2+2"
client.reqEval "2+2", (err, res) ->
console.error res
assert.ok not err
assert.equal "4", res.text
assert.equal 4, res.value
done()
return
return
connectCount = 0
script = "setTimeout(function () { console.log(\"blah\"); });" + "setInterval(function () {}, 1000000);"
nodeProcess = undefined
run()
process.on "exit", (code) ->
assert.equal expectedConnections, connectCount unless code
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.
# Make sure split messages go in.
# Make sure that if we get backed up, we still manage to get all the
# messages
addTest = (cb) ->
expectedConnections++
tests.push cb
return
doTest = (cb, done) ->
args = [
"--debug=" + debugPort
"-e"
script
]
nodeProcess = spawn(process.execPath, args)
nodeProcess.stdout.once "data", (c) ->
console.log ">>> new node process: %d", nodeProcess.pid
failed = true
try
process._debugProcess nodeProcess.pid
failed = false
finally
# At least TRY not to leave zombie procs if this fails.
nodeProcess.kill "SIGTERM" if failed
console.log ">>> starting debugger session"
return
didTryConnect = false
nodeProcess.stderr.setEncoding "utf8"
b = ""
nodeProcess.stderr.on "data", (data) ->
console.error "got stderr data %j", data
nodeProcess.stderr.resume()
b += data
if didTryConnect is false and b.match(/Debugger listening on port/)
# The timeout is here to expose a race in the bootstrap process.
# Without the early SIGUSR1 debug handler, it effectively results
# in an infinite ECONNREFUSED loop.
tryConnect = ->
# Wait for some data before trying to connect
c = new debug.Client()
console.error ">>> connecting..."
c.connect debug.port
c.on "break", (brk) ->
c.reqContinue ->
return
c.on "ready", ->
connectCount++
console.log "ready!"
cb c, ->
c.end()
c.on "end", ->
console.error ">>> killing node process %d\n\n", nodeProcess.pid
nodeProcess.kill()
done()
return
return
return
c.on "error", (err) ->
throw err if err.code isnt "ECONNREFUSED"
setTimeout tryConnect, 10
return
return
didTryConnect = true
setTimeout tryConnect, 100
return
return
run = ->
t = tests[0]
return unless t
doTest t, ->
tests.shift()
run()
return
return
process.env.NODE_DEBUGGER_TIMEOUT = 2000
common = require("../common")
assert = require("assert")
debug = require("_debugger")
debugPort = common.PORT + 1337
debug.port = debugPort
spawn = require("child_process").spawn
setTimeout(->
nodeProcess.kill "SIGTERM" if nodeProcess
throw new Error("timeout")return
, 10000).unref()
resCount = 0
p = new debug.Protocol()
p.onResponse = (res) ->
resCount++
return
p.execute "Type: connect\r\n" + "V8-Version: 3.0.4.1\r\n" + "Protocol-Version: 1\r\n" + "Embedding-Host: node v0.3.3-pre\r\n" + "Content-Length: 0\r\n\r\n"
assert.equal 1, resCount
parts = []
parts.push "Content-Length: 336\r\n"
assert.equal 21, parts[0].length
parts.push "\r\n"
assert.equal 2, parts[1].length
bodyLength = 0
parts.push "{\"seq\":12,\"type\":\"event\",\"event\":\"break\",\"body\":" + "{\"invocationText\":\"#<a Server>"
assert.equal 78, parts[2].length
bodyLength += parts[2].length
parts.push ".[anonymous](req=#<an IncomingMessage>, " + "res=#<a ServerResponse>)\",\"sourceLine\""
assert.equal 78, parts[3].length
bodyLength += parts[3].length
parts.push ":45,\"sourceColumn\":4,\"sourceLineText\":\" debugger;\"," + "\"script\":{\"id\":24,\"name\":\"/home/ryan/projects/node/" + "benchmark/http_simple.js\",\"lineOffset\":0,\"columnOffset\":0," + "\"lineCount\":98}}}"
assert.equal 180, parts[4].length
bodyLength += parts[4].length
assert.equal 336, bodyLength
i = 0
while i < parts.length
p.execute parts[i]
i++
assert.equal 2, resCount
d = "Content-Length: 466\r\n\r\n" + "{\"seq\":10,\"type\":\"event\",\"event\":\"afterCompile\",\"success\":true," + "\"body\":{\"script\":{\"handle\":1,\"type\":\"script\",\"name\":\"dns.js\"," + "\"id\":34,\"lineOffset\":0,\"columnOffset\":0,\"lineCount\":241," + "\"sourceStart\":\"(function (module, exports, require) {" + "var dns = process.binding('cares')" + ";\\nvar ne\",\"sourceLength\":6137,\"scriptType\":2,\"compilationType\":0," + "\"context\":{\"ref\":0},\"text\":\"dns.js (lines: 241)\"}},\"refs\":" + "[{\"handle\":0" + ",\"type\":\"context\",\"text\":\"#<a ContextMirror>\"}],\"running\":true}" + "Content-Length: 119\r\n\r\n" + "{\"seq\":11,\"type\":\"event\",\"event\":\"scriptCollected\",\"success\":true," + "\"body\":{\"script\":{\"id\":26}},\"refs\":[],\"running\":true}"
p.execute d
assert.equal 4, resCount
expectedConnections = 0
tests = []
addTest (client, done) ->
console.error "requesting version"
client.reqVersion (err, v) ->
assert.ok not err
console.log "version: %s", v
assert.equal process.versions.v8, v
done()
return
return
addTest (client, done) ->
console.error "requesting scripts"
client.reqScripts (err) ->
assert.ok not err
console.error "got %d scripts", Object.keys(client.scripts).length
foundMainScript = false
for k of client.scripts
script = client.scripts[k]
if script and script.name is "node.js"
foundMainScript = true
break
assert.ok foundMainScript
done()
return
return
addTest (client, done) ->
console.error "eval 2+2"
client.reqEval "2+2", (err, res) ->
console.error res
assert.ok not err
assert.equal "4", res.text
assert.equal 4, res.value
done()
return
return
connectCount = 0
script = "setTimeout(function () { console.log(\"blah\"); });" + "setInterval(function () {}, 1000000);"
nodeProcess = undefined
run()
process.on "exit", (code) ->
assert.equal expectedConnections, connectCount unless code
return
|
[
{
"context": "mersDataContext: ->\n customers: [\n name: 'Foo'\n email: 'foo@example.com'\n ]\n\nreactiveCh",
"end": 14567,
"score": 0.9936703443527222,
"start": 14564,
"tag": "NAME",
"value": "Foo"
},
{
"context": "\n customers: [\n name: 'Foo'\n email: 'foo@example.com'\n ]\n\nreactiveChild1 = new ReactiveField false\n",
"end": 14598,
"score": 0.9999111294746399,
"start": 14583,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": "td>Foo</td>\n <td class=\"insideContent\">foo@example.com</td>\n <td>TestBlockComponent/TestBl",
"end": 29493,
"score": 0.9994121193885803,
"start": 29482,
"tag": "EMAIL",
"value": "foo@example"
},
{
"context": "d>\n <td class=\"insideContentComponent\">bar@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 29712,
"score": 0.9999063611030579,
"start": 29697,
"tag": "EMAIL",
"value": "bar@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">baz@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 29896,
"score": 0.9998084902763367,
"start": 29881,
"tag": "EMAIL",
"value": "baz@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">nameFromComponent1@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 30097,
"score": 0.9999080896377563,
"start": 30067,
"tag": "EMAIL",
"value": "nameFromComponent1@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">bac@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 30281,
"score": 0.9998895525932312,
"start": 30266,
"tag": "EMAIL",
"value": "bac@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">nameFromComponent2@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 30482,
"score": 0.9999151229858398,
"start": 30452,
"tag": "EMAIL",
"value": "nameFromComponent2@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">nameFromComponent3@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 30683,
"score": 0.9998983144760132,
"start": 30653,
"tag": "EMAIL",
"value": "nameFromComponent3@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">bam@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 30867,
"score": 0.9998237490653992,
"start": 30852,
"tag": "EMAIL",
"value": "bam@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">bav@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 31051,
"score": 0.9989879727363586,
"start": 31036,
"tag": "EMAIL",
"value": "bav@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">bak@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 31235,
"score": 0.999686062335968,
"start": 31220,
"tag": "EMAIL",
"value": "bak@example.com"
},
{
"context": "d>\n <td class=\"insideContentComponent\">bal@example.com</td>\n <td>RowComponent/RowComponent/Ro",
"end": 31419,
"score": 0.9998971223831177,
"start": 31404,
"tag": "EMAIL",
"value": "bal@example.com"
},
{
"context": " component: 'RowComponent'\n data: {name: 'Bar', email: 'bar@example.com'}\n children: [{}",
"end": 32132,
"score": 0.9960818886756897,
"start": 32129,
"tag": "NAME",
"value": "Bar"
},
{
"context": "RowComponent'\n data: {name: 'Bar', email: 'bar@example.com'}\n children: [{}]\n ,\n componen",
"end": 32158,
"score": 0.9999216198921204,
"start": 32143,
"tag": "EMAIL",
"value": "bar@example.com"
},
{
"context": " component: 'RowComponent'\n data: {name: 'Baz', email: 'baz@example.com'}\n children: [{}",
"end": 32251,
"score": 0.9979735612869263,
"start": 32248,
"tag": "NAME",
"value": "Baz"
},
{
"context": "RowComponent'\n data: {name: 'Baz', email: 'baz@example.com'}\n children: [{}]\n ,\n componen",
"end": 32277,
"score": 0.9999217987060547,
"start": 32262,
"tag": "EMAIL",
"value": "baz@example.com"
},
{
"context": " component: 'RowComponent'\n data: {name: 'Works', email: 'nameFromComponent1@example.com'}\n ",
"end": 32372,
"score": 0.9929004907608032,
"start": 32367,
"tag": "NAME",
"value": "Works"
},
{
"context": "wComponent'\n data: {name: 'Works', email: 'nameFromComponent1@example.com'}\n children: [{}]\n ,\n componen",
"end": 32413,
"score": 0.9999259114265442,
"start": 32383,
"tag": "EMAIL",
"value": "nameFromComponent1@example.com"
},
{
"context": " component: 'RowComponent'\n data: {name: 'Bac', email: 'bac@example.com'}\n children: [{}",
"end": 32506,
"score": 0.9987298250198364,
"start": 32503,
"tag": "NAME",
"value": "Bac"
},
{
"context": "RowComponent'\n data: {name: 'Bac', email: 'bac@example.com'}\n children: [{}]\n ,\n componen",
"end": 32532,
"score": 0.9999222755432129,
"start": 32517,
"tag": "EMAIL",
"value": "bac@example.com"
},
{
"context": " component: 'RowComponent'\n data: {name: 'Works', email: 'nameFromComponent2@example.com'}\n ",
"end": 32627,
"score": 0.9738633632659912,
"start": 32622,
"tag": "NAME",
"value": "Works"
},
{
"context": "wComponent'\n data: {name: 'Works', email: 'nameFromComponent2@example.com'}\n children: [{}]\n ,\n componen",
"end": 32668,
"score": 0.9999281167984009,
"start": 32638,
"tag": "EMAIL",
"value": "nameFromComponent2@example.com"
},
{
"context": " component: 'RowComponent'\n data: {name: 'Works', email: 'nameFromComponent3@example.com'}\n ",
"end": 32763,
"score": 0.9934855103492737,
"start": 32758,
"tag": "NAME",
"value": "Works"
},
{
"context": "wComponent'\n data: {name: 'Works', email: 'nameFromComponent3@example.com'}\n children: [{}]\n ,\n componen",
"end": 32804,
"score": 0.9999288320541382,
"start": 32774,
"tag": "EMAIL",
"value": "nameFromComponent3@example.com"
},
{
"context": " component: 'RowComponent'\n data: {name: 'Bam', email: 'bam@example.com'}\n children: [{}",
"end": 32897,
"score": 0.9976365566253662,
"start": 32894,
"tag": "NAME",
"value": "Bam"
},
{
"context": "RowComponent'\n data: {name: 'Bam', email: 'bam@example.com'}\n children: [{}]\n ,\n componen",
"end": 32923,
"score": 0.9999229311943054,
"start": 32908,
"tag": "EMAIL",
"value": "bam@example.com"
},
{
"context": " component: 'RowComponent'\n data: {name: 'Bav', email: 'bav@example.com'}\n children: [{}",
"end": 33016,
"score": 0.9978327751159668,
"start": 33013,
"tag": "NAME",
"value": "Bav"
},
{
"context": "RowComponent'\n data: {name: 'Bav', email: 'bav@example.com'}\n children: [{}]\n ,\n componen",
"end": 33042,
"score": 0.9999210238456726,
"start": 33027,
"tag": "EMAIL",
"value": "bav@example.com"
},
{
"context": "component: 'RowComponent'\n data: {name: 'Bak', email: 'bak@example.com'}\n children: [",
"end": 33225,
"score": 0.9942255020141602,
"start": 33222,
"tag": "NAME",
"value": "Bak"
},
{
"context": "wComponent'\n data: {name: 'Bak', email: 'bak@example.com'}\n children: [{}]\n ,\n co",
"end": 33251,
"score": 0.9999235272407532,
"start": 33236,
"tag": "EMAIL",
"value": "bak@example.com"
},
{
"context": "component: 'RowComponent'\n data: {name: 'Bal', email: 'bal@example.com'}\n children: [",
"end": 33352,
"score": 0.9980167150497437,
"start": 33349,
"tag": "NAME",
"value": "Bal"
},
{
"context": "wComponent'\n data: {name: 'Bal', email: 'bal@example.com'}\n children: [{}]\n ,\n {}",
"end": 33378,
"score": 0.9999257326126099,
"start": 33363,
"tag": "EMAIL",
"value": "bal@example.com"
},
{
"context": "op\":\"42\"}</p>\n <p>{\"customers\":[{\"name\":\"Foo\",\"email\":\"foo@example.com\"}]}</p>\n <p cl",
"end": 67039,
"score": 0.9793081879615784,
"start": 67036,
"tag": "NAME",
"value": "Foo"
},
{
"context": " <p>{\"customers\":[{\"name\":\"Foo\",\"email\":\"foo@example.com\"}]}</p>\n <p class=\"inside\">{\"top\":\"42\"}<",
"end": 67065,
"score": 0.9999119639396667,
"start": 67050,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": "p\":\"42\"}</p>\n <td>Foo</td>\n <td>foo@example.com</td>\n </tbody>\n </table>\n <tabl",
"end": 67171,
"score": 0.9999165534973145,
"start": 67156,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": " <tbody>\n <p>{\"customers\":[{\"name\":\"Foo\",\"email\":\"foo@example.com\"}]}</p>\n <p>{\"",
"end": 67396,
"score": 0.9807743430137634,
"start": 67393,
"tag": "NAME",
"value": "Foo"
},
{
"context": " <p>{\"customers\":[{\"name\":\"Foo\",\"email\":\"foo@example.com\"}]}</p>\n <p>{\"a\":\"3a\",\"b\":\"4a\"}</p>\n ",
"end": 67422,
"score": 0.9999238848686218,
"start": 67407,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": "p\":\"42\"}</p>\n <td>Foo</td>\n <td>foo@example.com</td>\n </tbody>\n </table>\n <tabl",
"end": 67565,
"score": 0.9999000430107117,
"start": 67550,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": "op\":\"42\"}</p>\n <p>{\"customers\":[{\"name\":\"Foo\",\"email\":\"foo@example.com\"}]}</p>\n <p cl",
"end": 67820,
"score": 0.7998245358467102,
"start": 67817,
"tag": "NAME",
"value": "Foo"
},
{
"context": " <p>{\"customers\":[{\"name\":\"Foo\",\"email\":\"foo@example.com\"}]}</p>\n <p class=\"inside\">{\"top\":\"42\"}<",
"end": 67846,
"score": 0.9999220967292786,
"start": 67831,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": "p\":\"42\"}</p>\n <td>Foo</td>\n <td>foo@example.com</td>\n </tbody>\n </table>\n <tabl",
"end": 67952,
"score": 0.999923586845398,
"start": 67937,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": "op\":\"42\"}</p>\n <p>{\"customers\":[{\"name\":\"Foo\",\"email\":\"foo@example.com\"}]}</p>\n <p cl",
"end": 68207,
"score": 0.8559575080871582,
"start": 68204,
"tag": "NAME",
"value": "Foo"
},
{
"context": " <p>{\"customers\":[{\"name\":\"Foo\",\"email\":\"foo@example.com\"}]}</p>\n <p class=\"inside\">{\"top\":\"42\"}<",
"end": 68233,
"score": 0.9999245405197144,
"start": 68218,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": "p\":\"42\"}</p>\n <td>Foo</td>\n <td>foo@example.com</td>\n </tbody>\n </table>\n \"\"\"\n\n t",
"end": 68339,
"score": 0.9999181628227234,
"start": 68324,
"tag": "EMAIL",
"value": "foo@example.com"
},
{
"context": "StateChanges\n ]\n\n # Test for https://github.com/peerlibrary/meteor-blaze-components/issues/30.\n testTemplate",
"end": 96696,
"score": 0.9995307922363281,
"start": 96685,
"tag": "USERNAME",
"value": "peerlibrary"
},
{
"context": "2\"}]\n ]\n ]\n\n # Test for https://github.com/peerlibrary/meteor-blaze-components/issues/30.\n testLexicalA",
"end": 103277,
"score": 0.9995505809783936,
"start": 103266,
"tag": "USERNAME",
"value": "peerlibrary"
},
{
"context": "), trim \"\"\"42\"\"\"\n\n # Test for https://github.com/peerlibrary/meteor-blaze-components/issues/109.\n testIndex: ",
"end": 103561,
"score": 0.9995054006576538,
"start": 103550,
"tag": "USERNAME",
"value": "peerlibrary"
}
] | tests/tests.coffee | pouya-eghbali/meteor-blaze-components | 0 | trim = (html) =>
html = html.replace />\s+/g, '>'
html = html.replace /\s+</g, '<'
html.trim()
class MainComponent extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
# To test when name of the component mismatches the template name. Template name should have precedence.
'MainComponent2'
foobar: ->
"#{@componentName()}/MainComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/MainComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@componentName()}/MainComponent.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
isMainComponent: ->
@constructor is MainComponent
onClick: (event) ->
assert not Tracker.active
@constructor.calls.push [@componentName(), 'MainComponent.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: ->
assert not Tracker.active
[
'click': @onClick
]
onCreated: ->
self = @
# To test that a computation is bound to the component.
@autorun (computation) ->
assert.equal @, self
BlazeComponent.register 'MainComponent', MainComponent
# Template should match registered name.
class FooComponent extends BlazeComponent
BlazeComponent.register 'FooComponent', FooComponent
class SelfRegisterComponent extends BlazeComponent
# Alternative way of registering components.
@register 'SelfRegisterComponent'
class SubComponent extends MainComponent
@calls: []
foobar: ->
"#{@componentName()}/SubComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/SubComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not override foobar3.
onClick: (event) ->
@constructor.calls.push [@componentName(), 'SubComponent.onClick', @data(), @currentData(), @currentComponent().componentName()]
BlazeComponent.register 'SubComponent', SubComponent
class UnregisteredComponent extends SubComponent
foobar: ->
"#{@componentName()}/UnregisteredComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/UnregisteredComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# Name has to be set manually.
UnregisteredComponent.componentName 'UnregisteredComponent'
class SelfNameUnregisteredComponent extends UnregisteredComponent
# Alternative way of setting the name manually.
@componentName 'SelfNameUnregisteredComponent'
# We do not extend any helper on purpose. So they should all use "UnregisteredComponent".
class AnimatedListComponent extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
'AnimatedListComponent'
onCreated: ->
assert not Tracker.active
# To test inserts, moves, and removals.
@_list = new ReactiveField [1, 2, 3, 4, 5]
@_handle = Meteor.setInterval =>
list = @_list()
# Moves the last number to the first place.
list = [list[4]].concat list[0...4]
# Removes the smallest number.
list = _.without list, _.min list
# Adds one more number, one larger than the current largest.
list = list.concat [_.max(list) + 1]
@_list list
, 1000 # ms
onDestroyed: ->
assert not Tracker.active
Meteor.clearInterval @_handle
list: ->
_id: i for i in @_list()
insertDOMElement: (parent, node, before) ->
assert not Tracker.active
@constructor.calls.push ['insertDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML), trim(before?.outerHTML or '')]
super arguments...
moveDOMElement: (parent, node, before) ->
assert not Tracker.active
@constructor.calls.push ['moveDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML), trim(before?.outerHTML or '')]
super arguments...
removeDOMElement: (parent, node) ->
assert not Tracker.active
@constructor.calls.push ['removeDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML)]
super arguments...
BlazeComponent.register 'AnimatedListComponent', AnimatedListComponent
class DummyComponent extends BlazeComponent
@register 'DummyComponent'
class ArgumentsComponent extends BlazeComponent
@calls: []
@constructorStateChanges: []
@onCreatedStateChanges: []
template: ->
assert not Tracker.active
'ArgumentsComponent'
constructor: ->
super arguments...
assert not Tracker.active
@constructor.calls.push arguments[0]
@arguments = arguments
@componentId = Random.id()
@handles = []
@collectStateChanges @constructor.constructorStateChanges
onCreated: ->
assert not Tracker.active
super arguments...
@collectStateChanges @constructor.onCreatedStateChanges
collectStateChanges: (output) ->
output.push
componentId: @componentId
view: Blaze.currentView
templateInstance: Template.instance()
for method in ['isCreated', 'isRendered', 'isDestroyed', 'data', 'currentData', 'component', 'currentComponent', 'firstNode', 'lastNode', 'subscriptionsReady']
do (method) =>
@handles.push Tracker.autorun (computation) =>
data =
componentId: @componentId
data[method] = @[method]()
output.push data
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
find: @find('*')
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
findAll: @findAll('*')
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
$: @$('*')
onDestroyed: ->
assert not Tracker.active
super arguments...
Tracker.afterFlush =>
while handle = @handles.pop()
handle.stop()
dataContext: ->
EJSON.stringify @data()
currentDataContext: ->
EJSON.stringify @currentData()
constructorArguments: ->
EJSON.stringify @arguments
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
BlazeComponent.register 'ArgumentsComponent', ArgumentsComponent
class MyNamespace
class MyNamespace.Foo
class MyNamespace.Foo.ArgumentsComponent extends ArgumentsComponent
@register 'MyNamespace.Foo.ArgumentsComponent'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'MyNamespace.Foo.ArgumentsComponent'
# We want to test if a component with the same name as the namespace can coexist.
class OurNamespace extends ArgumentsComponent
@register 'OurNamespace'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'OurNamespace'
class OurNamespace.ArgumentsComponent extends ArgumentsComponent
@register 'OurNamespace.ArgumentsComponent'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'OurNamespace.ArgumentsComponent'
reactiveContext = new ReactiveField {}
reactiveArguments = new ReactiveField {}
class ArgumentsTestComponent extends BlazeComponent
@register 'ArgumentsTestComponent'
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.namespacedArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.ourNamespacedArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.ourNamespaceComponentArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
class ExistingClassHierarchyBase
foobar: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
class ExistingClassHierarchyChild extends ExistingClassHierarchyBase
class ExistingClassHierarchyBaseComponent extends ExistingClassHierarchyChild
for property, value of BlazeComponent when property not in ['__super__']
ExistingClassHierarchyBaseComponent[property] = value
for property, value of (BlazeComponent::) when property not in ['constructor']
ExistingClassHierarchyBaseComponent::[property] = value
class ExistingClassHierarchyComponent extends ExistingClassHierarchyBaseComponent
template: ->
assert not Tracker.active
'MainComponent2'
foobar: ->
"#{@componentName()}/ExistingClassHierarchyComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/ExistingClassHierarchyComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not override foobar3.
ExistingClassHierarchyComponent.register 'ExistingClassHierarchyComponent', ExistingClassHierarchyComponent
class FirstMixin extends BlazeComponent
@calls: []
foobar: ->
"#{@component().componentName()}/FirstMixin.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@component().componentName()}/FirstMixin.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@component().componentName()}/FirstMixin.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
isMainComponent: ->
@component().constructor is WithMixinsComponent
onClick: (event) ->
@constructor.calls.push [@component().componentName(), 'FirstMixin.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: -> [
'click': @onClick
]
class SecondMixin extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
@_template()
_template: ->
'MainComponent2'
foobar: ->
"#{@component().componentName()}/SecondMixin.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@component().componentName()}/SecondMixin.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not provide foobar3.
onClick: (event) ->
@constructor.calls.push [@component().componentName(), 'SecondMixin.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: ->
assert not Tracker.active
[
'click': @onClick
]
onCreated: ->
assert not Tracker.active
# To test if adding a dependency during onCreated will make sure
# to call onCreated on the added dependency as well.
@mixinParent().requireMixin DependencyMixin
SecondMixin.componentName 'SecondMixin'
class DependencyMixin extends BlazeComponent
@calls: []
onCreated: ->
assert not Tracker.active
@constructor.calls.push true
class WithMixinsComponent extends BlazeComponent
@output: []
mixins: ->
assert not Tracker.active
[SecondMixin, FirstMixin]
onDestroyed: ->
firstMixin = @getMixin FirstMixin
@constructor.output.push @
@constructor.output.push firstMixin
@constructor.output.push @getMixin firstMixin
@constructor.output.push @getMixin @
@constructor.output.push @getMixin DependencyMixin
@constructor.output.push @getMixin 'FirstMixin'
@constructor.output.push @getMixin 'SecondMixin'
@constructor.output.push @getFirstWith null, 'isMainComponent'
@constructor.output.push @getFirstWith null, (child, parent) =>
!!child.constructor.output
@constructor.output.push @getFirstWith null, (child, parent) =>
child is parent
@constructor.output.push @getFirstWith null, (child, parent) =>
child._template?() is 'MainComponent2'
BlazeComponent.register 'WithMixinsComponent', WithMixinsComponent
class AfterCreateValueComponent extends BlazeComponent
template: ->
assert not Tracker.active
'AfterCreateValueComponent'
onCreated: ->
assert not Tracker.active
@foobar = '42'
@_foobar = '43'
BlazeComponent.register 'AfterCreateValueComponent', AfterCreateValueComponent
class PostMessageButtonComponent extends BlazeComponent
onCreated: ->
assert not Tracker.active
@color = new ReactiveField "Red"
$(window).on 'message.buttonComponent', (event) =>
if color = event.originalEvent.data?.color
@color color
onDestroyed: ->
$(window).off '.buttonComponent'
BlazeComponent.register 'PostMessageButtonComponent', PostMessageButtonComponent
class TableWrapperBlockComponent extends BlazeComponent
template: ->
assert not Tracker.active
'TableWrapperBlockComponent'
currentDataContext: ->
EJSON.stringify @currentData()
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
BlazeComponent.register 'TableWrapperBlockComponent', TableWrapperBlockComponent
Template.testBlockComponent.helpers
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
customersDataContext: ->
customers: [
name: 'Foo'
email: 'foo@example.com'
]
reactiveChild1 = new ReactiveField false
reactiveChild2 = new ReactiveField false
class ChildComponent extends BlazeComponent
template: ->
assert not Tracker.active
'ChildComponent'
constructor: (@childName) ->
super arguments...
assert not Tracker.active
onCreated: ->
assert not Tracker.active
@domChanged = new ReactiveField 0
insertDOMElement: (parent, node, before) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
moveDOMElement: (parent, node, before) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
removeDOMElement: (parent, node) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
BlazeComponent.register 'ChildComponent', ChildComponent
class ParentComponent extends BlazeComponent
template: ->
assert not Tracker.active
'ParentComponent'
child1: ->
reactiveChild1()
child2: ->
reactiveChild2()
BlazeComponent.register 'ParentComponent', ParentComponent
class CaseComponent extends BlazeComponent
@register 'CaseComponent'
constructor: (kwargs) ->
super arguments...
assert not Tracker.active
@cases = kwargs.hash
renderCase: ->
caseComponent = @cases[@data().case]
return null unless caseComponent
BlazeComponent.getComponent(caseComponent).renderComponent @
class LeftComponent extends BlazeComponent
@register 'LeftComponent'
template: ->
assert not Tracker.active
'LeftComponent'
class MiddleComponent extends BlazeComponent
@register 'MiddleComponent'
template: ->
assert not Tracker.active
'MiddleComponent'
class RightComponent extends BlazeComponent
@register 'RightComponent'
template: ->
assert not Tracker.active
'RightComponent'
class MyComponent extends BlazeComponent
@register 'MyComponent'
mixins: ->
assert not Tracker.active
[FirstMixin2, new SecondMixin2 'foobar']
alternativeName: ->
@callFirstWith null, 'templateHelper'
values: ->
'a' + (@callFirstWith(@, 'values') or '')
class FirstMixinBase extends BlazeComponent
@calls: []
templateHelper: ->
"42"
extendedHelper: ->
1
onClick: ->
throw new Error() if @values() isnt @valuesPredicton
@constructor.calls.push true
class FirstMixin2 extends FirstMixinBase
extendedHelper: ->
super() + 2
values: ->
'b' + (@mixinParent().callFirstWith(@, 'values') or '')
dataContext: ->
EJSON.stringify @data()
events: ->
assert not Tracker.active
super.concat
'click': @onClick
onCreated: ->
assert not Tracker.active
@valuesPredicton = 'bc'
class SecondMixin2
constructor: (@name) ->
assert not Tracker.active
mixinParent: (mixinParent) ->
@_mixinParent = mixinParent if mixinParent
@_mixinParent
values: ->
'c' + (@mixinParent().callFirstWith(@, 'values') or '')
# Example from the README.
class ExampleComponent extends BlazeComponent
@register 'ExampleComponent'
onCreated: ->
assert not Tracker.active
super arguments...
@counter = new ReactiveField 0
events: ->
assert not Tracker.active
super.concat
'click .increment': @onClick
onClick: (event) ->
@counter @counter() + 1
customHelper: ->
if @counter() > 10
"Too many times"
else if @counter() is 10
"Just enough"
else
"Click more"
class OuterComponent extends BlazeComponent
@register 'OuterComponent'
@calls: []
template: ->
assert not Tracker.active
'OuterComponent'
onCreated: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onCreated'
onRendered: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onRendered'
onDestroyed: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onDestroyed'
class InnerComponent extends BlazeComponent
@register 'InnerComponent'
template: ->
assert not Tracker.active
'InnerComponent'
onCreated: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onCreated'
onRendered: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onRendered'
onDestroyed: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onDestroyed'
class TemplateDynamicTestComponent extends MainComponent
@register 'TemplateDynamicTestComponent'
@calls: []
template: ->
assert not Tracker.active
'TemplateDynamicTestComponent'
isMainComponent: ->
@constructor is TemplateDynamicTestComponent
class ExtraTableWrapperBlockComponent extends BlazeComponent
@register 'ExtraTableWrapperBlockComponent'
class TestBlockComponent extends BlazeComponent
@register 'TestBlockComponent'
nameFromComponent: ->
"Works"
renderRow: ->
BlazeComponent.getComponent('RowComponent').renderComponent @currentComponent()
class RowComponent extends BlazeComponent
@register 'RowComponent'
class FootComponent extends BlazeComponent
@register 'FootComponent'
class CaptionComponent extends BlazeComponent
@register 'CaptionComponent'
class RenderRowComponent extends BlazeComponent
@register 'RenderRowComponent'
parentComponentRenderRow: ->
@parentComponent().parentComponent().renderRow()
class TestingComponentDebug extends BlazeComponentDebug
@structure: {}
stack = []
@lastElement: (structure) ->
return structure if 'children' not of structure
stack[stack.length - 1] = structure.children
@lastElement structure.children[structure.children.length - 1]
@startComponent: (component) ->
stack.push null
element = @lastElement @structure
element.component = component.componentName()
element.data = component.data()
element.children = [{}]
@endComponent: (component) ->
# Only the top-level stack element stays null and is not set to a children array.
stack[stack.length - 1].push {} if stack.length > 1
stack.pop()
@startMarkedComponent: (component) ->
@startComponent component
@endMarkedComponent: (component) ->
@endComponent component
class LexicalArgumentsComponent extends BlazeComponent
@register 'LexicalArgumentsComponent'
rowOfCurrentData: ->
EJSON.stringify @currentData()
rowOfFooAndIndex: ->
"#{EJSON.stringify @currentData 'foo'}/#{@currentData '@index'}"
mainComponent3Calls = []
Template.mainComponent3.events
'click': (event, template) ->
assert.equal Template.instance(), template
assert not Tracker.active
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onClick', @, Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.helpers
foobar: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
foobar2: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar2/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
foobar3: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar3/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
Template.mainComponent3.onCreated ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onCreated', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.onRendered ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onRendered', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.onDestroyed ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onDestroyed', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
class MainComponent3 extends BlazeComponent
@register 'MainComponent3'
template: ->
'mainComponent3'
foobar: ->
# An ugly way to extend a base template helper.
helper = @_componentInternals.templateBase.__helpers.get 'foobar'
# Blaze template helpers expect current data context bound to "this".
result = helper.call @currentData()
'super:' + result
reactiveArguments = new ReactiveField null
class InlineEventsComponent extends BlazeComponent
@calls: []
@register 'InlineEventsComponent'
onButton1Click: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton1Click', @data(), @currentData(), @currentComponent().componentName()]
onButton2Click: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton2Click', @data(), @currentData(), @currentComponent().componentName()]
onClick1Extra: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onClick1Extra', @data(), @currentData(), @currentComponent().componentName()]
onButton3Click: (event, args...) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton3Click', @data(), @currentData(), @currentComponent().componentName()].concat args
onButton4Click: (event, args...) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton4Click', @data(), @currentData(), @currentComponent().componentName()].concat args
dynamicArgument: ->
reactiveArguments()
onChange: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onChange', @data(), @currentData(), @currentComponent().componentName()]
onTextClick: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onTextClick', @data(), @currentData(), @currentComponent().componentName()]
extraArgs1: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.extraArgs1', @data(), @currentData(), @currentComponent().componentName()]
extraArgs2: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.extraArgs2', @data(), @currentData(), @currentComponent().componentName()]
extraArgs: ->
title: "Foobar"
onClick: [
@extraArgs1
,
@extraArgs2
]
class InvalidInlineEventsComponent extends BlazeComponent
@register 'InvalidInlineEventsComponent'
class LevelOneComponent extends BlazeComponent
@register 'LevelOneComponent'
class LevelTwoComponent extends BlazeComponent
@children: []
@register 'LevelTwoComponent'
onCreated: ->
super arguments...
@autorun =>
@constructor.children.push all: @childComponents().length
@autorun =>
@constructor.children.push topValue: @childComponentsWith(topValue: 41).length
@autorun =>
@constructor.children.push hasValue: @childComponentsWith(hasValue: 42).length
@autorun =>
@constructor.children.push hasNoValue: @childComponentsWith(hasNoValue: 43).length
class LevelOneMixin extends BlazeComponent
mixins: ->
[LevelTwoMixin]
# This one should be resolved in the template.
hasValue: ->
42
class LevelTwoMixin extends BlazeComponent
# This one should not be resolved in the template.
hasNoValue: ->
43
class ComponentWithNestedMixins extends BlazeComponent
@register 'ComponentWithNestedMixins'
mixins: ->
[LevelOneMixin]
topValue: ->
41
class BasicTestCase extends ClassyTestCase
@testName: 'blaze-components - basic'
FOO_COMPONENT_CONTENT = ->
"""
<p>Other component: FooComponent</p>
<button>Foo2</button>
<p></p>
<button>Foo3</button>
<p></p>
<p></p>
"""
COMPONENT_CONTENT = (componentName, helperComponentName, mainComponent) ->
helperComponentName ?= componentName
mainComponent ?= 'MainComponent'
"""
<p>Main component: #{componentName}</p>
<button>Foo1</button>
<p>#{componentName}/#{helperComponentName}.foobar/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<button>Foo2</button>
<p>#{componentName}/#{helperComponentName}.foobar2/{"top":"42"}/{"a":"1","b":"2"}/#{componentName}</p>
<p>#{componentName}/#{mainComponent}.foobar3/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<p>Subtemplate</p>
<button>Foo1</button>
<p>#{componentName}/#{helperComponentName}.foobar/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<button>Foo2</button>
<p>#{componentName}/#{helperComponentName}.foobar2/{"top":"42"}/{"a":"3","b":"4"}/#{componentName}</p>
<p>#{componentName}/#{mainComponent}.foobar3/{"top":"42"}/{"top":"42"}/#{componentName}</p>
#{FOO_COMPONENT_CONTENT()}
"""
TEST_BLOCK_COMPONENT_CONTENT = ->
"""
<h2>Names and emails and components (CaptionComponent/CaptionComponent/CaptionComponent)</h2>
<h3 class="insideBlockHelperTemplate">(ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent)</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th class="insideBlockHelper">Email</th>
<th>Component (ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Foo</td>
<td class="insideContent">foo@example.com</td>
<td>TestBlockComponent/TestBlockComponent/ExtraTableWrapperBlockComponent</td>
</tr>
<tr>
<td>Bar</td>
<td class="insideContentComponent">bar@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Baz</td>
<td class="insideContentComponent">baz@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent">nameFromComponent1@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bac</td>
<td class="insideContentComponent">bac@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent">nameFromComponent2@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent">nameFromComponent3@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bam</td>
<td class="insideContentComponent">bam@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bav</td>
<td class="insideContentComponent">bav@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bak</td>
<td class="insideContentComponent">bak@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bal</td>
<td class="insideContentComponent">bal@example.com</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th class="insideBlockHelperComponent">Email</th>
<th>Component (FootComponent/FootComponent/FootComponent)</th>
</tr>
</tfoot>
</table>
"""
TEST_BLOCK_COMPONENT_STRUCTURE = ->
component: 'TestBlockComponent'
data: {top: '42'}
children: [
component: 'ExtraTableWrapperBlockComponent'
data: {block: '43'}
children: [
component: 'CaptionComponent'
data: {block: '43'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Bar', email: 'bar@example.com'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Baz', email: 'baz@example.com'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Works', email: 'nameFromComponent1@example.com'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Bac', email: 'bac@example.com'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Works', email: 'nameFromComponent2@example.com'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Works', email: 'nameFromComponent3@example.com'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Bam', email: 'bam@example.com'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Bav', email: 'bav@example.com'}
children: [{}]
,
component: 'RenderRowComponent'
data: {top: '42'}
children: [
component: 'RowComponent'
data: {name: 'Bak', email: 'bak@example.com'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'Bal', email: 'bal@example.com'}
children: [{}]
,
{}
]
,
component: 'FootComponent'
data: {block: '43'}
children: [{}]
,
{}
]
,
{}
]
testComponents: ->
output = BlazeComponent.getComponent('MainComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = new (BlazeComponent.getComponent('MainComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = BlazeComponent.getComponent('FooComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = new (BlazeComponent.getComponent('FooComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = BlazeComponent.getComponent('SubComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
output = new (BlazeComponent.getComponent('SubComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
testGetComponent: ->
@assertEqual BlazeComponent.getComponent('MainComponent'), MainComponent
@assertEqual BlazeComponent.getComponent('FooComponent'), FooComponent
@assertEqual BlazeComponent.getComponent('SubComponent'), SubComponent
@assertEqual BlazeComponent.getComponent('unknown'), null
testComponentName: ->
@assertEqual MainComponent.componentName(), 'MainComponent'
@assertEqual FooComponent.componentName(), 'FooComponent'
@assertEqual SubComponent.componentName(), 'SubComponent'
@assertEqual BlazeComponent.componentName(), null
testSelfRegister: ->
@assertTrue BlazeComponent.getComponent 'SelfRegisterComponent'
testUnregisteredComponent: ->
output = UnregisteredComponent.renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'UnregisteredComponent'
output = new UnregisteredComponent().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'UnregisteredComponent'
output = SelfNameUnregisteredComponent.renderComponentToHTML null, null,
top: '42'
# We have not extended any helper on purpose, so they should still use "UnregisteredComponent".
@assertEqual trim(output), trim COMPONENT_CONTENT 'SelfNameUnregisteredComponent', 'UnregisteredComponent'
output = new SelfNameUnregisteredComponent().renderComponentToHTML null, null,
top: '42'
# We have not extended any helper on purpose, so they should still use "UnregisteredComponent".
@assertEqual trim(output), trim COMPONENT_CONTENT 'SelfNameUnregisteredComponent', 'UnregisteredComponent'
testErrors: ->
@assertThrows =>
BlazeComponent.register()
,
/Component name is required for registration/
@assertThrows =>
BlazeComponent.register 'MainComponent', null
,
/Component 'MainComponent' already registered/
@assertThrows =>
BlazeComponent.register 'OtherMainComponent', MainComponent
,
/Component 'OtherMainComponent' already registered under the name 'MainComponent'/
class WithoutTemplateComponent extends BlazeComponent
@assertThrows =>
WithoutTemplateComponent.renderComponentToHTML()
,
/Template for the component 'unnamed' not provided/
@assertThrows =>
new WithoutTemplateComponent().renderComponentToHTML()
,
/Template for the component 'unnamed' not provided/
class WithUnknownTemplateComponent extends BlazeComponent
@componentName 'WithoutTemplateComponent'
template: ->
'TemplateWhichDoesNotExist'
@assertThrows =>
WithUnknownTemplateComponent.renderComponentToHTML()
,
/Template 'TemplateWhichDoesNotExist' cannot be found/
@assertThrows =>
new WithUnknownTemplateComponent().renderComponentToHTML()
,
/Template 'TemplateWhichDoesNotExist' cannot be found/
testClientEvents: [
->
MainComponent.calls = []
SubComponent.calls = []
@renderedComponent = Blaze.render Template.eventsTestTemplate, $('body').get(0)
Tracker.afterFlush @expect()
,
->
$('.eventsTestTemplate button').each (i, button) =>
$(button).click()
@assertEqual MainComponent.calls, [
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
@assertEqual SubComponent.calls, [
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
Blaze.remove @renderedComponent
]
testClientAnimation: [
->
AnimatedListComponent.calls = []
@renderedComponent = Blaze.render Template.animationTestTemplate, $('body').get(0)
Meteor.setTimeout @expect(), 2500 # ms
,
->
Blaze.remove @renderedComponent
calls = AnimatedListComponent.calls
AnimatedListComponent.calls = []
expectedCalls = [
['insertDOMElement', 'AnimatedListComponent', '<div class="animationTestTemplate"></div>', '<div><ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul></div>', '']
['removeDOMElement', 'AnimatedListComponent', '<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>', '<li>1</li>']
['moveDOMElement', 'AnimatedListComponent', '<ul><li>2</li><li>3</li><li>4</li><li>5</li></ul>', '<li>5</li>', '']
['insertDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>2</li><li>3</li><li>4</li></ul>', '<li>6</li>', '']
['removeDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>2</li><li>3</li><li>4</li><li>6</li></ul>', '<li>2</li>']
['moveDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>3</li><li>4</li><li>6</li></ul>', '<li>6</li>', '']
['insertDOMElement', 'AnimatedListComponent', '<ul><li>6</li><li>5</li><li>3</li><li>4</li></ul>', '<li>7</li>', '']
]
# There could be some more calls made, we ignore them and just take the first 8.
@assertEqual calls[0...8], expectedCalls
Meteor.setTimeout @expect(), 2000 # ms
,
->
# After we removed the component no more calls should be made.
@assertEqual AnimatedListComponent.calls, []
]
assertArgumentsConstructorStateChanges: (stateChanges, wrappedInComponent=true, staticRender=false) ->
firstSteps = (dataContext) =>
change = stateChanges.shift()
componentId = change.componentId
@assertTrue change.view
@assertTrue change.templateInstance
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isDestroyed
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.currentData, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.component, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
if wrappedInComponent
@assertInstanceOf change.currentComponent, ArgumentsTestComponent
else
@assertIsNull change.currentComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
componentId
firstComponentId = firstSteps a: "1", b: "2"
secondComponentId = firstSteps a:"3a", b: "4a"
thirdComponentId = firstSteps a: "5", b: "6"
forthComponentId = firstSteps {}
if staticRender
@assertEqual stateChanges, []
return
secondSteps = (componentId, dataContext) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.data, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isCreated
secondSteps firstComponentId, a: "1", b: "2"
secondSteps secondComponentId, a:"3a", b: "4a"
secondSteps thirdComponentId, a: "5", b: "6"
secondSteps forthComponentId, {}
thirdSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.firstNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.lastNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.find?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.findAll), ["P", "P", "P", "P"]
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.$), ["P", "P", "P", "P"]
thirdSteps firstComponentId
thirdSteps secondComponentId
thirdSteps thirdComponentId
thirdSteps forthComponentId
# TODO: This change is probably unnecessary? Could we prevent it?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
if change.data
# TODO: In Chrome data is set. Why?
@assertEqual change.data, a: "10", b: "11"
else
# TODO: In Firefox data is undefined. Why?
@assertIsUndefined change.data
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertIsUndefined change.currentData
fifthComponentId = firstSteps a: "10", b: "11"
forthSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
forthSteps forthComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertEqual change.data, a: "10", b: "11"
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isCreated
forthSteps firstComponentId
forthSteps secondComponentId
forthSteps thirdComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertFalse change.isCreated
# TODO: Why is isRendered not set to false and all related other fields which require it (firstNode, lastNode, find, findAll, $)?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.subscriptionsReady
@assertEqual stateChanges, []
assertArgumentsOnCreatedStateChanges: (stateChanges, staticRender=false) ->
firstSteps = (dataContext) =>
change = stateChanges.shift()
componentId = change.componentId
@assertTrue change.view
@assertTrue change.templateInstance
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isDestroyed
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.data, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.currentData, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.component, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.currentComponent, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
componentId
firstComponentId = firstSteps a: "1", b: "2"
secondComponentId = firstSteps a:"3a", b: "4a"
thirdComponentId = firstSteps a: "5", b: "6"
forthComponentId = firstSteps {}
if staticRender
@assertEqual stateChanges, []
return
thirdSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.firstNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.lastNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.find?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.findAll), ["P", "P", "P", "P"]
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.$), ["P", "P", "P", "P"]
thirdSteps firstComponentId
thirdSteps secondComponentId
thirdSteps thirdComponentId
thirdSteps forthComponentId
# TODO: This change is probably unnecessary? Could we prevent it?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertEqual change.data, a: "10", b: "11"
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertIsUndefined change.currentData
fifthComponentId = firstSteps a: "10", b: "11"
forthSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
forthSteps forthComponentId
forthSteps firstComponentId
forthSteps secondComponentId
forthSteps thirdComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertFalse change.isCreated
# TODO: Why is isRendered not set to false and all related other fields which require it (firstNode, lastNode, find, findAll, $)?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.subscriptionsReady
@assertEqual stateChanges, []
testArguments: ->
ArgumentsComponent.calls = []
ArgumentsComponent.constructorStateChanges = []
ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.argumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="argumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual ArgumentsComponent.calls.length, 4
@assertEqual ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges ArgumentsComponent.constructorStateChanges, true, true
@assertArgumentsOnCreatedStateChanges ArgumentsComponent.onCreatedStateChanges, true
testClientArguments: [
->
ArgumentsComponent.calls = []
ArgumentsComponent.constructorStateChanges = []
ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.argumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual ArgumentsComponent.calls.length, 5
@assertEqual ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges ArgumentsComponent.constructorStateChanges
@assertArgumentsOnCreatedStateChanges ArgumentsComponent.onCreatedStateChanges
]
testExistingClassHierarchy: ->
# We want to allow one to reuse existing class hierarchy they might already have and only
# add the Meteor components "nature" to it. This is simply done by extending the base class
# and base class prototype with those from a wanted base class and prototype.
output = BlazeComponent.getComponent('ExistingClassHierarchyComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'ExistingClassHierarchyComponent', 'ExistingClassHierarchyComponent', 'ExistingClassHierarchyBase'
testMixins: ->
DependencyMixin.calls = []
WithMixinsComponent.output = []
output = BlazeComponent.getComponent('WithMixinsComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'WithMixinsComponent', 'SecondMixin', 'FirstMixin'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
@assertEqual DependencyMixin.calls, [true]
@assertInstanceOf WithMixinsComponent.output[1], FirstMixin
@assertEqual WithMixinsComponent.output[2], WithMixinsComponent.output[1]
@assertEqual WithMixinsComponent.output[3], null
@assertInstanceOf WithMixinsComponent.output[4], DependencyMixin
@assertEqual WithMixinsComponent.output[5], null
@assertInstanceOf WithMixinsComponent.output[6], SecondMixin
@assertEqual WithMixinsComponent.output[7], WithMixinsComponent.output[1]
@assertEqual WithMixinsComponent.output[8], WithMixinsComponent.output[0]
@assertEqual WithMixinsComponent.output[9], WithMixinsComponent.output[0]
@assertEqual WithMixinsComponent.output[10], WithMixinsComponent.output[6]
output = new (BlazeComponent.getComponent('WithMixinsComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'WithMixinsComponent', 'SecondMixin', 'FirstMixin'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
testClientMixinEvents: ->
FirstMixin.calls = []
SecondMixin.calls = []
SubComponent.calls = []
renderedComponent = Blaze.render Template.mixinEventsTestTemplate, $('body').get(0)
$('.mixinEventsTestTemplate button').each (i, button) =>
$(button).click()
@assertEqual FirstMixin.calls, [
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
# Event handlers are independent from each other among mixins. SecondMixin has its own onClick
# handler registered, so it should be called as well.
@assertEqual SecondMixin.calls, [
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
@assertEqual SubComponent.calls, [
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
Blaze.remove renderedComponent
testAfterCreateValue: ->
# We want to test that also properties added in onCreated hook are available in the template.
output = BlazeComponent.getComponent('AfterCreateValueComponent').renderComponentToHTML()
@assertEqual trim(output), trim """
<p>42</p>
<p>43</p>
"""
testClientPostMessageExample: [
->
@renderedComponent = Blaze.render PostMessageButtonComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.postMessageButtonComponent').html()), trim """
<button>Red</button>
"""
window.postMessage {color: "Blue"}, '*'
# Wait a bit for a message and also wait for a flush.
Meteor.setTimeout @expect(), 50 # ms
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.postMessageButtonComponent').html()), trim """
<button>Blue</button>
"""
Blaze.remove @renderedComponent
]
testBlockComponent: ->
output = Blaze.toHTMLWithData Template.testBlockComponent,
top: '42'
@assertEqual trim(output), trim """
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"Foo","email":"foo@example.com"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td>foo@example.com</td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"customers":[{"name":"Foo","email":"foo@example.com"}]}</p>
<p>{"a":"3a","b":"4a"}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td>foo@example.com</td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"Foo","email":"foo@example.com"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td>foo@example.com</td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"Foo","email":"foo@example.com"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td>foo@example.com</td>
</tbody>
</table>
"""
testClientComponentParent: [
->
reactiveChild1 false
reactiveChild2 false
@component = new ParentComponent()
@childComponents = []
@handle = Tracker.autorun (computation) =>
@childComponents.push @component.childComponents()
@childComponentsChild1 = []
@handleChild1 = Tracker.autorun (computation) =>
@childComponentsChild1.push @component.childComponentsWith childName: 'child1'
@childComponentsChild1DOM = []
@handleChild1DOM = Tracker.autorun (computation) =>
@childComponentsChild1DOM.push @component.childComponentsWith (child) ->
# We can search also based on DOM. We use domChanged to be sure check is called
# every time DOM changes. But it does not seem to be really necessary in this
# particular test (it passes without it as well). On the other hand domChanged
# also does not capture all changes. We are searching for an element by CSS class
# and domChanged is not changed when a class changes on a DOM element.
#child.domChanged()
child.$('.child1')?.length
@renderedComponent = Blaze.render @component.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), []
reactiveChild1 true
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents().length, 1
@child1Component = @component.childComponents()[0]
@assertEqual @child1Component.parentComponent(), @component
reactiveChild2 true
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents().length, 2
@child2Component = @component.childComponents()[1]
@assertEqual @child2Component.parentComponent(), @component
reactiveChild1 false
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), [@child2Component]
@assertEqual @child1Component.parentComponent(), null
reactiveChild2 false
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), []
@assertEqual @child2Component.parentComponent(), null
Blaze.remove @renderedComponent
@handle.stop()
@handleChild1.stop()
@handleChild1DOM.stop()
@assertEqual @childComponents, [
[]
[@child1Component]
[@child1Component, @child2Component]
[@child2Component]
[]
]
@assertEqual @childComponentsChild1, [
[]
[@child1Component]
[]
]
@assertEqual @childComponentsChild1DOM, [
[]
[@child1Component]
[]
]
]
testClientCases: [
->
@dataContext = new ReactiveField {case: 'left'}
@renderedComponent = Blaze.renderWithData Template.useCaseTemplate, (=> @dataContext()), $('body').get(0)
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Left</p>
"""
@dataContext {case: 'middle'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Middle</p>
"""
@dataContext {case: 'right'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Right</p>
"""
@dataContext {case: 'unknown'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """"""
Blaze.remove @renderedComponent
]
testClientMixinsExample: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('MyComponent').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: abc</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testClientReadmeExample: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponent').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientReadmeExampleJS: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponentJS').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientMixinsExampleWithJavaScript: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('OurComponentJS').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: >>>abc<<<</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testClientReadmeExampleES2015: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponentES2015').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientMixinsExampleWithES2015: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('OurComponentES2015').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: >>>abc<<<</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testOnDestroyedOrder: ->
OuterComponent.calls = []
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@states = []
@autorun =>
@states.push ['outer', @outerComponent.isCreated(), @outerComponent.isRendered(), @outerComponent.isDestroyed()]
@autorun =>
@states.push ['inner', @outerComponent.childComponents()[0]?.isCreated(), @outerComponent.childComponents()[0]?.isRendered(), @outerComponent.childComponents()[0]?.isDestroyed()]
output = @outerComponent.renderComponentToHTML()
@assertEqual trim(output), trim """
<div class="outerComponent">
<p class="innerComponent">Content.</p>
</div>
"""
@assertEqual OuterComponent.calls, [
'OuterComponent onCreated'
'InnerComponent onCreated'
'InnerComponent onDestroyed'
'OuterComponent onDestroyed'
]
@assertEqual @states, [
['outer', false, false, false]
['inner', undefined, undefined, undefined]
['outer', true, false, false]
['inner', true, false, false]
['inner', undefined, undefined, undefined]
['outer', false, false, true]
]
testClientOnDestroyedOrder: [
->
OuterComponent.calls = []
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@states = []
@autorun =>
@states.push ['outer', @outerComponent.isCreated(), @outerComponent.isRendered(), @outerComponent.isDestroyed()]
@autorun =>
@states.push ['inner', @outerComponent.childComponents()[0]?.isCreated(), @outerComponent.childComponents()[0]?.isRendered(), @outerComponent.childComponents()[0]?.isDestroyed()]
@renderedComponent = Blaze.render @outerComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
Blaze.remove @renderedComponent
Tracker.afterFlush @expect()
,
->
@assertEqual OuterComponent.calls, [
'OuterComponent onCreated'
'InnerComponent onCreated'
'InnerComponent onRendered'
'OuterComponent onRendered'
'InnerComponent onDestroyed'
'OuterComponent onDestroyed'
]
@assertEqual @states, [
['outer', false, false, false]
['inner', undefined, undefined, undefined]
['outer', true, false, false]
['inner', true, false, false]
['inner', true, true, false]
['outer', true, true, false]
['inner', undefined, undefined, undefined]
['outer', false, false, true]
]
]
testNamespacedArguments: ->
MyNamespace.Foo.ArgumentsComponent.calls = []
MyNamespace.Foo.ArgumentsComponent.constructorStateChanges = []
MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.namespacedArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="namespacedArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls.length, 4
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges MyNamespace.Foo.ArgumentsComponent.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges, true
OurNamespace.ArgumentsComponent.calls = []
OurNamespace.ArgumentsComponent.constructorStateChanges = []
OurNamespace.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.ourNamespacedArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="ourNamespacedArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual OurNamespace.ArgumentsComponent.calls.length, 4
@assertEqual OurNamespace.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges OurNamespace.ArgumentsComponent.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges OurNamespace.ArgumentsComponent.onCreatedStateChanges, true
OurNamespace.calls = []
OurNamespace.constructorStateChanges = []
OurNamespace.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.ourNamespaceComponentArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="ourNamespaceComponentArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual OurNamespace.calls.length, 4
@assertEqual OurNamespace.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges OurNamespace.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges OurNamespace.onCreatedStateChanges, true
testClientNamespacedArguments: [
->
MyNamespace.Foo.ArgumentsComponent.calls = []
MyNamespace.Foo.ArgumentsComponent.constructorStateChanges = []
MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.namespacedArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls.length, 5
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges MyNamespace.Foo.ArgumentsComponent.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges
,
->
OurNamespace.ArgumentsComponent.calls = []
OurNamespace.ArgumentsComponent.constructorStateChanges = []
OurNamespace.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.ourNamespacedArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual OurNamespace.ArgumentsComponent.calls.length, 5
@assertEqual OurNamespace.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges OurNamespace.ArgumentsComponent.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges OurNamespace.ArgumentsComponent.onCreatedStateChanges
,
->
OurNamespace.calls = []
OurNamespace.constructorStateChanges = []
OurNamespace.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.ourNamespaceComponentArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual OurNamespace.calls.length, 5
@assertEqual OurNamespace.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges OurNamespace.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges OurNamespace.onCreatedStateChanges
]
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/30.
testTemplateDynamic: ->
output = BlazeComponent.getComponent('TemplateDynamicTestComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'TemplateDynamicTestComponent', 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = new (BlazeComponent.getComponent('TemplateDynamicTestComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'TemplateDynamicTestComponent', 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = BlazeComponent.getComponent('FooComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = new (BlazeComponent.getComponent('FooComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = BlazeComponent.getComponent('SubComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
output = new (BlazeComponent.getComponent('SubComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
testClientGetComponentForElement: [
->
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@renderedComponent = Blaze.render @outerComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@innerComponent = @outerComponent.childComponents()[0]
@assertTrue @innerComponent
@assertEqual BlazeComponent.getComponentForElement($('.outerComponent').get(0)), @outerComponent
@assertEqual BlazeComponent.getComponentForElement($('.innerComponent').get(0)), @innerComponent
Blaze.remove @renderedComponent
]
testBlockHelpersStructure: ->
component = new (BlazeComponent.getComponent('TestBlockComponent'))()
@assertTrue component
output = component.renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim(TEST_BLOCK_COMPONENT_CONTENT())
testClientBlockHelpersStructure: [
->
@renderedComponent = Blaze.render Template.extraTestBlockComponent, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.extraTestBlockComponent').html()), trim(TEST_BLOCK_COMPONENT_CONTENT())
TestingComponentDebug.structure = {}
TestingComponentDebug.dumpComponentTree $('.extraTestBlockComponent table').get(0)
@assertEqual TestingComponentDebug.structure, TEST_BLOCK_COMPONENT_STRUCTURE()
@assertEqual BlazeComponent.getComponentForElement($('.insideContent').get(0)).componentName(), 'TestBlockComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideContentComponent').get(0)).componentName(), 'RowComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelper').get(0)).componentName(), 'ExtraTableWrapperBlockComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelperComponent').get(0)).componentName(), 'FootComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelperTemplate').get(0)).componentName(), 'ExtraTableWrapperBlockComponent'
Blaze.remove @renderedComponent
]
testClientExtendingTemplate: [
->
mainComponent3Calls = []
# To make sure we know what to expect from a template, we first test the template.
@renderedTemplate = Blaze.renderWithData Template.mainComponent3Test, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.mainComponent3').html()), trim """
<button>Foo1</button>
<p>mainComponent3.foobar/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
<button>Foo2</button>
<p>mainComponent3.foobar2/{"a":"3","b":"4"}/{"a":"3","b":"4"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}</p>
<p>mainComponent3.foobar3/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
"""
$('.mainComponent3 button').each (i, button) =>
$(button).click()
Blaze.remove @renderedTemplate
Tracker.afterFlush @expect()
,
->
@assertEqual mainComponent3Calls, [
[Template.mainComponent3, 'mainComponent3.onCreated', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onRendered', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onClick', {a: "1", b: "2"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onClick', {a: "3", b: "4"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onDestroyed', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
]
,
->
mainComponent3Calls = []
# And now we make a component which extends it.
@renderedTemplate = Blaze.renderWithData Template.mainComponent3ComponentTest, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.mainComponent3').html()), trim """
<button>Foo1</button>
<p>super:mainComponent3.foobar/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
<button>Foo2</button>
<p>mainComponent3.foobar2/{"a":"3","b":"4"}/{"a":"3","b":"4"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}</p>
<p>mainComponent3.foobar3/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
"""
$('.mainComponent3 button').each (i, button) =>
$(button).click()
Blaze.remove @renderedTemplate
Tracker.afterFlush @expect()
,
->
@assertEqual mainComponent3Calls, [
[MainComponent3, 'mainComponent3.onCreated', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onRendered', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onClick', {a: "1", b: "2"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onClick', {a: "3", b: "4"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onDestroyed', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
]
]
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/30.
testLexicalArguments: ->
return unless Blaze._lexicalBindingLookup
output = Blaze.toHTMLWithData Template.testLexicalArguments,
test: ['42']
@assertEqual trim(output), trim """42"""
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/109.
testIndex: ->
return unless Blaze._lexicalBindingLookup
output = Blaze.toHTMLWithData Template.testIndex,
test: ['42']
@assertEqual trim(output), trim """0"""
testLexicalArgumentsComponent: ->
output = BlazeComponent.getComponent('LexicalArgumentsComponent').renderComponentToHTML null, null,
test: [1, 2, 3]
@assertEqual trim(output), trim """
<div>{"test":[1,2,3]}</div>
<div>1/0</div>
<div>{"test":[1,2,3]}</div>
<div>2/1</div>
<div>{"test":[1,2,3]}</div>
<div>3/2</div>
"""
testInlineEventsToHTML: ->
output = Blaze.toHTML Template.inlineEventsTestTemplate
@assertEqual trim(output), trim """
<div class="inlineEventsTestTemplate">
<form>
<div>
<button class="button1" type="button">Button 1</button>
<button class="button2" type="button">Button 2</button>
<button class="button3 dynamic" type="button">Button 3</button>
<button class="button4 dynamic" type="button">Button 4</button>
<button class="button5" type="button" title="Foobar">Button 5</button>
<input type="text">
<textarea></textarea>
</div>
</form>
</div>
"""
testClientInlineEvents: [
->
reactiveArguments {z: 1}
InlineEventsComponent.calls = []
@renderedComponent = Blaze.render Template.inlineEventsTestTemplate, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.inlineEventsTestTemplate').html()), trim """
<form>
<div>
<button class="button1" type="button">Button 1</button>
<button class="button2" type="button">Button 2</button>
<button class="button3 dynamic" type="button">Button 3</button>
<button class="button4 dynamic" type="button">Button 4</button>
<button class="button5" type="button" title="Foobar">Button 5</button>
<input type="text">
<textarea></textarea>
</div>
</form>
"""
# Event handlers should not be called like template heleprs.
@assertEqual InlineEventsComponent.calls, []
InlineEventsComponent.calls = []
$('.inlineEventsTestTemplate button').each (i, button) =>
$(button).click()
$('.inlineEventsTestTemplate textarea').each (i, textarea) =>
$(textarea).change()
$('.inlineEventsTestTemplate input').each (i, input) =>
$(input).click()
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton1Click', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onClick1Extra', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton2Click', {top: '42'}, {a: '3', b: '4'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 1}, new Spacebars.kw()]
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 1}})]
['InlineEventsComponent', 'InlineEventsComponent.extraArgs1', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.extraArgs2', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onChange', {top: '42'}, {top: '42'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onTextClick', {top: '42'}, {a: '11', b: '12'}, 'InlineEventsComponent']
]
InlineEventsComponent.calls = []
reactiveArguments {z: 2}
Tracker.afterFlush @expect()
,
->
$('.inlineEventsTestTemplate button').each (i, button) =>
$(button).click()
$('.inlineEventsTestTemplate textarea').each (i, textarea) =>
$(textarea).change()
$('.inlineEventsTestTemplate input').each (i, input) =>
$(input).click()
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton1Click', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onClick1Extra', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton2Click', {top: '42'}, {a: '3', b: '4'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 2}, new Spacebars.kw()]
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 2}})]
['InlineEventsComponent', 'InlineEventsComponent.extraArgs1', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.extraArgs2', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onChange', {top: '42'}, {top: '42'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onTextClick', {top: '42'}, {a: '11', b: '12'}, 'InlineEventsComponent']
]
InlineEventsComponent.calls = []
$('.inlineEventsTestTemplate button.dynamic').each (i, button) =>
$(button).trigger('click', 'extraArgument')
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 2}, new Spacebars.kw(), 'extraArgument']
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 2}}), 'extraArgument']
]
Blaze.remove @renderedComponent
]
testClientInvalidInlineEvents: ->
@assertThrows =>
Blaze.render Template.invalidInlineEventsTestTemplate, $('body').get(0)
,
/Invalid event handler/
testClientBody: ->
output = Blaze.toHTML Template.body
@assertTrue $($.parseHTML(output)).is('.bodyTest')
testServerBody: ->
output = Blaze.toHTML Template.body
@assertEqual trim(output), trim """
<div class="bodyTest">Body test.</div>
"""
testClientHead: ->
@assertTrue jQuery('head').find('noscript').length
testNestedMixins: ->
LevelTwoComponent.children = []
output = BlazeComponent.getComponent('LevelOneComponent').renderComponentToHTML null, null
@assertEqual trim(output), trim """
<span>41</span>
<span>42</span>
<span></span>
"""
@assertEqual LevelTwoComponent.children, [
all: 0
,
topValue: 0
,
hasValue: 0
,
hasNoValue: 0
,
all: 1
,
topValue: 1
,
hasValue: 1
,
all: 0
,
topValue: 0
,
hasValue: 0
]
ClassyTestCase.addTest new BasicTestCase()
| 198070 | trim = (html) =>
html = html.replace />\s+/g, '>'
html = html.replace /\s+</g, '<'
html.trim()
class MainComponent extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
# To test when name of the component mismatches the template name. Template name should have precedence.
'MainComponent2'
foobar: ->
"#{@componentName()}/MainComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/MainComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@componentName()}/MainComponent.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
isMainComponent: ->
@constructor is MainComponent
onClick: (event) ->
assert not Tracker.active
@constructor.calls.push [@componentName(), 'MainComponent.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: ->
assert not Tracker.active
[
'click': @onClick
]
onCreated: ->
self = @
# To test that a computation is bound to the component.
@autorun (computation) ->
assert.equal @, self
BlazeComponent.register 'MainComponent', MainComponent
# Template should match registered name.
class FooComponent extends BlazeComponent
BlazeComponent.register 'FooComponent', FooComponent
class SelfRegisterComponent extends BlazeComponent
# Alternative way of registering components.
@register 'SelfRegisterComponent'
class SubComponent extends MainComponent
@calls: []
foobar: ->
"#{@componentName()}/SubComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/SubComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not override foobar3.
onClick: (event) ->
@constructor.calls.push [@componentName(), 'SubComponent.onClick', @data(), @currentData(), @currentComponent().componentName()]
BlazeComponent.register 'SubComponent', SubComponent
class UnregisteredComponent extends SubComponent
foobar: ->
"#{@componentName()}/UnregisteredComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/UnregisteredComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# Name has to be set manually.
UnregisteredComponent.componentName 'UnregisteredComponent'
class SelfNameUnregisteredComponent extends UnregisteredComponent
# Alternative way of setting the name manually.
@componentName 'SelfNameUnregisteredComponent'
# We do not extend any helper on purpose. So they should all use "UnregisteredComponent".
class AnimatedListComponent extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
'AnimatedListComponent'
onCreated: ->
assert not Tracker.active
# To test inserts, moves, and removals.
@_list = new ReactiveField [1, 2, 3, 4, 5]
@_handle = Meteor.setInterval =>
list = @_list()
# Moves the last number to the first place.
list = [list[4]].concat list[0...4]
# Removes the smallest number.
list = _.without list, _.min list
# Adds one more number, one larger than the current largest.
list = list.concat [_.max(list) + 1]
@_list list
, 1000 # ms
onDestroyed: ->
assert not Tracker.active
Meteor.clearInterval @_handle
list: ->
_id: i for i in @_list()
insertDOMElement: (parent, node, before) ->
assert not Tracker.active
@constructor.calls.push ['insertDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML), trim(before?.outerHTML or '')]
super arguments...
moveDOMElement: (parent, node, before) ->
assert not Tracker.active
@constructor.calls.push ['moveDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML), trim(before?.outerHTML or '')]
super arguments...
removeDOMElement: (parent, node) ->
assert not Tracker.active
@constructor.calls.push ['removeDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML)]
super arguments...
BlazeComponent.register 'AnimatedListComponent', AnimatedListComponent
class DummyComponent extends BlazeComponent
@register 'DummyComponent'
class ArgumentsComponent extends BlazeComponent
@calls: []
@constructorStateChanges: []
@onCreatedStateChanges: []
template: ->
assert not Tracker.active
'ArgumentsComponent'
constructor: ->
super arguments...
assert not Tracker.active
@constructor.calls.push arguments[0]
@arguments = arguments
@componentId = Random.id()
@handles = []
@collectStateChanges @constructor.constructorStateChanges
onCreated: ->
assert not Tracker.active
super arguments...
@collectStateChanges @constructor.onCreatedStateChanges
collectStateChanges: (output) ->
output.push
componentId: @componentId
view: Blaze.currentView
templateInstance: Template.instance()
for method in ['isCreated', 'isRendered', 'isDestroyed', 'data', 'currentData', 'component', 'currentComponent', 'firstNode', 'lastNode', 'subscriptionsReady']
do (method) =>
@handles.push Tracker.autorun (computation) =>
data =
componentId: @componentId
data[method] = @[method]()
output.push data
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
find: @find('*')
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
findAll: @findAll('*')
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
$: @$('*')
onDestroyed: ->
assert not Tracker.active
super arguments...
Tracker.afterFlush =>
while handle = @handles.pop()
handle.stop()
dataContext: ->
EJSON.stringify @data()
currentDataContext: ->
EJSON.stringify @currentData()
constructorArguments: ->
EJSON.stringify @arguments
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
BlazeComponent.register 'ArgumentsComponent', ArgumentsComponent
class MyNamespace
class MyNamespace.Foo
class MyNamespace.Foo.ArgumentsComponent extends ArgumentsComponent
@register 'MyNamespace.Foo.ArgumentsComponent'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'MyNamespace.Foo.ArgumentsComponent'
# We want to test if a component with the same name as the namespace can coexist.
class OurNamespace extends ArgumentsComponent
@register 'OurNamespace'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'OurNamespace'
class OurNamespace.ArgumentsComponent extends ArgumentsComponent
@register 'OurNamespace.ArgumentsComponent'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'OurNamespace.ArgumentsComponent'
reactiveContext = new ReactiveField {}
reactiveArguments = new ReactiveField {}
class ArgumentsTestComponent extends BlazeComponent
@register 'ArgumentsTestComponent'
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.namespacedArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.ourNamespacedArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.ourNamespaceComponentArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
class ExistingClassHierarchyBase
foobar: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
class ExistingClassHierarchyChild extends ExistingClassHierarchyBase
class ExistingClassHierarchyBaseComponent extends ExistingClassHierarchyChild
for property, value of BlazeComponent when property not in ['__super__']
ExistingClassHierarchyBaseComponent[property] = value
for property, value of (BlazeComponent::) when property not in ['constructor']
ExistingClassHierarchyBaseComponent::[property] = value
class ExistingClassHierarchyComponent extends ExistingClassHierarchyBaseComponent
template: ->
assert not Tracker.active
'MainComponent2'
foobar: ->
"#{@componentName()}/ExistingClassHierarchyComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/ExistingClassHierarchyComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not override foobar3.
ExistingClassHierarchyComponent.register 'ExistingClassHierarchyComponent', ExistingClassHierarchyComponent
class FirstMixin extends BlazeComponent
@calls: []
foobar: ->
"#{@component().componentName()}/FirstMixin.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@component().componentName()}/FirstMixin.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@component().componentName()}/FirstMixin.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
isMainComponent: ->
@component().constructor is WithMixinsComponent
onClick: (event) ->
@constructor.calls.push [@component().componentName(), 'FirstMixin.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: -> [
'click': @onClick
]
class SecondMixin extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
@_template()
_template: ->
'MainComponent2'
foobar: ->
"#{@component().componentName()}/SecondMixin.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@component().componentName()}/SecondMixin.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not provide foobar3.
onClick: (event) ->
@constructor.calls.push [@component().componentName(), 'SecondMixin.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: ->
assert not Tracker.active
[
'click': @onClick
]
onCreated: ->
assert not Tracker.active
# To test if adding a dependency during onCreated will make sure
# to call onCreated on the added dependency as well.
@mixinParent().requireMixin DependencyMixin
SecondMixin.componentName 'SecondMixin'
class DependencyMixin extends BlazeComponent
@calls: []
onCreated: ->
assert not Tracker.active
@constructor.calls.push true
class WithMixinsComponent extends BlazeComponent
@output: []
mixins: ->
assert not Tracker.active
[SecondMixin, FirstMixin]
onDestroyed: ->
firstMixin = @getMixin FirstMixin
@constructor.output.push @
@constructor.output.push firstMixin
@constructor.output.push @getMixin firstMixin
@constructor.output.push @getMixin @
@constructor.output.push @getMixin DependencyMixin
@constructor.output.push @getMixin 'FirstMixin'
@constructor.output.push @getMixin 'SecondMixin'
@constructor.output.push @getFirstWith null, 'isMainComponent'
@constructor.output.push @getFirstWith null, (child, parent) =>
!!child.constructor.output
@constructor.output.push @getFirstWith null, (child, parent) =>
child is parent
@constructor.output.push @getFirstWith null, (child, parent) =>
child._template?() is 'MainComponent2'
BlazeComponent.register 'WithMixinsComponent', WithMixinsComponent
class AfterCreateValueComponent extends BlazeComponent
template: ->
assert not Tracker.active
'AfterCreateValueComponent'
onCreated: ->
assert not Tracker.active
@foobar = '42'
@_foobar = '43'
BlazeComponent.register 'AfterCreateValueComponent', AfterCreateValueComponent
class PostMessageButtonComponent extends BlazeComponent
onCreated: ->
assert not Tracker.active
@color = new ReactiveField "Red"
$(window).on 'message.buttonComponent', (event) =>
if color = event.originalEvent.data?.color
@color color
onDestroyed: ->
$(window).off '.buttonComponent'
BlazeComponent.register 'PostMessageButtonComponent', PostMessageButtonComponent
class TableWrapperBlockComponent extends BlazeComponent
template: ->
assert not Tracker.active
'TableWrapperBlockComponent'
currentDataContext: ->
EJSON.stringify @currentData()
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
BlazeComponent.register 'TableWrapperBlockComponent', TableWrapperBlockComponent
Template.testBlockComponent.helpers
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
customersDataContext: ->
customers: [
name: '<NAME>'
email: '<EMAIL>'
]
reactiveChild1 = new ReactiveField false
reactiveChild2 = new ReactiveField false
class ChildComponent extends BlazeComponent
template: ->
assert not Tracker.active
'ChildComponent'
constructor: (@childName) ->
super arguments...
assert not Tracker.active
onCreated: ->
assert not Tracker.active
@domChanged = new ReactiveField 0
insertDOMElement: (parent, node, before) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
moveDOMElement: (parent, node, before) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
removeDOMElement: (parent, node) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
BlazeComponent.register 'ChildComponent', ChildComponent
class ParentComponent extends BlazeComponent
template: ->
assert not Tracker.active
'ParentComponent'
child1: ->
reactiveChild1()
child2: ->
reactiveChild2()
BlazeComponent.register 'ParentComponent', ParentComponent
class CaseComponent extends BlazeComponent
@register 'CaseComponent'
constructor: (kwargs) ->
super arguments...
assert not Tracker.active
@cases = kwargs.hash
renderCase: ->
caseComponent = @cases[@data().case]
return null unless caseComponent
BlazeComponent.getComponent(caseComponent).renderComponent @
class LeftComponent extends BlazeComponent
@register 'LeftComponent'
template: ->
assert not Tracker.active
'LeftComponent'
class MiddleComponent extends BlazeComponent
@register 'MiddleComponent'
template: ->
assert not Tracker.active
'MiddleComponent'
class RightComponent extends BlazeComponent
@register 'RightComponent'
template: ->
assert not Tracker.active
'RightComponent'
class MyComponent extends BlazeComponent
@register 'MyComponent'
mixins: ->
assert not Tracker.active
[FirstMixin2, new SecondMixin2 'foobar']
alternativeName: ->
@callFirstWith null, 'templateHelper'
values: ->
'a' + (@callFirstWith(@, 'values') or '')
class FirstMixinBase extends BlazeComponent
@calls: []
templateHelper: ->
"42"
extendedHelper: ->
1
onClick: ->
throw new Error() if @values() isnt @valuesPredicton
@constructor.calls.push true
class FirstMixin2 extends FirstMixinBase
extendedHelper: ->
super() + 2
values: ->
'b' + (@mixinParent().callFirstWith(@, 'values') or '')
dataContext: ->
EJSON.stringify @data()
events: ->
assert not Tracker.active
super.concat
'click': @onClick
onCreated: ->
assert not Tracker.active
@valuesPredicton = 'bc'
class SecondMixin2
constructor: (@name) ->
assert not Tracker.active
mixinParent: (mixinParent) ->
@_mixinParent = mixinParent if mixinParent
@_mixinParent
values: ->
'c' + (@mixinParent().callFirstWith(@, 'values') or '')
# Example from the README.
class ExampleComponent extends BlazeComponent
@register 'ExampleComponent'
onCreated: ->
assert not Tracker.active
super arguments...
@counter = new ReactiveField 0
events: ->
assert not Tracker.active
super.concat
'click .increment': @onClick
onClick: (event) ->
@counter @counter() + 1
customHelper: ->
if @counter() > 10
"Too many times"
else if @counter() is 10
"Just enough"
else
"Click more"
class OuterComponent extends BlazeComponent
@register 'OuterComponent'
@calls: []
template: ->
assert not Tracker.active
'OuterComponent'
onCreated: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onCreated'
onRendered: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onRendered'
onDestroyed: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onDestroyed'
class InnerComponent extends BlazeComponent
@register 'InnerComponent'
template: ->
assert not Tracker.active
'InnerComponent'
onCreated: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onCreated'
onRendered: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onRendered'
onDestroyed: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onDestroyed'
class TemplateDynamicTestComponent extends MainComponent
@register 'TemplateDynamicTestComponent'
@calls: []
template: ->
assert not Tracker.active
'TemplateDynamicTestComponent'
isMainComponent: ->
@constructor is TemplateDynamicTestComponent
class ExtraTableWrapperBlockComponent extends BlazeComponent
@register 'ExtraTableWrapperBlockComponent'
class TestBlockComponent extends BlazeComponent
@register 'TestBlockComponent'
nameFromComponent: ->
"Works"
renderRow: ->
BlazeComponent.getComponent('RowComponent').renderComponent @currentComponent()
class RowComponent extends BlazeComponent
@register 'RowComponent'
class FootComponent extends BlazeComponent
@register 'FootComponent'
class CaptionComponent extends BlazeComponent
@register 'CaptionComponent'
class RenderRowComponent extends BlazeComponent
@register 'RenderRowComponent'
parentComponentRenderRow: ->
@parentComponent().parentComponent().renderRow()
class TestingComponentDebug extends BlazeComponentDebug
@structure: {}
stack = []
@lastElement: (structure) ->
return structure if 'children' not of structure
stack[stack.length - 1] = structure.children
@lastElement structure.children[structure.children.length - 1]
@startComponent: (component) ->
stack.push null
element = @lastElement @structure
element.component = component.componentName()
element.data = component.data()
element.children = [{}]
@endComponent: (component) ->
# Only the top-level stack element stays null and is not set to a children array.
stack[stack.length - 1].push {} if stack.length > 1
stack.pop()
@startMarkedComponent: (component) ->
@startComponent component
@endMarkedComponent: (component) ->
@endComponent component
class LexicalArgumentsComponent extends BlazeComponent
@register 'LexicalArgumentsComponent'
rowOfCurrentData: ->
EJSON.stringify @currentData()
rowOfFooAndIndex: ->
"#{EJSON.stringify @currentData 'foo'}/#{@currentData '@index'}"
mainComponent3Calls = []
Template.mainComponent3.events
'click': (event, template) ->
assert.equal Template.instance(), template
assert not Tracker.active
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onClick', @, Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.helpers
foobar: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
foobar2: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar2/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
foobar3: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar3/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
Template.mainComponent3.onCreated ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onCreated', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.onRendered ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onRendered', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.onDestroyed ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onDestroyed', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
class MainComponent3 extends BlazeComponent
@register 'MainComponent3'
template: ->
'mainComponent3'
foobar: ->
# An ugly way to extend a base template helper.
helper = @_componentInternals.templateBase.__helpers.get 'foobar'
# Blaze template helpers expect current data context bound to "this".
result = helper.call @currentData()
'super:' + result
reactiveArguments = new ReactiveField null
class InlineEventsComponent extends BlazeComponent
@calls: []
@register 'InlineEventsComponent'
onButton1Click: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton1Click', @data(), @currentData(), @currentComponent().componentName()]
onButton2Click: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton2Click', @data(), @currentData(), @currentComponent().componentName()]
onClick1Extra: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onClick1Extra', @data(), @currentData(), @currentComponent().componentName()]
onButton3Click: (event, args...) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton3Click', @data(), @currentData(), @currentComponent().componentName()].concat args
onButton4Click: (event, args...) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton4Click', @data(), @currentData(), @currentComponent().componentName()].concat args
dynamicArgument: ->
reactiveArguments()
onChange: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onChange', @data(), @currentData(), @currentComponent().componentName()]
onTextClick: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onTextClick', @data(), @currentData(), @currentComponent().componentName()]
extraArgs1: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.extraArgs1', @data(), @currentData(), @currentComponent().componentName()]
extraArgs2: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.extraArgs2', @data(), @currentData(), @currentComponent().componentName()]
extraArgs: ->
title: "Foobar"
onClick: [
@extraArgs1
,
@extraArgs2
]
class InvalidInlineEventsComponent extends BlazeComponent
@register 'InvalidInlineEventsComponent'
class LevelOneComponent extends BlazeComponent
@register 'LevelOneComponent'
class LevelTwoComponent extends BlazeComponent
@children: []
@register 'LevelTwoComponent'
onCreated: ->
super arguments...
@autorun =>
@constructor.children.push all: @childComponents().length
@autorun =>
@constructor.children.push topValue: @childComponentsWith(topValue: 41).length
@autorun =>
@constructor.children.push hasValue: @childComponentsWith(hasValue: 42).length
@autorun =>
@constructor.children.push hasNoValue: @childComponentsWith(hasNoValue: 43).length
class LevelOneMixin extends BlazeComponent
mixins: ->
[LevelTwoMixin]
# This one should be resolved in the template.
hasValue: ->
42
class LevelTwoMixin extends BlazeComponent
# This one should not be resolved in the template.
hasNoValue: ->
43
class ComponentWithNestedMixins extends BlazeComponent
@register 'ComponentWithNestedMixins'
mixins: ->
[LevelOneMixin]
topValue: ->
41
class BasicTestCase extends ClassyTestCase
@testName: 'blaze-components - basic'
FOO_COMPONENT_CONTENT = ->
"""
<p>Other component: FooComponent</p>
<button>Foo2</button>
<p></p>
<button>Foo3</button>
<p></p>
<p></p>
"""
COMPONENT_CONTENT = (componentName, helperComponentName, mainComponent) ->
helperComponentName ?= componentName
mainComponent ?= 'MainComponent'
"""
<p>Main component: #{componentName}</p>
<button>Foo1</button>
<p>#{componentName}/#{helperComponentName}.foobar/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<button>Foo2</button>
<p>#{componentName}/#{helperComponentName}.foobar2/{"top":"42"}/{"a":"1","b":"2"}/#{componentName}</p>
<p>#{componentName}/#{mainComponent}.foobar3/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<p>Subtemplate</p>
<button>Foo1</button>
<p>#{componentName}/#{helperComponentName}.foobar/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<button>Foo2</button>
<p>#{componentName}/#{helperComponentName}.foobar2/{"top":"42"}/{"a":"3","b":"4"}/#{componentName}</p>
<p>#{componentName}/#{mainComponent}.foobar3/{"top":"42"}/{"top":"42"}/#{componentName}</p>
#{FOO_COMPONENT_CONTENT()}
"""
TEST_BLOCK_COMPONENT_CONTENT = ->
"""
<h2>Names and emails and components (CaptionComponent/CaptionComponent/CaptionComponent)</h2>
<h3 class="insideBlockHelperTemplate">(ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent)</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th class="insideBlockHelper">Email</th>
<th>Component (ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Foo</td>
<td class="insideContent"><EMAIL>.com</td>
<td>TestBlockComponent/TestBlockComponent/ExtraTableWrapperBlockComponent</td>
</tr>
<tr>
<td>Bar</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Baz</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bac</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bam</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bav</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bak</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bal</td>
<td class="insideContentComponent"><EMAIL></td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th class="insideBlockHelperComponent">Email</th>
<th>Component (FootComponent/FootComponent/FootComponent)</th>
</tr>
</tfoot>
</table>
"""
TEST_BLOCK_COMPONENT_STRUCTURE = ->
component: 'TestBlockComponent'
data: {top: '42'}
children: [
component: 'ExtraTableWrapperBlockComponent'
data: {block: '43'}
children: [
component: 'CaptionComponent'
data: {block: '43'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RenderRowComponent'
data: {top: '42'}
children: [
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
component: 'RowComponent'
data: {name: '<NAME>', email: '<EMAIL>'}
children: [{}]
,
{}
]
,
component: 'FootComponent'
data: {block: '43'}
children: [{}]
,
{}
]
,
{}
]
testComponents: ->
output = BlazeComponent.getComponent('MainComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = new (BlazeComponent.getComponent('MainComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = BlazeComponent.getComponent('FooComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = new (BlazeComponent.getComponent('FooComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = BlazeComponent.getComponent('SubComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
output = new (BlazeComponent.getComponent('SubComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
testGetComponent: ->
@assertEqual BlazeComponent.getComponent('MainComponent'), MainComponent
@assertEqual BlazeComponent.getComponent('FooComponent'), FooComponent
@assertEqual BlazeComponent.getComponent('SubComponent'), SubComponent
@assertEqual BlazeComponent.getComponent('unknown'), null
testComponentName: ->
@assertEqual MainComponent.componentName(), 'MainComponent'
@assertEqual FooComponent.componentName(), 'FooComponent'
@assertEqual SubComponent.componentName(), 'SubComponent'
@assertEqual BlazeComponent.componentName(), null
testSelfRegister: ->
@assertTrue BlazeComponent.getComponent 'SelfRegisterComponent'
testUnregisteredComponent: ->
output = UnregisteredComponent.renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'UnregisteredComponent'
output = new UnregisteredComponent().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'UnregisteredComponent'
output = SelfNameUnregisteredComponent.renderComponentToHTML null, null,
top: '42'
# We have not extended any helper on purpose, so they should still use "UnregisteredComponent".
@assertEqual trim(output), trim COMPONENT_CONTENT 'SelfNameUnregisteredComponent', 'UnregisteredComponent'
output = new SelfNameUnregisteredComponent().renderComponentToHTML null, null,
top: '42'
# We have not extended any helper on purpose, so they should still use "UnregisteredComponent".
@assertEqual trim(output), trim COMPONENT_CONTENT 'SelfNameUnregisteredComponent', 'UnregisteredComponent'
testErrors: ->
@assertThrows =>
BlazeComponent.register()
,
/Component name is required for registration/
@assertThrows =>
BlazeComponent.register 'MainComponent', null
,
/Component 'MainComponent' already registered/
@assertThrows =>
BlazeComponent.register 'OtherMainComponent', MainComponent
,
/Component 'OtherMainComponent' already registered under the name 'MainComponent'/
class WithoutTemplateComponent extends BlazeComponent
@assertThrows =>
WithoutTemplateComponent.renderComponentToHTML()
,
/Template for the component 'unnamed' not provided/
@assertThrows =>
new WithoutTemplateComponent().renderComponentToHTML()
,
/Template for the component 'unnamed' not provided/
class WithUnknownTemplateComponent extends BlazeComponent
@componentName 'WithoutTemplateComponent'
template: ->
'TemplateWhichDoesNotExist'
@assertThrows =>
WithUnknownTemplateComponent.renderComponentToHTML()
,
/Template 'TemplateWhichDoesNotExist' cannot be found/
@assertThrows =>
new WithUnknownTemplateComponent().renderComponentToHTML()
,
/Template 'TemplateWhichDoesNotExist' cannot be found/
testClientEvents: [
->
MainComponent.calls = []
SubComponent.calls = []
@renderedComponent = Blaze.render Template.eventsTestTemplate, $('body').get(0)
Tracker.afterFlush @expect()
,
->
$('.eventsTestTemplate button').each (i, button) =>
$(button).click()
@assertEqual MainComponent.calls, [
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
@assertEqual SubComponent.calls, [
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
Blaze.remove @renderedComponent
]
testClientAnimation: [
->
AnimatedListComponent.calls = []
@renderedComponent = Blaze.render Template.animationTestTemplate, $('body').get(0)
Meteor.setTimeout @expect(), 2500 # ms
,
->
Blaze.remove @renderedComponent
calls = AnimatedListComponent.calls
AnimatedListComponent.calls = []
expectedCalls = [
['insertDOMElement', 'AnimatedListComponent', '<div class="animationTestTemplate"></div>', '<div><ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul></div>', '']
['removeDOMElement', 'AnimatedListComponent', '<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>', '<li>1</li>']
['moveDOMElement', 'AnimatedListComponent', '<ul><li>2</li><li>3</li><li>4</li><li>5</li></ul>', '<li>5</li>', '']
['insertDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>2</li><li>3</li><li>4</li></ul>', '<li>6</li>', '']
['removeDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>2</li><li>3</li><li>4</li><li>6</li></ul>', '<li>2</li>']
['moveDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>3</li><li>4</li><li>6</li></ul>', '<li>6</li>', '']
['insertDOMElement', 'AnimatedListComponent', '<ul><li>6</li><li>5</li><li>3</li><li>4</li></ul>', '<li>7</li>', '']
]
# There could be some more calls made, we ignore them and just take the first 8.
@assertEqual calls[0...8], expectedCalls
Meteor.setTimeout @expect(), 2000 # ms
,
->
# After we removed the component no more calls should be made.
@assertEqual AnimatedListComponent.calls, []
]
assertArgumentsConstructorStateChanges: (stateChanges, wrappedInComponent=true, staticRender=false) ->
firstSteps = (dataContext) =>
change = stateChanges.shift()
componentId = change.componentId
@assertTrue change.view
@assertTrue change.templateInstance
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isDestroyed
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.currentData, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.component, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
if wrappedInComponent
@assertInstanceOf change.currentComponent, ArgumentsTestComponent
else
@assertIsNull change.currentComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
componentId
firstComponentId = firstSteps a: "1", b: "2"
secondComponentId = firstSteps a:"3a", b: "4a"
thirdComponentId = firstSteps a: "5", b: "6"
forthComponentId = firstSteps {}
if staticRender
@assertEqual stateChanges, []
return
secondSteps = (componentId, dataContext) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.data, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isCreated
secondSteps firstComponentId, a: "1", b: "2"
secondSteps secondComponentId, a:"3a", b: "4a"
secondSteps thirdComponentId, a: "5", b: "6"
secondSteps forthComponentId, {}
thirdSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.firstNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.lastNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.find?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.findAll), ["P", "P", "P", "P"]
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.$), ["P", "P", "P", "P"]
thirdSteps firstComponentId
thirdSteps secondComponentId
thirdSteps thirdComponentId
thirdSteps forthComponentId
# TODO: This change is probably unnecessary? Could we prevent it?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
if change.data
# TODO: In Chrome data is set. Why?
@assertEqual change.data, a: "10", b: "11"
else
# TODO: In Firefox data is undefined. Why?
@assertIsUndefined change.data
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertIsUndefined change.currentData
fifthComponentId = firstSteps a: "10", b: "11"
forthSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
forthSteps forthComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertEqual change.data, a: "10", b: "11"
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isCreated
forthSteps firstComponentId
forthSteps secondComponentId
forthSteps thirdComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertFalse change.isCreated
# TODO: Why is isRendered not set to false and all related other fields which require it (firstNode, lastNode, find, findAll, $)?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.subscriptionsReady
@assertEqual stateChanges, []
assertArgumentsOnCreatedStateChanges: (stateChanges, staticRender=false) ->
firstSteps = (dataContext) =>
change = stateChanges.shift()
componentId = change.componentId
@assertTrue change.view
@assertTrue change.templateInstance
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isDestroyed
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.data, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.currentData, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.component, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.currentComponent, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
componentId
firstComponentId = firstSteps a: "1", b: "2"
secondComponentId = firstSteps a:"3a", b: "4a"
thirdComponentId = firstSteps a: "5", b: "6"
forthComponentId = firstSteps {}
if staticRender
@assertEqual stateChanges, []
return
thirdSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.firstNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.lastNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.find?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.findAll), ["P", "P", "P", "P"]
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.$), ["P", "P", "P", "P"]
thirdSteps firstComponentId
thirdSteps secondComponentId
thirdSteps thirdComponentId
thirdSteps forthComponentId
# TODO: This change is probably unnecessary? Could we prevent it?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertEqual change.data, a: "10", b: "11"
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertIsUndefined change.currentData
fifthComponentId = firstSteps a: "10", b: "11"
forthSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
forthSteps forthComponentId
forthSteps firstComponentId
forthSteps secondComponentId
forthSteps thirdComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertFalse change.isCreated
# TODO: Why is isRendered not set to false and all related other fields which require it (firstNode, lastNode, find, findAll, $)?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.subscriptionsReady
@assertEqual stateChanges, []
testArguments: ->
ArgumentsComponent.calls = []
ArgumentsComponent.constructorStateChanges = []
ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.argumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="argumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual ArgumentsComponent.calls.length, 4
@assertEqual ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges ArgumentsComponent.constructorStateChanges, true, true
@assertArgumentsOnCreatedStateChanges ArgumentsComponent.onCreatedStateChanges, true
testClientArguments: [
->
ArgumentsComponent.calls = []
ArgumentsComponent.constructorStateChanges = []
ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.argumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual ArgumentsComponent.calls.length, 5
@assertEqual ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges ArgumentsComponent.constructorStateChanges
@assertArgumentsOnCreatedStateChanges ArgumentsComponent.onCreatedStateChanges
]
testExistingClassHierarchy: ->
# We want to allow one to reuse existing class hierarchy they might already have and only
# add the Meteor components "nature" to it. This is simply done by extending the base class
# and base class prototype with those from a wanted base class and prototype.
output = BlazeComponent.getComponent('ExistingClassHierarchyComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'ExistingClassHierarchyComponent', 'ExistingClassHierarchyComponent', 'ExistingClassHierarchyBase'
testMixins: ->
DependencyMixin.calls = []
WithMixinsComponent.output = []
output = BlazeComponent.getComponent('WithMixinsComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'WithMixinsComponent', 'SecondMixin', 'FirstMixin'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
@assertEqual DependencyMixin.calls, [true]
@assertInstanceOf WithMixinsComponent.output[1], FirstMixin
@assertEqual WithMixinsComponent.output[2], WithMixinsComponent.output[1]
@assertEqual WithMixinsComponent.output[3], null
@assertInstanceOf WithMixinsComponent.output[4], DependencyMixin
@assertEqual WithMixinsComponent.output[5], null
@assertInstanceOf WithMixinsComponent.output[6], SecondMixin
@assertEqual WithMixinsComponent.output[7], WithMixinsComponent.output[1]
@assertEqual WithMixinsComponent.output[8], WithMixinsComponent.output[0]
@assertEqual WithMixinsComponent.output[9], WithMixinsComponent.output[0]
@assertEqual WithMixinsComponent.output[10], WithMixinsComponent.output[6]
output = new (BlazeComponent.getComponent('WithMixinsComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'WithMixinsComponent', 'SecondMixin', 'FirstMixin'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
testClientMixinEvents: ->
FirstMixin.calls = []
SecondMixin.calls = []
SubComponent.calls = []
renderedComponent = Blaze.render Template.mixinEventsTestTemplate, $('body').get(0)
$('.mixinEventsTestTemplate button').each (i, button) =>
$(button).click()
@assertEqual FirstMixin.calls, [
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
# Event handlers are independent from each other among mixins. SecondMixin has its own onClick
# handler registered, so it should be called as well.
@assertEqual SecondMixin.calls, [
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
@assertEqual SubComponent.calls, [
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
Blaze.remove renderedComponent
testAfterCreateValue: ->
# We want to test that also properties added in onCreated hook are available in the template.
output = BlazeComponent.getComponent('AfterCreateValueComponent').renderComponentToHTML()
@assertEqual trim(output), trim """
<p>42</p>
<p>43</p>
"""
testClientPostMessageExample: [
->
@renderedComponent = Blaze.render PostMessageButtonComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.postMessageButtonComponent').html()), trim """
<button>Red</button>
"""
window.postMessage {color: "Blue"}, '*'
# Wait a bit for a message and also wait for a flush.
Meteor.setTimeout @expect(), 50 # ms
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.postMessageButtonComponent').html()), trim """
<button>Blue</button>
"""
Blaze.remove @renderedComponent
]
testBlockComponent: ->
output = Blaze.toHTMLWithData Template.testBlockComponent,
top: '42'
@assertEqual trim(output), trim """
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"<NAME>","email":"<EMAIL>"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td><EMAIL></td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"customers":[{"name":"<NAME>","email":"<EMAIL>"}]}</p>
<p>{"a":"3a","b":"4a"}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td><EMAIL></td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"<NAME>","email":"<EMAIL>"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td><EMAIL></td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"<NAME>","email":"<EMAIL>"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td><EMAIL></td>
</tbody>
</table>
"""
testClientComponentParent: [
->
reactiveChild1 false
reactiveChild2 false
@component = new ParentComponent()
@childComponents = []
@handle = Tracker.autorun (computation) =>
@childComponents.push @component.childComponents()
@childComponentsChild1 = []
@handleChild1 = Tracker.autorun (computation) =>
@childComponentsChild1.push @component.childComponentsWith childName: 'child1'
@childComponentsChild1DOM = []
@handleChild1DOM = Tracker.autorun (computation) =>
@childComponentsChild1DOM.push @component.childComponentsWith (child) ->
# We can search also based on DOM. We use domChanged to be sure check is called
# every time DOM changes. But it does not seem to be really necessary in this
# particular test (it passes without it as well). On the other hand domChanged
# also does not capture all changes. We are searching for an element by CSS class
# and domChanged is not changed when a class changes on a DOM element.
#child.domChanged()
child.$('.child1')?.length
@renderedComponent = Blaze.render @component.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), []
reactiveChild1 true
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents().length, 1
@child1Component = @component.childComponents()[0]
@assertEqual @child1Component.parentComponent(), @component
reactiveChild2 true
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents().length, 2
@child2Component = @component.childComponents()[1]
@assertEqual @child2Component.parentComponent(), @component
reactiveChild1 false
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), [@child2Component]
@assertEqual @child1Component.parentComponent(), null
reactiveChild2 false
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), []
@assertEqual @child2Component.parentComponent(), null
Blaze.remove @renderedComponent
@handle.stop()
@handleChild1.stop()
@handleChild1DOM.stop()
@assertEqual @childComponents, [
[]
[@child1Component]
[@child1Component, @child2Component]
[@child2Component]
[]
]
@assertEqual @childComponentsChild1, [
[]
[@child1Component]
[]
]
@assertEqual @childComponentsChild1DOM, [
[]
[@child1Component]
[]
]
]
testClientCases: [
->
@dataContext = new ReactiveField {case: 'left'}
@renderedComponent = Blaze.renderWithData Template.useCaseTemplate, (=> @dataContext()), $('body').get(0)
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Left</p>
"""
@dataContext {case: 'middle'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Middle</p>
"""
@dataContext {case: 'right'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Right</p>
"""
@dataContext {case: 'unknown'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """"""
Blaze.remove @renderedComponent
]
testClientMixinsExample: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('MyComponent').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: abc</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testClientReadmeExample: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponent').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientReadmeExampleJS: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponentJS').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientMixinsExampleWithJavaScript: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('OurComponentJS').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: >>>abc<<<</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testClientReadmeExampleES2015: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponentES2015').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientMixinsExampleWithES2015: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('OurComponentES2015').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: >>>abc<<<</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testOnDestroyedOrder: ->
OuterComponent.calls = []
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@states = []
@autorun =>
@states.push ['outer', @outerComponent.isCreated(), @outerComponent.isRendered(), @outerComponent.isDestroyed()]
@autorun =>
@states.push ['inner', @outerComponent.childComponents()[0]?.isCreated(), @outerComponent.childComponents()[0]?.isRendered(), @outerComponent.childComponents()[0]?.isDestroyed()]
output = @outerComponent.renderComponentToHTML()
@assertEqual trim(output), trim """
<div class="outerComponent">
<p class="innerComponent">Content.</p>
</div>
"""
@assertEqual OuterComponent.calls, [
'OuterComponent onCreated'
'InnerComponent onCreated'
'InnerComponent onDestroyed'
'OuterComponent onDestroyed'
]
@assertEqual @states, [
['outer', false, false, false]
['inner', undefined, undefined, undefined]
['outer', true, false, false]
['inner', true, false, false]
['inner', undefined, undefined, undefined]
['outer', false, false, true]
]
testClientOnDestroyedOrder: [
->
OuterComponent.calls = []
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@states = []
@autorun =>
@states.push ['outer', @outerComponent.isCreated(), @outerComponent.isRendered(), @outerComponent.isDestroyed()]
@autorun =>
@states.push ['inner', @outerComponent.childComponents()[0]?.isCreated(), @outerComponent.childComponents()[0]?.isRendered(), @outerComponent.childComponents()[0]?.isDestroyed()]
@renderedComponent = Blaze.render @outerComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
Blaze.remove @renderedComponent
Tracker.afterFlush @expect()
,
->
@assertEqual OuterComponent.calls, [
'OuterComponent onCreated'
'InnerComponent onCreated'
'InnerComponent onRendered'
'OuterComponent onRendered'
'InnerComponent onDestroyed'
'OuterComponent onDestroyed'
]
@assertEqual @states, [
['outer', false, false, false]
['inner', undefined, undefined, undefined]
['outer', true, false, false]
['inner', true, false, false]
['inner', true, true, false]
['outer', true, true, false]
['inner', undefined, undefined, undefined]
['outer', false, false, true]
]
]
testNamespacedArguments: ->
MyNamespace.Foo.ArgumentsComponent.calls = []
MyNamespace.Foo.ArgumentsComponent.constructorStateChanges = []
MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.namespacedArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="namespacedArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls.length, 4
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges MyNamespace.Foo.ArgumentsComponent.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges, true
OurNamespace.ArgumentsComponent.calls = []
OurNamespace.ArgumentsComponent.constructorStateChanges = []
OurNamespace.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.ourNamespacedArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="ourNamespacedArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual OurNamespace.ArgumentsComponent.calls.length, 4
@assertEqual OurNamespace.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges OurNamespace.ArgumentsComponent.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges OurNamespace.ArgumentsComponent.onCreatedStateChanges, true
OurNamespace.calls = []
OurNamespace.constructorStateChanges = []
OurNamespace.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.ourNamespaceComponentArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="ourNamespaceComponentArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual OurNamespace.calls.length, 4
@assertEqual OurNamespace.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges OurNamespace.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges OurNamespace.onCreatedStateChanges, true
testClientNamespacedArguments: [
->
MyNamespace.Foo.ArgumentsComponent.calls = []
MyNamespace.Foo.ArgumentsComponent.constructorStateChanges = []
MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.namespacedArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls.length, 5
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges MyNamespace.Foo.ArgumentsComponent.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges
,
->
OurNamespace.ArgumentsComponent.calls = []
OurNamespace.ArgumentsComponent.constructorStateChanges = []
OurNamespace.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.ourNamespacedArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual OurNamespace.ArgumentsComponent.calls.length, 5
@assertEqual OurNamespace.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges OurNamespace.ArgumentsComponent.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges OurNamespace.ArgumentsComponent.onCreatedStateChanges
,
->
OurNamespace.calls = []
OurNamespace.constructorStateChanges = []
OurNamespace.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.ourNamespaceComponentArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual OurNamespace.calls.length, 5
@assertEqual OurNamespace.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges OurNamespace.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges OurNamespace.onCreatedStateChanges
]
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/30.
testTemplateDynamic: ->
output = BlazeComponent.getComponent('TemplateDynamicTestComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'TemplateDynamicTestComponent', 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = new (BlazeComponent.getComponent('TemplateDynamicTestComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'TemplateDynamicTestComponent', 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = BlazeComponent.getComponent('FooComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = new (BlazeComponent.getComponent('FooComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = BlazeComponent.getComponent('SubComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
output = new (BlazeComponent.getComponent('SubComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
testClientGetComponentForElement: [
->
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@renderedComponent = Blaze.render @outerComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@innerComponent = @outerComponent.childComponents()[0]
@assertTrue @innerComponent
@assertEqual BlazeComponent.getComponentForElement($('.outerComponent').get(0)), @outerComponent
@assertEqual BlazeComponent.getComponentForElement($('.innerComponent').get(0)), @innerComponent
Blaze.remove @renderedComponent
]
testBlockHelpersStructure: ->
component = new (BlazeComponent.getComponent('TestBlockComponent'))()
@assertTrue component
output = component.renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim(TEST_BLOCK_COMPONENT_CONTENT())
testClientBlockHelpersStructure: [
->
@renderedComponent = Blaze.render Template.extraTestBlockComponent, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.extraTestBlockComponent').html()), trim(TEST_BLOCK_COMPONENT_CONTENT())
TestingComponentDebug.structure = {}
TestingComponentDebug.dumpComponentTree $('.extraTestBlockComponent table').get(0)
@assertEqual TestingComponentDebug.structure, TEST_BLOCK_COMPONENT_STRUCTURE()
@assertEqual BlazeComponent.getComponentForElement($('.insideContent').get(0)).componentName(), 'TestBlockComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideContentComponent').get(0)).componentName(), 'RowComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelper').get(0)).componentName(), 'ExtraTableWrapperBlockComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelperComponent').get(0)).componentName(), 'FootComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelperTemplate').get(0)).componentName(), 'ExtraTableWrapperBlockComponent'
Blaze.remove @renderedComponent
]
testClientExtendingTemplate: [
->
mainComponent3Calls = []
# To make sure we know what to expect from a template, we first test the template.
@renderedTemplate = Blaze.renderWithData Template.mainComponent3Test, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.mainComponent3').html()), trim """
<button>Foo1</button>
<p>mainComponent3.foobar/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
<button>Foo2</button>
<p>mainComponent3.foobar2/{"a":"3","b":"4"}/{"a":"3","b":"4"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}</p>
<p>mainComponent3.foobar3/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
"""
$('.mainComponent3 button').each (i, button) =>
$(button).click()
Blaze.remove @renderedTemplate
Tracker.afterFlush @expect()
,
->
@assertEqual mainComponent3Calls, [
[Template.mainComponent3, 'mainComponent3.onCreated', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onRendered', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onClick', {a: "1", b: "2"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onClick', {a: "3", b: "4"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onDestroyed', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
]
,
->
mainComponent3Calls = []
# And now we make a component which extends it.
@renderedTemplate = Blaze.renderWithData Template.mainComponent3ComponentTest, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.mainComponent3').html()), trim """
<button>Foo1</button>
<p>super:mainComponent3.foobar/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
<button>Foo2</button>
<p>mainComponent3.foobar2/{"a":"3","b":"4"}/{"a":"3","b":"4"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}</p>
<p>mainComponent3.foobar3/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
"""
$('.mainComponent3 button').each (i, button) =>
$(button).click()
Blaze.remove @renderedTemplate
Tracker.afterFlush @expect()
,
->
@assertEqual mainComponent3Calls, [
[MainComponent3, 'mainComponent3.onCreated', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onRendered', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onClick', {a: "1", b: "2"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onClick', {a: "3", b: "4"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onDestroyed', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
]
]
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/30.
testLexicalArguments: ->
return unless Blaze._lexicalBindingLookup
output = Blaze.toHTMLWithData Template.testLexicalArguments,
test: ['42']
@assertEqual trim(output), trim """42"""
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/109.
testIndex: ->
return unless Blaze._lexicalBindingLookup
output = Blaze.toHTMLWithData Template.testIndex,
test: ['42']
@assertEqual trim(output), trim """0"""
testLexicalArgumentsComponent: ->
output = BlazeComponent.getComponent('LexicalArgumentsComponent').renderComponentToHTML null, null,
test: [1, 2, 3]
@assertEqual trim(output), trim """
<div>{"test":[1,2,3]}</div>
<div>1/0</div>
<div>{"test":[1,2,3]}</div>
<div>2/1</div>
<div>{"test":[1,2,3]}</div>
<div>3/2</div>
"""
testInlineEventsToHTML: ->
output = Blaze.toHTML Template.inlineEventsTestTemplate
@assertEqual trim(output), trim """
<div class="inlineEventsTestTemplate">
<form>
<div>
<button class="button1" type="button">Button 1</button>
<button class="button2" type="button">Button 2</button>
<button class="button3 dynamic" type="button">Button 3</button>
<button class="button4 dynamic" type="button">Button 4</button>
<button class="button5" type="button" title="Foobar">Button 5</button>
<input type="text">
<textarea></textarea>
</div>
</form>
</div>
"""
testClientInlineEvents: [
->
reactiveArguments {z: 1}
InlineEventsComponent.calls = []
@renderedComponent = Blaze.render Template.inlineEventsTestTemplate, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.inlineEventsTestTemplate').html()), trim """
<form>
<div>
<button class="button1" type="button">Button 1</button>
<button class="button2" type="button">Button 2</button>
<button class="button3 dynamic" type="button">Button 3</button>
<button class="button4 dynamic" type="button">Button 4</button>
<button class="button5" type="button" title="Foobar">Button 5</button>
<input type="text">
<textarea></textarea>
</div>
</form>
"""
# Event handlers should not be called like template heleprs.
@assertEqual InlineEventsComponent.calls, []
InlineEventsComponent.calls = []
$('.inlineEventsTestTemplate button').each (i, button) =>
$(button).click()
$('.inlineEventsTestTemplate textarea').each (i, textarea) =>
$(textarea).change()
$('.inlineEventsTestTemplate input').each (i, input) =>
$(input).click()
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton1Click', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onClick1Extra', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton2Click', {top: '42'}, {a: '3', b: '4'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 1}, new Spacebars.kw()]
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 1}})]
['InlineEventsComponent', 'InlineEventsComponent.extraArgs1', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.extraArgs2', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onChange', {top: '42'}, {top: '42'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onTextClick', {top: '42'}, {a: '11', b: '12'}, 'InlineEventsComponent']
]
InlineEventsComponent.calls = []
reactiveArguments {z: 2}
Tracker.afterFlush @expect()
,
->
$('.inlineEventsTestTemplate button').each (i, button) =>
$(button).click()
$('.inlineEventsTestTemplate textarea').each (i, textarea) =>
$(textarea).change()
$('.inlineEventsTestTemplate input').each (i, input) =>
$(input).click()
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton1Click', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onClick1Extra', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton2Click', {top: '42'}, {a: '3', b: '4'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 2}, new Spacebars.kw()]
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 2}})]
['InlineEventsComponent', 'InlineEventsComponent.extraArgs1', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.extraArgs2', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onChange', {top: '42'}, {top: '42'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onTextClick', {top: '42'}, {a: '11', b: '12'}, 'InlineEventsComponent']
]
InlineEventsComponent.calls = []
$('.inlineEventsTestTemplate button.dynamic').each (i, button) =>
$(button).trigger('click', 'extraArgument')
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 2}, new Spacebars.kw(), 'extraArgument']
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 2}}), 'extraArgument']
]
Blaze.remove @renderedComponent
]
testClientInvalidInlineEvents: ->
@assertThrows =>
Blaze.render Template.invalidInlineEventsTestTemplate, $('body').get(0)
,
/Invalid event handler/
testClientBody: ->
output = Blaze.toHTML Template.body
@assertTrue $($.parseHTML(output)).is('.bodyTest')
testServerBody: ->
output = Blaze.toHTML Template.body
@assertEqual trim(output), trim """
<div class="bodyTest">Body test.</div>
"""
testClientHead: ->
@assertTrue jQuery('head').find('noscript').length
testNestedMixins: ->
LevelTwoComponent.children = []
output = BlazeComponent.getComponent('LevelOneComponent').renderComponentToHTML null, null
@assertEqual trim(output), trim """
<span>41</span>
<span>42</span>
<span></span>
"""
@assertEqual LevelTwoComponent.children, [
all: 0
,
topValue: 0
,
hasValue: 0
,
hasNoValue: 0
,
all: 1
,
topValue: 1
,
hasValue: 1
,
all: 0
,
topValue: 0
,
hasValue: 0
]
ClassyTestCase.addTest new BasicTestCase()
| true | trim = (html) =>
html = html.replace />\s+/g, '>'
html = html.replace /\s+</g, '<'
html.trim()
class MainComponent extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
# To test when name of the component mismatches the template name. Template name should have precedence.
'MainComponent2'
foobar: ->
"#{@componentName()}/MainComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/MainComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@componentName()}/MainComponent.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
isMainComponent: ->
@constructor is MainComponent
onClick: (event) ->
assert not Tracker.active
@constructor.calls.push [@componentName(), 'MainComponent.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: ->
assert not Tracker.active
[
'click': @onClick
]
onCreated: ->
self = @
# To test that a computation is bound to the component.
@autorun (computation) ->
assert.equal @, self
BlazeComponent.register 'MainComponent', MainComponent
# Template should match registered name.
class FooComponent extends BlazeComponent
BlazeComponent.register 'FooComponent', FooComponent
class SelfRegisterComponent extends BlazeComponent
# Alternative way of registering components.
@register 'SelfRegisterComponent'
class SubComponent extends MainComponent
@calls: []
foobar: ->
"#{@componentName()}/SubComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/SubComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not override foobar3.
onClick: (event) ->
@constructor.calls.push [@componentName(), 'SubComponent.onClick', @data(), @currentData(), @currentComponent().componentName()]
BlazeComponent.register 'SubComponent', SubComponent
class UnregisteredComponent extends SubComponent
foobar: ->
"#{@componentName()}/UnregisteredComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/UnregisteredComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# Name has to be set manually.
UnregisteredComponent.componentName 'UnregisteredComponent'
class SelfNameUnregisteredComponent extends UnregisteredComponent
# Alternative way of setting the name manually.
@componentName 'SelfNameUnregisteredComponent'
# We do not extend any helper on purpose. So they should all use "UnregisteredComponent".
class AnimatedListComponent extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
'AnimatedListComponent'
onCreated: ->
assert not Tracker.active
# To test inserts, moves, and removals.
@_list = new ReactiveField [1, 2, 3, 4, 5]
@_handle = Meteor.setInterval =>
list = @_list()
# Moves the last number to the first place.
list = [list[4]].concat list[0...4]
# Removes the smallest number.
list = _.without list, _.min list
# Adds one more number, one larger than the current largest.
list = list.concat [_.max(list) + 1]
@_list list
, 1000 # ms
onDestroyed: ->
assert not Tracker.active
Meteor.clearInterval @_handle
list: ->
_id: i for i in @_list()
insertDOMElement: (parent, node, before) ->
assert not Tracker.active
@constructor.calls.push ['insertDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML), trim(before?.outerHTML or '')]
super arguments...
moveDOMElement: (parent, node, before) ->
assert not Tracker.active
@constructor.calls.push ['moveDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML), trim(before?.outerHTML or '')]
super arguments...
removeDOMElement: (parent, node) ->
assert not Tracker.active
@constructor.calls.push ['removeDOMElement', @componentName(), trim(parent.outerHTML), trim(node.outerHTML)]
super arguments...
BlazeComponent.register 'AnimatedListComponent', AnimatedListComponent
class DummyComponent extends BlazeComponent
@register 'DummyComponent'
class ArgumentsComponent extends BlazeComponent
@calls: []
@constructorStateChanges: []
@onCreatedStateChanges: []
template: ->
assert not Tracker.active
'ArgumentsComponent'
constructor: ->
super arguments...
assert not Tracker.active
@constructor.calls.push arguments[0]
@arguments = arguments
@componentId = Random.id()
@handles = []
@collectStateChanges @constructor.constructorStateChanges
onCreated: ->
assert not Tracker.active
super arguments...
@collectStateChanges @constructor.onCreatedStateChanges
collectStateChanges: (output) ->
output.push
componentId: @componentId
view: Blaze.currentView
templateInstance: Template.instance()
for method in ['isCreated', 'isRendered', 'isDestroyed', 'data', 'currentData', 'component', 'currentComponent', 'firstNode', 'lastNode', 'subscriptionsReady']
do (method) =>
@handles.push Tracker.autorun (computation) =>
data =
componentId: @componentId
data[method] = @[method]()
output.push data
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
find: @find('*')
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
findAll: @findAll('*')
@handles.push Tracker.autorun (computation) =>
output.push
componentId: @componentId
$: @$('*')
onDestroyed: ->
assert not Tracker.active
super arguments...
Tracker.afterFlush =>
while handle = @handles.pop()
handle.stop()
dataContext: ->
EJSON.stringify @data()
currentDataContext: ->
EJSON.stringify @currentData()
constructorArguments: ->
EJSON.stringify @arguments
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
BlazeComponent.register 'ArgumentsComponent', ArgumentsComponent
class MyNamespace
class MyNamespace.Foo
class MyNamespace.Foo.ArgumentsComponent extends ArgumentsComponent
@register 'MyNamespace.Foo.ArgumentsComponent'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'MyNamespace.Foo.ArgumentsComponent'
# We want to test if a component with the same name as the namespace can coexist.
class OurNamespace extends ArgumentsComponent
@register 'OurNamespace'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'OurNamespace'
class OurNamespace.ArgumentsComponent extends ArgumentsComponent
@register 'OurNamespace.ArgumentsComponent'
template: ->
assert not Tracker.active
# We could simply use "ArgumentsComponent" here and not have to copy the
# template, but we want to test if a template name with dots works.
'OurNamespace.ArgumentsComponent'
reactiveContext = new ReactiveField {}
reactiveArguments = new ReactiveField {}
class ArgumentsTestComponent extends BlazeComponent
@register 'ArgumentsTestComponent'
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.namespacedArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.ourNamespacedArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
Template.ourNamespaceComponentArgumentsTestTemplate.helpers
reactiveContext: ->
reactiveContext()
reactiveArguments: ->
reactiveArguments()
class ExistingClassHierarchyBase
foobar: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@componentName()}/ExistingClassHierarchyBase.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
class ExistingClassHierarchyChild extends ExistingClassHierarchyBase
class ExistingClassHierarchyBaseComponent extends ExistingClassHierarchyChild
for property, value of BlazeComponent when property not in ['__super__']
ExistingClassHierarchyBaseComponent[property] = value
for property, value of (BlazeComponent::) when property not in ['constructor']
ExistingClassHierarchyBaseComponent::[property] = value
class ExistingClassHierarchyComponent extends ExistingClassHierarchyBaseComponent
template: ->
assert not Tracker.active
'MainComponent2'
foobar: ->
"#{@componentName()}/ExistingClassHierarchyComponent.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@componentName()}/ExistingClassHierarchyComponent.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not override foobar3.
ExistingClassHierarchyComponent.register 'ExistingClassHierarchyComponent', ExistingClassHierarchyComponent
class FirstMixin extends BlazeComponent
@calls: []
foobar: ->
"#{@component().componentName()}/FirstMixin.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@component().componentName()}/FirstMixin.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar3: ->
"#{@component().componentName()}/FirstMixin.foobar3/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
isMainComponent: ->
@component().constructor is WithMixinsComponent
onClick: (event) ->
@constructor.calls.push [@component().componentName(), 'FirstMixin.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: -> [
'click': @onClick
]
class SecondMixin extends BlazeComponent
@calls: []
template: ->
assert not Tracker.active
@_template()
_template: ->
'MainComponent2'
foobar: ->
"#{@component().componentName()}/SecondMixin.foobar/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
foobar2: ->
"#{@component().componentName()}/SecondMixin.foobar2/#{EJSON.stringify @data()}/#{EJSON.stringify @currentData()}/#{@currentComponent().componentName()}"
# We on purpose do not provide foobar3.
onClick: (event) ->
@constructor.calls.push [@component().componentName(), 'SecondMixin.onClick', @data(), @currentData(), @currentComponent().componentName()]
events: ->
assert not Tracker.active
[
'click': @onClick
]
onCreated: ->
assert not Tracker.active
# To test if adding a dependency during onCreated will make sure
# to call onCreated on the added dependency as well.
@mixinParent().requireMixin DependencyMixin
SecondMixin.componentName 'SecondMixin'
class DependencyMixin extends BlazeComponent
@calls: []
onCreated: ->
assert not Tracker.active
@constructor.calls.push true
class WithMixinsComponent extends BlazeComponent
@output: []
mixins: ->
assert not Tracker.active
[SecondMixin, FirstMixin]
onDestroyed: ->
firstMixin = @getMixin FirstMixin
@constructor.output.push @
@constructor.output.push firstMixin
@constructor.output.push @getMixin firstMixin
@constructor.output.push @getMixin @
@constructor.output.push @getMixin DependencyMixin
@constructor.output.push @getMixin 'FirstMixin'
@constructor.output.push @getMixin 'SecondMixin'
@constructor.output.push @getFirstWith null, 'isMainComponent'
@constructor.output.push @getFirstWith null, (child, parent) =>
!!child.constructor.output
@constructor.output.push @getFirstWith null, (child, parent) =>
child is parent
@constructor.output.push @getFirstWith null, (child, parent) =>
child._template?() is 'MainComponent2'
BlazeComponent.register 'WithMixinsComponent', WithMixinsComponent
class AfterCreateValueComponent extends BlazeComponent
template: ->
assert not Tracker.active
'AfterCreateValueComponent'
onCreated: ->
assert not Tracker.active
@foobar = '42'
@_foobar = '43'
BlazeComponent.register 'AfterCreateValueComponent', AfterCreateValueComponent
class PostMessageButtonComponent extends BlazeComponent
onCreated: ->
assert not Tracker.active
@color = new ReactiveField "Red"
$(window).on 'message.buttonComponent', (event) =>
if color = event.originalEvent.data?.color
@color color
onDestroyed: ->
$(window).off '.buttonComponent'
BlazeComponent.register 'PostMessageButtonComponent', PostMessageButtonComponent
class TableWrapperBlockComponent extends BlazeComponent
template: ->
assert not Tracker.active
'TableWrapperBlockComponent'
currentDataContext: ->
EJSON.stringify @currentData()
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
BlazeComponent.register 'TableWrapperBlockComponent', TableWrapperBlockComponent
Template.testBlockComponent.helpers
parentDataContext: ->
# We would like to make sure data context hierarchy
# is without intermediate arguments data context.
EJSON.stringify Template.parentData()
customersDataContext: ->
customers: [
name: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
]
reactiveChild1 = new ReactiveField false
reactiveChild2 = new ReactiveField false
class ChildComponent extends BlazeComponent
template: ->
assert not Tracker.active
'ChildComponent'
constructor: (@childName) ->
super arguments...
assert not Tracker.active
onCreated: ->
assert not Tracker.active
@domChanged = new ReactiveField 0
insertDOMElement: (parent, node, before) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
moveDOMElement: (parent, node, before) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
removeDOMElement: (parent, node) ->
assert not Tracker.active
super arguments...
@domChanged Tracker.nonreactive =>
@domChanged() + 1
BlazeComponent.register 'ChildComponent', ChildComponent
class ParentComponent extends BlazeComponent
template: ->
assert not Tracker.active
'ParentComponent'
child1: ->
reactiveChild1()
child2: ->
reactiveChild2()
BlazeComponent.register 'ParentComponent', ParentComponent
class CaseComponent extends BlazeComponent
@register 'CaseComponent'
constructor: (kwargs) ->
super arguments...
assert not Tracker.active
@cases = kwargs.hash
renderCase: ->
caseComponent = @cases[@data().case]
return null unless caseComponent
BlazeComponent.getComponent(caseComponent).renderComponent @
class LeftComponent extends BlazeComponent
@register 'LeftComponent'
template: ->
assert not Tracker.active
'LeftComponent'
class MiddleComponent extends BlazeComponent
@register 'MiddleComponent'
template: ->
assert not Tracker.active
'MiddleComponent'
class RightComponent extends BlazeComponent
@register 'RightComponent'
template: ->
assert not Tracker.active
'RightComponent'
class MyComponent extends BlazeComponent
@register 'MyComponent'
mixins: ->
assert not Tracker.active
[FirstMixin2, new SecondMixin2 'foobar']
alternativeName: ->
@callFirstWith null, 'templateHelper'
values: ->
'a' + (@callFirstWith(@, 'values') or '')
class FirstMixinBase extends BlazeComponent
@calls: []
templateHelper: ->
"42"
extendedHelper: ->
1
onClick: ->
throw new Error() if @values() isnt @valuesPredicton
@constructor.calls.push true
class FirstMixin2 extends FirstMixinBase
extendedHelper: ->
super() + 2
values: ->
'b' + (@mixinParent().callFirstWith(@, 'values') or '')
dataContext: ->
EJSON.stringify @data()
events: ->
assert not Tracker.active
super.concat
'click': @onClick
onCreated: ->
assert not Tracker.active
@valuesPredicton = 'bc'
class SecondMixin2
constructor: (@name) ->
assert not Tracker.active
mixinParent: (mixinParent) ->
@_mixinParent = mixinParent if mixinParent
@_mixinParent
values: ->
'c' + (@mixinParent().callFirstWith(@, 'values') or '')
# Example from the README.
class ExampleComponent extends BlazeComponent
@register 'ExampleComponent'
onCreated: ->
assert not Tracker.active
super arguments...
@counter = new ReactiveField 0
events: ->
assert not Tracker.active
super.concat
'click .increment': @onClick
onClick: (event) ->
@counter @counter() + 1
customHelper: ->
if @counter() > 10
"Too many times"
else if @counter() is 10
"Just enough"
else
"Click more"
class OuterComponent extends BlazeComponent
@register 'OuterComponent'
@calls: []
template: ->
assert not Tracker.active
'OuterComponent'
onCreated: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onCreated'
onRendered: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onRendered'
onDestroyed: ->
assert not Tracker.active
OuterComponent.calls.push 'OuterComponent onDestroyed'
class InnerComponent extends BlazeComponent
@register 'InnerComponent'
template: ->
assert not Tracker.active
'InnerComponent'
onCreated: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onCreated'
onRendered: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onRendered'
onDestroyed: ->
assert not Tracker.active
OuterComponent.calls.push 'InnerComponent onDestroyed'
class TemplateDynamicTestComponent extends MainComponent
@register 'TemplateDynamicTestComponent'
@calls: []
template: ->
assert not Tracker.active
'TemplateDynamicTestComponent'
isMainComponent: ->
@constructor is TemplateDynamicTestComponent
class ExtraTableWrapperBlockComponent extends BlazeComponent
@register 'ExtraTableWrapperBlockComponent'
class TestBlockComponent extends BlazeComponent
@register 'TestBlockComponent'
nameFromComponent: ->
"Works"
renderRow: ->
BlazeComponent.getComponent('RowComponent').renderComponent @currentComponent()
class RowComponent extends BlazeComponent
@register 'RowComponent'
class FootComponent extends BlazeComponent
@register 'FootComponent'
class CaptionComponent extends BlazeComponent
@register 'CaptionComponent'
class RenderRowComponent extends BlazeComponent
@register 'RenderRowComponent'
parentComponentRenderRow: ->
@parentComponent().parentComponent().renderRow()
class TestingComponentDebug extends BlazeComponentDebug
@structure: {}
stack = []
@lastElement: (structure) ->
return structure if 'children' not of structure
stack[stack.length - 1] = structure.children
@lastElement structure.children[structure.children.length - 1]
@startComponent: (component) ->
stack.push null
element = @lastElement @structure
element.component = component.componentName()
element.data = component.data()
element.children = [{}]
@endComponent: (component) ->
# Only the top-level stack element stays null and is not set to a children array.
stack[stack.length - 1].push {} if stack.length > 1
stack.pop()
@startMarkedComponent: (component) ->
@startComponent component
@endMarkedComponent: (component) ->
@endComponent component
class LexicalArgumentsComponent extends BlazeComponent
@register 'LexicalArgumentsComponent'
rowOfCurrentData: ->
EJSON.stringify @currentData()
rowOfFooAndIndex: ->
"#{EJSON.stringify @currentData 'foo'}/#{@currentData '@index'}"
mainComponent3Calls = []
Template.mainComponent3.events
'click': (event, template) ->
assert.equal Template.instance(), template
assert not Tracker.active
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onClick', @, Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.helpers
foobar: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
foobar2: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar2/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
foobar3: ->
if Template.instance().component
assert.equal Template.instance().component.constructor, MainComponent3
else
assert.equal Template.instance().view.template, Template.mainComponent3
"mainComponent3.foobar3/#{EJSON.stringify @}/#{EJSON.stringify Template.currentData()}/#{EJSON.stringify Blaze.getData(Template.instance().view)}/#{EJSON.stringify Template.parentData()}"
Template.mainComponent3.onCreated ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onCreated', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.onRendered ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onRendered', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
Template.mainComponent3.onDestroyed ->
assert not Tracker.active
assert.equal Template.instance(), @
if Template.instance().component
template = Template.instance().component.constructor
else
template = Template.instance().view.template
mainComponent3Calls.push [template, 'mainComponent3.onDestroyed', Template.currentData(), Blaze.getData(Template.instance().view), Template.parentData()]
class MainComponent3 extends BlazeComponent
@register 'MainComponent3'
template: ->
'mainComponent3'
foobar: ->
# An ugly way to extend a base template helper.
helper = @_componentInternals.templateBase.__helpers.get 'foobar'
# Blaze template helpers expect current data context bound to "this".
result = helper.call @currentData()
'super:' + result
reactiveArguments = new ReactiveField null
class InlineEventsComponent extends BlazeComponent
@calls: []
@register 'InlineEventsComponent'
onButton1Click: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton1Click', @data(), @currentData(), @currentComponent().componentName()]
onButton2Click: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton2Click', @data(), @currentData(), @currentComponent().componentName()]
onClick1Extra: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onClick1Extra', @data(), @currentData(), @currentComponent().componentName()]
onButton3Click: (event, args...) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton3Click', @data(), @currentData(), @currentComponent().componentName()].concat args
onButton4Click: (event, args...) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onButton4Click', @data(), @currentData(), @currentComponent().componentName()].concat args
dynamicArgument: ->
reactiveArguments()
onChange: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onChange', @data(), @currentData(), @currentComponent().componentName()]
onTextClick: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.onTextClick', @data(), @currentData(), @currentComponent().componentName()]
extraArgs1: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.extraArgs1', @data(), @currentData(), @currentComponent().componentName()]
extraArgs2: (event) ->
@constructor.calls.push [@componentName(), 'InlineEventsComponent.extraArgs2', @data(), @currentData(), @currentComponent().componentName()]
extraArgs: ->
title: "Foobar"
onClick: [
@extraArgs1
,
@extraArgs2
]
class InvalidInlineEventsComponent extends BlazeComponent
@register 'InvalidInlineEventsComponent'
class LevelOneComponent extends BlazeComponent
@register 'LevelOneComponent'
class LevelTwoComponent extends BlazeComponent
@children: []
@register 'LevelTwoComponent'
onCreated: ->
super arguments...
@autorun =>
@constructor.children.push all: @childComponents().length
@autorun =>
@constructor.children.push topValue: @childComponentsWith(topValue: 41).length
@autorun =>
@constructor.children.push hasValue: @childComponentsWith(hasValue: 42).length
@autorun =>
@constructor.children.push hasNoValue: @childComponentsWith(hasNoValue: 43).length
class LevelOneMixin extends BlazeComponent
mixins: ->
[LevelTwoMixin]
# This one should be resolved in the template.
hasValue: ->
42
class LevelTwoMixin extends BlazeComponent
# This one should not be resolved in the template.
hasNoValue: ->
43
class ComponentWithNestedMixins extends BlazeComponent
@register 'ComponentWithNestedMixins'
mixins: ->
[LevelOneMixin]
topValue: ->
41
class BasicTestCase extends ClassyTestCase
@testName: 'blaze-components - basic'
FOO_COMPONENT_CONTENT = ->
"""
<p>Other component: FooComponent</p>
<button>Foo2</button>
<p></p>
<button>Foo3</button>
<p></p>
<p></p>
"""
COMPONENT_CONTENT = (componentName, helperComponentName, mainComponent) ->
helperComponentName ?= componentName
mainComponent ?= 'MainComponent'
"""
<p>Main component: #{componentName}</p>
<button>Foo1</button>
<p>#{componentName}/#{helperComponentName}.foobar/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<button>Foo2</button>
<p>#{componentName}/#{helperComponentName}.foobar2/{"top":"42"}/{"a":"1","b":"2"}/#{componentName}</p>
<p>#{componentName}/#{mainComponent}.foobar3/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<p>Subtemplate</p>
<button>Foo1</button>
<p>#{componentName}/#{helperComponentName}.foobar/{"top":"42"}/{"top":"42"}/#{componentName}</p>
<button>Foo2</button>
<p>#{componentName}/#{helperComponentName}.foobar2/{"top":"42"}/{"a":"3","b":"4"}/#{componentName}</p>
<p>#{componentName}/#{mainComponent}.foobar3/{"top":"42"}/{"top":"42"}/#{componentName}</p>
#{FOO_COMPONENT_CONTENT()}
"""
TEST_BLOCK_COMPONENT_CONTENT = ->
"""
<h2>Names and emails and components (CaptionComponent/CaptionComponent/CaptionComponent)</h2>
<h3 class="insideBlockHelperTemplate">(ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent)</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th class="insideBlockHelper">Email</th>
<th>Component (ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent/ExtraTableWrapperBlockComponent)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Foo</td>
<td class="insideContent">PI:EMAIL:<EMAIL>END_PI.com</td>
<td>TestBlockComponent/TestBlockComponent/ExtraTableWrapperBlockComponent</td>
</tr>
<tr>
<td>Bar</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Baz</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bac</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Works</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bam</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bav</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bak</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
<tr>
<td>Bal</td>
<td class="insideContentComponent">PI:EMAIL:<EMAIL>END_PI</td>
<td>RowComponent/RowComponent/RowComponent</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th class="insideBlockHelperComponent">Email</th>
<th>Component (FootComponent/FootComponent/FootComponent)</th>
</tr>
</tfoot>
</table>
"""
TEST_BLOCK_COMPONENT_STRUCTURE = ->
component: 'TestBlockComponent'
data: {top: '42'}
children: [
component: 'ExtraTableWrapperBlockComponent'
data: {block: '43'}
children: [
component: 'CaptionComponent'
data: {block: '43'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RenderRowComponent'
data: {top: '42'}
children: [
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
component: 'RowComponent'
data: {name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI'}
children: [{}]
,
{}
]
,
component: 'FootComponent'
data: {block: '43'}
children: [{}]
,
{}
]
,
{}
]
testComponents: ->
output = BlazeComponent.getComponent('MainComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = new (BlazeComponent.getComponent('MainComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = BlazeComponent.getComponent('FooComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = new (BlazeComponent.getComponent('FooComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = BlazeComponent.getComponent('SubComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
output = new (BlazeComponent.getComponent('SubComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
testGetComponent: ->
@assertEqual BlazeComponent.getComponent('MainComponent'), MainComponent
@assertEqual BlazeComponent.getComponent('FooComponent'), FooComponent
@assertEqual BlazeComponent.getComponent('SubComponent'), SubComponent
@assertEqual BlazeComponent.getComponent('unknown'), null
testComponentName: ->
@assertEqual MainComponent.componentName(), 'MainComponent'
@assertEqual FooComponent.componentName(), 'FooComponent'
@assertEqual SubComponent.componentName(), 'SubComponent'
@assertEqual BlazeComponent.componentName(), null
testSelfRegister: ->
@assertTrue BlazeComponent.getComponent 'SelfRegisterComponent'
testUnregisteredComponent: ->
output = UnregisteredComponent.renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'UnregisteredComponent'
output = new UnregisteredComponent().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'UnregisteredComponent'
output = SelfNameUnregisteredComponent.renderComponentToHTML null, null,
top: '42'
# We have not extended any helper on purpose, so they should still use "UnregisteredComponent".
@assertEqual trim(output), trim COMPONENT_CONTENT 'SelfNameUnregisteredComponent', 'UnregisteredComponent'
output = new SelfNameUnregisteredComponent().renderComponentToHTML null, null,
top: '42'
# We have not extended any helper on purpose, so they should still use "UnregisteredComponent".
@assertEqual trim(output), trim COMPONENT_CONTENT 'SelfNameUnregisteredComponent', 'UnregisteredComponent'
testErrors: ->
@assertThrows =>
BlazeComponent.register()
,
/Component name is required for registration/
@assertThrows =>
BlazeComponent.register 'MainComponent', null
,
/Component 'MainComponent' already registered/
@assertThrows =>
BlazeComponent.register 'OtherMainComponent', MainComponent
,
/Component 'OtherMainComponent' already registered under the name 'MainComponent'/
class WithoutTemplateComponent extends BlazeComponent
@assertThrows =>
WithoutTemplateComponent.renderComponentToHTML()
,
/Template for the component 'unnamed' not provided/
@assertThrows =>
new WithoutTemplateComponent().renderComponentToHTML()
,
/Template for the component 'unnamed' not provided/
class WithUnknownTemplateComponent extends BlazeComponent
@componentName 'WithoutTemplateComponent'
template: ->
'TemplateWhichDoesNotExist'
@assertThrows =>
WithUnknownTemplateComponent.renderComponentToHTML()
,
/Template 'TemplateWhichDoesNotExist' cannot be found/
@assertThrows =>
new WithUnknownTemplateComponent().renderComponentToHTML()
,
/Template 'TemplateWhichDoesNotExist' cannot be found/
testClientEvents: [
->
MainComponent.calls = []
SubComponent.calls = []
@renderedComponent = Blaze.render Template.eventsTestTemplate, $('body').get(0)
Tracker.afterFlush @expect()
,
->
$('.eventsTestTemplate button').each (i, button) =>
$(button).click()
@assertEqual MainComponent.calls, [
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'MainComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['MainComponent', 'MainComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
@assertEqual SubComponent.calls, [
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
Blaze.remove @renderedComponent
]
testClientAnimation: [
->
AnimatedListComponent.calls = []
@renderedComponent = Blaze.render Template.animationTestTemplate, $('body').get(0)
Meteor.setTimeout @expect(), 2500 # ms
,
->
Blaze.remove @renderedComponent
calls = AnimatedListComponent.calls
AnimatedListComponent.calls = []
expectedCalls = [
['insertDOMElement', 'AnimatedListComponent', '<div class="animationTestTemplate"></div>', '<div><ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul></div>', '']
['removeDOMElement', 'AnimatedListComponent', '<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>', '<li>1</li>']
['moveDOMElement', 'AnimatedListComponent', '<ul><li>2</li><li>3</li><li>4</li><li>5</li></ul>', '<li>5</li>', '']
['insertDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>2</li><li>3</li><li>4</li></ul>', '<li>6</li>', '']
['removeDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>2</li><li>3</li><li>4</li><li>6</li></ul>', '<li>2</li>']
['moveDOMElement', 'AnimatedListComponent', '<ul><li>5</li><li>3</li><li>4</li><li>6</li></ul>', '<li>6</li>', '']
['insertDOMElement', 'AnimatedListComponent', '<ul><li>6</li><li>5</li><li>3</li><li>4</li></ul>', '<li>7</li>', '']
]
# There could be some more calls made, we ignore them and just take the first 8.
@assertEqual calls[0...8], expectedCalls
Meteor.setTimeout @expect(), 2000 # ms
,
->
# After we removed the component no more calls should be made.
@assertEqual AnimatedListComponent.calls, []
]
assertArgumentsConstructorStateChanges: (stateChanges, wrappedInComponent=true, staticRender=false) ->
firstSteps = (dataContext) =>
change = stateChanges.shift()
componentId = change.componentId
@assertTrue change.view
@assertTrue change.templateInstance
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isDestroyed
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.currentData, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.component, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
if wrappedInComponent
@assertInstanceOf change.currentComponent, ArgumentsTestComponent
else
@assertIsNull change.currentComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
componentId
firstComponentId = firstSteps a: "1", b: "2"
secondComponentId = firstSteps a:"3a", b: "4a"
thirdComponentId = firstSteps a: "5", b: "6"
forthComponentId = firstSteps {}
if staticRender
@assertEqual stateChanges, []
return
secondSteps = (componentId, dataContext) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.data, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isCreated
secondSteps firstComponentId, a: "1", b: "2"
secondSteps secondComponentId, a:"3a", b: "4a"
secondSteps thirdComponentId, a: "5", b: "6"
secondSteps forthComponentId, {}
thirdSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.firstNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.lastNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.find?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.findAll), ["P", "P", "P", "P"]
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.$), ["P", "P", "P", "P"]
thirdSteps firstComponentId
thirdSteps secondComponentId
thirdSteps thirdComponentId
thirdSteps forthComponentId
# TODO: This change is probably unnecessary? Could we prevent it?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
if change.data
# TODO: In Chrome data is set. Why?
@assertEqual change.data, a: "10", b: "11"
else
# TODO: In Firefox data is undefined. Why?
@assertIsUndefined change.data
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertIsUndefined change.currentData
fifthComponentId = firstSteps a: "10", b: "11"
forthSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
forthSteps forthComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertEqual change.data, a: "10", b: "11"
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isCreated
forthSteps firstComponentId
forthSteps secondComponentId
forthSteps thirdComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertFalse change.isCreated
# TODO: Why is isRendered not set to false and all related other fields which require it (firstNode, lastNode, find, findAll, $)?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.subscriptionsReady
@assertEqual stateChanges, []
assertArgumentsOnCreatedStateChanges: (stateChanges, staticRender=false) ->
firstSteps = (dataContext) =>
change = stateChanges.shift()
componentId = change.componentId
@assertTrue change.view
@assertTrue change.templateInstance
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isDestroyed
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.data, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.currentData, dataContext
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.component, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertInstanceOf change.currentComponent, ArgumentsComponent
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.subscriptionsReady
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
componentId
firstComponentId = firstSteps a: "1", b: "2"
secondComponentId = firstSteps a:"3a", b: "4a"
thirdComponentId = firstSteps a: "5", b: "6"
forthComponentId = firstSteps {}
if staticRender
@assertEqual stateChanges, []
return
thirdSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.firstNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.lastNode?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual change.find?.nodeName, "P"
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.findAll), ["P", "P", "P", "P"]
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertEqual (c?.nodeName for c in change.$), ["P", "P", "P", "P"]
thirdSteps firstComponentId
thirdSteps secondComponentId
thirdSteps thirdComponentId
thirdSteps forthComponentId
# TODO: This change is probably unnecessary? Could we prevent it?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertEqual change.data, a: "10", b: "11"
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, forthComponentId
@assertIsUndefined change.currentData
fifthComponentId = firstSteps a: "10", b: "11"
forthSteps = (componentId) =>
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isCreated
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertFalse change.isRendered
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.firstNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.lastNode
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.find
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.findAll
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.$
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, componentId
@assertIsUndefined change.subscriptionsReady
forthSteps forthComponentId
forthSteps firstComponentId
forthSteps secondComponentId
forthSteps thirdComponentId
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertFalse change.isCreated
# TODO: Why is isRendered not set to false and all related other fields which require it (firstNode, lastNode, find, findAll, $)?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertTrue change.isDestroyed
# TODO: Not sure why this change happens?
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.data
change = stateChanges.shift()
@assertEqual change.componentId, fifthComponentId
@assertIsUndefined change.subscriptionsReady
@assertEqual stateChanges, []
testArguments: ->
ArgumentsComponent.calls = []
ArgumentsComponent.constructorStateChanges = []
ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.argumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="argumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual ArgumentsComponent.calls.length, 4
@assertEqual ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges ArgumentsComponent.constructorStateChanges, true, true
@assertArgumentsOnCreatedStateChanges ArgumentsComponent.onCreatedStateChanges, true
testClientArguments: [
->
ArgumentsComponent.calls = []
ArgumentsComponent.constructorStateChanges = []
ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.argumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.argumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual ArgumentsComponent.calls.length, 5
@assertEqual ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges ArgumentsComponent.constructorStateChanges
@assertArgumentsOnCreatedStateChanges ArgumentsComponent.onCreatedStateChanges
]
testExistingClassHierarchy: ->
# We want to allow one to reuse existing class hierarchy they might already have and only
# add the Meteor components "nature" to it. This is simply done by extending the base class
# and base class prototype with those from a wanted base class and prototype.
output = BlazeComponent.getComponent('ExistingClassHierarchyComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'ExistingClassHierarchyComponent', 'ExistingClassHierarchyComponent', 'ExistingClassHierarchyBase'
testMixins: ->
DependencyMixin.calls = []
WithMixinsComponent.output = []
output = BlazeComponent.getComponent('WithMixinsComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'WithMixinsComponent', 'SecondMixin', 'FirstMixin'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
@assertEqual DependencyMixin.calls, [true]
@assertInstanceOf WithMixinsComponent.output[1], FirstMixin
@assertEqual WithMixinsComponent.output[2], WithMixinsComponent.output[1]
@assertEqual WithMixinsComponent.output[3], null
@assertInstanceOf WithMixinsComponent.output[4], DependencyMixin
@assertEqual WithMixinsComponent.output[5], null
@assertInstanceOf WithMixinsComponent.output[6], SecondMixin
@assertEqual WithMixinsComponent.output[7], WithMixinsComponent.output[1]
@assertEqual WithMixinsComponent.output[8], WithMixinsComponent.output[0]
@assertEqual WithMixinsComponent.output[9], WithMixinsComponent.output[0]
@assertEqual WithMixinsComponent.output[10], WithMixinsComponent.output[6]
output = new (BlazeComponent.getComponent('WithMixinsComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'WithMixinsComponent', 'SecondMixin', 'FirstMixin'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
testClientMixinEvents: ->
FirstMixin.calls = []
SecondMixin.calls = []
SubComponent.calls = []
renderedComponent = Blaze.render Template.mixinEventsTestTemplate, $('body').get(0)
$('.mixinEventsTestTemplate button').each (i, button) =>
$(button).click()
@assertEqual FirstMixin.calls, [
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'WithMixinsComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'FirstMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
# Event handlers are independent from each other among mixins. SecondMixin has its own onClick
# handler registered, so it should be called as well.
@assertEqual SecondMixin.calls, [
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'WithMixinsComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['WithMixinsComponent', 'SecondMixin.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
@assertEqual SubComponent.calls, [
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '1', b: '2'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '3', b: '4'}, 'SubComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {top: '42'}, 'FooComponent']
['SubComponent', 'SubComponent.onClick', {top: '42'}, {a: '5', b: '6'}, 'FooComponent']
]
Blaze.remove renderedComponent
testAfterCreateValue: ->
# We want to test that also properties added in onCreated hook are available in the template.
output = BlazeComponent.getComponent('AfterCreateValueComponent').renderComponentToHTML()
@assertEqual trim(output), trim """
<p>42</p>
<p>43</p>
"""
testClientPostMessageExample: [
->
@renderedComponent = Blaze.render PostMessageButtonComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.postMessageButtonComponent').html()), trim """
<button>Red</button>
"""
window.postMessage {color: "Blue"}, '*'
# Wait a bit for a message and also wait for a flush.
Meteor.setTimeout @expect(), 50 # ms
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.postMessageButtonComponent').html()), trim """
<button>Blue</button>
"""
Blaze.remove @renderedComponent
]
testBlockComponent: ->
output = Blaze.toHTMLWithData Template.testBlockComponent,
top: '42'
@assertEqual trim(output), trim """
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"PI:NAME:<NAME>END_PI","email":"PI:EMAIL:<EMAIL>END_PI"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td>PI:EMAIL:<EMAIL>END_PI</td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"customers":[{"name":"PI:NAME:<NAME>END_PI","email":"PI:EMAIL:<EMAIL>END_PI"}]}</p>
<p>{"a":"3a","b":"4a"}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td>PI:EMAIL:<EMAIL>END_PI</td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"PI:NAME:<NAME>END_PI","email":"PI:EMAIL:<EMAIL>END_PI"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td>PI:EMAIL:<EMAIL>END_PI</td>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<p>{"top":"42"}</p>
<p>{"customers":[{"name":"PI:NAME:<NAME>END_PI","email":"PI:EMAIL:<EMAIL>END_PI"}]}</p>
<p class="inside">{"top":"42"}</p>
<td>Foo</td>
<td>PI:EMAIL:<EMAIL>END_PI</td>
</tbody>
</table>
"""
testClientComponentParent: [
->
reactiveChild1 false
reactiveChild2 false
@component = new ParentComponent()
@childComponents = []
@handle = Tracker.autorun (computation) =>
@childComponents.push @component.childComponents()
@childComponentsChild1 = []
@handleChild1 = Tracker.autorun (computation) =>
@childComponentsChild1.push @component.childComponentsWith childName: 'child1'
@childComponentsChild1DOM = []
@handleChild1DOM = Tracker.autorun (computation) =>
@childComponentsChild1DOM.push @component.childComponentsWith (child) ->
# We can search also based on DOM. We use domChanged to be sure check is called
# every time DOM changes. But it does not seem to be really necessary in this
# particular test (it passes without it as well). On the other hand domChanged
# also does not capture all changes. We are searching for an element by CSS class
# and domChanged is not changed when a class changes on a DOM element.
#child.domChanged()
child.$('.child1')?.length
@renderedComponent = Blaze.render @component.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), []
reactiveChild1 true
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents().length, 1
@child1Component = @component.childComponents()[0]
@assertEqual @child1Component.parentComponent(), @component
reactiveChild2 true
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents().length, 2
@child2Component = @component.childComponents()[1]
@assertEqual @child2Component.parentComponent(), @component
reactiveChild1 false
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), [@child2Component]
@assertEqual @child1Component.parentComponent(), null
reactiveChild2 false
Tracker.afterFlush @expect()
,
->
@assertEqual @component.childComponents(), []
@assertEqual @child2Component.parentComponent(), null
Blaze.remove @renderedComponent
@handle.stop()
@handleChild1.stop()
@handleChild1DOM.stop()
@assertEqual @childComponents, [
[]
[@child1Component]
[@child1Component, @child2Component]
[@child2Component]
[]
]
@assertEqual @childComponentsChild1, [
[]
[@child1Component]
[]
]
@assertEqual @childComponentsChild1DOM, [
[]
[@child1Component]
[]
]
]
testClientCases: [
->
@dataContext = new ReactiveField {case: 'left'}
@renderedComponent = Blaze.renderWithData Template.useCaseTemplate, (=> @dataContext()), $('body').get(0)
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Left</p>
"""
@dataContext {case: 'middle'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Middle</p>
"""
@dataContext {case: 'right'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """
<p>Right</p>
"""
@dataContext {case: 'unknown'}
Tracker.afterFlush @expect()
->
@assertEqual trim($('.useCaseTemplate').html()), trim """"""
Blaze.remove @renderedComponent
]
testClientMixinsExample: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('MyComponent').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: abc</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testClientReadmeExample: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponent').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientReadmeExampleJS: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponentJS').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientMixinsExampleWithJavaScript: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('OurComponentJS').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: >>>abc<<<</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testClientReadmeExampleES2015: [
->
@renderedComponent = Blaze.render BlazeComponent.getComponent('ExampleComponentES2015').renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 0</p>
<p>Message: Click more</p>
"""
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 1</p>
<p>Message: Click more</p>
"""
for i in [0..15]
$('.exampleComponent .increment').click()
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.exampleComponent').html()), trim """
<button class="increment">Click me</button>
<p>Counter: 17</p>
<p>Message: Too many times</p>
"""
Blaze.remove @renderedComponent
]
testClientMixinsExampleWithES2015: [
->
@renderedComponent = Blaze.renderWithData BlazeComponent.getComponent('OurComponentES2015').renderComponent(), {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.myComponent').html()), trim """
<p>alternativeName: 42</p>
<p>values: >>>abc<<<</p>
<p>templateHelper: 42</p>
<p>extendedHelper: 3</p>
<p>name: foobar</p>
<p>dataContext: {"top":"42"}</p>
"""
FirstMixin2.calls = []
$('.myComponent').click()
@assertEqual FirstMixin2.calls, [true]
Blaze.remove @renderedComponent
]
testOnDestroyedOrder: ->
OuterComponent.calls = []
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@states = []
@autorun =>
@states.push ['outer', @outerComponent.isCreated(), @outerComponent.isRendered(), @outerComponent.isDestroyed()]
@autorun =>
@states.push ['inner', @outerComponent.childComponents()[0]?.isCreated(), @outerComponent.childComponents()[0]?.isRendered(), @outerComponent.childComponents()[0]?.isDestroyed()]
output = @outerComponent.renderComponentToHTML()
@assertEqual trim(output), trim """
<div class="outerComponent">
<p class="innerComponent">Content.</p>
</div>
"""
@assertEqual OuterComponent.calls, [
'OuterComponent onCreated'
'InnerComponent onCreated'
'InnerComponent onDestroyed'
'OuterComponent onDestroyed'
]
@assertEqual @states, [
['outer', false, false, false]
['inner', undefined, undefined, undefined]
['outer', true, false, false]
['inner', true, false, false]
['inner', undefined, undefined, undefined]
['outer', false, false, true]
]
testClientOnDestroyedOrder: [
->
OuterComponent.calls = []
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@states = []
@autorun =>
@states.push ['outer', @outerComponent.isCreated(), @outerComponent.isRendered(), @outerComponent.isDestroyed()]
@autorun =>
@states.push ['inner', @outerComponent.childComponents()[0]?.isCreated(), @outerComponent.childComponents()[0]?.isRendered(), @outerComponent.childComponents()[0]?.isDestroyed()]
@renderedComponent = Blaze.render @outerComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
Blaze.remove @renderedComponent
Tracker.afterFlush @expect()
,
->
@assertEqual OuterComponent.calls, [
'OuterComponent onCreated'
'InnerComponent onCreated'
'InnerComponent onRendered'
'OuterComponent onRendered'
'InnerComponent onDestroyed'
'OuterComponent onDestroyed'
]
@assertEqual @states, [
['outer', false, false, false]
['inner', undefined, undefined, undefined]
['outer', true, false, false]
['inner', true, false, false]
['inner', true, true, false]
['outer', true, true, false]
['inner', undefined, undefined, undefined]
['outer', false, false, true]
]
]
testNamespacedArguments: ->
MyNamespace.Foo.ArgumentsComponent.calls = []
MyNamespace.Foo.ArgumentsComponent.constructorStateChanges = []
MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.namespacedArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="namespacedArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls.length, 4
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges MyNamespace.Foo.ArgumentsComponent.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges, true
OurNamespace.ArgumentsComponent.calls = []
OurNamespace.ArgumentsComponent.constructorStateChanges = []
OurNamespace.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.ourNamespacedArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="ourNamespacedArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual OurNamespace.ArgumentsComponent.calls.length, 4
@assertEqual OurNamespace.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges OurNamespace.ArgumentsComponent.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges OurNamespace.ArgumentsComponent.onCreatedStateChanges, true
OurNamespace.calls = []
OurNamespace.constructorStateChanges = []
OurNamespace.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
output = Blaze.toHTMLWithData Template.ourNamespaceComponentArgumentsTestTemplate,
top: '42'
@assertEqual trim(output), trim """
<div class="ourNamespaceComponentArgumentsTestTemplate">
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
</div>
"""
@assertEqual OurNamespace.calls.length, 4
@assertEqual OurNamespace.calls, [
undefined
undefined
'7'
{}
]
@assertArgumentsConstructorStateChanges OurNamespace.constructorStateChanges, false, true
@assertArgumentsOnCreatedStateChanges OurNamespace.onCreatedStateChanges, true
testClientNamespacedArguments: [
->
MyNamespace.Foo.ArgumentsComponent.calls = []
MyNamespace.Foo.ArgumentsComponent.constructorStateChanges = []
MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.namespacedArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.namespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls.length, 5
@assertEqual MyNamespace.Foo.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges MyNamespace.Foo.ArgumentsComponent.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges MyNamespace.Foo.ArgumentsComponent.onCreatedStateChanges
,
->
OurNamespace.ArgumentsComponent.calls = []
OurNamespace.ArgumentsComponent.constructorStateChanges = []
OurNamespace.ArgumentsComponent.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.ourNamespacedArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespacedArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual OurNamespace.ArgumentsComponent.calls.length, 5
@assertEqual OurNamespace.ArgumentsComponent.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges OurNamespace.ArgumentsComponent.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges OurNamespace.ArgumentsComponent.onCreatedStateChanges
,
->
OurNamespace.calls = []
OurNamespace.constructorStateChanges = []
OurNamespace.onCreatedStateChanges = []
reactiveContext {}
reactiveArguments {}
@renderedComponent = Blaze.renderWithData Template.ourNamespaceComponentArgumentsTestTemplate, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {}</p>
<p>Current data context: {}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveContext {a: '10', b: '11'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{},{"hash":{}}]</p>
"""
reactiveArguments {a: '12', b: '13'}
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.ourNamespaceComponentArgumentsTestTemplate').html()), trim """
<p>Component data context: {"a":"1","b":"2"}</p>
<p>Current data context: {"a":"1","b":"2"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"3a","b":"4a"}</p>
<p>Current data context: {"a":"3a","b":"4a"}</p>
<p>Parent data context: {"a":"3","b":"4"}</p>
<p>Arguments: []</p>
<p>Component data context: {"a":"5","b":"6"}</p>
<p>Current data context: {"a":"5","b":"6"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: ["7",{"hash":{"a":"8","b":"9"}}]</p>
<p>Component data context: {"a":"10","b":"11"}</p>
<p>Current data context: {"a":"10","b":"11"}</p>
<p>Parent data context: {"top":"42"}</p>
<p>Arguments: [{"a":"12","b":"13"},{"hash":{}}]</p>
"""
Blaze.remove @renderedComponent
# It is important that this is 5, not 6, because we have 3 components with static arguments, and we change
# arguments twice. Component should not be created once more just because we changed its data context.
# Only when we change its arguments.
@assertEqual OurNamespace.calls.length, 5
@assertEqual OurNamespace.calls, [
undefined
undefined
'7'
{}
{a: '12', b: '13'}
]
Tracker.afterFlush @expect()
,
->
@assertArgumentsConstructorStateChanges OurNamespace.constructorStateChanges, false
@assertArgumentsOnCreatedStateChanges OurNamespace.onCreatedStateChanges
]
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/30.
testTemplateDynamic: ->
output = BlazeComponent.getComponent('TemplateDynamicTestComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'TemplateDynamicTestComponent', 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = new (BlazeComponent.getComponent('TemplateDynamicTestComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim """
#{COMPONENT_CONTENT 'TemplateDynamicTestComponent', 'MainComponent'}
<hr>
#{COMPONENT_CONTENT 'SubComponent'}
"""
output = BlazeComponent.getComponent('FooComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = new (BlazeComponent.getComponent('FooComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim FOO_COMPONENT_CONTENT()
output = BlazeComponent.getComponent('SubComponent').renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
output = new (BlazeComponent.getComponent('SubComponent'))().renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim COMPONENT_CONTENT 'SubComponent'
testClientGetComponentForElement: [
->
@outerComponent = new (BlazeComponent.getComponent('OuterComponent'))()
@renderedComponent = Blaze.render @outerComponent.renderComponent(), $('body').get(0)
Tracker.afterFlush @expect()
,
->
@innerComponent = @outerComponent.childComponents()[0]
@assertTrue @innerComponent
@assertEqual BlazeComponent.getComponentForElement($('.outerComponent').get(0)), @outerComponent
@assertEqual BlazeComponent.getComponentForElement($('.innerComponent').get(0)), @innerComponent
Blaze.remove @renderedComponent
]
testBlockHelpersStructure: ->
component = new (BlazeComponent.getComponent('TestBlockComponent'))()
@assertTrue component
output = component.renderComponentToHTML null, null,
top: '42'
@assertEqual trim(output), trim(TEST_BLOCK_COMPONENT_CONTENT())
testClientBlockHelpersStructure: [
->
@renderedComponent = Blaze.render Template.extraTestBlockComponent, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.extraTestBlockComponent').html()), trim(TEST_BLOCK_COMPONENT_CONTENT())
TestingComponentDebug.structure = {}
TestingComponentDebug.dumpComponentTree $('.extraTestBlockComponent table').get(0)
@assertEqual TestingComponentDebug.structure, TEST_BLOCK_COMPONENT_STRUCTURE()
@assertEqual BlazeComponent.getComponentForElement($('.insideContent').get(0)).componentName(), 'TestBlockComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideContentComponent').get(0)).componentName(), 'RowComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelper').get(0)).componentName(), 'ExtraTableWrapperBlockComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelperComponent').get(0)).componentName(), 'FootComponent'
@assertEqual BlazeComponent.getComponentForElement($('.insideBlockHelperTemplate').get(0)).componentName(), 'ExtraTableWrapperBlockComponent'
Blaze.remove @renderedComponent
]
testClientExtendingTemplate: [
->
mainComponent3Calls = []
# To make sure we know what to expect from a template, we first test the template.
@renderedTemplate = Blaze.renderWithData Template.mainComponent3Test, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.mainComponent3').html()), trim """
<button>Foo1</button>
<p>mainComponent3.foobar/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
<button>Foo2</button>
<p>mainComponent3.foobar2/{"a":"3","b":"4"}/{"a":"3","b":"4"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}</p>
<p>mainComponent3.foobar3/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
"""
$('.mainComponent3 button').each (i, button) =>
$(button).click()
Blaze.remove @renderedTemplate
Tracker.afterFlush @expect()
,
->
@assertEqual mainComponent3Calls, [
[Template.mainComponent3, 'mainComponent3.onCreated', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onRendered', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onClick', {a: "1", b: "2"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onClick', {a: "3", b: "4"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[Template.mainComponent3, 'mainComponent3.onDestroyed', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
]
,
->
mainComponent3Calls = []
# And now we make a component which extends it.
@renderedTemplate = Blaze.renderWithData Template.mainComponent3ComponentTest, {top: '42'}, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.mainComponent3').html()), trim """
<button>Foo1</button>
<p>super:mainComponent3.foobar/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
<button>Foo2</button>
<p>mainComponent3.foobar2/{"a":"3","b":"4"}/{"a":"3","b":"4"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}</p>
<p>mainComponent3.foobar3/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"a":"1","b":"2"}/{"top":"42"}</p>
"""
$('.mainComponent3 button').each (i, button) =>
$(button).click()
Blaze.remove @renderedTemplate
Tracker.afterFlush @expect()
,
->
@assertEqual mainComponent3Calls, [
[MainComponent3, 'mainComponent3.onCreated', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onRendered', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onClick', {a: "1", b: "2"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onClick', {a: "3", b: "4"}, {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
[MainComponent3, 'mainComponent3.onDestroyed', {a: "1", b: "2"}, {a: "1", b: "2"}, {top: "42"}]
]
]
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/30.
testLexicalArguments: ->
return unless Blaze._lexicalBindingLookup
output = Blaze.toHTMLWithData Template.testLexicalArguments,
test: ['42']
@assertEqual trim(output), trim """42"""
# Test for https://github.com/peerlibrary/meteor-blaze-components/issues/109.
testIndex: ->
return unless Blaze._lexicalBindingLookup
output = Blaze.toHTMLWithData Template.testIndex,
test: ['42']
@assertEqual trim(output), trim """0"""
testLexicalArgumentsComponent: ->
output = BlazeComponent.getComponent('LexicalArgumentsComponent').renderComponentToHTML null, null,
test: [1, 2, 3]
@assertEqual trim(output), trim """
<div>{"test":[1,2,3]}</div>
<div>1/0</div>
<div>{"test":[1,2,3]}</div>
<div>2/1</div>
<div>{"test":[1,2,3]}</div>
<div>3/2</div>
"""
testInlineEventsToHTML: ->
output = Blaze.toHTML Template.inlineEventsTestTemplate
@assertEqual trim(output), trim """
<div class="inlineEventsTestTemplate">
<form>
<div>
<button class="button1" type="button">Button 1</button>
<button class="button2" type="button">Button 2</button>
<button class="button3 dynamic" type="button">Button 3</button>
<button class="button4 dynamic" type="button">Button 4</button>
<button class="button5" type="button" title="Foobar">Button 5</button>
<input type="text">
<textarea></textarea>
</div>
</form>
</div>
"""
testClientInlineEvents: [
->
reactiveArguments {z: 1}
InlineEventsComponent.calls = []
@renderedComponent = Blaze.render Template.inlineEventsTestTemplate, $('body').get(0)
Tracker.afterFlush @expect()
,
->
@assertEqual trim($('.inlineEventsTestTemplate').html()), trim """
<form>
<div>
<button class="button1" type="button">Button 1</button>
<button class="button2" type="button">Button 2</button>
<button class="button3 dynamic" type="button">Button 3</button>
<button class="button4 dynamic" type="button">Button 4</button>
<button class="button5" type="button" title="Foobar">Button 5</button>
<input type="text">
<textarea></textarea>
</div>
</form>
"""
# Event handlers should not be called like template heleprs.
@assertEqual InlineEventsComponent.calls, []
InlineEventsComponent.calls = []
$('.inlineEventsTestTemplate button').each (i, button) =>
$(button).click()
$('.inlineEventsTestTemplate textarea').each (i, textarea) =>
$(textarea).change()
$('.inlineEventsTestTemplate input').each (i, input) =>
$(input).click()
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton1Click', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onClick1Extra', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton2Click', {top: '42'}, {a: '3', b: '4'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 1}, new Spacebars.kw()]
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 1}})]
['InlineEventsComponent', 'InlineEventsComponent.extraArgs1', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.extraArgs2', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onChange', {top: '42'}, {top: '42'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onTextClick', {top: '42'}, {a: '11', b: '12'}, 'InlineEventsComponent']
]
InlineEventsComponent.calls = []
reactiveArguments {z: 2}
Tracker.afterFlush @expect()
,
->
$('.inlineEventsTestTemplate button').each (i, button) =>
$(button).click()
$('.inlineEventsTestTemplate textarea').each (i, textarea) =>
$(textarea).change()
$('.inlineEventsTestTemplate input').each (i, input) =>
$(input).click()
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton1Click', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onClick1Extra', {top: '42'}, {a: '1', b: '2'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton2Click', {top: '42'}, {a: '3', b: '4'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 2}, new Spacebars.kw()]
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 2}})]
['InlineEventsComponent', 'InlineEventsComponent.extraArgs1', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.extraArgs2', {top: '42'}, {a: '9', b: '10'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onChange', {top: '42'}, {top: '42'}, 'InlineEventsComponent']
['InlineEventsComponent', 'InlineEventsComponent.onTextClick', {top: '42'}, {a: '11', b: '12'}, 'InlineEventsComponent']
]
InlineEventsComponent.calls = []
$('.inlineEventsTestTemplate button.dynamic').each (i, button) =>
$(button).trigger('click', 'extraArgument')
@assertEqual InlineEventsComponent.calls, [
['InlineEventsComponent', 'InlineEventsComponent.onButton3Click', {top: '42'}, {a: '5', b: '6'}, 'InlineEventsComponent', 'foobar', {z: 2}, new Spacebars.kw(), 'extraArgument']
['InlineEventsComponent', 'InlineEventsComponent.onButton4Click', {top: '42'}, {a: '7', b: '8'}, 'InlineEventsComponent', new Spacebars.kw({foo: {z: 2}}), 'extraArgument']
]
Blaze.remove @renderedComponent
]
testClientInvalidInlineEvents: ->
@assertThrows =>
Blaze.render Template.invalidInlineEventsTestTemplate, $('body').get(0)
,
/Invalid event handler/
testClientBody: ->
output = Blaze.toHTML Template.body
@assertTrue $($.parseHTML(output)).is('.bodyTest')
testServerBody: ->
output = Blaze.toHTML Template.body
@assertEqual trim(output), trim """
<div class="bodyTest">Body test.</div>
"""
testClientHead: ->
@assertTrue jQuery('head').find('noscript').length
testNestedMixins: ->
LevelTwoComponent.children = []
output = BlazeComponent.getComponent('LevelOneComponent').renderComponentToHTML null, null
@assertEqual trim(output), trim """
<span>41</span>
<span>42</span>
<span></span>
"""
@assertEqual LevelTwoComponent.children, [
all: 0
,
topValue: 0
,
hasValue: 0
,
hasNoValue: 0
,
all: 1
,
topValue: 1
,
hasValue: 1
,
all: 0
,
topValue: 0
,
hasValue: 0
]
ClassyTestCase.addTest new BasicTestCase()
|
[
{
"context": "oken = null\n\t\t@expires = null\n\t\t@userId = null\n\t\t@username = null\n\t\t@analyticsData = null\n\t\t@justRegistered ",
"end": 652,
"score": 0.8207358717918396,
"start": 644,
"tag": "USERNAME",
"value": "username"
},
{
"context": "l\n\t\t@expires = null\n\t\t@userId = null\n\t\t@username = null\n\t\t@analyticsData = null\n\t\t@justRegistered = null\n",
"end": 659,
"score": 0.9789703488349915,
"start": 655,
"tag": "USERNAME",
"value": "null"
},
{
"context": "mise (resolve, reject) =>\n\t\t\t@fbRef = new Firebase(@fbUrl)\n\t\t\t@fbRef.authWithCustomToken token, (err, res) ",
"end": 1646,
"score": 0.946049153804779,
"start": 1640,
"tag": "USERNAME",
"value": "@fbUrl"
},
{
"context": "{usernameOrEmail}\")\n\n\t\tbody = {}\n\t\tbody.password = password\n\t\tif usernameOrEmail.indexOf('@') > 0\n\t\t\tbody.ema",
"end": 2433,
"score": 0.9989126920700073,
"start": 2425,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "opts)\n\t\t)\n\t\t.bind(this)\n\t\t.timeout(10000)\n\t\t.catch(@_networkError)\n\t\t.then (@_checkResponse)\n\t\t.then (data) =>\n\t\t\td",
"end": 4012,
"score": 0.7400193214416504,
"start": 3998,
"tag": "USERNAME",
"value": "@_networkError"
},
{
"context": "timeout(10000)\n\t\t.catch(@_networkError)\n\t\t.then (@_checkResponse)\n\t\t.then (data) =>\n\t\t\tdebug data\n\t\t\t",
"end": 4024,
"score": 0.6571735143661499,
"start": 4024,
"tag": "USERNAME",
"value": ""
},
{
"context": "il: opts.email, username: opts.username, password: opts.password}\n\n\tisEmailAvailable: (email) ->\n\t\treturn Promise.",
"end": 4198,
"score": 0.9121685028076172,
"start": 4185,
"tag": "PASSWORD",
"value": "opts.password"
},
{
"context": "lication/json'\n\t\t\t\tbody: JSON.stringify({username: username})\n\t\t)\n\t\t.then (res) ->\n\t\t\t# available\n\t\t\tif res.o",
"end": 5119,
"score": 0.9016472101211548,
"start": 5111,
"tag": "USERNAME",
"value": "username"
},
{
"context": " #{e.message}\")\n\t\t\treturn true\n\n\tchangeUsername: (new_username) ->\n\t\treturn Promise.resolve(\n\t\t\tfetch \"#{@url}/s",
"end": 5567,
"score": 0.7074003219604492,
"start": 5555,
"tag": "USERNAME",
"value": "new_username"
},
{
"context": "#{@token}\"\n\t\t\t\tbody: JSON.stringify({new_username: new_username})\n\t\t)\n\t\t.bind(this)\n\t\t.timeout(10000)\n\t\t.catch(@_",
"end": 5841,
"score": 0.9879637360572815,
"start": 5829,
"tag": "USERNAME",
"value": "new_username"
},
{
"context": "\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tcurrent_password: currentPassword,\n\t\t\t\t\tnew_password: new_password\n\t\t\t\t})\n\t\t)\n\t\t.bi",
"end": 6265,
"score": 0.9990248680114746,
"start": 6250,
"tag": "PASSWORD",
"value": "currentPassword"
},
{
"context": "rent_password: currentPassword,\n\t\t\t\t\tnew_password: new_password\n\t\t\t\t})\n\t\t)\n\t\t.bind(this)\n\t\t.timeout(5000)\n\t\t.catc",
"end": 6298,
"score": 0.9981649518013,
"start": 6286,
"tag": "PASSWORD",
"value": "new_password"
},
{
"context": "Id})\n\t\t)\n\t\t.bind(this)\n\t\t.timeout(5000)\n\t\t.catch(@_networkError)\n\t\t.then(@_checkResponse)\n\n\tforgot: (email) ",
"end": 7222,
"score": 0.5722824931144714,
"start": 7215,
"tag": "USERNAME",
"value": "network"
},
{
"context": "l})\n\t\t)\n\t\t.bind(this)\n\t\t.timeout(10000)\n\t\t.catch(@_networkError)\n\t\t.then (res) ->\n\t\t\tif res.ok then r",
"end": 7521,
"score": 0.5458738207817078,
"start": 7521,
"tag": "USERNAME",
"value": ""
},
{
"context": ".ok}\")\n\t\t\tif not res.ok then return null\n\t\t\t#TODO: @marwan what is the proper way to prevent _checkResponse'",
"end": 8449,
"score": 0.9991397857666016,
"start": 8442,
"tag": "USERNAME",
"value": "@marwan"
}
] | app/common/session2.coffee | willroberts/duelyst | 5 | debug = require('debug')('session')
{EventEmitter} = require 'events'
Promise = require 'bluebird'
Firebase = require 'firebase'
fetch = require 'isomorphic-fetch'
moment = require 'moment'
Storage = require('app/common/storage')
i18next = require('i18next')
class Session extends EventEmitter
constructor: (options = {}) ->
@url = process.env.API_URL || options.url || 'http://localhost:5000'
@fbUrl = process.env.FIREBASE_URL || options.fbUrl || 'https://duelyst-development.firebaseio.com/'
debug("constructor: #{@url} : #{@fbUrl}")
# init props for reference
@fbRef = null
@token = null
@expires = null
@userId = null
@username = null
@analyticsData = null
@justRegistered = null
@_cachedPremiumBalance = null
return
_checkResponse: (res) ->
if res.ok
debug("_checkResponse: #{res.status}")
return res.json()
.then (data) ->
data.status = res.status
return data
else
err = new Error(res.statusText)
err.status = res.status
if res.status == 400 || res.status == 401
return res.json().then (data) =>
err.innerMessage = if data.codeMessage then data.codeMessage else data.message
debug("_checkResponse: #{res.status} : #{err.message} : #{err.innerMessage}")
@emit 'error', err
throw err
else
err.innerMessage = 'Please try again'
debug("_checkResponse: #{res.status} : #{err.message}")
@emit 'error', err
throw err
_networkError: (e) ->
debug("_networkError: #{e.message}")
throw new Error('Please try again')
_authFirebase: (token) ->
debug('authFirebase')
return new Promise (resolve, reject) =>
@fbRef = new Firebase(@fbUrl)
@fbRef.authWithCustomToken token, (err, res) ->
debug('authWithCustomToken')
if err then return reject(err)
resolve(res)
_deauthFirebase: () ->
debug('deauthFirebase')
if @userId
@fbRef
.child("users")
.child(@userId)
.child("presence")
.update({
status: "offline"
ended: Firebase.ServerValue.TIMESTAMP
})
@fbRef.unauth()
_decodeFirebaseToken: (token) ->
debug('_decodeFirebaseToken')
@userId = token.auth.id
@username = token.auth.username
@expires = token.expires
###
Show url for purchasing premium currency on external site
###
initPremiumPurchase: () ->
return Promise.resolve("")
login: (usernameOrEmail, password, silent = false) ->
debug("login: #{usernameOrEmail}")
body = {}
body.password = password
if usernameOrEmail.indexOf('@') > 0
body.email = usernameOrEmail
else
body.username = usernameOrEmail
return Promise.resolve(
fetch "#{@url}/session",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify(body)
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (@_checkResponse)
.then (res) =>
@analyticsData = res.analytics_data
@token = res.token
return @_authFirebase(@token)
.then (res) =>
debug(res)
@userId = res.auth.id
@username = res.auth.username
@expires = res.expires
data = {token: @token, userId: @userId, analyticsData:@analyticsData}
if !silent
@emit 'login', data
return data
logout: () ->
debug('logout')
if window.isSteam
return
# if @userId
# @_deauthFirebase()
if @token
fetch "#{@url}/session/logout",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
.catch () ->
@fbRef = null
@token = null
@expires = null
@userId = null
@username = null
@analyticsData = null
# clear storage
@emit 'logout'
register: (opts) ->
debug("register #{JSON.stringify(opts)}")
opts.is_desktop = window.isDesktop || false
return Promise.resolve(
fetch "#{@url}/session/register",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify(opts)
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (@_checkResponse)
.then (data) =>
debug data
@justRegistered = true
@emit 'registered'
return {email: opts.email, username: opts.username, password: opts.password}
isEmailAvailable: (email) ->
return Promise.resolve(
fetch "#{@url}/session/email_available",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({email: email})
)
.then (res) ->
# available
if res.ok then return true
# 401 result suggests email is bad or unavailable
if res.status == 401 then return false
# all other results suggest server is unavailable or had an error
# so assume email is valid and let the server handle it in the later registration request
return true
.catch (e) ->
debug("isEmailAvailable #{e.message}")
return true
isUsernameAvailable: (username) ->
return Promise.resolve(
fetch "#{@url}/session/username_available",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({username: username})
)
.then (res) ->
# available
if res.ok then return true
# 401 result suggests email is bad or unavailable
if res.status == 401 then return false
# all other results suggest server is unavailable or had an error
# so assume email is valid and let the server handle it in the later registration request
return true
.catch (e) ->
debug("isUsernameAvailable #{e.message}")
return true
changeUsername: (new_username) ->
return Promise.resolve(
fetch "#{@url}/session/change_username",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({new_username: new_username})
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then(@_checkResponse)
changePassword: (currentPassword, new_password) ->
return Promise.resolve(
fetch "#{@url}/session/change_password",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({
current_password: currentPassword,
new_password: new_password
})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
changePortrait: (portraitId) ->
if !portraitId?
return Promise.reject(new Error("Invalid portrait!"))
return Promise.resolve(
fetch "#{@url}/api/me/profile/portrait_id",
method: 'PUT'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({portrait_id: portraitId})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
changeBattlemap: (battlemapId) ->
return Promise.resolve(
fetch "#{@url}/api/me/profile/battle_map_id",
method: 'PUT'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({battle_map_id: battlemapId})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
forgot: (email) ->
return Promise.resolve(
fetch "#{@url}/forgot",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({email: email})
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (res) ->
if res.ok then return email
if res.status == 404
throw new Error('That email was not found')
else
throw new Error('Please try again')
isAuthenticated: (token) ->
if not token? then return Promise.resolve(false)
# decode with Firebase
return @_authFirebase(token)
.bind(@)
.timeout(15000)
.then (decodedToken) =>
debug('isAuthenticated:authFirebase', decodedToken)
# use decoded token to init params
@token = token
@userId = decodedToken.auth.id
@username = decodedToken.auth.username
@expires = decodedToken.expires
# validate token with our servers
return fetch "#{@url}/session",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
.then (res) =>
debug("isAuthenticated:fetch #{res.ok}")
if not res.ok then return null
#TODO: @marwan what is the proper way to prevent _checkResponse's errors from causing this to go to the try catch
#I'm guessing you were trying to avoid that by only checking res.ok?
return @_checkResponse(res)
.then (data) =>
if data == null then return false
@analyticsData = data.analytics_data
@emit 'login', {token: @token, userId: @userId, analyticsData: @analyticsData}
return true
.catch (e) ->
debug("isAuthenticated:failed #{e.message}")
return false
refreshToken: (silent = false) ->
if not @token? then return Promise.resolve(null)
return Promise.resolve(
fetch "#{@url}/session",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
)
.bind(@)
.then (res) =>
debug("refreshToken:fetch #{res.ok}")
if not res.ok then return null
return @_checkResponse(res)
.then (data) =>
if data == null then return null
# override existing token and analytics with new ones
@token = data.token
@analyticsData = data.analytics_data
return @_authFirebase(@token)
.then (decodedToken) =>
@userId = decodedToken.auth.id
@username = decodedToken.auth.username
@expires = decodedToken.expires
# emit login event with whatever data we currently have
if !silent
@emit 'login', {@token, @analyticsData, @userId}
return true
.catch (e) ->
debug("refreshToken:failed #{e.message}")
return null
# Returns whether this is the player's first session of the day based on their last session timestamp
# Note: this can change during the session if a new day begins
getIsFirstSessionOfDay: () ->
# If no analytics data this is being called before auth, shouldn't happen but return false
if not @.analyticsData?
return false
# Having no last_session_at means this is their first session ever
if not @.analyticsData.last_session_at?
return true
startOfTodayMoment = moment.utc().startOf('day')
lastSessionStartOfDayMoment = moment.utc(@.analyticsData.last_session_at).startOf('day')
return lastSessionStartOfDayMoment.valueOf() < startOfTodayMoment.valueOf()
saveToStorage: () ->
if @token
Storage.set('token', @token)
clearStorage: () ->
Storage.remove('token')
module.exports = new Session()
module.exports.create = (options) ->
return new Session(options)
| 154301 | debug = require('debug')('session')
{EventEmitter} = require 'events'
Promise = require 'bluebird'
Firebase = require 'firebase'
fetch = require 'isomorphic-fetch'
moment = require 'moment'
Storage = require('app/common/storage')
i18next = require('i18next')
class Session extends EventEmitter
constructor: (options = {}) ->
@url = process.env.API_URL || options.url || 'http://localhost:5000'
@fbUrl = process.env.FIREBASE_URL || options.fbUrl || 'https://duelyst-development.firebaseio.com/'
debug("constructor: #{@url} : #{@fbUrl}")
# init props for reference
@fbRef = null
@token = null
@expires = null
@userId = null
@username = null
@analyticsData = null
@justRegistered = null
@_cachedPremiumBalance = null
return
_checkResponse: (res) ->
if res.ok
debug("_checkResponse: #{res.status}")
return res.json()
.then (data) ->
data.status = res.status
return data
else
err = new Error(res.statusText)
err.status = res.status
if res.status == 400 || res.status == 401
return res.json().then (data) =>
err.innerMessage = if data.codeMessage then data.codeMessage else data.message
debug("_checkResponse: #{res.status} : #{err.message} : #{err.innerMessage}")
@emit 'error', err
throw err
else
err.innerMessage = 'Please try again'
debug("_checkResponse: #{res.status} : #{err.message}")
@emit 'error', err
throw err
_networkError: (e) ->
debug("_networkError: #{e.message}")
throw new Error('Please try again')
_authFirebase: (token) ->
debug('authFirebase')
return new Promise (resolve, reject) =>
@fbRef = new Firebase(@fbUrl)
@fbRef.authWithCustomToken token, (err, res) ->
debug('authWithCustomToken')
if err then return reject(err)
resolve(res)
_deauthFirebase: () ->
debug('deauthFirebase')
if @userId
@fbRef
.child("users")
.child(@userId)
.child("presence")
.update({
status: "offline"
ended: Firebase.ServerValue.TIMESTAMP
})
@fbRef.unauth()
_decodeFirebaseToken: (token) ->
debug('_decodeFirebaseToken')
@userId = token.auth.id
@username = token.auth.username
@expires = token.expires
###
Show url for purchasing premium currency on external site
###
initPremiumPurchase: () ->
return Promise.resolve("")
login: (usernameOrEmail, password, silent = false) ->
debug("login: #{usernameOrEmail}")
body = {}
body.password = <PASSWORD>
if usernameOrEmail.indexOf('@') > 0
body.email = usernameOrEmail
else
body.username = usernameOrEmail
return Promise.resolve(
fetch "#{@url}/session",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify(body)
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (@_checkResponse)
.then (res) =>
@analyticsData = res.analytics_data
@token = res.token
return @_authFirebase(@token)
.then (res) =>
debug(res)
@userId = res.auth.id
@username = res.auth.username
@expires = res.expires
data = {token: @token, userId: @userId, analyticsData:@analyticsData}
if !silent
@emit 'login', data
return data
logout: () ->
debug('logout')
if window.isSteam
return
# if @userId
# @_deauthFirebase()
if @token
fetch "#{@url}/session/logout",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
.catch () ->
@fbRef = null
@token = null
@expires = null
@userId = null
@username = null
@analyticsData = null
# clear storage
@emit 'logout'
register: (opts) ->
debug("register #{JSON.stringify(opts)}")
opts.is_desktop = window.isDesktop || false
return Promise.resolve(
fetch "#{@url}/session/register",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify(opts)
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (@_checkResponse)
.then (data) =>
debug data
@justRegistered = true
@emit 'registered'
return {email: opts.email, username: opts.username, password: <PASSWORD>}
isEmailAvailable: (email) ->
return Promise.resolve(
fetch "#{@url}/session/email_available",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({email: email})
)
.then (res) ->
# available
if res.ok then return true
# 401 result suggests email is bad or unavailable
if res.status == 401 then return false
# all other results suggest server is unavailable or had an error
# so assume email is valid and let the server handle it in the later registration request
return true
.catch (e) ->
debug("isEmailAvailable #{e.message}")
return true
isUsernameAvailable: (username) ->
return Promise.resolve(
fetch "#{@url}/session/username_available",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({username: username})
)
.then (res) ->
# available
if res.ok then return true
# 401 result suggests email is bad or unavailable
if res.status == 401 then return false
# all other results suggest server is unavailable or had an error
# so assume email is valid and let the server handle it in the later registration request
return true
.catch (e) ->
debug("isUsernameAvailable #{e.message}")
return true
changeUsername: (new_username) ->
return Promise.resolve(
fetch "#{@url}/session/change_username",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({new_username: new_username})
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then(@_checkResponse)
changePassword: (currentPassword, new_password) ->
return Promise.resolve(
fetch "#{@url}/session/change_password",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({
current_password: <PASSWORD>,
new_password: <PASSWORD>
})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
changePortrait: (portraitId) ->
if !portraitId?
return Promise.reject(new Error("Invalid portrait!"))
return Promise.resolve(
fetch "#{@url}/api/me/profile/portrait_id",
method: 'PUT'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({portrait_id: portraitId})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
changeBattlemap: (battlemapId) ->
return Promise.resolve(
fetch "#{@url}/api/me/profile/battle_map_id",
method: 'PUT'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({battle_map_id: battlemapId})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
forgot: (email) ->
return Promise.resolve(
fetch "#{@url}/forgot",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({email: email})
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (res) ->
if res.ok then return email
if res.status == 404
throw new Error('That email was not found')
else
throw new Error('Please try again')
isAuthenticated: (token) ->
if not token? then return Promise.resolve(false)
# decode with Firebase
return @_authFirebase(token)
.bind(@)
.timeout(15000)
.then (decodedToken) =>
debug('isAuthenticated:authFirebase', decodedToken)
# use decoded token to init params
@token = token
@userId = decodedToken.auth.id
@username = decodedToken.auth.username
@expires = decodedToken.expires
# validate token with our servers
return fetch "#{@url}/session",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
.then (res) =>
debug("isAuthenticated:fetch #{res.ok}")
if not res.ok then return null
#TODO: @marwan what is the proper way to prevent _checkResponse's errors from causing this to go to the try catch
#I'm guessing you were trying to avoid that by only checking res.ok?
return @_checkResponse(res)
.then (data) =>
if data == null then return false
@analyticsData = data.analytics_data
@emit 'login', {token: @token, userId: @userId, analyticsData: @analyticsData}
return true
.catch (e) ->
debug("isAuthenticated:failed #{e.message}")
return false
refreshToken: (silent = false) ->
if not @token? then return Promise.resolve(null)
return Promise.resolve(
fetch "#{@url}/session",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
)
.bind(@)
.then (res) =>
debug("refreshToken:fetch #{res.ok}")
if not res.ok then return null
return @_checkResponse(res)
.then (data) =>
if data == null then return null
# override existing token and analytics with new ones
@token = data.token
@analyticsData = data.analytics_data
return @_authFirebase(@token)
.then (decodedToken) =>
@userId = decodedToken.auth.id
@username = decodedToken.auth.username
@expires = decodedToken.expires
# emit login event with whatever data we currently have
if !silent
@emit 'login', {@token, @analyticsData, @userId}
return true
.catch (e) ->
debug("refreshToken:failed #{e.message}")
return null
# Returns whether this is the player's first session of the day based on their last session timestamp
# Note: this can change during the session if a new day begins
getIsFirstSessionOfDay: () ->
# If no analytics data this is being called before auth, shouldn't happen but return false
if not @.analyticsData?
return false
# Having no last_session_at means this is their first session ever
if not @.analyticsData.last_session_at?
return true
startOfTodayMoment = moment.utc().startOf('day')
lastSessionStartOfDayMoment = moment.utc(@.analyticsData.last_session_at).startOf('day')
return lastSessionStartOfDayMoment.valueOf() < startOfTodayMoment.valueOf()
saveToStorage: () ->
if @token
Storage.set('token', @token)
clearStorage: () ->
Storage.remove('token')
module.exports = new Session()
module.exports.create = (options) ->
return new Session(options)
| true | debug = require('debug')('session')
{EventEmitter} = require 'events'
Promise = require 'bluebird'
Firebase = require 'firebase'
fetch = require 'isomorphic-fetch'
moment = require 'moment'
Storage = require('app/common/storage')
i18next = require('i18next')
class Session extends EventEmitter
constructor: (options = {}) ->
@url = process.env.API_URL || options.url || 'http://localhost:5000'
@fbUrl = process.env.FIREBASE_URL || options.fbUrl || 'https://duelyst-development.firebaseio.com/'
debug("constructor: #{@url} : #{@fbUrl}")
# init props for reference
@fbRef = null
@token = null
@expires = null
@userId = null
@username = null
@analyticsData = null
@justRegistered = null
@_cachedPremiumBalance = null
return
_checkResponse: (res) ->
if res.ok
debug("_checkResponse: #{res.status}")
return res.json()
.then (data) ->
data.status = res.status
return data
else
err = new Error(res.statusText)
err.status = res.status
if res.status == 400 || res.status == 401
return res.json().then (data) =>
err.innerMessage = if data.codeMessage then data.codeMessage else data.message
debug("_checkResponse: #{res.status} : #{err.message} : #{err.innerMessage}")
@emit 'error', err
throw err
else
err.innerMessage = 'Please try again'
debug("_checkResponse: #{res.status} : #{err.message}")
@emit 'error', err
throw err
_networkError: (e) ->
debug("_networkError: #{e.message}")
throw new Error('Please try again')
_authFirebase: (token) ->
debug('authFirebase')
return new Promise (resolve, reject) =>
@fbRef = new Firebase(@fbUrl)
@fbRef.authWithCustomToken token, (err, res) ->
debug('authWithCustomToken')
if err then return reject(err)
resolve(res)
_deauthFirebase: () ->
debug('deauthFirebase')
if @userId
@fbRef
.child("users")
.child(@userId)
.child("presence")
.update({
status: "offline"
ended: Firebase.ServerValue.TIMESTAMP
})
@fbRef.unauth()
_decodeFirebaseToken: (token) ->
debug('_decodeFirebaseToken')
@userId = token.auth.id
@username = token.auth.username
@expires = token.expires
###
Show url for purchasing premium currency on external site
###
initPremiumPurchase: () ->
return Promise.resolve("")
login: (usernameOrEmail, password, silent = false) ->
debug("login: #{usernameOrEmail}")
body = {}
body.password = PI:PASSWORD:<PASSWORD>END_PI
if usernameOrEmail.indexOf('@') > 0
body.email = usernameOrEmail
else
body.username = usernameOrEmail
return Promise.resolve(
fetch "#{@url}/session",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify(body)
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (@_checkResponse)
.then (res) =>
@analyticsData = res.analytics_data
@token = res.token
return @_authFirebase(@token)
.then (res) =>
debug(res)
@userId = res.auth.id
@username = res.auth.username
@expires = res.expires
data = {token: @token, userId: @userId, analyticsData:@analyticsData}
if !silent
@emit 'login', data
return data
logout: () ->
debug('logout')
if window.isSteam
return
# if @userId
# @_deauthFirebase()
if @token
fetch "#{@url}/session/logout",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
.catch () ->
@fbRef = null
@token = null
@expires = null
@userId = null
@username = null
@analyticsData = null
# clear storage
@emit 'logout'
register: (opts) ->
debug("register #{JSON.stringify(opts)}")
opts.is_desktop = window.isDesktop || false
return Promise.resolve(
fetch "#{@url}/session/register",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify(opts)
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (@_checkResponse)
.then (data) =>
debug data
@justRegistered = true
@emit 'registered'
return {email: opts.email, username: opts.username, password: PI:PASSWORD:<PASSWORD>END_PI}
isEmailAvailable: (email) ->
return Promise.resolve(
fetch "#{@url}/session/email_available",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({email: email})
)
.then (res) ->
# available
if res.ok then return true
# 401 result suggests email is bad or unavailable
if res.status == 401 then return false
# all other results suggest server is unavailable or had an error
# so assume email is valid and let the server handle it in the later registration request
return true
.catch (e) ->
debug("isEmailAvailable #{e.message}")
return true
isUsernameAvailable: (username) ->
return Promise.resolve(
fetch "#{@url}/session/username_available",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({username: username})
)
.then (res) ->
# available
if res.ok then return true
# 401 result suggests email is bad or unavailable
if res.status == 401 then return false
# all other results suggest server is unavailable or had an error
# so assume email is valid and let the server handle it in the later registration request
return true
.catch (e) ->
debug("isUsernameAvailable #{e.message}")
return true
changeUsername: (new_username) ->
return Promise.resolve(
fetch "#{@url}/session/change_username",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({new_username: new_username})
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then(@_checkResponse)
changePassword: (currentPassword, new_password) ->
return Promise.resolve(
fetch "#{@url}/session/change_password",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({
current_password: PI:PASSWORD:<PASSWORD>END_PI,
new_password: PI:PASSWORD:<PASSWORD>END_PI
})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
changePortrait: (portraitId) ->
if !portraitId?
return Promise.reject(new Error("Invalid portrait!"))
return Promise.resolve(
fetch "#{@url}/api/me/profile/portrait_id",
method: 'PUT'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({portrait_id: portraitId})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
changeBattlemap: (battlemapId) ->
return Promise.resolve(
fetch "#{@url}/api/me/profile/battle_map_id",
method: 'PUT'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
body: JSON.stringify({battle_map_id: battlemapId})
)
.bind(this)
.timeout(5000)
.catch(@_networkError)
.then(@_checkResponse)
forgot: (email) ->
return Promise.resolve(
fetch "#{@url}/forgot",
method: 'POST'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
body: JSON.stringify({email: email})
)
.bind(this)
.timeout(10000)
.catch(@_networkError)
.then (res) ->
if res.ok then return email
if res.status == 404
throw new Error('That email was not found')
else
throw new Error('Please try again')
isAuthenticated: (token) ->
if not token? then return Promise.resolve(false)
# decode with Firebase
return @_authFirebase(token)
.bind(@)
.timeout(15000)
.then (decodedToken) =>
debug('isAuthenticated:authFirebase', decodedToken)
# use decoded token to init params
@token = token
@userId = decodedToken.auth.id
@username = decodedToken.auth.username
@expires = decodedToken.expires
# validate token with our servers
return fetch "#{@url}/session",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
.then (res) =>
debug("isAuthenticated:fetch #{res.ok}")
if not res.ok then return null
#TODO: @marwan what is the proper way to prevent _checkResponse's errors from causing this to go to the try catch
#I'm guessing you were trying to avoid that by only checking res.ok?
return @_checkResponse(res)
.then (data) =>
if data == null then return false
@analyticsData = data.analytics_data
@emit 'login', {token: @token, userId: @userId, analyticsData: @analyticsData}
return true
.catch (e) ->
debug("isAuthenticated:failed #{e.message}")
return false
refreshToken: (silent = false) ->
if not @token? then return Promise.resolve(null)
return Promise.resolve(
fetch "#{@url}/session",
method: 'GET'
headers:
'Accept': 'application/json'
'Content-Type': 'application/json'
'Authorization': "Bearer #{@token}"
)
.bind(@)
.then (res) =>
debug("refreshToken:fetch #{res.ok}")
if not res.ok then return null
return @_checkResponse(res)
.then (data) =>
if data == null then return null
# override existing token and analytics with new ones
@token = data.token
@analyticsData = data.analytics_data
return @_authFirebase(@token)
.then (decodedToken) =>
@userId = decodedToken.auth.id
@username = decodedToken.auth.username
@expires = decodedToken.expires
# emit login event with whatever data we currently have
if !silent
@emit 'login', {@token, @analyticsData, @userId}
return true
.catch (e) ->
debug("refreshToken:failed #{e.message}")
return null
# Returns whether this is the player's first session of the day based on their last session timestamp
# Note: this can change during the session if a new day begins
getIsFirstSessionOfDay: () ->
# If no analytics data this is being called before auth, shouldn't happen but return false
if not @.analyticsData?
return false
# Having no last_session_at means this is their first session ever
if not @.analyticsData.last_session_at?
return true
startOfTodayMoment = moment.utc().startOf('day')
lastSessionStartOfDayMoment = moment.utc(@.analyticsData.last_session_at).startOf('day')
return lastSessionStartOfDayMoment.valueOf() < startOfTodayMoment.valueOf()
saveToStorage: () ->
if @token
Storage.set('token', @token)
clearStorage: () ->
Storage.remove('token')
module.exports = new Session()
module.exports.create = (options) ->
return new Session(options)
|
[
{
"context": "achedResource('villain', '/villain/:name', { name: '@name'})\n villains = Villain.query()\n $log.rese",
"end": 352,
"score": 0.9969945549964905,
"start": 346,
"tag": "USERNAME",
"value": "'@name"
},
{
"context": "nd.expectGET('/villain').respond [\n { name: 'Dracula', powers: ['Superhuman strength', 'Immortality', ",
"end": 522,
"score": 0.9974193572998047,
"start": 515,
"tag": "NAME",
"value": "Dracula"
}
] | test/bound_params_nonexistent.test.coffee | goodeggs/angular-cached-resource | 152 | describe 'bound params do not match array response', ->
{villains, $httpBackend, $log} = {}
beforeEach ->
inject ($injector) ->
$log = $injector.get '$log'
$httpBackend = $injector.get '$httpBackend'
$cachedResource = $injector.get '$cachedResource'
Villain = $cachedResource('villain', '/villain/:name', { name: '@name'})
villains = Villain.query()
$log.reset()
it 'should display a warning message', ->
$httpBackend.expectGET('/villain').respond [
{ name: 'Dracula', powers: ['Superhuman strength', 'Immortality', 'Shapeshifting'], weakness: 'Decapitation' }
{ nickname: 'You-Know-Who', powers: ['Magic', 'Flight', 'Parcelmouth'], weakness: 'Killing curse' }
]
$httpBackend.flush()
expect($log.error.logs.length).to.equal 1
expect($log.error.logs[0][0]).to.equal 'ngCachedResource'
expect($log.error.logs[0][1]).to.contain "'villain' instance doesn't have any boundParams"
| 73292 | describe 'bound params do not match array response', ->
{villains, $httpBackend, $log} = {}
beforeEach ->
inject ($injector) ->
$log = $injector.get '$log'
$httpBackend = $injector.get '$httpBackend'
$cachedResource = $injector.get '$cachedResource'
Villain = $cachedResource('villain', '/villain/:name', { name: '@name'})
villains = Villain.query()
$log.reset()
it 'should display a warning message', ->
$httpBackend.expectGET('/villain').respond [
{ name: '<NAME>', powers: ['Superhuman strength', 'Immortality', 'Shapeshifting'], weakness: 'Decapitation' }
{ nickname: 'You-Know-Who', powers: ['Magic', 'Flight', 'Parcelmouth'], weakness: 'Killing curse' }
]
$httpBackend.flush()
expect($log.error.logs.length).to.equal 1
expect($log.error.logs[0][0]).to.equal 'ngCachedResource'
expect($log.error.logs[0][1]).to.contain "'villain' instance doesn't have any boundParams"
| true | describe 'bound params do not match array response', ->
{villains, $httpBackend, $log} = {}
beforeEach ->
inject ($injector) ->
$log = $injector.get '$log'
$httpBackend = $injector.get '$httpBackend'
$cachedResource = $injector.get '$cachedResource'
Villain = $cachedResource('villain', '/villain/:name', { name: '@name'})
villains = Villain.query()
$log.reset()
it 'should display a warning message', ->
$httpBackend.expectGET('/villain').respond [
{ name: 'PI:NAME:<NAME>END_PI', powers: ['Superhuman strength', 'Immortality', 'Shapeshifting'], weakness: 'Decapitation' }
{ nickname: 'You-Know-Who', powers: ['Magic', 'Flight', 'Parcelmouth'], weakness: 'Killing curse' }
]
$httpBackend.flush()
expect($log.error.logs.length).to.equal 1
expect($log.error.logs[0][0]).to.equal 'ngCachedResource'
expect($log.error.logs[0][1]).to.contain "'villain' instance doesn't have any boundParams"
|
[
{
"context": " render: ->\n super\n @main.form.value text: \"soyjavi\", password: 1234\n\n setTimeout =>\n @exampl",
"end": 151,
"score": 0.9886714220046997,
"start": 144,
"tag": "USERNAME",
"value": "soyjavi"
},
{
"context": "r\n @main.form.value text: \"soyjavi\", password: 1234\n\n setTimeout =>\n @example.form.range.valu",
"end": 168,
"score": 0.9989309906959534,
"start": 164,
"tag": "PASSWORD",
"value": "1234"
}
] | source/organisms/article.form.coffee | tapquo/atoms-app-kitchensink | 0 | class Form extends Atoms.Organism.Article
@scaffold "assets/scaffolds/article.form.json"
render: ->
super
@main.form.value text: "soyjavi", password: 1234
setTimeout =>
@example.form.range.value 5
@example.form.checkbox.value false
@example.form.switch.value false
setTimeout =>
@example.form.range.value 0
@example.form.checkbox.value true
@example.form.switch.value true
, 1000
, 1000
# -- Children Bubble Events --------------------------------------------------
onClear: ->
@example.form.clean()
false
onFormChange: (event, form, hierarchy...) ->
console.info "onFormChange", event, form, hierarchy
onFormSubmit: (event, form, hierarchy...) ->
console.info "onFormSubmit", form.value()
onFormError: (event, form, hierarchy...) ->
console.info "onFormError", form.value()
onFormComplete: (event, form, hierarchy...) ->
console.info "onFormComplete", form.value()
onButtonTouch: (event, atom) ->
atom.el.addClass("loading").attr "disabled", true
setTimeout =>
atom.el.removeClass("loading").removeAttr "disabled"
, 1000
form = new Form()
| 216959 | class Form extends Atoms.Organism.Article
@scaffold "assets/scaffolds/article.form.json"
render: ->
super
@main.form.value text: "soyjavi", password: <PASSWORD>
setTimeout =>
@example.form.range.value 5
@example.form.checkbox.value false
@example.form.switch.value false
setTimeout =>
@example.form.range.value 0
@example.form.checkbox.value true
@example.form.switch.value true
, 1000
, 1000
# -- Children Bubble Events --------------------------------------------------
onClear: ->
@example.form.clean()
false
onFormChange: (event, form, hierarchy...) ->
console.info "onFormChange", event, form, hierarchy
onFormSubmit: (event, form, hierarchy...) ->
console.info "onFormSubmit", form.value()
onFormError: (event, form, hierarchy...) ->
console.info "onFormError", form.value()
onFormComplete: (event, form, hierarchy...) ->
console.info "onFormComplete", form.value()
onButtonTouch: (event, atom) ->
atom.el.addClass("loading").attr "disabled", true
setTimeout =>
atom.el.removeClass("loading").removeAttr "disabled"
, 1000
form = new Form()
| true | class Form extends Atoms.Organism.Article
@scaffold "assets/scaffolds/article.form.json"
render: ->
super
@main.form.value text: "soyjavi", password: PI:PASSWORD:<PASSWORD>END_PI
setTimeout =>
@example.form.range.value 5
@example.form.checkbox.value false
@example.form.switch.value false
setTimeout =>
@example.form.range.value 0
@example.form.checkbox.value true
@example.form.switch.value true
, 1000
, 1000
# -- Children Bubble Events --------------------------------------------------
onClear: ->
@example.form.clean()
false
onFormChange: (event, form, hierarchy...) ->
console.info "onFormChange", event, form, hierarchy
onFormSubmit: (event, form, hierarchy...) ->
console.info "onFormSubmit", form.value()
onFormError: (event, form, hierarchy...) ->
console.info "onFormError", form.value()
onFormComplete: (event, form, hierarchy...) ->
console.info "onFormComplete", form.value()
onButtonTouch: (event, atom) ->
atom.el.addClass("loading").attr "disabled", true
setTimeout =>
atom.el.removeClass("loading").removeAttr "disabled"
, 1000
form = new Form()
|
[
{
"context": "#Based on http://www.math.rwth-aachen.de/~Gerhard.Hiss/Students/DiplomarbeitPfeiffer.pdf\n#algorithm 3, 4",
"end": 54,
"score": 0.9990158081054688,
"start": 42,
"tag": "NAME",
"value": "Gerhard.Hiss"
}
] | src/core/knuth_bendix.coffee | undeadinu/hyperbolic-ca-simulator | 32 | #Based on http://www.math.rwth-aachen.de/~Gerhard.Hiss/Students/DiplomarbeitPfeiffer.pdf
#algorithm 3, 4
#import itertools
#values are encoded as simple strings.
# User is responsible
print = (s ... ) -> console.log( s.join(" ") )
#COnvert "less or equal" function to the JS-compatible comparator function
le2cmp = ( leFunc ) ->
(a,b) ->
if a is b
0
else if leFunc(a,b)
-1
else
1
exports.RewriteRuleset = class RewriteRuleset
constructor: (rules)->
@rules = rules
pprint: ()->
print ("{")
for [v, w] in @_sortedItems()
print " #{v} -> #{w}"
print "}"
copy: ()->
new RewriteRuleset(JSON.parse JSON.stringify @rules)
_sortedItems: ()->
items = @items()
items.sort le2cmp(shortLex)
return items
suffices: -> (k for k of @rules)
size: -> @suffices().length
items: -> ( [k, v] for k, v of @rules )
__equalOneSided: (other) ->
for k, v of @rules
if other.rules[k] isnt v
return false
return true
equals: ( other)-> this.__equalOneSided(other) and other.__equalOneSided(this)
#__hash__: ()-> return hash(@rules)
add: ( v, w)->
@rules[v] = w
remove: ( v)->
delete @rules[v]
normalize: ( lessOrEq )->
SS = {}
for v, w of @rules
[v, w] = sortPairReverse(v, w, lessOrEq)
#v is biggest now
if not SS[v]?
SS[v] = w
else
#resolve conflict by chosing the lowest of 2.
SS[v] = sortPairReverse(w, SS[v], lessOrEq)[1]
return new RewriteRuleset(SS)
__ruleLengths: ()->
lens = {}
for k of @rules
lens[k.length] = null
lenslist = (parseInt(k, 10) for k of lens)
lenslist.sort()
return lenslist
appendRewrite: ( s, xs_)->
#"""Append elements of the string xs_ to the string s, running all rewrite rules"""
rules = @rules
return s if xs_.length is 0
xs = xs_.split("")
xs.reverse()
lengths = @__ruleLengths()
while xs.length > 0
s = s + xs.pop()
for suffixLen in lengths
suffix = s.substring(s.length-suffixLen)
#console.log "suf: #{suffix}, len: #{suffixLen}"
rewriteAs = rules[suffix]
if rewriteAs?
#Rewrite found!
#console.log " Rewrite found: #{suffix}, #{rewriteAs}"
s = s.substring(0, s.length - suffixLen)
for i in [rewriteAs.length-1 .. 0] by -1
xs.push rewriteAs[i]
continue
return s
has: (key) -> @rules.hasOwnProperty key
rewrite: ( s )-> @appendRewrite( "", s )
exports.shortLex = shortLex = (s1, s2)->
#"""Shortlex less or equal comparator"""
if s1.length > s2.length
return false
if s1.length < s2.length
return true
return s1 <= s2
exports.overlap = overlap = (s1, s2)->
#"""Two strings: s1, s2.
#Reutnrs x,y,z such as:
#s1 = xy
#s2 = yz
#"""
if s2.length is 0
return [s1, "", s2]
[i1, i2] = [0, 0]
#i1, i2: indices in s1, s2
s2_0 = s2[0]
istart = Math.max( 0, s1.length - s2.length )
for i in [istart ... s1.length]
s1_i = s1[i]
if s1_i is s2_0
#console.log "Comparing #{s1.substring(i+1)} and #{s2.substring(1, s1.length-i)}"
if s1.substring(i+1) is s2.substring(1, s1.length-i)
return [s1.substring(0,i), s1.substring(i), s2.substring(s1.length-i)]
return [s1, "", s2]
exports.splitBy = splitBy = (s1, s2)->
#"""Split sequence s1 by sequence s2.
#Returns True and prefix + postfix, or just False and None None
#"""
if s2.length == 0
[true, s1, ""]
for i in [0...s1.length - s2.length+1]
if s1.substring(i, i+s2.length) is s2
return [true, s1.substring(0,i), s1.substring(i+s2.length)]
return [false, null, null]
sortPairReverse = ( a, b, lessOrEq )->
#"""return a1, b1 such that a1 >= b1"""
if lessOrEq(a,b)
[b, a]
else [a,b]
findOverlap = ( v1, w1, v2, w2 )->
#"""Find a sequence that is can be rewritten in 2 ways using given rules"""
# if v1=xy and v2=yz
[x, y, z] = overlap(v1, v2)
if y #if there is nonempty overlap
return [true, x+w2, w1+z]
[hasSplit, x, z] = splitBy(v1, v2)
if hasSplit# and x.length>0 and z.length>0
return [true, w1, x+w2+z]
return [false, null, null]
knuthBendixCompletion = (S, lessOrEqual)->
#"""S :: dict of rewrite rules: (original, rewrite)
#lessorequal :: (x, y) -> boolean
#"""
SS = S.copy()
#
for [v1, w1] in S.items()
for [v2, w2] in S.items()
# if v1=xy and v2=yz
#[x, y, z] = overlap(v1, v2)
[hasOverlap, s1, s2] = findOverlap(v1,w1, v2,w2)
if hasOverlap
t1 = S.rewrite s1
t2 = S.rewrite s2
if t1 isnt t2
#dprint ("Conflict found", v1, w1, v2, w2)
[t1, t2] = sortPairReverse(t1, t2, lessOrEqual)
#dprint(" add rule:", (t1,t2) )
SS.add(t1, t2)
return SS
simplifyRules = (S_, lessOrEqual)->
S = S_.copy()
Slist = S_.items() #used to iterate
while Slist.length > 0
[v,w] = vw = Slist.pop()
S.remove(v)
vv = S.rewrite vw[0]
ww = S.rewrite vw[1]
addBack = true
if vv is ww
#dprint("Redundant rewrite", v, w)
addBack = false
else
vw1 = sortPairReverse(vv,ww, lessOrEqual)
if vw1[0] isnt vw[0] and vw1[1] isnt vw[1]
#dprint ("Simplify rule:", vw, "->", vw1 )
S.add( vw1... )
Slist.push(vw1)
addBack = false
if addBack
S.add(v,w)
return S
exports.knuthBendix = (S0, lessOrEqual=shortLex, maxIters = 1000, maxRulesetSize = 1000, onIteration=null)->
#"""Main funciton of the Knuth-Bendix completion algorithm.
#arguments:
#S - original rewrite table
#lessOrEqual - comparator for strings. shortLex is the default one.
#maxIters - maximal number of iterations. If reached, exception is raised.
#maxRulesetSize - maximal number of ruleset. If reached, exception is raised.
#onIteration - callback, called each iteration of the method. It receives iteration number and current table.
#"""
S = S0.normalize(lessOrEqual)
for i in [0...maxIters]
if S.size() > maxRulesetSize
throw new Error("Ruleset grew too big")
SS = simplifyRules(S, lessOrEqual)
SSS = knuthBendixCompletion(SS, lessOrEqual)
if SSS.equals S
#Convergence achieved!
return SSS
if onIteration?
onIteration( i, S )
S = SSS
throw new Error("Iterations exceeded")
| 157553 | #Based on http://www.math.rwth-aachen.de/~<NAME>/Students/DiplomarbeitPfeiffer.pdf
#algorithm 3, 4
#import itertools
#values are encoded as simple strings.
# User is responsible
print = (s ... ) -> console.log( s.join(" ") )
#COnvert "less or equal" function to the JS-compatible comparator function
le2cmp = ( leFunc ) ->
(a,b) ->
if a is b
0
else if leFunc(a,b)
-1
else
1
exports.RewriteRuleset = class RewriteRuleset
constructor: (rules)->
@rules = rules
pprint: ()->
print ("{")
for [v, w] in @_sortedItems()
print " #{v} -> #{w}"
print "}"
copy: ()->
new RewriteRuleset(JSON.parse JSON.stringify @rules)
_sortedItems: ()->
items = @items()
items.sort le2cmp(shortLex)
return items
suffices: -> (k for k of @rules)
size: -> @suffices().length
items: -> ( [k, v] for k, v of @rules )
__equalOneSided: (other) ->
for k, v of @rules
if other.rules[k] isnt v
return false
return true
equals: ( other)-> this.__equalOneSided(other) and other.__equalOneSided(this)
#__hash__: ()-> return hash(@rules)
add: ( v, w)->
@rules[v] = w
remove: ( v)->
delete @rules[v]
normalize: ( lessOrEq )->
SS = {}
for v, w of @rules
[v, w] = sortPairReverse(v, w, lessOrEq)
#v is biggest now
if not SS[v]?
SS[v] = w
else
#resolve conflict by chosing the lowest of 2.
SS[v] = sortPairReverse(w, SS[v], lessOrEq)[1]
return new RewriteRuleset(SS)
__ruleLengths: ()->
lens = {}
for k of @rules
lens[k.length] = null
lenslist = (parseInt(k, 10) for k of lens)
lenslist.sort()
return lenslist
appendRewrite: ( s, xs_)->
#"""Append elements of the string xs_ to the string s, running all rewrite rules"""
rules = @rules
return s if xs_.length is 0
xs = xs_.split("")
xs.reverse()
lengths = @__ruleLengths()
while xs.length > 0
s = s + xs.pop()
for suffixLen in lengths
suffix = s.substring(s.length-suffixLen)
#console.log "suf: #{suffix}, len: #{suffixLen}"
rewriteAs = rules[suffix]
if rewriteAs?
#Rewrite found!
#console.log " Rewrite found: #{suffix}, #{rewriteAs}"
s = s.substring(0, s.length - suffixLen)
for i in [rewriteAs.length-1 .. 0] by -1
xs.push rewriteAs[i]
continue
return s
has: (key) -> @rules.hasOwnProperty key
rewrite: ( s )-> @appendRewrite( "", s )
exports.shortLex = shortLex = (s1, s2)->
#"""Shortlex less or equal comparator"""
if s1.length > s2.length
return false
if s1.length < s2.length
return true
return s1 <= s2
exports.overlap = overlap = (s1, s2)->
#"""Two strings: s1, s2.
#Reutnrs x,y,z such as:
#s1 = xy
#s2 = yz
#"""
if s2.length is 0
return [s1, "", s2]
[i1, i2] = [0, 0]
#i1, i2: indices in s1, s2
s2_0 = s2[0]
istart = Math.max( 0, s1.length - s2.length )
for i in [istart ... s1.length]
s1_i = s1[i]
if s1_i is s2_0
#console.log "Comparing #{s1.substring(i+1)} and #{s2.substring(1, s1.length-i)}"
if s1.substring(i+1) is s2.substring(1, s1.length-i)
return [s1.substring(0,i), s1.substring(i), s2.substring(s1.length-i)]
return [s1, "", s2]
exports.splitBy = splitBy = (s1, s2)->
#"""Split sequence s1 by sequence s2.
#Returns True and prefix + postfix, or just False and None None
#"""
if s2.length == 0
[true, s1, ""]
for i in [0...s1.length - s2.length+1]
if s1.substring(i, i+s2.length) is s2
return [true, s1.substring(0,i), s1.substring(i+s2.length)]
return [false, null, null]
sortPairReverse = ( a, b, lessOrEq )->
#"""return a1, b1 such that a1 >= b1"""
if lessOrEq(a,b)
[b, a]
else [a,b]
findOverlap = ( v1, w1, v2, w2 )->
#"""Find a sequence that is can be rewritten in 2 ways using given rules"""
# if v1=xy and v2=yz
[x, y, z] = overlap(v1, v2)
if y #if there is nonempty overlap
return [true, x+w2, w1+z]
[hasSplit, x, z] = splitBy(v1, v2)
if hasSplit# and x.length>0 and z.length>0
return [true, w1, x+w2+z]
return [false, null, null]
knuthBendixCompletion = (S, lessOrEqual)->
#"""S :: dict of rewrite rules: (original, rewrite)
#lessorequal :: (x, y) -> boolean
#"""
SS = S.copy()
#
for [v1, w1] in S.items()
for [v2, w2] in S.items()
# if v1=xy and v2=yz
#[x, y, z] = overlap(v1, v2)
[hasOverlap, s1, s2] = findOverlap(v1,w1, v2,w2)
if hasOverlap
t1 = S.rewrite s1
t2 = S.rewrite s2
if t1 isnt t2
#dprint ("Conflict found", v1, w1, v2, w2)
[t1, t2] = sortPairReverse(t1, t2, lessOrEqual)
#dprint(" add rule:", (t1,t2) )
SS.add(t1, t2)
return SS
simplifyRules = (S_, lessOrEqual)->
S = S_.copy()
Slist = S_.items() #used to iterate
while Slist.length > 0
[v,w] = vw = Slist.pop()
S.remove(v)
vv = S.rewrite vw[0]
ww = S.rewrite vw[1]
addBack = true
if vv is ww
#dprint("Redundant rewrite", v, w)
addBack = false
else
vw1 = sortPairReverse(vv,ww, lessOrEqual)
if vw1[0] isnt vw[0] and vw1[1] isnt vw[1]
#dprint ("Simplify rule:", vw, "->", vw1 )
S.add( vw1... )
Slist.push(vw1)
addBack = false
if addBack
S.add(v,w)
return S
exports.knuthBendix = (S0, lessOrEqual=shortLex, maxIters = 1000, maxRulesetSize = 1000, onIteration=null)->
#"""Main funciton of the Knuth-Bendix completion algorithm.
#arguments:
#S - original rewrite table
#lessOrEqual - comparator for strings. shortLex is the default one.
#maxIters - maximal number of iterations. If reached, exception is raised.
#maxRulesetSize - maximal number of ruleset. If reached, exception is raised.
#onIteration - callback, called each iteration of the method. It receives iteration number and current table.
#"""
S = S0.normalize(lessOrEqual)
for i in [0...maxIters]
if S.size() > maxRulesetSize
throw new Error("Ruleset grew too big")
SS = simplifyRules(S, lessOrEqual)
SSS = knuthBendixCompletion(SS, lessOrEqual)
if SSS.equals S
#Convergence achieved!
return SSS
if onIteration?
onIteration( i, S )
S = SSS
throw new Error("Iterations exceeded")
| true | #Based on http://www.math.rwth-aachen.de/~PI:NAME:<NAME>END_PI/Students/DiplomarbeitPfeiffer.pdf
#algorithm 3, 4
#import itertools
#values are encoded as simple strings.
# User is responsible
print = (s ... ) -> console.log( s.join(" ") )
#COnvert "less or equal" function to the JS-compatible comparator function
le2cmp = ( leFunc ) ->
(a,b) ->
if a is b
0
else if leFunc(a,b)
-1
else
1
exports.RewriteRuleset = class RewriteRuleset
constructor: (rules)->
@rules = rules
pprint: ()->
print ("{")
for [v, w] in @_sortedItems()
print " #{v} -> #{w}"
print "}"
copy: ()->
new RewriteRuleset(JSON.parse JSON.stringify @rules)
_sortedItems: ()->
items = @items()
items.sort le2cmp(shortLex)
return items
suffices: -> (k for k of @rules)
size: -> @suffices().length
items: -> ( [k, v] for k, v of @rules )
__equalOneSided: (other) ->
for k, v of @rules
if other.rules[k] isnt v
return false
return true
equals: ( other)-> this.__equalOneSided(other) and other.__equalOneSided(this)
#__hash__: ()-> return hash(@rules)
add: ( v, w)->
@rules[v] = w
remove: ( v)->
delete @rules[v]
normalize: ( lessOrEq )->
SS = {}
for v, w of @rules
[v, w] = sortPairReverse(v, w, lessOrEq)
#v is biggest now
if not SS[v]?
SS[v] = w
else
#resolve conflict by chosing the lowest of 2.
SS[v] = sortPairReverse(w, SS[v], lessOrEq)[1]
return new RewriteRuleset(SS)
__ruleLengths: ()->
lens = {}
for k of @rules
lens[k.length] = null
lenslist = (parseInt(k, 10) for k of lens)
lenslist.sort()
return lenslist
appendRewrite: ( s, xs_)->
#"""Append elements of the string xs_ to the string s, running all rewrite rules"""
rules = @rules
return s if xs_.length is 0
xs = xs_.split("")
xs.reverse()
lengths = @__ruleLengths()
while xs.length > 0
s = s + xs.pop()
for suffixLen in lengths
suffix = s.substring(s.length-suffixLen)
#console.log "suf: #{suffix}, len: #{suffixLen}"
rewriteAs = rules[suffix]
if rewriteAs?
#Rewrite found!
#console.log " Rewrite found: #{suffix}, #{rewriteAs}"
s = s.substring(0, s.length - suffixLen)
for i in [rewriteAs.length-1 .. 0] by -1
xs.push rewriteAs[i]
continue
return s
has: (key) -> @rules.hasOwnProperty key
rewrite: ( s )-> @appendRewrite( "", s )
exports.shortLex = shortLex = (s1, s2)->
#"""Shortlex less or equal comparator"""
if s1.length > s2.length
return false
if s1.length < s2.length
return true
return s1 <= s2
exports.overlap = overlap = (s1, s2)->
#"""Two strings: s1, s2.
#Reutnrs x,y,z such as:
#s1 = xy
#s2 = yz
#"""
if s2.length is 0
return [s1, "", s2]
[i1, i2] = [0, 0]
#i1, i2: indices in s1, s2
s2_0 = s2[0]
istart = Math.max( 0, s1.length - s2.length )
for i in [istart ... s1.length]
s1_i = s1[i]
if s1_i is s2_0
#console.log "Comparing #{s1.substring(i+1)} and #{s2.substring(1, s1.length-i)}"
if s1.substring(i+1) is s2.substring(1, s1.length-i)
return [s1.substring(0,i), s1.substring(i), s2.substring(s1.length-i)]
return [s1, "", s2]
exports.splitBy = splitBy = (s1, s2)->
#"""Split sequence s1 by sequence s2.
#Returns True and prefix + postfix, or just False and None None
#"""
if s2.length == 0
[true, s1, ""]
for i in [0...s1.length - s2.length+1]
if s1.substring(i, i+s2.length) is s2
return [true, s1.substring(0,i), s1.substring(i+s2.length)]
return [false, null, null]
sortPairReverse = ( a, b, lessOrEq )->
#"""return a1, b1 such that a1 >= b1"""
if lessOrEq(a,b)
[b, a]
else [a,b]
findOverlap = ( v1, w1, v2, w2 )->
#"""Find a sequence that is can be rewritten in 2 ways using given rules"""
# if v1=xy and v2=yz
[x, y, z] = overlap(v1, v2)
if y #if there is nonempty overlap
return [true, x+w2, w1+z]
[hasSplit, x, z] = splitBy(v1, v2)
if hasSplit# and x.length>0 and z.length>0
return [true, w1, x+w2+z]
return [false, null, null]
knuthBendixCompletion = (S, lessOrEqual)->
#"""S :: dict of rewrite rules: (original, rewrite)
#lessorequal :: (x, y) -> boolean
#"""
SS = S.copy()
#
for [v1, w1] in S.items()
for [v2, w2] in S.items()
# if v1=xy and v2=yz
#[x, y, z] = overlap(v1, v2)
[hasOverlap, s1, s2] = findOverlap(v1,w1, v2,w2)
if hasOverlap
t1 = S.rewrite s1
t2 = S.rewrite s2
if t1 isnt t2
#dprint ("Conflict found", v1, w1, v2, w2)
[t1, t2] = sortPairReverse(t1, t2, lessOrEqual)
#dprint(" add rule:", (t1,t2) )
SS.add(t1, t2)
return SS
simplifyRules = (S_, lessOrEqual)->
S = S_.copy()
Slist = S_.items() #used to iterate
while Slist.length > 0
[v,w] = vw = Slist.pop()
S.remove(v)
vv = S.rewrite vw[0]
ww = S.rewrite vw[1]
addBack = true
if vv is ww
#dprint("Redundant rewrite", v, w)
addBack = false
else
vw1 = sortPairReverse(vv,ww, lessOrEqual)
if vw1[0] isnt vw[0] and vw1[1] isnt vw[1]
#dprint ("Simplify rule:", vw, "->", vw1 )
S.add( vw1... )
Slist.push(vw1)
addBack = false
if addBack
S.add(v,w)
return S
exports.knuthBendix = (S0, lessOrEqual=shortLex, maxIters = 1000, maxRulesetSize = 1000, onIteration=null)->
#"""Main funciton of the Knuth-Bendix completion algorithm.
#arguments:
#S - original rewrite table
#lessOrEqual - comparator for strings. shortLex is the default one.
#maxIters - maximal number of iterations. If reached, exception is raised.
#maxRulesetSize - maximal number of ruleset. If reached, exception is raised.
#onIteration - callback, called each iteration of the method. It receives iteration number and current table.
#"""
S = S0.normalize(lessOrEqual)
for i in [0...maxIters]
if S.size() > maxRulesetSize
throw new Error("Ruleset grew too big")
SS = simplifyRules(S, lessOrEqual)
SSS = knuthBendixCompletion(SS, lessOrEqual)
if SSS.equals S
#Convergence achieved!
return SSS
if onIteration?
onIteration( i, S )
S = SSS
throw new Error("Iterations exceeded")
|
[
{
"context": ".inDir DEST\n .withOptions\n realname: 'Alex Gorbatchev'\n githubUrl: 'https://github.com/alexgorba",
"end": 427,
"score": 0.9998837113380432,
"start": 412,
"tag": "NAME",
"value": "Alex Gorbatchev"
},
{
"context": "orbatchev'\n githubUrl: 'https://github.com/alexgorbatchev'\n .withPrompts\n githubUser: 'alexgorb",
"end": 482,
"score": 0.9988940954208374,
"start": 468,
"tag": "USERNAME",
"value": "alexgorbatchev"
},
{
"context": "rbatchev'\n .withPrompts\n githubUser: 'alexgorbatchev'\n generatorName: GENERATOR_NAME\n .on ",
"end": 538,
"score": 0.9995278120040894,
"start": 524,
"tag": "USERNAME",
"value": "alexgorbatchev"
}
] | test/app.spec.coffee | octoblu/generator-octoblu-sentinel | 0 | {before, describe, it} = global
{expect} = require 'chai'
path = require 'path'
helpers = require('yeoman-test')
assert = require('yeoman-assert')
GENERATOR_NAME = 'app'
DEST = path.join __dirname, '..', 'temp', "sentinel-#{GENERATOR_NAME}"
describe 'app', ->
before (done) ->
@timeout 2000
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: 'Alex Gorbatchev'
githubUrl: 'https://github.com/alexgorbatchev'
.withPrompts
githubUser: 'alexgorbatchev'
generatorName: GENERATOR_NAME
.on 'end', done
it 'creates expected files', ->
assert.file '''
.gitignore
.travis.yml
LICENSE
README.md
package.json
'''.split /\s+/g
| 9871 | {before, describe, it} = global
{expect} = require 'chai'
path = require 'path'
helpers = require('yeoman-test')
assert = require('yeoman-assert')
GENERATOR_NAME = 'app'
DEST = path.join __dirname, '..', 'temp', "sentinel-#{GENERATOR_NAME}"
describe 'app', ->
before (done) ->
@timeout 2000
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: '<NAME>'
githubUrl: 'https://github.com/alexgorbatchev'
.withPrompts
githubUser: 'alexgorbatchev'
generatorName: GENERATOR_NAME
.on 'end', done
it 'creates expected files', ->
assert.file '''
.gitignore
.travis.yml
LICENSE
README.md
package.json
'''.split /\s+/g
| true | {before, describe, it} = global
{expect} = require 'chai'
path = require 'path'
helpers = require('yeoman-test')
assert = require('yeoman-assert')
GENERATOR_NAME = 'app'
DEST = path.join __dirname, '..', 'temp', "sentinel-#{GENERATOR_NAME}"
describe 'app', ->
before (done) ->
@timeout 2000
helpers
.run path.join __dirname, '..', 'app'
.inDir DEST
.withOptions
realname: 'PI:NAME:<NAME>END_PI'
githubUrl: 'https://github.com/alexgorbatchev'
.withPrompts
githubUser: 'alexgorbatchev'
generatorName: GENERATOR_NAME
.on 'end', done
it 'creates expected files', ->
assert.file '''
.gitignore
.travis.yml
LICENSE
README.md
package.json
'''.split /\s+/g
|
[
{
"context": "scopeName: 'source.julia.console'\nname: 'Julia Console'\ncomment: \"Not sure what this will be used for...",
"end": 54,
"score": 0.9099414348602295,
"start": 41,
"tag": "NAME",
"value": "Julia Console"
}
] | grammars/julia-console.cson | alyst/atom-language-julia | 35 | scopeName: 'source.julia.console'
name: 'Julia Console'
comment: "Not sure what this will be used for... Maybe if we have a REPL someday"
patterns: [
{
match: '^(julia>|\\.{3}|In \\[\\d+\\]:) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.julia.console'
'2':
patterns: [
include: 'source.julia'
]
}
{
match: '^(shell>) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.shell.julia.console'
'2':
patterns: [
include: 'source.shell'
]
}
{
match: '^(help\\?>) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.help.julia.console'
'2':
patterns: [
include: 'source.julia'
]
}
]
| 45394 | scopeName: 'source.julia.console'
name: '<NAME>'
comment: "Not sure what this will be used for... Maybe if we have a REPL someday"
patterns: [
{
match: '^(julia>|\\.{3}|In \\[\\d+\\]:) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.julia.console'
'2':
patterns: [
include: 'source.julia'
]
}
{
match: '^(shell>) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.shell.julia.console'
'2':
patterns: [
include: 'source.shell'
]
}
{
match: '^(help\\?>) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.help.julia.console'
'2':
patterns: [
include: 'source.julia'
]
}
]
| true | scopeName: 'source.julia.console'
name: 'PI:NAME:<NAME>END_PI'
comment: "Not sure what this will be used for... Maybe if we have a REPL someday"
patterns: [
{
match: '^(julia>|\\.{3}|In \\[\\d+\\]:) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.julia.console'
'2':
patterns: [
include: 'source.julia'
]
}
{
match: '^(shell>) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.shell.julia.console'
'2':
patterns: [
include: 'source.shell'
]
}
{
match: '^(help\\?>) (.+)$'
captures:
'1':
name: 'punctuation.separator.prompt.help.julia.console'
'2':
patterns: [
include: 'source.julia'
]
}
]
|
[
{
"context": " players = [player1Id, player2Id].sort()\n key = \"#{players[0]}:#{players[1]}\"\n @recentlyMatched[key]?\n\n addRecentMatch: (pl",
"end": 1530,
"score": 0.9982498288154602,
"start": 1501,
"tag": "KEY",
"value": "\"#{players[0]}:#{players[1]}\""
},
{
"context": " players = [player1Id, player2Id].sort()\n key = \"#{players[0]}:#{players[1]}\"\n @recentlyMatched[key] = true\n setTimeout((",
"end": 1686,
"score": 0.9961855411529541,
"start": 1657,
"tag": "KEY",
"value": "\"#{players[0]}:#{players[1]}\""
}
] | server/queue.coffee | sarenji/pokebattle-sim | 5 | ratings = require('./ratings')
alts = require('./alts')
INITIAL_RANGE = 100
RANGE_INCREMENT = 100
class QueuedPlayer
constructor: (player) ->
@player = player
@range = INITIAL_RANGE
@rating = null # needs to be updated by getRatings
intersectsWith: (other) ->
leftMin = @rating - (@range / 2)
leftMax = @rating + (@range / 2)
rightMin = other.rating - (other.range / 2)
rightMax = other.rating + (other.range / 2)
return false if leftMin > rightMax
return false if leftMax < rightMin
true
# A queue of users waiting for a battle
class @BattleQueue
constructor: ->
@queue = {}
@newPlayers = []
@recentlyMatched = {}
@length = 0
# Adds a player to the queue.
# "name" can either be the real name, or an alt
add: (playerId, name, team, ratingKey=playerId) ->
return false if !playerId
return false if playerId of @queue
playerObject = {id: playerId, name, team, ratingKey}
player = new QueuedPlayer(playerObject)
@queue[playerId] = player
@newPlayers.push(player)
@length += 1
return true
remove: (playerIds) ->
playerIds = Array(playerIds) if playerIds not instanceof Array
for playerId in playerIds
if playerId of @queue
delete @queue[playerId]
@length -= 1
queuedPlayers: ->
Object.keys(@queue)
hasUserId: (playerId) ->
@queue[playerId]?
hasRecentlyMatched: (player1Id, player2Id) ->
players = [player1Id, player2Id].sort()
key = "#{players[0]}:#{players[1]}"
@recentlyMatched[key]?
addRecentMatch: (player1Id, player2Id) ->
players = [player1Id, player2Id].sort()
key = "#{players[0]}:#{players[1]}"
@recentlyMatched[key] = true
setTimeout((=> delete @recentlyMatched[key]), 30 * 60 * 1000) # expire in 30 minutes
size: ->
@length
# An internal function which loads ratings for newly queued players
# and removes them from the newly queued list
updateNewPlayers: (next) ->
ratingKeys = (queued.player.ratingKey for queued in @newPlayers)
return next(null) if ratingKeys.length == 0
ratings.getRatings ratingKeys, (err, returnedRatings) =>
if err then return next(err)
ratings.setActive ratingKeys, (err) =>
if err then return next(err)
# Update the ratings in the player objects
for rating, i in returnedRatings
continue unless @hasUserId(@newPlayers[i].player.id)
@newPlayers[i].rating = rating
# reset the new players list, we're done
@newPlayers.splice(0, @newPlayers.length)
next(null)
# Returns an array of pairs. Each pair is a queue object that contains
# a player and team key, corresponding to the player socket and player's team.
pairPlayers: (next) ->
return next(null, []) if @size() == 0
@updateNewPlayers (err) =>
if err then return next(err, null)
sortedPlayers = (queued for id, queued of @queue)
sortedPlayers.sort((a, b) -> a.rating - b.rating)
alreadyMatched = (false for [0...sortedPlayers.length])
pairs = []
for leftIdx in [0...sortedPlayers.length]
continue if alreadyMatched[leftIdx]
for rightIdx in [(leftIdx + 1)...sortedPlayers.length]
continue if alreadyMatched[rightIdx]
left = sortedPlayers[leftIdx]
right = sortedPlayers[rightIdx]
leftPlayer = left.player
rightPlayer = right.player
# Continue if these two players already played
continue if @hasRecentlyMatched(leftPlayer.id, rightPlayer.id)
# If the rating difference is too large break out, we have no possible match for left
break unless left.intersectsWith(right)
# Everything checks out, so make the pair and break out
pairs.push([leftPlayer, rightPlayer])
@remove([leftPlayer.id, rightPlayer.id])
@addRecentMatch(leftPlayer.id, rightPlayer.id)
alreadyMatched[leftIdx] = alreadyMatched[rightIdx] = true
break
# Expand the range of all unmatched players
queued.range += RANGE_INCREMENT for id, queued of @queue
# Return the list of paired players
next(null, pairs)
| 151865 | ratings = require('./ratings')
alts = require('./alts')
INITIAL_RANGE = 100
RANGE_INCREMENT = 100
class QueuedPlayer
constructor: (player) ->
@player = player
@range = INITIAL_RANGE
@rating = null # needs to be updated by getRatings
intersectsWith: (other) ->
leftMin = @rating - (@range / 2)
leftMax = @rating + (@range / 2)
rightMin = other.rating - (other.range / 2)
rightMax = other.rating + (other.range / 2)
return false if leftMin > rightMax
return false if leftMax < rightMin
true
# A queue of users waiting for a battle
class @BattleQueue
constructor: ->
@queue = {}
@newPlayers = []
@recentlyMatched = {}
@length = 0
# Adds a player to the queue.
# "name" can either be the real name, or an alt
add: (playerId, name, team, ratingKey=playerId) ->
return false if !playerId
return false if playerId of @queue
playerObject = {id: playerId, name, team, ratingKey}
player = new QueuedPlayer(playerObject)
@queue[playerId] = player
@newPlayers.push(player)
@length += 1
return true
remove: (playerIds) ->
playerIds = Array(playerIds) if playerIds not instanceof Array
for playerId in playerIds
if playerId of @queue
delete @queue[playerId]
@length -= 1
queuedPlayers: ->
Object.keys(@queue)
hasUserId: (playerId) ->
@queue[playerId]?
hasRecentlyMatched: (player1Id, player2Id) ->
players = [player1Id, player2Id].sort()
key = <KEY>
@recentlyMatched[key]?
addRecentMatch: (player1Id, player2Id) ->
players = [player1Id, player2Id].sort()
key = <KEY>
@recentlyMatched[key] = true
setTimeout((=> delete @recentlyMatched[key]), 30 * 60 * 1000) # expire in 30 minutes
size: ->
@length
# An internal function which loads ratings for newly queued players
# and removes them from the newly queued list
updateNewPlayers: (next) ->
ratingKeys = (queued.player.ratingKey for queued in @newPlayers)
return next(null) if ratingKeys.length == 0
ratings.getRatings ratingKeys, (err, returnedRatings) =>
if err then return next(err)
ratings.setActive ratingKeys, (err) =>
if err then return next(err)
# Update the ratings in the player objects
for rating, i in returnedRatings
continue unless @hasUserId(@newPlayers[i].player.id)
@newPlayers[i].rating = rating
# reset the new players list, we're done
@newPlayers.splice(0, @newPlayers.length)
next(null)
# Returns an array of pairs. Each pair is a queue object that contains
# a player and team key, corresponding to the player socket and player's team.
pairPlayers: (next) ->
return next(null, []) if @size() == 0
@updateNewPlayers (err) =>
if err then return next(err, null)
sortedPlayers = (queued for id, queued of @queue)
sortedPlayers.sort((a, b) -> a.rating - b.rating)
alreadyMatched = (false for [0...sortedPlayers.length])
pairs = []
for leftIdx in [0...sortedPlayers.length]
continue if alreadyMatched[leftIdx]
for rightIdx in [(leftIdx + 1)...sortedPlayers.length]
continue if alreadyMatched[rightIdx]
left = sortedPlayers[leftIdx]
right = sortedPlayers[rightIdx]
leftPlayer = left.player
rightPlayer = right.player
# Continue if these two players already played
continue if @hasRecentlyMatched(leftPlayer.id, rightPlayer.id)
# If the rating difference is too large break out, we have no possible match for left
break unless left.intersectsWith(right)
# Everything checks out, so make the pair and break out
pairs.push([leftPlayer, rightPlayer])
@remove([leftPlayer.id, rightPlayer.id])
@addRecentMatch(leftPlayer.id, rightPlayer.id)
alreadyMatched[leftIdx] = alreadyMatched[rightIdx] = true
break
# Expand the range of all unmatched players
queued.range += RANGE_INCREMENT for id, queued of @queue
# Return the list of paired players
next(null, pairs)
| true | ratings = require('./ratings')
alts = require('./alts')
INITIAL_RANGE = 100
RANGE_INCREMENT = 100
class QueuedPlayer
constructor: (player) ->
@player = player
@range = INITIAL_RANGE
@rating = null # needs to be updated by getRatings
intersectsWith: (other) ->
leftMin = @rating - (@range / 2)
leftMax = @rating + (@range / 2)
rightMin = other.rating - (other.range / 2)
rightMax = other.rating + (other.range / 2)
return false if leftMin > rightMax
return false if leftMax < rightMin
true
# A queue of users waiting for a battle
class @BattleQueue
constructor: ->
@queue = {}
@newPlayers = []
@recentlyMatched = {}
@length = 0
# Adds a player to the queue.
# "name" can either be the real name, or an alt
add: (playerId, name, team, ratingKey=playerId) ->
return false if !playerId
return false if playerId of @queue
playerObject = {id: playerId, name, team, ratingKey}
player = new QueuedPlayer(playerObject)
@queue[playerId] = player
@newPlayers.push(player)
@length += 1
return true
remove: (playerIds) ->
playerIds = Array(playerIds) if playerIds not instanceof Array
for playerId in playerIds
if playerId of @queue
delete @queue[playerId]
@length -= 1
queuedPlayers: ->
Object.keys(@queue)
hasUserId: (playerId) ->
@queue[playerId]?
hasRecentlyMatched: (player1Id, player2Id) ->
players = [player1Id, player2Id].sort()
key = PI:KEY:<KEY>END_PI
@recentlyMatched[key]?
addRecentMatch: (player1Id, player2Id) ->
players = [player1Id, player2Id].sort()
key = PI:KEY:<KEY>END_PI
@recentlyMatched[key] = true
setTimeout((=> delete @recentlyMatched[key]), 30 * 60 * 1000) # expire in 30 minutes
size: ->
@length
# An internal function which loads ratings for newly queued players
# and removes them from the newly queued list
updateNewPlayers: (next) ->
ratingKeys = (queued.player.ratingKey for queued in @newPlayers)
return next(null) if ratingKeys.length == 0
ratings.getRatings ratingKeys, (err, returnedRatings) =>
if err then return next(err)
ratings.setActive ratingKeys, (err) =>
if err then return next(err)
# Update the ratings in the player objects
for rating, i in returnedRatings
continue unless @hasUserId(@newPlayers[i].player.id)
@newPlayers[i].rating = rating
# reset the new players list, we're done
@newPlayers.splice(0, @newPlayers.length)
next(null)
# Returns an array of pairs. Each pair is a queue object that contains
# a player and team key, corresponding to the player socket and player's team.
pairPlayers: (next) ->
return next(null, []) if @size() == 0
@updateNewPlayers (err) =>
if err then return next(err, null)
sortedPlayers = (queued for id, queued of @queue)
sortedPlayers.sort((a, b) -> a.rating - b.rating)
alreadyMatched = (false for [0...sortedPlayers.length])
pairs = []
for leftIdx in [0...sortedPlayers.length]
continue if alreadyMatched[leftIdx]
for rightIdx in [(leftIdx + 1)...sortedPlayers.length]
continue if alreadyMatched[rightIdx]
left = sortedPlayers[leftIdx]
right = sortedPlayers[rightIdx]
leftPlayer = left.player
rightPlayer = right.player
# Continue if these two players already played
continue if @hasRecentlyMatched(leftPlayer.id, rightPlayer.id)
# If the rating difference is too large break out, we have no possible match for left
break unless left.intersectsWith(right)
# Everything checks out, so make the pair and break out
pairs.push([leftPlayer, rightPlayer])
@remove([leftPlayer.id, rightPlayer.id])
@addRecentMatch(leftPlayer.id, rightPlayer.id)
alreadyMatched[leftIdx] = alreadyMatched[rightIdx] = true
break
# Expand the range of all unmatched players
queued.range += RANGE_INCREMENT for id, queued of @queue
# Return the list of paired players
next(null, pairs)
|
[
{
"context": "set()\n \n @client._onIdentify({public_key: \"toto\"})\n expect(@client.emit).toHaveBeenCalledWith(",
"end": 3152,
"score": 0.963523268699646,
"start": 3149,
"tag": "KEY",
"value": "oto"
}
] | app/spec/m2fa/client_spec.coffee | romanornr/ledger-wallet-crw | 173 | describe "m2fa.Client", ->
beforeEach ->
spyOn(window, 'WebSocket')
@pairingId = "aPairingId"
@client = new ledger.m2fa.Client(@pairingId)
@client.ws = @ws = jasmine.createSpyObj('ws', ['send', 'close'])
[@ws.onopen, @ws.onmessage, @ws.onclose] = [ws.onopen, ws.onmessage, ws.onclose]
spyOn(@client, "_send").and.callThrough()
@ws.readyState = WebSocket.OPEN
afterEach ->
@client.stop()
it "connect to 2fa on creation and set event callbacks", ->
expect(window.WebSocket).toHaveBeenCalledWith(ledger.config.m2fa.baseUrl)
expect(@ws.onopen).toBeDefined()
expect(@ws.onmessage).toBeDefined()
expect(@ws.onclose).toBeDefined()
it "send challenge send good stringified message", ->
challenge = "XxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx"
@client.sendChallenge(challenge)
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:"challenge","data":challenge))
it "confirm pairing send good stringified message", ->
@client.confirmPairing()
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'pairing', is_successful:true))
it "reject pairing send good stringified message", ->
@client.rejectPairing()
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'pairing', is_successful:false))
it "request validation send good stringified message", ->
data = "11XxXxXxXxXxXx88XxXxXxXxXxXxXxFF"
@client.requestValidation(data)
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'request', second_factor_data:data))
it "leave room send message and close connection", ->
@client._leaveRoom()
expect(@ws.send).toHaveBeenCalledWith(JSON.stringify(type:'leave'))
expect(@ws.close).toHaveBeenCalled()
it "join correct room on connection", ->
@client._onOpen()
expect(@ws.send).toHaveBeenCalledWith(JSON.stringify(type:'join', room: @pairingId))
it "parse message and call correct handler on message", ->
message = {data: '{"type":"challenge","data":"0x1x2x3x"}'}
spyOn(@client, '_onChallenge')
@client._onMessage(message)
expect(@client._onChallenge).toHaveBeenCalledWith({"type":"challenge","data":"0x1x2x3x"})
spyOn(@client, '_onConnect')
message = {data: '{"type":"connect"}'}
@client._onMessage(message)
expect(@client._onConnect).toHaveBeenCalled()
it "rejoin correct room on connection closed", ->
spyOn(@client, '_joinRoom')
@client._onClose()
expect(@client._joinRoom).toHaveBeenCalled()
it "emit event on most messages", ->
spyOn(@client, 'emit')
@client._onConnect({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.connect')
@client.emit.calls.reset()
@client._onDisconnect({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.disconnect')
@client.emit.calls.reset()
@client._onAccept({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.accept')
@client.emit.calls.reset()
@client._onResponse({pin: "01020304", is_accepted: true})
expect(@client.emit).toHaveBeenCalledWith('m2fa.response', "01020304")
@client.emit.calls.reset()
@client._onIdentify({public_key: "toto"})
expect(@client.emit).toHaveBeenCalledWith('m2fa.identify', "toto")
@client.emit.calls.reset()
@client._onChallenge({"data":"data"})
expect(@client.emit).toHaveBeenCalledWith('m2fa.challenge', "data")
@client.emit.calls.reset()
it "resend last request on repeat", ->
@client._lastRequest = '{"type":"challenge","data":"0x1x2x3x"}'
@client._onRepeat()
expect(@ws.send).toHaveBeenCalledWith('{"type":"challenge","data":"0x1x2x3x"}')
| 216790 | describe "m2fa.Client", ->
beforeEach ->
spyOn(window, 'WebSocket')
@pairingId = "aPairingId"
@client = new ledger.m2fa.Client(@pairingId)
@client.ws = @ws = jasmine.createSpyObj('ws', ['send', 'close'])
[@ws.onopen, @ws.onmessage, @ws.onclose] = [ws.onopen, ws.onmessage, ws.onclose]
spyOn(@client, "_send").and.callThrough()
@ws.readyState = WebSocket.OPEN
afterEach ->
@client.stop()
it "connect to 2fa on creation and set event callbacks", ->
expect(window.WebSocket).toHaveBeenCalledWith(ledger.config.m2fa.baseUrl)
expect(@ws.onopen).toBeDefined()
expect(@ws.onmessage).toBeDefined()
expect(@ws.onclose).toBeDefined()
it "send challenge send good stringified message", ->
challenge = "XxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx"
@client.sendChallenge(challenge)
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:"challenge","data":challenge))
it "confirm pairing send good stringified message", ->
@client.confirmPairing()
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'pairing', is_successful:true))
it "reject pairing send good stringified message", ->
@client.rejectPairing()
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'pairing', is_successful:false))
it "request validation send good stringified message", ->
data = "11XxXxXxXxXxXx88XxXxXxXxXxXxXxFF"
@client.requestValidation(data)
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'request', second_factor_data:data))
it "leave room send message and close connection", ->
@client._leaveRoom()
expect(@ws.send).toHaveBeenCalledWith(JSON.stringify(type:'leave'))
expect(@ws.close).toHaveBeenCalled()
it "join correct room on connection", ->
@client._onOpen()
expect(@ws.send).toHaveBeenCalledWith(JSON.stringify(type:'join', room: @pairingId))
it "parse message and call correct handler on message", ->
message = {data: '{"type":"challenge","data":"0x1x2x3x"}'}
spyOn(@client, '_onChallenge')
@client._onMessage(message)
expect(@client._onChallenge).toHaveBeenCalledWith({"type":"challenge","data":"0x1x2x3x"})
spyOn(@client, '_onConnect')
message = {data: '{"type":"connect"}'}
@client._onMessage(message)
expect(@client._onConnect).toHaveBeenCalled()
it "rejoin correct room on connection closed", ->
spyOn(@client, '_joinRoom')
@client._onClose()
expect(@client._joinRoom).toHaveBeenCalled()
it "emit event on most messages", ->
spyOn(@client, 'emit')
@client._onConnect({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.connect')
@client.emit.calls.reset()
@client._onDisconnect({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.disconnect')
@client.emit.calls.reset()
@client._onAccept({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.accept')
@client.emit.calls.reset()
@client._onResponse({pin: "01020304", is_accepted: true})
expect(@client.emit).toHaveBeenCalledWith('m2fa.response', "01020304")
@client.emit.calls.reset()
@client._onIdentify({public_key: "t<KEY>"})
expect(@client.emit).toHaveBeenCalledWith('m2fa.identify', "toto")
@client.emit.calls.reset()
@client._onChallenge({"data":"data"})
expect(@client.emit).toHaveBeenCalledWith('m2fa.challenge', "data")
@client.emit.calls.reset()
it "resend last request on repeat", ->
@client._lastRequest = '{"type":"challenge","data":"0x1x2x3x"}'
@client._onRepeat()
expect(@ws.send).toHaveBeenCalledWith('{"type":"challenge","data":"0x1x2x3x"}')
| true | describe "m2fa.Client", ->
beforeEach ->
spyOn(window, 'WebSocket')
@pairingId = "aPairingId"
@client = new ledger.m2fa.Client(@pairingId)
@client.ws = @ws = jasmine.createSpyObj('ws', ['send', 'close'])
[@ws.onopen, @ws.onmessage, @ws.onclose] = [ws.onopen, ws.onmessage, ws.onclose]
spyOn(@client, "_send").and.callThrough()
@ws.readyState = WebSocket.OPEN
afterEach ->
@client.stop()
it "connect to 2fa on creation and set event callbacks", ->
expect(window.WebSocket).toHaveBeenCalledWith(ledger.config.m2fa.baseUrl)
expect(@ws.onopen).toBeDefined()
expect(@ws.onmessage).toBeDefined()
expect(@ws.onclose).toBeDefined()
it "send challenge send good stringified message", ->
challenge = "XxXxXxXxXxXxXxXxXxXxXxXxXxXxXxXx"
@client.sendChallenge(challenge)
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:"challenge","data":challenge))
it "confirm pairing send good stringified message", ->
@client.confirmPairing()
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'pairing', is_successful:true))
it "reject pairing send good stringified message", ->
@client.rejectPairing()
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'pairing', is_successful:false))
it "request validation send good stringified message", ->
data = "11XxXxXxXxXxXx88XxXxXxXxXxXxXxFF"
@client.requestValidation(data)
expect(@client._send).toHaveBeenCalledWith(JSON.stringify(type:'request', second_factor_data:data))
it "leave room send message and close connection", ->
@client._leaveRoom()
expect(@ws.send).toHaveBeenCalledWith(JSON.stringify(type:'leave'))
expect(@ws.close).toHaveBeenCalled()
it "join correct room on connection", ->
@client._onOpen()
expect(@ws.send).toHaveBeenCalledWith(JSON.stringify(type:'join', room: @pairingId))
it "parse message and call correct handler on message", ->
message = {data: '{"type":"challenge","data":"0x1x2x3x"}'}
spyOn(@client, '_onChallenge')
@client._onMessage(message)
expect(@client._onChallenge).toHaveBeenCalledWith({"type":"challenge","data":"0x1x2x3x"})
spyOn(@client, '_onConnect')
message = {data: '{"type":"connect"}'}
@client._onMessage(message)
expect(@client._onConnect).toHaveBeenCalled()
it "rejoin correct room on connection closed", ->
spyOn(@client, '_joinRoom')
@client._onClose()
expect(@client._joinRoom).toHaveBeenCalled()
it "emit event on most messages", ->
spyOn(@client, 'emit')
@client._onConnect({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.connect')
@client.emit.calls.reset()
@client._onDisconnect({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.disconnect')
@client.emit.calls.reset()
@client._onAccept({})
expect(@client.emit).toHaveBeenCalledWith('m2fa.accept')
@client.emit.calls.reset()
@client._onResponse({pin: "01020304", is_accepted: true})
expect(@client.emit).toHaveBeenCalledWith('m2fa.response', "01020304")
@client.emit.calls.reset()
@client._onIdentify({public_key: "tPI:KEY:<KEY>END_PI"})
expect(@client.emit).toHaveBeenCalledWith('m2fa.identify', "toto")
@client.emit.calls.reset()
@client._onChallenge({"data":"data"})
expect(@client.emit).toHaveBeenCalledWith('m2fa.challenge', "data")
@client.emit.calls.reset()
it "resend last request on repeat", ->
@client._lastRequest = '{"type":"challenge","data":"0x1x2x3x"}'
@client._onRepeat()
expect(@ws.send).toHaveBeenCalledWith('{"type":"challenge","data":"0x1x2x3x"}')
|
[
{
"context": " fields: [\n {\n name: 'lastName'\n type: 'string'\n toolt",
"end": 941,
"score": 0.9987501502037048,
"start": 933,
"tag": "NAME",
"value": "lastName"
},
{
"context": " tooltip: 'Фамилия клиента'\n label: 'Фамилия'\n label_css: ''\n css_cl",
"end": 1042,
"score": 0.9987239837646484,
"start": 1035,
"tag": "NAME",
"value": "Фамилия"
},
{
"context": " },\n {\n name: 'firstName'\n type: 'string'\n toolt",
"end": 1215,
"score": 0.9977298378944397,
"start": 1206,
"tag": "NAME",
"value": "firstName"
},
{
"context": " tooltip: 'Имя клиента'\n label: 'Имя'\n label_css: ''\n css_cl",
"end": 1308,
"score": 0.9913292527198792,
"start": 1305,
"tag": "NAME",
"value": "Имя"
},
{
"context": " },\n {\n name: 'parentName'\n type: 'string'\n t",
"end": 1448,
"score": 0.8866721987724304,
"start": 1442,
"tag": "NAME",
"value": "parent"
},
{
"context": "s_class: 'btn btn-primary'},\n { name: 'Азимут', value: 'Азимут', css_class: '",
"end": 7062,
"score": 0.8747305870056152,
"start": 7056,
"tag": "NAME",
"value": "Азимут"
},
{
"context": "},\n { name: 'Азимут', value: 'Азимут', css_class: 'btn btn-warning'},\n ",
"end": 7088,
"score": 0.707515299320221,
"start": 7082,
"tag": "NAME",
"value": "Азимут"
}
] | hbw/app/assets/javascripts/hbw/test_form.js.coffee | napramirez/homs | 0 | modulejs.define 'HBWTestForm', [], ()->
class TestForm
@with_all_controls = {
name: 'Тестовая форма',
description: ['Это форма для тестирования рендеринга всех видов контролов', 'Пожалуйста, дочитайте это многострочное пояснение до конца', 'Возможно, это поможет вам сделать меньше ошибок' ],
css_class: 'col-xs-12 col-sm-6 col-md-5 col-lg-4',
fields: [
{
name: 'note1'
type: 'note'
html: '<H1>Внимание!</H1>Это форма для тестирования рендеринга всех видов контролов<br/>Пожалуйста, дочитайте это многострочное пояснение до конца<br/>Возможно, это поможет вам сделать меньше ошибок'
css_class: 'col-xs-12'
},
{
name: 'group1'
type: 'group' # Тип поля формы
label: 'Общие данные'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: 'lastName'
type: 'string'
tooltip: 'Фамилия клиента'
label: 'Фамилия'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
editable: false
},
{
name: 'firstName'
type: 'string'
tooltip: 'Имя клиента'
label: 'Имя'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
},
{
name: 'parentName'
type: 'string'
tooltip: 'Отчество клиента'
label: 'Отчество'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
},
{
name: 'phone'
type: 'string'
tooltip: 'Контактный телефон клиента'
label: 'Телефон'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
pattern: '+7 ({{999}}) {{999}}-{{99}}-{{99}}'
},
{
name: 'buildingAddress'
type: 'string'
tooltip: 'Адрес дома'
label: 'Адрес дома'
label_css: ''
css_class: 'col-xs-6 col-sm-6 col-md-5'
},
{
name: 'flatNo'
type: 'string'
tooltip: 'Номер квартиры'
label: 'Кв.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'wingNo'
type: 'string'
tooltip: 'Номер подъезда'
label: 'под.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'floorNo'
type: 'string'
tooltip: 'Номер этажа'
label: 'эт.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'comment'
type: 'text'
rows: 3
tooltip: 'Комментарий к заказу'
label: 'Комментарий'
label_css: ''
css_class: 'col-xs-12'
editable: false
}
]
},
{
name: 'group2'
type: 'group'
label: 'Паспортные данные'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: 'docType'
type: 'list'
css_class: 'col-xs-4 col-sm-5 col-md-3'
tooltip: 'Тип удостоверяющего документа'
label: 'Документ'
label_css: ''
choices: ['паспорт', 'вод.удостоверение', 'загран.паспорт']
},
{
name: 'passportSerie'
type: 'string'
tooltip: 'Серия паспорта'
label: 'Серия'
label_css: ''
css_class: 'col-xs-3 col-sm-2 col-md-2'
pattern: '{{99}} {{99}}'
},
{
name: 'passportNo'
type: 'string'
tooltip: 'Номер паспорта'
label: 'Номер'
label_css: ''
css_class: 'col-xs-5 col-sm-3 col-md-2'
pattern: '{{999}} {{999}}'
},
{
name: 'passportIssuerDept'
type: 'string'
tooltip: 'Код подразделения'
label: 'Подр.'
label_css: ''
css_class: 'col-xs-3 col-sm-2 col-md-2'
pattern: '{{999}}-{{999}}'
},
{
name: 'passportIssueDate'
type: 'datetime'
tooltip: 'Дата выдачи паспорта'
label: 'Дата'
label_css: ''
css_class: 'col-xs-4 col-sm-3 col-md-3'
format: 'DD.MM.YYYY'
},
{
name: 'passportIssuer'
type: 'string'
tooltip: 'Паспорт выдан'
label: 'Выдан'
label_css: ''
css_class: 'col-xs-12 col-sm-9 col-md-12'
},
{
name: 'passportValid'
type: 'checkbox'
tooltip: 'Паспорт действителен'
label: 'Действителен'
label_css: ''
css_class: 'col-xs-12 col-sm-9 col-md-12'
}
]
},
{
name: 'group3'
type: 'group'
label: 'Входной опрос'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: 'someEvent'
type: 'datetime'
tooltip: 'Дата со временем для проверки схлопывания формы'
label: 'Дата и время'
label_css: ''
css_class: 'col-xs-4 col-sm-3 col-md-3'
format: 'DD.MM.YYYY HH:MM'
},
{
name: 'marketingChannel'
type: 'list'
css_class: 'col-xs-12 col-sm-6 col-md-4'
tooltip: 'Откуда вы о нас узнали?'
label: 'Маркетинговый канал'
label_css: ''
choices: ['рекомендация друзей/знакомых', 'поиск/реклама в интернете', 'реклама в печатных изданиях', 'реклама на улице', 'листовки', 'не помню', 'другое']
}
]
},
{
name: 'currentProvider'
type: 'submit_select'
css_class: 'col-xs-12'
options: [
{ name: 'Не пользовался', value: 'Не пользовался', css_class: 'btn btn-primary'},
{ name: 'Offline Telecom', value: 'Offline Telecom', css_class: 'btn btn-warning'},
{ name: 'Goodlife', value: 'Goodlife', css_class: 'btn btn-primary'},
{ name: 'ОчХорИнтернет', value: 'ОчХорИнтернет', css_class: 'btn btn-warning'},
{ name: 'Вектор', value: 'Вектор', css_class: 'btn btn-primary'},
{ name: 'Азимут', value: 'Азимут', css_class: 'btn btn-warning'},
{ name: 'Другое', value: 'Другое', css_class: 'btn btn-primary'},
]
}
]
}
| 120340 | modulejs.define 'HBWTestForm', [], ()->
class TestForm
@with_all_controls = {
name: 'Тестовая форма',
description: ['Это форма для тестирования рендеринга всех видов контролов', 'Пожалуйста, дочитайте это многострочное пояснение до конца', 'Возможно, это поможет вам сделать меньше ошибок' ],
css_class: 'col-xs-12 col-sm-6 col-md-5 col-lg-4',
fields: [
{
name: 'note1'
type: 'note'
html: '<H1>Внимание!</H1>Это форма для тестирования рендеринга всех видов контролов<br/>Пожалуйста, дочитайте это многострочное пояснение до конца<br/>Возможно, это поможет вам сделать меньше ошибок'
css_class: 'col-xs-12'
},
{
name: 'group1'
type: 'group' # Тип поля формы
label: 'Общие данные'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: '<NAME>'
type: 'string'
tooltip: 'Фамилия клиента'
label: '<NAME>'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
editable: false
},
{
name: '<NAME>'
type: 'string'
tooltip: 'Имя клиента'
label: '<NAME>'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
},
{
name: '<NAME>Name'
type: 'string'
tooltip: 'Отчество клиента'
label: 'Отчество'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
},
{
name: 'phone'
type: 'string'
tooltip: 'Контактный телефон клиента'
label: 'Телефон'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
pattern: '+7 ({{999}}) {{999}}-{{99}}-{{99}}'
},
{
name: 'buildingAddress'
type: 'string'
tooltip: 'Адрес дома'
label: 'Адрес дома'
label_css: ''
css_class: 'col-xs-6 col-sm-6 col-md-5'
},
{
name: 'flatNo'
type: 'string'
tooltip: 'Номер квартиры'
label: 'Кв.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'wingNo'
type: 'string'
tooltip: 'Номер подъезда'
label: 'под.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'floorNo'
type: 'string'
tooltip: 'Номер этажа'
label: 'эт.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'comment'
type: 'text'
rows: 3
tooltip: 'Комментарий к заказу'
label: 'Комментарий'
label_css: ''
css_class: 'col-xs-12'
editable: false
}
]
},
{
name: 'group2'
type: 'group'
label: 'Паспортные данные'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: 'docType'
type: 'list'
css_class: 'col-xs-4 col-sm-5 col-md-3'
tooltip: 'Тип удостоверяющего документа'
label: 'Документ'
label_css: ''
choices: ['паспорт', 'вод.удостоверение', 'загран.паспорт']
},
{
name: 'passportSerie'
type: 'string'
tooltip: 'Серия паспорта'
label: 'Серия'
label_css: ''
css_class: 'col-xs-3 col-sm-2 col-md-2'
pattern: '{{99}} {{99}}'
},
{
name: 'passportNo'
type: 'string'
tooltip: 'Номер паспорта'
label: 'Номер'
label_css: ''
css_class: 'col-xs-5 col-sm-3 col-md-2'
pattern: '{{999}} {{999}}'
},
{
name: 'passportIssuerDept'
type: 'string'
tooltip: 'Код подразделения'
label: 'Подр.'
label_css: ''
css_class: 'col-xs-3 col-sm-2 col-md-2'
pattern: '{{999}}-{{999}}'
},
{
name: 'passportIssueDate'
type: 'datetime'
tooltip: 'Дата выдачи паспорта'
label: 'Дата'
label_css: ''
css_class: 'col-xs-4 col-sm-3 col-md-3'
format: 'DD.MM.YYYY'
},
{
name: 'passportIssuer'
type: 'string'
tooltip: 'Паспорт выдан'
label: 'Выдан'
label_css: ''
css_class: 'col-xs-12 col-sm-9 col-md-12'
},
{
name: 'passportValid'
type: 'checkbox'
tooltip: 'Паспорт действителен'
label: 'Действителен'
label_css: ''
css_class: 'col-xs-12 col-sm-9 col-md-12'
}
]
},
{
name: 'group3'
type: 'group'
label: 'Входной опрос'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: 'someEvent'
type: 'datetime'
tooltip: 'Дата со временем для проверки схлопывания формы'
label: 'Дата и время'
label_css: ''
css_class: 'col-xs-4 col-sm-3 col-md-3'
format: 'DD.MM.YYYY HH:MM'
},
{
name: 'marketingChannel'
type: 'list'
css_class: 'col-xs-12 col-sm-6 col-md-4'
tooltip: 'Откуда вы о нас узнали?'
label: 'Маркетинговый канал'
label_css: ''
choices: ['рекомендация друзей/знакомых', 'поиск/реклама в интернете', 'реклама в печатных изданиях', 'реклама на улице', 'листовки', 'не помню', 'другое']
}
]
},
{
name: 'currentProvider'
type: 'submit_select'
css_class: 'col-xs-12'
options: [
{ name: 'Не пользовался', value: 'Не пользовался', css_class: 'btn btn-primary'},
{ name: 'Offline Telecom', value: 'Offline Telecom', css_class: 'btn btn-warning'},
{ name: 'Goodlife', value: 'Goodlife', css_class: 'btn btn-primary'},
{ name: 'ОчХорИнтернет', value: 'ОчХорИнтернет', css_class: 'btn btn-warning'},
{ name: 'Вектор', value: 'Вектор', css_class: 'btn btn-primary'},
{ name: '<NAME>', value: '<NAME>', css_class: 'btn btn-warning'},
{ name: 'Другое', value: 'Другое', css_class: 'btn btn-primary'},
]
}
]
}
| true | modulejs.define 'HBWTestForm', [], ()->
class TestForm
@with_all_controls = {
name: 'Тестовая форма',
description: ['Это форма для тестирования рендеринга всех видов контролов', 'Пожалуйста, дочитайте это многострочное пояснение до конца', 'Возможно, это поможет вам сделать меньше ошибок' ],
css_class: 'col-xs-12 col-sm-6 col-md-5 col-lg-4',
fields: [
{
name: 'note1'
type: 'note'
html: '<H1>Внимание!</H1>Это форма для тестирования рендеринга всех видов контролов<br/>Пожалуйста, дочитайте это многострочное пояснение до конца<br/>Возможно, это поможет вам сделать меньше ошибок'
css_class: 'col-xs-12'
},
{
name: 'group1'
type: 'group' # Тип поля формы
label: 'Общие данные'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: 'PI:NAME:<NAME>END_PI'
type: 'string'
tooltip: 'Фамилия клиента'
label: 'PI:NAME:<NAME>END_PI'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
editable: false
},
{
name: 'PI:NAME:<NAME>END_PI'
type: 'string'
tooltip: 'Имя клиента'
label: 'PI:NAME:<NAME>END_PI'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
},
{
name: 'PI:NAME:<NAME>END_PIName'
type: 'string'
tooltip: 'Отчество клиента'
label: 'Отчество'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
},
{
name: 'phone'
type: 'string'
tooltip: 'Контактный телефон клиента'
label: 'Телефон'
label_css: ''
css_class: 'col-xs-6 col-sm-4 col-md-3'
pattern: '+7 ({{999}}) {{999}}-{{99}}-{{99}}'
},
{
name: 'buildingAddress'
type: 'string'
tooltip: 'Адрес дома'
label: 'Адрес дома'
label_css: ''
css_class: 'col-xs-6 col-sm-6 col-md-5'
},
{
name: 'flatNo'
type: 'string'
tooltip: 'Номер квартиры'
label: 'Кв.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'wingNo'
type: 'string'
tooltip: 'Номер подъезда'
label: 'под.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'floorNo'
type: 'string'
tooltip: 'Номер этажа'
label: 'эт.'
label_css: ''
css_class: 'col-xs-2 col-sm-2 col-md-1 col-lg-1'
},
{
name: 'comment'
type: 'text'
rows: 3
tooltip: 'Комментарий к заказу'
label: 'Комментарий'
label_css: ''
css_class: 'col-xs-12'
editable: false
}
]
},
{
name: 'group2'
type: 'group'
label: 'Паспортные данные'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: 'docType'
type: 'list'
css_class: 'col-xs-4 col-sm-5 col-md-3'
tooltip: 'Тип удостоверяющего документа'
label: 'Документ'
label_css: ''
choices: ['паспорт', 'вод.удостоверение', 'загран.паспорт']
},
{
name: 'passportSerie'
type: 'string'
tooltip: 'Серия паспорта'
label: 'Серия'
label_css: ''
css_class: 'col-xs-3 col-sm-2 col-md-2'
pattern: '{{99}} {{99}}'
},
{
name: 'passportNo'
type: 'string'
tooltip: 'Номер паспорта'
label: 'Номер'
label_css: ''
css_class: 'col-xs-5 col-sm-3 col-md-2'
pattern: '{{999}} {{999}}'
},
{
name: 'passportIssuerDept'
type: 'string'
tooltip: 'Код подразделения'
label: 'Подр.'
label_css: ''
css_class: 'col-xs-3 col-sm-2 col-md-2'
pattern: '{{999}}-{{999}}'
},
{
name: 'passportIssueDate'
type: 'datetime'
tooltip: 'Дата выдачи паспорта'
label: 'Дата'
label_css: ''
css_class: 'col-xs-4 col-sm-3 col-md-3'
format: 'DD.MM.YYYY'
},
{
name: 'passportIssuer'
type: 'string'
tooltip: 'Паспорт выдан'
label: 'Выдан'
label_css: ''
css_class: 'col-xs-12 col-sm-9 col-md-12'
},
{
name: 'passportValid'
type: 'checkbox'
tooltip: 'Паспорт действителен'
label: 'Действителен'
label_css: ''
css_class: 'col-xs-12 col-sm-9 col-md-12'
}
]
},
{
name: 'group3'
type: 'group'
label: 'Входной опрос'
tooltip: 'Какое-то пояснение'
css_class: 'col-xs-12'
fields: [
{
name: 'someEvent'
type: 'datetime'
tooltip: 'Дата со временем для проверки схлопывания формы'
label: 'Дата и время'
label_css: ''
css_class: 'col-xs-4 col-sm-3 col-md-3'
format: 'DD.MM.YYYY HH:MM'
},
{
name: 'marketingChannel'
type: 'list'
css_class: 'col-xs-12 col-sm-6 col-md-4'
tooltip: 'Откуда вы о нас узнали?'
label: 'Маркетинговый канал'
label_css: ''
choices: ['рекомендация друзей/знакомых', 'поиск/реклама в интернете', 'реклама в печатных изданиях', 'реклама на улице', 'листовки', 'не помню', 'другое']
}
]
},
{
name: 'currentProvider'
type: 'submit_select'
css_class: 'col-xs-12'
options: [
{ name: 'Не пользовался', value: 'Не пользовался', css_class: 'btn btn-primary'},
{ name: 'Offline Telecom', value: 'Offline Telecom', css_class: 'btn btn-warning'},
{ name: 'Goodlife', value: 'Goodlife', css_class: 'btn btn-primary'},
{ name: 'ОчХорИнтернет', value: 'ОчХорИнтернет', css_class: 'btn btn-warning'},
{ name: 'Вектор', value: 'Вектор', css_class: 'btn btn-primary'},
{ name: 'PI:NAME:<NAME>END_PI', value: 'PI:NAME:<NAME>END_PI', css_class: 'btn btn-warning'},
{ name: 'Другое', value: 'Другое', css_class: 'btn btn-primary'},
]
}
]
}
|
[
{
"context": "tectFromCSRF = true\n Batman.config.CSRF_TOKEN = 'configOption!'\n\n @Model.get('all')\n equal @lastRequest.options",
"end": 2779,
"score": 0.7519547343254089,
"start": 2767,
"tag": "PASSWORD",
"value": "configOption"
}
] | tests/batman/extras/rails_extra_test.coffee | amco/batman | 0 | oldOffset = Batman.Encoders.railsDate.defaultTimezoneOffset
QUnit.module "Batman.Rails: date encoding",
teardown: ->
Batman.Encoders.railsDate.defaultTimezoneOffset = oldOffset
dateEqual = (a, b, args...) ->
equal a.getTime(), b.getTime(), args...
test "it should parse ISO 8601 dates", ->
# Date not during DST
Batman.Encoders.railsDate.defaultTimezoneOffset = 300
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06"), new Date("Tues, 03 Jan 2012 13:35:06 EST")
# Date during DST
Batman.Encoders.railsDate.defaultTimezoneOffset = 240
dateEqual Batman.Encoders.railsDate.decode("2012-04-13T13:35:06"), new Date("Sun, 13 Apr 2012 13:35:06 EDT")
test "it should parse ISO 8601 dates with timezones", ->
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06-05:00"), new Date(1325615706000)
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06-07:00"), new Date(1325622906000)
QUnit.module "encodeTimestamps",
setup: ->
class @Model extends Batman.Model
test "it should be defined on models", ->
ok Batman.Model.encodeTimestamps
test "with no options should decode created_at and updated_at", ->
@Model.encodeTimestamps()
# FIXME when this is a model testcase, this could use assertDecoders
decoders = []
@Model::_batman.get("encoders").forEach (key, encoder) ->
decoders.push(key) if encoder.decode
notEqual decoders.indexOf('created_at', 'updated_at'), -1
test "should properly decode a Rails date", ->
@Model.encodeTimestamps('tested_at')
instance = @Model.createFromJSON(tested_at: "2012-01-03T13:35:06-05:00")
ok instance.get('tested_at') instanceof Date
dateEqual instance.get('tested_at'), new Date(1325615706000)
QUnit.module "Batman.Rails: CSRF protection",
setup: ->
theTest = this
class MockRailsStorage extends Batman.RailsStorage
request: (env) ->
theTest.lastRequest = env
class @Model extends Batman.Model
@persist MockRailsStorage
test "if protectFromCSRF is false, the request does not include a CSRF header", ->
Batman.config.protectFromCSRF = false
@Model.get('all')
ok !@lastRequest.options.headers?['X-CSRF-Token']
test "if protectFromCSRF is true and the appropriate meta tag exists, the request should include a CSRF header", ->
Batman.config.protectFromCSRF = true
meta = document.createElement('meta')
meta.setAttribute('name', 'csrf-token')
meta.setAttribute('content', 'metaTag!')
document.head.appendChild(meta)
@Model.get('all')
equal @lastRequest.options.headers['X-CSRF-Token'], 'metaTag!'
test "if protectFromCSRF is true and the appropriate config option exists, the request should include a CSRF header", ->
Batman.config.protectFromCSRF = true
Batman.config.CSRF_TOKEN = 'configOption!'
@Model.get('all')
equal @lastRequest.options.headers['X-CSRF-Token'], 'configOption!'
| 225997 | oldOffset = Batman.Encoders.railsDate.defaultTimezoneOffset
QUnit.module "Batman.Rails: date encoding",
teardown: ->
Batman.Encoders.railsDate.defaultTimezoneOffset = oldOffset
dateEqual = (a, b, args...) ->
equal a.getTime(), b.getTime(), args...
test "it should parse ISO 8601 dates", ->
# Date not during DST
Batman.Encoders.railsDate.defaultTimezoneOffset = 300
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06"), new Date("Tues, 03 Jan 2012 13:35:06 EST")
# Date during DST
Batman.Encoders.railsDate.defaultTimezoneOffset = 240
dateEqual Batman.Encoders.railsDate.decode("2012-04-13T13:35:06"), new Date("Sun, 13 Apr 2012 13:35:06 EDT")
test "it should parse ISO 8601 dates with timezones", ->
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06-05:00"), new Date(1325615706000)
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06-07:00"), new Date(1325622906000)
QUnit.module "encodeTimestamps",
setup: ->
class @Model extends Batman.Model
test "it should be defined on models", ->
ok Batman.Model.encodeTimestamps
test "with no options should decode created_at and updated_at", ->
@Model.encodeTimestamps()
# FIXME when this is a model testcase, this could use assertDecoders
decoders = []
@Model::_batman.get("encoders").forEach (key, encoder) ->
decoders.push(key) if encoder.decode
notEqual decoders.indexOf('created_at', 'updated_at'), -1
test "should properly decode a Rails date", ->
@Model.encodeTimestamps('tested_at')
instance = @Model.createFromJSON(tested_at: "2012-01-03T13:35:06-05:00")
ok instance.get('tested_at') instanceof Date
dateEqual instance.get('tested_at'), new Date(1325615706000)
QUnit.module "Batman.Rails: CSRF protection",
setup: ->
theTest = this
class MockRailsStorage extends Batman.RailsStorage
request: (env) ->
theTest.lastRequest = env
class @Model extends Batman.Model
@persist MockRailsStorage
test "if protectFromCSRF is false, the request does not include a CSRF header", ->
Batman.config.protectFromCSRF = false
@Model.get('all')
ok !@lastRequest.options.headers?['X-CSRF-Token']
test "if protectFromCSRF is true and the appropriate meta tag exists, the request should include a CSRF header", ->
Batman.config.protectFromCSRF = true
meta = document.createElement('meta')
meta.setAttribute('name', 'csrf-token')
meta.setAttribute('content', 'metaTag!')
document.head.appendChild(meta)
@Model.get('all')
equal @lastRequest.options.headers['X-CSRF-Token'], 'metaTag!'
test "if protectFromCSRF is true and the appropriate config option exists, the request should include a CSRF header", ->
Batman.config.protectFromCSRF = true
Batman.config.CSRF_TOKEN = '<PASSWORD>!'
@Model.get('all')
equal @lastRequest.options.headers['X-CSRF-Token'], 'configOption!'
| true | oldOffset = Batman.Encoders.railsDate.defaultTimezoneOffset
QUnit.module "Batman.Rails: date encoding",
teardown: ->
Batman.Encoders.railsDate.defaultTimezoneOffset = oldOffset
dateEqual = (a, b, args...) ->
equal a.getTime(), b.getTime(), args...
test "it should parse ISO 8601 dates", ->
# Date not during DST
Batman.Encoders.railsDate.defaultTimezoneOffset = 300
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06"), new Date("Tues, 03 Jan 2012 13:35:06 EST")
# Date during DST
Batman.Encoders.railsDate.defaultTimezoneOffset = 240
dateEqual Batman.Encoders.railsDate.decode("2012-04-13T13:35:06"), new Date("Sun, 13 Apr 2012 13:35:06 EDT")
test "it should parse ISO 8601 dates with timezones", ->
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06-05:00"), new Date(1325615706000)
dateEqual Batman.Encoders.railsDate.decode("2012-01-03T13:35:06-07:00"), new Date(1325622906000)
QUnit.module "encodeTimestamps",
setup: ->
class @Model extends Batman.Model
test "it should be defined on models", ->
ok Batman.Model.encodeTimestamps
test "with no options should decode created_at and updated_at", ->
@Model.encodeTimestamps()
# FIXME when this is a model testcase, this could use assertDecoders
decoders = []
@Model::_batman.get("encoders").forEach (key, encoder) ->
decoders.push(key) if encoder.decode
notEqual decoders.indexOf('created_at', 'updated_at'), -1
test "should properly decode a Rails date", ->
@Model.encodeTimestamps('tested_at')
instance = @Model.createFromJSON(tested_at: "2012-01-03T13:35:06-05:00")
ok instance.get('tested_at') instanceof Date
dateEqual instance.get('tested_at'), new Date(1325615706000)
QUnit.module "Batman.Rails: CSRF protection",
setup: ->
theTest = this
class MockRailsStorage extends Batman.RailsStorage
request: (env) ->
theTest.lastRequest = env
class @Model extends Batman.Model
@persist MockRailsStorage
test "if protectFromCSRF is false, the request does not include a CSRF header", ->
Batman.config.protectFromCSRF = false
@Model.get('all')
ok !@lastRequest.options.headers?['X-CSRF-Token']
test "if protectFromCSRF is true and the appropriate meta tag exists, the request should include a CSRF header", ->
Batman.config.protectFromCSRF = true
meta = document.createElement('meta')
meta.setAttribute('name', 'csrf-token')
meta.setAttribute('content', 'metaTag!')
document.head.appendChild(meta)
@Model.get('all')
equal @lastRequest.options.headers['X-CSRF-Token'], 'metaTag!'
test "if protectFromCSRF is true and the appropriate config option exists, the request should include a CSRF header", ->
Batman.config.protectFromCSRF = true
Batman.config.CSRF_TOKEN = 'PI:PASSWORD:<PASSWORD>END_PI!'
@Model.get('all')
equal @lastRequest.options.headers['X-CSRF-Token'], 'configOption!'
|
[
{
"context": "eometry, materials, json) =>\n\t\t\t\t\t\tgeometry.name = name\n\t\t\t\t\t\tgeometry.computeBoundingBox()\n\t\t\t\t\t\tgeometr",
"end": 3374,
"score": 0.8292661309242249,
"start": 3370,
"tag": "NAME",
"value": "name"
}
] | app/assets/javascripts/engine/controllers/preloader.coffee | ssachtleben/herowar | 1 | RendererCanvasController = require 'controllers/rendererCanvas'
materialHelper = require 'helper/materialHelper'
GeometryUtils = require 'util/geometryUtils'
textureUtils = require 'util/textureUtils'
JSONLoader = require 'util/threeloader'
Variables = require 'variables'
Eventbus = require 'eventbus'
log = require 'util/logger'
db = require 'database'
class Preloader extends RendererCanvasController
id: 'preloader'
redirectTo: ''
views:
'views/preloader' : ''
initialize: (options) ->
log.info 'Initialize preloader...'
@initVariables()
super options
if @options.data
@load @options.data
else
# TODO: get a proper solution here for the editor...
@load
textures:
'stone-natural-001' : 'assets/images/game/textures/stone/natural-001.jpg'
'stone-rough-001' : 'assets/images/game/textures/stone/rough-001.jpg'
'ground-rock' : 'assets/images/game/textures/ground/rock.jpg'
'ground-grass' : 'assets/images/game/textures/ground/grass.jpg'
'texture_ground_grass' : 'assets/images/game/textures/ground/texture_ground_grass.jpg'
'texture_ground_bare' : 'assets/images/game/textures/ground/texture_ground_bare.jpg'
'texture_ground_snow' : 'assets/images/game/textures/ground/texture_ground_snow.jpg'
texturesCube:
'default' : 'assets/images/game/skybox/default/%1.jpg'
initVariables: ->
@preloadComplete = false
@alpha = 1.0
@state = 1
@percentage = 0
@data = {}
@states = {}
@jsonLoader = new JSONLoader()
@types = [ 'textures', 'texturesCube', 'geometries', 'images' ]
for type in @types
@data[type] = {}
@states[type] = {}
@progress =
total: 0
remaining: 0
loaded: 0
finish: false
started: true
load: (data) ->
for type in @types
if type of data
size = 0
for key, value of data[type]
size++
@progress.total += size
@progress.remaining += size
@loadItem type, key, url for key, url of list for type, list of data
updateState: (type, name, state) ->
unless type of @states
log.error "Unkown loader type #{type}."
return
if state is true
@progress.remaining--
@progress.loaded++
@percentage = @progress.loaded / @progress.total * 100
@states[type][name] = state
@afterUpdateState()
@progress.finish = true if @progress.loaded is @progress.total
# Override to do someone after state update
afterUpdateState: ->
loadItem: (type, name, url) ->
log.info "Load [type=#{type}, name=#{name}, url=#{url}]"
@updateState type, name, false
switch type
when 'images'
img = new Image
img.onload = () =>
@data['textures'][name] = textureUtils.createFromImage
image: @data['images'][name]
alpha: true
@updateState type, name, true
img.src = url
@data[type][name] = img
when 'textures'
@data[type][name] = THREE.ImageUtils.loadTexture url, undefined, =>
@updateState type, name, true
when 'texturesCube'
urls = [
url.replace("%1", "px"), url.replace("%1", "nx"),
url.replace("%1", "py"), url.replace("%1", "ny"),
url.replace("%1", "pz"), url.replace("%1", "nz")
]
@data[type][name] = THREE.ImageUtils.loadTextureCube urls, new THREE.CubeRefractionMapping(), =>
@updateState type, name, true
when 'geometries'
@jsonLoader.load url,
(geometry, materials, json) =>
geometry.name = name
geometry.computeBoundingBox()
geometry.computeBoundingSphere()
geometry.computeMorphNormals()
geometry.computeFaceNormals()
geometry.computeVertexNormals()
THREE.GeometryUtils.center geometry
db.geometry name, 'main', geometry
db.geometry name, 'glow', GeometryUtils.clone geometry
@data[type][name] = [geometry, materials, json]
@updateState type, name, true
, 'assets/images/game/textures'
else
throw "The loader type '#{type}' is not supported"
animate: =>
requestAnimationFrame @animate unless @preloadComplete
@ctx.clearRect 0, 0, Variables.SCREEN_WIDTH, Variables.SCREEN_HEIGHT
@ctx.save()
if @state is 1
@ctx.font = '24px Arial'
@ctx.fillStyle = "rgba(200, 200, 200, #{@alpha})"
@ctx.fillText "Loading #{Math.round(@percentage)}%", Variables.SCREEN_WIDTH / 2, Variables.SCREEN_HEIGHT / 2 + 30
@ctx.restore()
if @progress.finish and @progress.started
@state = 2
@loadMap()
else
@ctx.font = '24px Arial'
@ctx.fillStyle = "rgba(200, 200, 200, #{@alpha})"
text = if @options.map then "Creating map #{@options.map}" else 'Creating default map'
@ctx.fillText text, Variables.SCREEN_WIDTH / 2, Variables.SCREEN_HEIGHT / 2 + 30
@ctx.restore()
if @state is 3
@alpha -= 0.05
@finish() if @alpha <= 0 and !@preloadComplete
loadMap: ->
jqxhr = $.ajax
url : if @options.map then "/api/editor/map/#{@options.map}" else '/api/editor/map/default'
type : 'GET'
dataType : 'json'
success : @onSuccess
onSuccess: (data) =>
world = db.get 'world'
oldGeo = data.terrain.geometry
data.terrain.geometry.materials = []
world.set @parseWorldData data
newGeo = world.attributes.terrain.geometry
newGeo.userData = {}
newGeo.userData.matIdMapper = oldGeo.matIdMapper
newGeo.userData.id = oldGeo.id
newGeo.userData.type = oldGeo.type
newGeo.userData.metadata = oldGeo.metadata
newGeo.userData.version = oldGeo.version
newGeo.userData.cdate = oldGeo.cdate
world.loadMaterials data.materials
console.log world
@state = 3
parseWorldData: (data) ->
if data.terrain.geometry.id
log.info "Parse geometry id #{data.terrain.geometry.id} with json loader"
loader = new THREE.JSONLoader()
result = loader.parse data.terrain.geometry
data.terrain.geometry = result.geometry
if data.staticGeometries
staticMeshes = []
for object in data.staticGeometries
result = loader.parse object
mesh = materialHelper.createMesh result.geometry, result.materials, object.name, object
mesh.userData.id = object.id
mesh.userData.matIdMapper = object.matIdMapper
staticMeshes.push mesh
data.staticGeometries = staticMeshes
data
finish: ->
log.info 'Preloading complete'
@preloadComplete = true
@$container.find('canvas').remove()
db.data @data
Backbone.history.loadUrl @redirectTo
return Preloader | 153904 | RendererCanvasController = require 'controllers/rendererCanvas'
materialHelper = require 'helper/materialHelper'
GeometryUtils = require 'util/geometryUtils'
textureUtils = require 'util/textureUtils'
JSONLoader = require 'util/threeloader'
Variables = require 'variables'
Eventbus = require 'eventbus'
log = require 'util/logger'
db = require 'database'
class Preloader extends RendererCanvasController
id: 'preloader'
redirectTo: ''
views:
'views/preloader' : ''
initialize: (options) ->
log.info 'Initialize preloader...'
@initVariables()
super options
if @options.data
@load @options.data
else
# TODO: get a proper solution here for the editor...
@load
textures:
'stone-natural-001' : 'assets/images/game/textures/stone/natural-001.jpg'
'stone-rough-001' : 'assets/images/game/textures/stone/rough-001.jpg'
'ground-rock' : 'assets/images/game/textures/ground/rock.jpg'
'ground-grass' : 'assets/images/game/textures/ground/grass.jpg'
'texture_ground_grass' : 'assets/images/game/textures/ground/texture_ground_grass.jpg'
'texture_ground_bare' : 'assets/images/game/textures/ground/texture_ground_bare.jpg'
'texture_ground_snow' : 'assets/images/game/textures/ground/texture_ground_snow.jpg'
texturesCube:
'default' : 'assets/images/game/skybox/default/%1.jpg'
initVariables: ->
@preloadComplete = false
@alpha = 1.0
@state = 1
@percentage = 0
@data = {}
@states = {}
@jsonLoader = new JSONLoader()
@types = [ 'textures', 'texturesCube', 'geometries', 'images' ]
for type in @types
@data[type] = {}
@states[type] = {}
@progress =
total: 0
remaining: 0
loaded: 0
finish: false
started: true
load: (data) ->
for type in @types
if type of data
size = 0
for key, value of data[type]
size++
@progress.total += size
@progress.remaining += size
@loadItem type, key, url for key, url of list for type, list of data
updateState: (type, name, state) ->
unless type of @states
log.error "Unkown loader type #{type}."
return
if state is true
@progress.remaining--
@progress.loaded++
@percentage = @progress.loaded / @progress.total * 100
@states[type][name] = state
@afterUpdateState()
@progress.finish = true if @progress.loaded is @progress.total
# Override to do someone after state update
afterUpdateState: ->
loadItem: (type, name, url) ->
log.info "Load [type=#{type}, name=#{name}, url=#{url}]"
@updateState type, name, false
switch type
when 'images'
img = new Image
img.onload = () =>
@data['textures'][name] = textureUtils.createFromImage
image: @data['images'][name]
alpha: true
@updateState type, name, true
img.src = url
@data[type][name] = img
when 'textures'
@data[type][name] = THREE.ImageUtils.loadTexture url, undefined, =>
@updateState type, name, true
when 'texturesCube'
urls = [
url.replace("%1", "px"), url.replace("%1", "nx"),
url.replace("%1", "py"), url.replace("%1", "ny"),
url.replace("%1", "pz"), url.replace("%1", "nz")
]
@data[type][name] = THREE.ImageUtils.loadTextureCube urls, new THREE.CubeRefractionMapping(), =>
@updateState type, name, true
when 'geometries'
@jsonLoader.load url,
(geometry, materials, json) =>
geometry.name = <NAME>
geometry.computeBoundingBox()
geometry.computeBoundingSphere()
geometry.computeMorphNormals()
geometry.computeFaceNormals()
geometry.computeVertexNormals()
THREE.GeometryUtils.center geometry
db.geometry name, 'main', geometry
db.geometry name, 'glow', GeometryUtils.clone geometry
@data[type][name] = [geometry, materials, json]
@updateState type, name, true
, 'assets/images/game/textures'
else
throw "The loader type '#{type}' is not supported"
animate: =>
requestAnimationFrame @animate unless @preloadComplete
@ctx.clearRect 0, 0, Variables.SCREEN_WIDTH, Variables.SCREEN_HEIGHT
@ctx.save()
if @state is 1
@ctx.font = '24px Arial'
@ctx.fillStyle = "rgba(200, 200, 200, #{@alpha})"
@ctx.fillText "Loading #{Math.round(@percentage)}%", Variables.SCREEN_WIDTH / 2, Variables.SCREEN_HEIGHT / 2 + 30
@ctx.restore()
if @progress.finish and @progress.started
@state = 2
@loadMap()
else
@ctx.font = '24px Arial'
@ctx.fillStyle = "rgba(200, 200, 200, #{@alpha})"
text = if @options.map then "Creating map #{@options.map}" else 'Creating default map'
@ctx.fillText text, Variables.SCREEN_WIDTH / 2, Variables.SCREEN_HEIGHT / 2 + 30
@ctx.restore()
if @state is 3
@alpha -= 0.05
@finish() if @alpha <= 0 and !@preloadComplete
loadMap: ->
jqxhr = $.ajax
url : if @options.map then "/api/editor/map/#{@options.map}" else '/api/editor/map/default'
type : 'GET'
dataType : 'json'
success : @onSuccess
onSuccess: (data) =>
world = db.get 'world'
oldGeo = data.terrain.geometry
data.terrain.geometry.materials = []
world.set @parseWorldData data
newGeo = world.attributes.terrain.geometry
newGeo.userData = {}
newGeo.userData.matIdMapper = oldGeo.matIdMapper
newGeo.userData.id = oldGeo.id
newGeo.userData.type = oldGeo.type
newGeo.userData.metadata = oldGeo.metadata
newGeo.userData.version = oldGeo.version
newGeo.userData.cdate = oldGeo.cdate
world.loadMaterials data.materials
console.log world
@state = 3
parseWorldData: (data) ->
if data.terrain.geometry.id
log.info "Parse geometry id #{data.terrain.geometry.id} with json loader"
loader = new THREE.JSONLoader()
result = loader.parse data.terrain.geometry
data.terrain.geometry = result.geometry
if data.staticGeometries
staticMeshes = []
for object in data.staticGeometries
result = loader.parse object
mesh = materialHelper.createMesh result.geometry, result.materials, object.name, object
mesh.userData.id = object.id
mesh.userData.matIdMapper = object.matIdMapper
staticMeshes.push mesh
data.staticGeometries = staticMeshes
data
finish: ->
log.info 'Preloading complete'
@preloadComplete = true
@$container.find('canvas').remove()
db.data @data
Backbone.history.loadUrl @redirectTo
return Preloader | true | RendererCanvasController = require 'controllers/rendererCanvas'
materialHelper = require 'helper/materialHelper'
GeometryUtils = require 'util/geometryUtils'
textureUtils = require 'util/textureUtils'
JSONLoader = require 'util/threeloader'
Variables = require 'variables'
Eventbus = require 'eventbus'
log = require 'util/logger'
db = require 'database'
class Preloader extends RendererCanvasController
id: 'preloader'
redirectTo: ''
views:
'views/preloader' : ''
initialize: (options) ->
log.info 'Initialize preloader...'
@initVariables()
super options
if @options.data
@load @options.data
else
# TODO: get a proper solution here for the editor...
@load
textures:
'stone-natural-001' : 'assets/images/game/textures/stone/natural-001.jpg'
'stone-rough-001' : 'assets/images/game/textures/stone/rough-001.jpg'
'ground-rock' : 'assets/images/game/textures/ground/rock.jpg'
'ground-grass' : 'assets/images/game/textures/ground/grass.jpg'
'texture_ground_grass' : 'assets/images/game/textures/ground/texture_ground_grass.jpg'
'texture_ground_bare' : 'assets/images/game/textures/ground/texture_ground_bare.jpg'
'texture_ground_snow' : 'assets/images/game/textures/ground/texture_ground_snow.jpg'
texturesCube:
'default' : 'assets/images/game/skybox/default/%1.jpg'
initVariables: ->
@preloadComplete = false
@alpha = 1.0
@state = 1
@percentage = 0
@data = {}
@states = {}
@jsonLoader = new JSONLoader()
@types = [ 'textures', 'texturesCube', 'geometries', 'images' ]
for type in @types
@data[type] = {}
@states[type] = {}
@progress =
total: 0
remaining: 0
loaded: 0
finish: false
started: true
load: (data) ->
for type in @types
if type of data
size = 0
for key, value of data[type]
size++
@progress.total += size
@progress.remaining += size
@loadItem type, key, url for key, url of list for type, list of data
updateState: (type, name, state) ->
unless type of @states
log.error "Unkown loader type #{type}."
return
if state is true
@progress.remaining--
@progress.loaded++
@percentage = @progress.loaded / @progress.total * 100
@states[type][name] = state
@afterUpdateState()
@progress.finish = true if @progress.loaded is @progress.total
# Override to do someone after state update
afterUpdateState: ->
loadItem: (type, name, url) ->
log.info "Load [type=#{type}, name=#{name}, url=#{url}]"
@updateState type, name, false
switch type
when 'images'
img = new Image
img.onload = () =>
@data['textures'][name] = textureUtils.createFromImage
image: @data['images'][name]
alpha: true
@updateState type, name, true
img.src = url
@data[type][name] = img
when 'textures'
@data[type][name] = THREE.ImageUtils.loadTexture url, undefined, =>
@updateState type, name, true
when 'texturesCube'
urls = [
url.replace("%1", "px"), url.replace("%1", "nx"),
url.replace("%1", "py"), url.replace("%1", "ny"),
url.replace("%1", "pz"), url.replace("%1", "nz")
]
@data[type][name] = THREE.ImageUtils.loadTextureCube urls, new THREE.CubeRefractionMapping(), =>
@updateState type, name, true
when 'geometries'
@jsonLoader.load url,
(geometry, materials, json) =>
geometry.name = PI:NAME:<NAME>END_PI
geometry.computeBoundingBox()
geometry.computeBoundingSphere()
geometry.computeMorphNormals()
geometry.computeFaceNormals()
geometry.computeVertexNormals()
THREE.GeometryUtils.center geometry
db.geometry name, 'main', geometry
db.geometry name, 'glow', GeometryUtils.clone geometry
@data[type][name] = [geometry, materials, json]
@updateState type, name, true
, 'assets/images/game/textures'
else
throw "The loader type '#{type}' is not supported"
animate: =>
requestAnimationFrame @animate unless @preloadComplete
@ctx.clearRect 0, 0, Variables.SCREEN_WIDTH, Variables.SCREEN_HEIGHT
@ctx.save()
if @state is 1
@ctx.font = '24px Arial'
@ctx.fillStyle = "rgba(200, 200, 200, #{@alpha})"
@ctx.fillText "Loading #{Math.round(@percentage)}%", Variables.SCREEN_WIDTH / 2, Variables.SCREEN_HEIGHT / 2 + 30
@ctx.restore()
if @progress.finish and @progress.started
@state = 2
@loadMap()
else
@ctx.font = '24px Arial'
@ctx.fillStyle = "rgba(200, 200, 200, #{@alpha})"
text = if @options.map then "Creating map #{@options.map}" else 'Creating default map'
@ctx.fillText text, Variables.SCREEN_WIDTH / 2, Variables.SCREEN_HEIGHT / 2 + 30
@ctx.restore()
if @state is 3
@alpha -= 0.05
@finish() if @alpha <= 0 and !@preloadComplete
loadMap: ->
jqxhr = $.ajax
url : if @options.map then "/api/editor/map/#{@options.map}" else '/api/editor/map/default'
type : 'GET'
dataType : 'json'
success : @onSuccess
onSuccess: (data) =>
world = db.get 'world'
oldGeo = data.terrain.geometry
data.terrain.geometry.materials = []
world.set @parseWorldData data
newGeo = world.attributes.terrain.geometry
newGeo.userData = {}
newGeo.userData.matIdMapper = oldGeo.matIdMapper
newGeo.userData.id = oldGeo.id
newGeo.userData.type = oldGeo.type
newGeo.userData.metadata = oldGeo.metadata
newGeo.userData.version = oldGeo.version
newGeo.userData.cdate = oldGeo.cdate
world.loadMaterials data.materials
console.log world
@state = 3
parseWorldData: (data) ->
if data.terrain.geometry.id
log.info "Parse geometry id #{data.terrain.geometry.id} with json loader"
loader = new THREE.JSONLoader()
result = loader.parse data.terrain.geometry
data.terrain.geometry = result.geometry
if data.staticGeometries
staticMeshes = []
for object in data.staticGeometries
result = loader.parse object
mesh = materialHelper.createMesh result.geometry, result.materials, object.name, object
mesh.userData.id = object.id
mesh.userData.matIdMapper = object.matIdMapper
staticMeshes.push mesh
data.staticGeometries = staticMeshes
data
finish: ->
log.info 'Preloading complete'
@preloadComplete = true
@$container.find('canvas').remove()
db.data @data
Backbone.history.loadUrl @redirectTo
return Preloader |
[
{
"context": "it id if the repo or ref changes.\n key = [ownerName, repoName, resolved.ref].join '/'\n if key != @contextKey\n",
"end": 5019,
"score": 0.7079018354415894,
"start": 5004,
"tag": "KEY",
"value": "Name, repoName,"
},
{
"context": "nges.\n key = [ownerName, repoName, resolved.ref].join '/'\n if key != @contextKey\n @contextKey = key",
"end": 5042,
"score": 0.911683976650238,
"start": 5034,
"tag": "KEY",
"value": "join '/'"
},
{
"context": " entries: children\n dst:\n ownerName: @owner\n repoName: @name\n NogFiles.call.addToDa",
"end": 18573,
"score": 0.8909511566162109,
"start": 18567,
"tag": "USERNAME",
"value": "@owner"
},
{
"context": "dst:\n ownerName: @owner\n repoName: @name\n NogFiles.call.addToDatalist opts, (err, res) ",
"end": 18597,
"score": 0.7349810600280762,
"start": 18593,
"tag": "USERNAME",
"value": "name"
},
{
"context": "itId: pdat1.commitId\n dst:\n ownerName: @owner\n repoName: @name\n NogFiles.call.addProg",
"end": 23339,
"score": 0.9907959699630737,
"start": 23333,
"tag": "USERNAME",
"value": "@owner"
},
{
"context": "dst:\n ownerName: @owner\n repoName: @name\n NogFiles.call.addProgram opts, (err, res) ->\n",
"end": 23363,
"score": 0.9143775105476379,
"start": 23359,
"tag": "USERNAME",
"value": "name"
},
{
"context": "itId: pdat1.commitId\n dst:\n ownerName: @owner\n repoName: @name\n NogFlow.call.addProgr",
"end": 24030,
"score": 0.9924739599227905,
"start": 24024,
"tag": "USERNAME",
"value": "@owner"
},
{
"context": "dst:\n ownerName: @owner\n repoName: @name\n NogFlow.call.addProgramToRegistry opts, (err,",
"end": 24054,
"score": 0.9101371169090271,
"start": 24050,
"tag": "USERNAME",
"value": "name"
},
{
"context": "get version', opts, err\n return\n key = EJSON.stringify _.pick(\n res, 'ownerName', 're",
"end": 35544,
"score": 0.8134974837303162,
"start": 35539,
"tag": "KEY",
"value": "EJSON"
},
{
"context": ": pdat.numericPath\n dependency:\n name: @name\n oldSha1: @sha1\n newSha1: @upst",
"end": 37468,
"score": 0.5803918838500977,
"start": 37468,
"tag": "USERNAME",
"value": ""
}
] | packages/nog-tree/nog-tree-ui.coffee | nogproject/nog | 0 | {defaultErrorHandler} = NogError
{asXiBUnit} = NogFmt
routerPath = (route, opts) -> FlowRouter.path route, opts
NULL_SHA1 = '0000000000000000000000000000000000000000'
if (c = NogApp?.subsCache)?
console.log 'Using main subs cache'
subsCache = c
else
subsCache = new SubsCache()
iskind = (entry, kind) -> _.isObject(entry.meta[kind])
iskindDatalist = (tree) -> iskind tree, 'datalist'
iskindPrograms = (tree) -> iskind tree, 'programs'
iskindJob = (tree) -> iskind tree, 'job'
iskindPackage = (tree) -> iskind tree, 'package'
iskindWorkspace = (tree) -> iskind tree, 'workspace'
iskindProgramRegistry = (tree) -> iskind tree, 'programRegistry'
iskindCatalog = (tree) -> iskind tree, 'catalog'
mayModifyRepo = (repo) ->
aopts = {ownerName: repo.owner, repoName: repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
entryContent = (e) ->
if e.type == 'object'
NogContent.objects.findOne e.sha1
else if e.type == 'tree'
NogContent.trees.findOne e.sha1
else
e
# Register entry representations: object reprs and tree reprs separately.
# XXX: The nog-flow-related representation should perhaps be moved to
# nog-repr-flow, where code could be shared to implement nog-file views, in
# case such views become relevant.
Meteor.startup ->
NogTree.registerEntryRepr
selector: (ctx) ->
unless ctx.last.type == 'object'
return null
content = ctx.last.content
name = content.name
if name == 'params' and iskind(content, 'program')
'objectReprProgramParams'
else if name == 'runtime' and iskind(content, 'program')
'objectReprProgramRuntime'
else
null
isWorkspaceProgramTree = (ctx) ->
(
ctx.contentPath.length == 2 and
iskindWorkspace(ctx.tree.content) and
iskindPrograms(ctx.contentPath[0].content) and
iskindPackage(ctx.last.content)
)
isRegistryProgramTree = (ctx) ->
(
ctx.contentPath.length == 2 and
iskindProgramRegistry(ctx.tree.content) and
iskindPrograms(ctx.contentPath[0].content) and
iskindPackage(ctx.last.content)
)
Meteor.startup ->
NogTree.registerEntryRepr
selector: (ctx) ->
unless ctx.last.type == 'tree'
return null
content = ctx.last.content
if iskindDatalist content
'treeReprDatalist'
else if isWorkspaceProgramTree ctx
'treeReprWorkspaceProgram'
else if isRegistryProgramTree ctx
'treeReprRegistryProgram'
else
null
# Provide a file scope function to reset the stable commit from anywhere until
# we have a better solution. A possible solution would be to put the stable
# commit into the query part of the URL. We rely on the URL for hrefs anyway.
# There can only be a single instance of treeContent at a time. So we can
# simply use the global state directly.
treeContentInstance = null
clearStable = ->
unless treeContentInstance
return
treeContentInstance.commitId.set null
Template.tree.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
treeCtx: ->
{
ownerName: FlowRouter.getParam('ownerName')
repoName: FlowRouter.getParam('repoName')
refTreePath: FlowRouter.getParam('refTreePath')
}
# Manage subscriptions explicitly in order to use `SubsCache`.
# `template.autorun` will automatically terminate when the template is
# destroyed and subscriptions inside an autorun will be automatically stopped,
# so it is nearly as good as `template.subscribe`. But we cannot use the
# template helper `Template.subscriptionsReady`, so we manage subscriptions in
# `subs` and provide the helper `isReady`. `subs` must be reactive in order to
# rerun `isReady` when the subscriptions change.
Template.treeContent.onCreated ->
treeContentInstance = @
@contextKey = null
@commitId = new ReactiveVar null
@subs = new ReactiveVar []
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
repoId = repo._id
NogRepoSettings.call.addToRecentRepos {repoId}, (err, res) ->
if err
return defaultErrorHandler err
@autorun =>
subs = []
subs.push subsCache.subscribe 'targetDatalists'
subs.push subsCache.subscribe 'targetProgramWorkspaces'
subs.push subsCache.subscribe 'targetProgramRegistries'
data = Template.currentData()
ownerName = data.ownerName
repoName = data.repoName
refTreePath = data.refTreePath
subs.push subsCache.subscribe 'repoWithRefTreePath',
repo:
owner: ownerName
name: repoName
refTreePath: refTreePath
@subs.set subs
repo = NogContent.repos.findOne {owner: ownerName, name: repoName}
unless repo?
return
unless (resolved = NogContent.resolveRefTreePath repo, refTreePath)?
return
# Reset stable commit id if the repo or ref changes.
key = [ownerName, repoName, resolved.ref].join '/'
if key != @contextKey
@contextKey = key
@commitId.set null
# Do not capture the commit id when browsing by id, since there cannot be
# updates.
if resolved.refType is 'id'
@commitId.set null
return
# When browsing by branch name, capture the current commit id for the
# change warning.
if not (@commitId.get())?
{commitId} = resolved
@commitId.set commitId
Template.treeContent.events
'click .js-latest': (ev, tpl) ->
ev.preventDefault()
tpl.commitId.set null
'click .js-previous': (ev, tpl) ->
ev.preventDefault()
params =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: tpl.commitId.get() + '/' + @treePath
if @last.type is 'tree'
FlowRouter.go 'repoTree', params
else
FlowRouter.go 'repoObject', params
Template.treeContent.helpers
isReady: ->
tpl = Template.instance()
_.all tpl.subs.get(), (s) -> s.ready()
reprTemplate: ->
NogTree.selectEntryRepr(@) ? 'entryReprDefault'
failResolveReason: ->
tpl = Template.instance()
ownerName = @ownerName
repoName = @repoName
sel = {owner: ownerName, name: repoName}
if NogContent.repos.findOne sel
return {pathResolveFailed: true}
sel = {oldFullNames: "#{ownerName}/#{repoName}"}
if (r = NogContent.repos.findOne sel)?
return {repoIsRenamed: true, newFullName: r.fullName}
return {repoIsUnknown: true}
resolvedPath: ->
tpl = Template.instance()
ownerName = @ownerName
repoName = @repoName
repoSel = {owner: ownerName, name: repoName}
unless (repo = NogContent.repos.findOne repoSel)?
return null
refTreePath = @refTreePath
NogContent.resolveRefTreePath repo, refTreePath
refHasChanged: ->
tpl = Template.instance()
prev = tpl.commitId.get()
(prev? and @commitId != prev)
rootHref: ->
href = routerPath 'repoTree',
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @ref
{href, name: @repo.name}
pathHrefs: ->
[initial..., last] = @namePath
hrefs = []
path = ''
for name in initial
path += "/#{name}"
hrefs.push
name: name
href: routerPath 'repoTree',
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @ref + path
if last?
hrefs.push {name: last}
hrefs
viewerInfo: ->
ownerName = @ownerName
repoName = @repoName
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
if (commit = NogContent.commits.findOne(repo.refs['branches/master']))?
if (tree = NogContent.trees.findOne(commit.tree))?
refTreePath = FlowRouter.getParam('refTreePath') ? ''
resolved = NogContent.resolveRefTreePath repo, refTreePath
{
fullName: repo.fullName
type: resolved.last.type
treePath: refTreePath.replace(/^master\/?/,'')
iskindWorkspace: iskindWorkspace(tree)
currentIsTechnical: true
iskindCatalog: iskindCatalog(tree)
}
Template.entryReprDefault.helpers
isTree: ->
@last.type is 'tree'
isObject: ->
@last.type is 'object'
Template.treeEntriesWithInlineMarkdown.helpers
resolvedInlineObject: ->
{repo, refTreePath} = @
for p in ['index.md', 'README.md', 'summary.md', 'report.md']
if (child = NogContent.resolveRefTreePath repo, refTreePath + '/' + p)?
return child
return null
Template.treeReprDatalist.helpers
mayUpload: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
# Manage the active info tab as global session state to maintain it when
# browsing to other repos.
#
# See <http://getbootstrap.com/javascript/#tabs-events>
Session.setDefault 'treeInfoTabs.current', 'summary'
Template.treeInfoTabs.events
'shown.bs.tab': (ev) ->
tabId = $(ev.target).attr('href')[1..]
Session.set 'treeInfoTabs.current', tabId
Template.treeInfoTabs.helpers
description: -> @last.content.meta.description
summaryActive: -> treeInfoTabsActive 'summary'
metaActive: -> treeInfoTabsActive 'meta'
historyActive: -> treeInfoTabsActive 'history'
iskindJob: -> iskindJob @last.content
treeInfoTabsActive = (tabId) ->
if Session.equals 'treeInfoTabs.current', tabId
'active'
else
null
Template.commitInfo.helpers
commitHref: ->
routeParams =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @commit._id
return {
subject: @commit.subject
shortId: @commit._id[0...10]
href: routerPath 'repoTree', routeParams
}
author: ->
@commit.authors[0]
authorRelDate: ->
@commit.authorDate.fromNow()
Template.refDropdown.helpers
titlePrefix: ->
switch @refType
when 'id' then 'commit'
when 'branch' then 'branch'
title: ->
switch @refType
when 'id' then @ref[0...10]
when 'branch' then @ref
isIdRef: -> @refType == 'id'
entries: ->
routeName = switch @last.type
when 'object' then 'repoObject'
when 'tree' then 'repoTree'
routeParams =
ownerName: @repo.owner
repoName: @repo.name
for refName of @repo.refs
[ty, name...] = refName.split '/'
{
name: name.join('/')
href: routerPath routeName, _.extend routeParams, {
refTreePath: [name, @namePath...].join('/')
}
}
hasKindChild = (tree, kind) ->
for e in tree.entries
e = entryContent(e)
if iskind e, kind
return true
return false
Template.workspaceActions.helpers
addMenuItems: ->
items = [
{name: 'Datalist', kind: 'datalist'}
{name: 'Programs', kind: 'programs'}
{name: 'Log', kind: 'log'}
]
for i in items
if hasKindChild @last.content, i.kind
i.disabled = 'disabled'
items
Template.workspaceActions.events
'click .js-add': (ev) ->
ev.preventDefault()
repo = Template.parentData(0).repo
opts =
ownerName: repo.owner
repoName: repo.name
kind: @kind
NogFlow.call.addWorkspaceKindTree opts, (err, res) ->
if err
return defaultErrorHandler err
Template.treeEntries.onCreated ->
@isEditing = new ReactiveVar(false)
editingCacheKey = null
@isSelected = new ReactiveDict()
@action = new ReactiveVar()
@editNames = new ReactiveDict()
@isModifiedName = new ReactiveDict()
@selectEntry = (idx) =>
@isSelected.set(idx, true)
@deselectEntry = (idx) =>
@isSelected.set(idx, false)
@selectAllEntries = (n) =>
for i in [0...n]
@selectEntry i
@deselectAllEntries = (n) =>
for i in [0...n]
@deselectEntry i
@clearAllEditNames = (n) =>
for i in [0...n]
@editNames.set(i, null)
@isModifiedName.set(i, false)
@autorun =>
# Stop editing and clear selection when navigating to a different path.
dat = Template.currentData()
ownerName = dat.repo.owner
repoName = dat.repo.name
editingCacheKey = [ownerName, repoName, dat.refTreePath].join('/')
if editingCacheKey != @editingCacheKey
@isEditing.set false
@deselectAllEntries dat.last.content.entries.length
@clearAllEditNames dat.last.content.entries.length
@editingCacheKey = editingCacheKey
Template.treeEntries.helpers
action: ->
tpl = Template.instance()
tpl.action.get()
isEditing: ->
tpl = Template.instance()
return tpl.isEditing.get()
isWorkspaceProgram: ->
pdat = Template.parentData(1)
return (
iskindWorkspace(pdat.tree.content) and
iskindPrograms(pdat.last.content) and
iskindPackage(@content)
)
isProgramPackage: ->
parent = Template.parentData(1).last.content
return (iskindPrograms(parent) and iskindPackage(@content))
# Rules for data dropdown:
#
# - Do not show it in a program registry.
# - Do not show it at the first level of a workspace.
# - Do not show it in the `programs` subtree of a workspace.
# - Show it everywhere in generic repos.
#
shouldShowDataEntryDropdown: ->
pdat = Template.currentData()
if iskindProgramRegistry(pdat.tree.content)
return false
if iskindWorkspace(pdat.tree.content)
if pdat.contentPath.length < 1
return false
if iskindPrograms(pdat.contentPath[0].content)
return false
return true
mayModify: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
isEntryNameModified: ->
tpl = Template.instance()
tpl.isModifiedName.get(@index)
isAnyEntryNameModified: ->
tpl = Template.instance()
nEntries = @last.content.entries.length
for i in [0...nEntries]
if tpl.isModifiedName.get(i)
return true
return false
entries: ->
tpl = Template.instance()
pathParams =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: [@ref, @namePath...].join('/')
# hrefs default to names, and use `index!` only if necessary to
# disambiguate identical names. `usedNames` tracks the names that have
# been used. If a name is encountered again, `index!` is used instead.
usedNames = {}
for e, idx in @last.content.entries
switch e.type
when 'object'
content = NogContent.objects.findOne(e.sha1)
icon = 'file'
routeName = 'repoObject'
when 'tree'
content = NogContent.trees.findOne(e.sha1)
icon = 'folder-close'
routeName = 'repoTree'
if content
name = content.name
if usedNames[name]?
tail = "index!#{idx}"
else
tail = name
usedNames[name] = true
routeParams = _.clone pathParams
routeParams.refTreePath += '/' + tail
treePath = @treePath + '/' + tail
{
name
icon
href: routerPath routeName, routeParams
description: content.meta.description
type: e.type
sha1: e.sha1
treePath
content
index: idx
isSelected: tpl.isSelected.get(idx)
}
Template.treeEntries.events
'click .js-toggle-entry': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.isSelected.set(@index, !tpl.isSelected.get(@index))
if tpl.isSelected.get(@index)
tpl.isEditing.set(true)
else
pdat = Template.parentData(0)
nEntries = pdat.last.content.entries.length
tpl.isEditing.set(false)
for i in [0...nEntries]
if tpl.isSelected.get(i)
tpl.isEditing.set(true)
if !tpl.isEditing.get()
tpl.clearAllEditNames @last.content.entries.length
'click .js-select-all': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectAllEntries @last.content.entries.length
tpl.isEditing.set(true)
'click .js-deselect-all': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.deselectAllEntries @last.content.entries.length
tpl.isEditing.set(false)
tpl.clearAllEditNames @last.content.entries.length
'click .js-delete': (ev) ->
ev.preventDefault()
tpl = Template.instance()
nEntries = @last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
children.push(i)
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
children
}
tpl.action.set 'deleting'
NogFiles.call.deleteChildren opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
clearStable()
'keyup .js-name-val': (ev) ->
val = $(ev.target).text()
tpl = Template.instance()
isModified = (val != @name)
tpl.editNames.set(@index, val)
tpl.isModifiedName.set(@index, isModified)
'click .js-rename': (ev) ->
ev.preventDefault()
tpl = Template.instance()
nEntries = @last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isModifiedName.get(i)
children.push
index: i
newName: tpl.editNames.get(i)
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
children
}
tpl.action.set 'renaming'
NogFiles.call.renameChildren opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
clearStable()
'click .js-starred': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
alert 'starred datalist not yet implemented'
# The event is emitted by `dataEntryDropdown` but handled here, since it
# requires the selection.
'click .js-add-to': (ev) ->
ev.preventDefault()
tpl = Template.instance()
dat = Template.currentData()
nEntries = dat.last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
entry = dat.last.content.entries[i]
children.push
type: entry.type
sha1: entry.sha1
tpl.action.set 'adding'
srcrepo = dat.repo
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
commitId: dat.commitId
entries: children
dst:
ownerName: @owner
repoName: @name
NogFiles.call.addToDatalist opts, (err, res) ->
if err
tpl.action.set null
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
# Don't clearStable(), since entries are usually added to another repo.
# We warn the user if the current repo gets modified.
tpl.action.set 'added'
clearOp = -> tpl.action.set null
setTimeout clearOp, 1000
'click .js-new-datalist': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
tpl = Template.instance()
tpl.$('.js-new-datalist-modal').modal()
# The event is emitted by `dataEntryDropdown` but handled here, since it
# requires the selection.
'click .js-create-and-add': (ev) ->
tpl = Template.instance()
dat = Template.currentData()
nEntries = dat.last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
entry = dat.last.content.entries[i]
children.push
type: entry.type
sha1: entry.sha1
name = tpl.$('.js-new-repo-name').val()
name = sanitizedRepoName name
tpl.action.set 'creating'
srcrepo = dat.repo
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
commitId: dat.commitId
entries: children
dst:
create: true
ownerName: Meteor.user().username
repoName: name
NogFiles.call.addToDatalist opts, (err, res) ->
tpl.$('.js-new-datalist-modal').modal('hide')
if err
tpl.action.set null
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
# Don't clearStable(), since entries are usually added to another repo.
# We warn the user if the current repo gets modified.
tpl.action.set 'created and added'
clearOp = -> tpl.action.set null
setTimeout clearOp, 1000
Template.treeEntriesAddFolder.onCreated ->
@inputIsEmpty = new ReactiveVar true
Template.treeEntriesAddFolder.helpers
inputIsEmpty: ->
tpl = Template.instance()
tpl.inputIsEmpty.get()
Template.treeEntriesAddFolder.events
'click .js-addFolder-start': (ev) ->
tpl = Template.instance()
tpl.$('.js-addFolder-modal').modal()
'keyup .js-addFolder-name': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-addFolder-name').val()
if name != ""
tpl.inputIsEmpty.set false
else
tpl.inputIsEmpty.set true
'click .js-addFolder-complete': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-addFolder-name').val()
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
folderName: name
}
NogFiles.call.addSubtree opts, (err, res) ->
if err
return defaultErrorHandler err
tpl.$('.js-addFolder-modal').modal('hide')
suggestRepoNameForEntry = (e) ->
parts = []
if (study = e.meta.study)?
parts.push study
if (specimen = e.meta.specimen)?
parts.push specimen
if parts.length == 0
parts.push e.name.split('.')[0]
parts.join('_')
sanitizedRepoName = (n) ->
n = n.replace /[^a-zA-Z0-9._-]/g, '_'
n = n.replace /__+/g, '__'
n
Template.dataEntryDropdown.helpers
dstWorkspaces: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['workspace', 'datalist']}
Template.newDatalistModal.onCreated ->
@inputIsEmpty = new ReactiveVar true
Template.newDatalistModal.events
'keyup .js-new-repo-name': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-new-repo-name').val()
if name != ""
tpl.inputIsEmpty.set false
else
tpl.inputIsEmpty.set true
Template.newDatalistModal.helpers
inputIsEmpty: ->
tpl = Template.instance()
tpl.inputIsEmpty.get()
Template.programPackageDropdown.onCreated ->
@operation = new ReactiveVar null
Template.programPackageDropdown.helpers
operation: ->
tpl = Template.instance()
tpl.operation.get()
dstWorkspaces: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['workspace', 'programs']}
dstRegistries: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['programRegistry']}
Template.programPackageDropdown.events
'click .js-add-to-workspace': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.operation.set 'Adding...'
pdat1 = Template.parentData(1)
srcrepo = pdat1.repo
entry = Template.currentData()
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
entries: [{sha1: entry.sha1}]
commitId: pdat1.commitId
dst:
ownerName: @owner
repoName: @name
NogFiles.call.addProgram opts, (err, res) ->
if err
tpl.operation.set null
return defaultErrorHandler err
tpl.operation.set 'Added'
clearOp = -> tpl.operation.set null
setTimeout clearOp, 1000
'click .js-add-to-registry': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.operation.set 'adding'
pdat1 = Template.parentData(1)
srcrepo = pdat1.repo
entry = Template.currentData()
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
sha1: entry.sha1
path: entry.treePath
commitId: pdat1.commitId
dst:
ownerName: @owner
repoName: @name
NogFlow.call.addProgramToRegistry opts, (err, res) ->
if err
tpl.operation.set null
return defaultErrorHandler err
tpl.operation.set 'added'
clearOp = -> tpl.operation.set null
setTimeout clearOp, 1000
# `resolveImgSrc()` calls the server to create an S3 link, which is cached
# locally. XXX: Consider factoring-out to a package with nog content helpers.
imgSrcs = new ReactiveDict()
NogContent.resolveImgSrc = (pathParams) ->
hash = EJSON.stringify pathParams
src = imgSrcs.get(hash)
now = new Date()
if not src? or now > src.expire
expire = new Date()
expire.setSeconds(expire.getSeconds() + 600)
src = {isPlaceholder: true, expire, href: 'https://placehold.it/1x1.png'}
imgSrcs.set(hash, src)
Meteor.call 'resolveImgSrc', pathParams, (err, href) ->
if href
src.isPlaceholder = false
src.href = href
imgSrcs.set hash, src
return src
Template.objectReprGeneric.helpers
blobHref: ->
unless (blob = @last.content.blob)?
return
if blob == NULL_SHA1
return
if (blobdoc = NogContent.blobs.findOne(blob))?
fileSize = asXiBUnit(blobdoc.size)
else
fileSize = null
return {
blob
name: @last.content.name
fileSize
}
content: ->
@last.content.meta.content
previewSrc: ->
if not (blob = @last.content.meta.preview?.blob)?
return null
NogContent.resolveImgSrc {
ownerName: @repo.owner
repoName: @repo.name
name: @last.content.meta.preview.type ? 'png'
blob
}
Template.objectReprProgramParams.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.objectReprProgramParams.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
paramsJSON: ->
params = @last.content.meta.program.params
EJSON.stringify params, {indent: true, canonical: true}
Template.objectReprProgramParams.events
'click .js-save-params': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-params').text()
try
params = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(params, @last.content.meta.program.params)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
params
}
tpl.action.set 'Saving...'
Session.set({'blockProgramRunButton': 'Saving'})
NogFlow.call.updateProgramParams opts, (err, res) =>
Session.set({'blockProgramRunButton': null})
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
if (ar = @actionRedirect)?
FlowRouter.go ar
else
FlowRouter.go routerPath('repoObject', res)
Template.objectReprProgramRuntime.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.objectReprProgramRuntime.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
runtimeJSON: ->
runtime = @last.content.meta.program.runtime ? {}
EJSON.stringify runtime, {indent: true, canonical: true}
Template.objectReprProgramRuntime.events
'click .js-save-runtime': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-runtime').text()
try
runtime = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(runtime, @last.content.meta.program.runtime)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
runtime
}
tpl.action.set 'Saving...'
NogFlow.call.updateProgramRuntime opts, (err, res) =>
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
if (ar = @actionRedirect)?
FlowRouter.go ar
else
FlowRouter.go routerPath('repoObject', res)
Template.metaView.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.metaView.events
'click .js-toggle-raw-meta': (ev, tpl) ->
ev.preventDefault()
'click .js-toggle-editing-meta': (ev) ->
ev.preventDefault()
Session.set('isRawMetaEditing', !Session.get('isRawMetaEditing'))
'click .js-save-meta': (ev) ->
ev.preventDefault()
tpl = Template.instance()
text = tpl.$('.js-meta-text').text()
try
proposed = JSON.parse text
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
old = @last.content.meta
if (e = NogFlow.metaChangeViolation(old, proposed))?
tpl.inputError.set e
return
tpl.inputError.set null
if _.isEqual(old, proposed)
return
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
meta: proposed
}
tpl.action.set 'Saving...'
NogFlow.call.setMeta opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.metaView.helpers
isEditing: -> Session.get('isRawMetaEditing')
inputError: ->
tpl = Template.instance()
tpl.inputError.get()
action: ->
tpl = Template.instance()
tpl.action.get()
meta: ->
EJSON.stringify @last.content.meta, {indent: true, canonical: true}
mayModify: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
Template.jobInfo.onCreated ->
@subs = new ReactiveVar []
@autorun =>
subs = []
dat = Template.currentData()
if (jobId = dat.last.content.meta?.job?.id)?
subs.push subsCache.subscribe 'jobStatus', [jobId]
@subs.set subs
Template.jobInfo.helpers
isReady: ->
tpl = Template.instance()
_.all tpl.subs.get(), (s) -> s.ready()
job: ->
unless (id = @last.content.meta?.job?.id)?
return null
NogExec.jobs.findOne({'data.jobId': id})
progressBarClass: ->
switch @status
when 'completed' then 'progress-bar-success'
when 'failed' then 'progress-bar-danger'
else null
progressPct: ->
Math.round(@progress.percent)
showProgressPct: ->
@progress.percent >= 15
# `jobExecutionRepo` returns an href to the repo to which the job results
# will be posted.
jobExecutionRepo: ->
pdat = Template.parentData()
thisRepo = "#{pdat.repo.owner}/#{pdat.repo.name}"
jobRepo = @data.workspaceRepo
if jobRepo == thisRepo
return null
[ownerName, repoName] = jobRepo.split('/')
{refTreePath} = pdat
href = routerPath 'repoTree', {ownerName, repoName, refTreePath}
return {
fullName: jobRepo
href
}
failure: ->
if @failures?.length
{
reason: (f.reason for f in @failures).join('. ')
}
else if @status == 'cancelled'
{
reason: 'Cancelled due to lack of progress.'
}
else
null
# FIXME: Notice that master has updated causes flickering.
Template.uploadToDatalist.events
'change .js-upload-files': (e) ->
e.preventDefault()
dat = Template.currentData()
for f in e.target.files
id = NogBlob.uploadFile f, (err, res) ->
if err
return defaultErrorHandler err
opts = {
ownerName: dat.repo.owner
repoName: dat.repo.name
numericPath: dat.numericPath
name: res.filename
blob: res.sha1
}
_id = res._id
NogFiles.call.addBlobToDatalist opts, (err, res) ->
if err
return defaultErrorHandler err
cleanup = -> NogBlob.files.remove _id
setTimeout cleanup, 1000
clearStable()
Template.uploadToDatalist.helpers
uploads: -> NogBlob.files.find()
Template.uploadToDatalist.helpers _.pick(
NogBlob.fileHelpers, 'name', 'progressWidth', 'uploadCompleteClass',
'sha1Progress', 'sha1', 'haveSha1'
)
Template.treeReprRegistryProgram.helpers
name: ->
@last.content.name
authors: ->
as = @last.content.meta.package?.authors ? []
(a.name for a in as).join(', ')
latestVersion: ->
entryContent(@last.content.entries[0])?.name
resolvedReadme: ->
{repo, refTreePath} = @
NogContent.resolveRefTreePath repo, refTreePath + '/index!0/README.md'
Template.treeReprWorkspaceProgram.helpers
mayRunProgram: -> mayModifyRepo @repo
name: ->
@last.content.name
latestVersion: ->
entryContent(@last.content.entries[0])?.name
resolvedReadme: ->
{repo, refTreePath} = @
NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/index!0/README.md'
)
resolvedParams: ->
{repo, refTreePath} = @
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/params'
)
unless resolved?
return
# Redirect 'Save Parameter' back to here.
resolved.actionRedirect = routerPath 'repoTree', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedRuntime: ->
{repo, refTreePath} = @
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/runtime'
)
unless resolved?
return
# Redirect 'Save Runtime Setting' back to here.
resolved.actionRedirect = routerPath 'repoTree', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
Template.treeReprWorkspaceProgramRunButton.onCreated ->
@action = new ReactiveVar()
Template.treeReprWorkspaceProgramRunButton.helpers
action: -> Template.instance().action.get()
blocked: -> Session.get('blockProgramRunButton')
Template.treeReprWorkspaceProgramRunButton.events
'click .js-run': (ev) ->
ev.preventDefault()
opts = {
ownerName: @repo.owner
repoName: @repo.name
commitId: @commit._id
sha1: @last.content._id
}
tpl = Template.instance()
tpl.action.set 'Submitting Job...'
NogFlow.call.runProgram opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
FlowRouter.go routerPath('repoTree', res)
versionString = (v) ->
if v.major?
"#{v.major}.#{v.minor}.#{v.patch}"
else if v.date?
v.date
else if v.sha1?
v.sha1
else
'unknown'
upstreamVersionsCache = new ReactiveDict
getLatestUpstreamVersion = (origin) ->
[ownerName, repoName] = origin.repoFullName.split('/')
unless (repo = NogContent.repos.findOne {owner: ownerName, name: repoName})?
return null
fixedOrigin = {
ownerName
repoName,
packageName: origin.name
commitId: repo.refs['branches/master']
}
cacheKey = EJSON.stringify fixedOrigin, {canonical: true}
ver = upstreamVersionsCache.get cacheKey
unless _.isUndefined(ver)
return ver
getVersion = (opts) ->
NogFlow.call.getPackageVersion opts, (err, res) ->
if err
console.log 'Failed to get version', opts, err
return
key = EJSON.stringify _.pick(
res, 'ownerName', 'repoName', 'packageName', 'commitId'
), {
canonical: true
}
upstreamVersionsCache.set key, res.version
getVersion {ownerName, repoName, packageName: origin.name}
return null
Template.treeReprWorkspaceProgramDeps.helpers
mayUpdateDep: -> mayModifyRepo Template.parentData().repo
deps: ->
latest = entryContent(@last.content.entries[0])
if latest
pkg = latest.meta.package
deps = {}
for d in pkg.dependencies
deps[d.name] = d
for f in pkg.frozen
version = versionString(f)
dep = {
name: f.name
version
sha1: f.sha1
}
if (origin = deps[f.name])?
upstream = getLatestUpstreamVersion origin
if upstream?
dep.upstreamVersion = versionString upstream
dep.upstreamSha1 = upstream.sha1
dep.isUpdateAvailable = (
dep.upstreamVersion? and version != dep.upstreamVersion
)
[ownerName, repoName] = origin.repoFullName.split('/')
dep.origin = {
ownerName
repoName
name: origin.repoFullName
href: '' +
'/' + origin.repoFullName +
'/tree/master/programs/' + origin.name
}
dep
Template.treeReprWorkspaceProgramDepsUpdateButton.onCreated ->
@action = new ReactiveVar()
Template.treeReprWorkspaceProgramDepsUpdateButton.helpers
action: -> Template.instance().action.get()
Template.treeReprWorkspaceProgramDepsUpdateButton.events
'click .js-update-dep': (ev) ->
ev.preventDefault()
tpl = Template.instance()
pdat = Template.parentData()
opts =
ownerName: pdat.repo.owner
repoName: pdat.repo.name
commitId: pdat.commitId
package:
numericPath: pdat.numericPath
dependency:
name: @name
oldSha1: @sha1
newSha1: @upstreamSha1
origin:
ownerName: @origin.ownerName
repoName: @origin.repoName
tpl.action.set 'Updating...'
NogFlow.call.updatePackageDependency opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
| 84490 | {defaultErrorHandler} = NogError
{asXiBUnit} = NogFmt
routerPath = (route, opts) -> FlowRouter.path route, opts
NULL_SHA1 = '0000000000000000000000000000000000000000'
if (c = NogApp?.subsCache)?
console.log 'Using main subs cache'
subsCache = c
else
subsCache = new SubsCache()
iskind = (entry, kind) -> _.isObject(entry.meta[kind])
iskindDatalist = (tree) -> iskind tree, 'datalist'
iskindPrograms = (tree) -> iskind tree, 'programs'
iskindJob = (tree) -> iskind tree, 'job'
iskindPackage = (tree) -> iskind tree, 'package'
iskindWorkspace = (tree) -> iskind tree, 'workspace'
iskindProgramRegistry = (tree) -> iskind tree, 'programRegistry'
iskindCatalog = (tree) -> iskind tree, 'catalog'
mayModifyRepo = (repo) ->
aopts = {ownerName: repo.owner, repoName: repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
entryContent = (e) ->
if e.type == 'object'
NogContent.objects.findOne e.sha1
else if e.type == 'tree'
NogContent.trees.findOne e.sha1
else
e
# Register entry representations: object reprs and tree reprs separately.
# XXX: The nog-flow-related representation should perhaps be moved to
# nog-repr-flow, where code could be shared to implement nog-file views, in
# case such views become relevant.
Meteor.startup ->
NogTree.registerEntryRepr
selector: (ctx) ->
unless ctx.last.type == 'object'
return null
content = ctx.last.content
name = content.name
if name == 'params' and iskind(content, 'program')
'objectReprProgramParams'
else if name == 'runtime' and iskind(content, 'program')
'objectReprProgramRuntime'
else
null
isWorkspaceProgramTree = (ctx) ->
(
ctx.contentPath.length == 2 and
iskindWorkspace(ctx.tree.content) and
iskindPrograms(ctx.contentPath[0].content) and
iskindPackage(ctx.last.content)
)
isRegistryProgramTree = (ctx) ->
(
ctx.contentPath.length == 2 and
iskindProgramRegistry(ctx.tree.content) and
iskindPrograms(ctx.contentPath[0].content) and
iskindPackage(ctx.last.content)
)
Meteor.startup ->
NogTree.registerEntryRepr
selector: (ctx) ->
unless ctx.last.type == 'tree'
return null
content = ctx.last.content
if iskindDatalist content
'treeReprDatalist'
else if isWorkspaceProgramTree ctx
'treeReprWorkspaceProgram'
else if isRegistryProgramTree ctx
'treeReprRegistryProgram'
else
null
# Provide a file scope function to reset the stable commit from anywhere until
# we have a better solution. A possible solution would be to put the stable
# commit into the query part of the URL. We rely on the URL for hrefs anyway.
# There can only be a single instance of treeContent at a time. So we can
# simply use the global state directly.
treeContentInstance = null
clearStable = ->
unless treeContentInstance
return
treeContentInstance.commitId.set null
Template.tree.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
treeCtx: ->
{
ownerName: FlowRouter.getParam('ownerName')
repoName: FlowRouter.getParam('repoName')
refTreePath: FlowRouter.getParam('refTreePath')
}
# Manage subscriptions explicitly in order to use `SubsCache`.
# `template.autorun` will automatically terminate when the template is
# destroyed and subscriptions inside an autorun will be automatically stopped,
# so it is nearly as good as `template.subscribe`. But we cannot use the
# template helper `Template.subscriptionsReady`, so we manage subscriptions in
# `subs` and provide the helper `isReady`. `subs` must be reactive in order to
# rerun `isReady` when the subscriptions change.
Template.treeContent.onCreated ->
treeContentInstance = @
@contextKey = null
@commitId = new ReactiveVar null
@subs = new ReactiveVar []
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
repoId = repo._id
NogRepoSettings.call.addToRecentRepos {repoId}, (err, res) ->
if err
return defaultErrorHandler err
@autorun =>
subs = []
subs.push subsCache.subscribe 'targetDatalists'
subs.push subsCache.subscribe 'targetProgramWorkspaces'
subs.push subsCache.subscribe 'targetProgramRegistries'
data = Template.currentData()
ownerName = data.ownerName
repoName = data.repoName
refTreePath = data.refTreePath
subs.push subsCache.subscribe 'repoWithRefTreePath',
repo:
owner: ownerName
name: repoName
refTreePath: refTreePath
@subs.set subs
repo = NogContent.repos.findOne {owner: ownerName, name: repoName}
unless repo?
return
unless (resolved = NogContent.resolveRefTreePath repo, refTreePath)?
return
# Reset stable commit id if the repo or ref changes.
key = [owner<KEY> resolved.ref].<KEY>
if key != @contextKey
@contextKey = key
@commitId.set null
# Do not capture the commit id when browsing by id, since there cannot be
# updates.
if resolved.refType is 'id'
@commitId.set null
return
# When browsing by branch name, capture the current commit id for the
# change warning.
if not (@commitId.get())?
{commitId} = resolved
@commitId.set commitId
Template.treeContent.events
'click .js-latest': (ev, tpl) ->
ev.preventDefault()
tpl.commitId.set null
'click .js-previous': (ev, tpl) ->
ev.preventDefault()
params =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: tpl.commitId.get() + '/' + @treePath
if @last.type is 'tree'
FlowRouter.go 'repoTree', params
else
FlowRouter.go 'repoObject', params
Template.treeContent.helpers
isReady: ->
tpl = Template.instance()
_.all tpl.subs.get(), (s) -> s.ready()
reprTemplate: ->
NogTree.selectEntryRepr(@) ? 'entryReprDefault'
failResolveReason: ->
tpl = Template.instance()
ownerName = @ownerName
repoName = @repoName
sel = {owner: ownerName, name: repoName}
if NogContent.repos.findOne sel
return {pathResolveFailed: true}
sel = {oldFullNames: "#{ownerName}/#{repoName}"}
if (r = NogContent.repos.findOne sel)?
return {repoIsRenamed: true, newFullName: r.fullName}
return {repoIsUnknown: true}
resolvedPath: ->
tpl = Template.instance()
ownerName = @ownerName
repoName = @repoName
repoSel = {owner: ownerName, name: repoName}
unless (repo = NogContent.repos.findOne repoSel)?
return null
refTreePath = @refTreePath
NogContent.resolveRefTreePath repo, refTreePath
refHasChanged: ->
tpl = Template.instance()
prev = tpl.commitId.get()
(prev? and @commitId != prev)
rootHref: ->
href = routerPath 'repoTree',
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @ref
{href, name: @repo.name}
pathHrefs: ->
[initial..., last] = @namePath
hrefs = []
path = ''
for name in initial
path += "/#{name}"
hrefs.push
name: name
href: routerPath 'repoTree',
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @ref + path
if last?
hrefs.push {name: last}
hrefs
viewerInfo: ->
ownerName = @ownerName
repoName = @repoName
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
if (commit = NogContent.commits.findOne(repo.refs['branches/master']))?
if (tree = NogContent.trees.findOne(commit.tree))?
refTreePath = FlowRouter.getParam('refTreePath') ? ''
resolved = NogContent.resolveRefTreePath repo, refTreePath
{
fullName: repo.fullName
type: resolved.last.type
treePath: refTreePath.replace(/^master\/?/,'')
iskindWorkspace: iskindWorkspace(tree)
currentIsTechnical: true
iskindCatalog: iskindCatalog(tree)
}
Template.entryReprDefault.helpers
isTree: ->
@last.type is 'tree'
isObject: ->
@last.type is 'object'
Template.treeEntriesWithInlineMarkdown.helpers
resolvedInlineObject: ->
{repo, refTreePath} = @
for p in ['index.md', 'README.md', 'summary.md', 'report.md']
if (child = NogContent.resolveRefTreePath repo, refTreePath + '/' + p)?
return child
return null
Template.treeReprDatalist.helpers
mayUpload: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
# Manage the active info tab as global session state to maintain it when
# browsing to other repos.
#
# See <http://getbootstrap.com/javascript/#tabs-events>
Session.setDefault 'treeInfoTabs.current', 'summary'
Template.treeInfoTabs.events
'shown.bs.tab': (ev) ->
tabId = $(ev.target).attr('href')[1..]
Session.set 'treeInfoTabs.current', tabId
Template.treeInfoTabs.helpers
description: -> @last.content.meta.description
summaryActive: -> treeInfoTabsActive 'summary'
metaActive: -> treeInfoTabsActive 'meta'
historyActive: -> treeInfoTabsActive 'history'
iskindJob: -> iskindJob @last.content
treeInfoTabsActive = (tabId) ->
if Session.equals 'treeInfoTabs.current', tabId
'active'
else
null
Template.commitInfo.helpers
commitHref: ->
routeParams =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @commit._id
return {
subject: @commit.subject
shortId: @commit._id[0...10]
href: routerPath 'repoTree', routeParams
}
author: ->
@commit.authors[0]
authorRelDate: ->
@commit.authorDate.fromNow()
Template.refDropdown.helpers
titlePrefix: ->
switch @refType
when 'id' then 'commit'
when 'branch' then 'branch'
title: ->
switch @refType
when 'id' then @ref[0...10]
when 'branch' then @ref
isIdRef: -> @refType == 'id'
entries: ->
routeName = switch @last.type
when 'object' then 'repoObject'
when 'tree' then 'repoTree'
routeParams =
ownerName: @repo.owner
repoName: @repo.name
for refName of @repo.refs
[ty, name...] = refName.split '/'
{
name: name.join('/')
href: routerPath routeName, _.extend routeParams, {
refTreePath: [name, @namePath...].join('/')
}
}
hasKindChild = (tree, kind) ->
for e in tree.entries
e = entryContent(e)
if iskind e, kind
return true
return false
Template.workspaceActions.helpers
addMenuItems: ->
items = [
{name: 'Datalist', kind: 'datalist'}
{name: 'Programs', kind: 'programs'}
{name: 'Log', kind: 'log'}
]
for i in items
if hasKindChild @last.content, i.kind
i.disabled = 'disabled'
items
Template.workspaceActions.events
'click .js-add': (ev) ->
ev.preventDefault()
repo = Template.parentData(0).repo
opts =
ownerName: repo.owner
repoName: repo.name
kind: @kind
NogFlow.call.addWorkspaceKindTree opts, (err, res) ->
if err
return defaultErrorHandler err
Template.treeEntries.onCreated ->
@isEditing = new ReactiveVar(false)
editingCacheKey = null
@isSelected = new ReactiveDict()
@action = new ReactiveVar()
@editNames = new ReactiveDict()
@isModifiedName = new ReactiveDict()
@selectEntry = (idx) =>
@isSelected.set(idx, true)
@deselectEntry = (idx) =>
@isSelected.set(idx, false)
@selectAllEntries = (n) =>
for i in [0...n]
@selectEntry i
@deselectAllEntries = (n) =>
for i in [0...n]
@deselectEntry i
@clearAllEditNames = (n) =>
for i in [0...n]
@editNames.set(i, null)
@isModifiedName.set(i, false)
@autorun =>
# Stop editing and clear selection when navigating to a different path.
dat = Template.currentData()
ownerName = dat.repo.owner
repoName = dat.repo.name
editingCacheKey = [ownerName, repoName, dat.refTreePath].join('/')
if editingCacheKey != @editingCacheKey
@isEditing.set false
@deselectAllEntries dat.last.content.entries.length
@clearAllEditNames dat.last.content.entries.length
@editingCacheKey = editingCacheKey
Template.treeEntries.helpers
action: ->
tpl = Template.instance()
tpl.action.get()
isEditing: ->
tpl = Template.instance()
return tpl.isEditing.get()
isWorkspaceProgram: ->
pdat = Template.parentData(1)
return (
iskindWorkspace(pdat.tree.content) and
iskindPrograms(pdat.last.content) and
iskindPackage(@content)
)
isProgramPackage: ->
parent = Template.parentData(1).last.content
return (iskindPrograms(parent) and iskindPackage(@content))
# Rules for data dropdown:
#
# - Do not show it in a program registry.
# - Do not show it at the first level of a workspace.
# - Do not show it in the `programs` subtree of a workspace.
# - Show it everywhere in generic repos.
#
shouldShowDataEntryDropdown: ->
pdat = Template.currentData()
if iskindProgramRegistry(pdat.tree.content)
return false
if iskindWorkspace(pdat.tree.content)
if pdat.contentPath.length < 1
return false
if iskindPrograms(pdat.contentPath[0].content)
return false
return true
mayModify: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
isEntryNameModified: ->
tpl = Template.instance()
tpl.isModifiedName.get(@index)
isAnyEntryNameModified: ->
tpl = Template.instance()
nEntries = @last.content.entries.length
for i in [0...nEntries]
if tpl.isModifiedName.get(i)
return true
return false
entries: ->
tpl = Template.instance()
pathParams =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: [@ref, @namePath...].join('/')
# hrefs default to names, and use `index!` only if necessary to
# disambiguate identical names. `usedNames` tracks the names that have
# been used. If a name is encountered again, `index!` is used instead.
usedNames = {}
for e, idx in @last.content.entries
switch e.type
when 'object'
content = NogContent.objects.findOne(e.sha1)
icon = 'file'
routeName = 'repoObject'
when 'tree'
content = NogContent.trees.findOne(e.sha1)
icon = 'folder-close'
routeName = 'repoTree'
if content
name = content.name
if usedNames[name]?
tail = "index!#{idx}"
else
tail = name
usedNames[name] = true
routeParams = _.clone pathParams
routeParams.refTreePath += '/' + tail
treePath = @treePath + '/' + tail
{
name
icon
href: routerPath routeName, routeParams
description: content.meta.description
type: e.type
sha1: e.sha1
treePath
content
index: idx
isSelected: tpl.isSelected.get(idx)
}
Template.treeEntries.events
'click .js-toggle-entry': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.isSelected.set(@index, !tpl.isSelected.get(@index))
if tpl.isSelected.get(@index)
tpl.isEditing.set(true)
else
pdat = Template.parentData(0)
nEntries = pdat.last.content.entries.length
tpl.isEditing.set(false)
for i in [0...nEntries]
if tpl.isSelected.get(i)
tpl.isEditing.set(true)
if !tpl.isEditing.get()
tpl.clearAllEditNames @last.content.entries.length
'click .js-select-all': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectAllEntries @last.content.entries.length
tpl.isEditing.set(true)
'click .js-deselect-all': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.deselectAllEntries @last.content.entries.length
tpl.isEditing.set(false)
tpl.clearAllEditNames @last.content.entries.length
'click .js-delete': (ev) ->
ev.preventDefault()
tpl = Template.instance()
nEntries = @last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
children.push(i)
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
children
}
tpl.action.set 'deleting'
NogFiles.call.deleteChildren opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
clearStable()
'keyup .js-name-val': (ev) ->
val = $(ev.target).text()
tpl = Template.instance()
isModified = (val != @name)
tpl.editNames.set(@index, val)
tpl.isModifiedName.set(@index, isModified)
'click .js-rename': (ev) ->
ev.preventDefault()
tpl = Template.instance()
nEntries = @last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isModifiedName.get(i)
children.push
index: i
newName: tpl.editNames.get(i)
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
children
}
tpl.action.set 'renaming'
NogFiles.call.renameChildren opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
clearStable()
'click .js-starred': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
alert 'starred datalist not yet implemented'
# The event is emitted by `dataEntryDropdown` but handled here, since it
# requires the selection.
'click .js-add-to': (ev) ->
ev.preventDefault()
tpl = Template.instance()
dat = Template.currentData()
nEntries = dat.last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
entry = dat.last.content.entries[i]
children.push
type: entry.type
sha1: entry.sha1
tpl.action.set 'adding'
srcrepo = dat.repo
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
commitId: dat.commitId
entries: children
dst:
ownerName: @owner
repoName: @name
NogFiles.call.addToDatalist opts, (err, res) ->
if err
tpl.action.set null
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
# Don't clearStable(), since entries are usually added to another repo.
# We warn the user if the current repo gets modified.
tpl.action.set 'added'
clearOp = -> tpl.action.set null
setTimeout clearOp, 1000
'click .js-new-datalist': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
tpl = Template.instance()
tpl.$('.js-new-datalist-modal').modal()
# The event is emitted by `dataEntryDropdown` but handled here, since it
# requires the selection.
'click .js-create-and-add': (ev) ->
tpl = Template.instance()
dat = Template.currentData()
nEntries = dat.last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
entry = dat.last.content.entries[i]
children.push
type: entry.type
sha1: entry.sha1
name = tpl.$('.js-new-repo-name').val()
name = sanitizedRepoName name
tpl.action.set 'creating'
srcrepo = dat.repo
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
commitId: dat.commitId
entries: children
dst:
create: true
ownerName: Meteor.user().username
repoName: name
NogFiles.call.addToDatalist opts, (err, res) ->
tpl.$('.js-new-datalist-modal').modal('hide')
if err
tpl.action.set null
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
# Don't clearStable(), since entries are usually added to another repo.
# We warn the user if the current repo gets modified.
tpl.action.set 'created and added'
clearOp = -> tpl.action.set null
setTimeout clearOp, 1000
Template.treeEntriesAddFolder.onCreated ->
@inputIsEmpty = new ReactiveVar true
Template.treeEntriesAddFolder.helpers
inputIsEmpty: ->
tpl = Template.instance()
tpl.inputIsEmpty.get()
Template.treeEntriesAddFolder.events
'click .js-addFolder-start': (ev) ->
tpl = Template.instance()
tpl.$('.js-addFolder-modal').modal()
'keyup .js-addFolder-name': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-addFolder-name').val()
if name != ""
tpl.inputIsEmpty.set false
else
tpl.inputIsEmpty.set true
'click .js-addFolder-complete': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-addFolder-name').val()
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
folderName: name
}
NogFiles.call.addSubtree opts, (err, res) ->
if err
return defaultErrorHandler err
tpl.$('.js-addFolder-modal').modal('hide')
suggestRepoNameForEntry = (e) ->
parts = []
if (study = e.meta.study)?
parts.push study
if (specimen = e.meta.specimen)?
parts.push specimen
if parts.length == 0
parts.push e.name.split('.')[0]
parts.join('_')
sanitizedRepoName = (n) ->
n = n.replace /[^a-zA-Z0-9._-]/g, '_'
n = n.replace /__+/g, '__'
n
Template.dataEntryDropdown.helpers
dstWorkspaces: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['workspace', 'datalist']}
Template.newDatalistModal.onCreated ->
@inputIsEmpty = new ReactiveVar true
Template.newDatalistModal.events
'keyup .js-new-repo-name': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-new-repo-name').val()
if name != ""
tpl.inputIsEmpty.set false
else
tpl.inputIsEmpty.set true
Template.newDatalistModal.helpers
inputIsEmpty: ->
tpl = Template.instance()
tpl.inputIsEmpty.get()
Template.programPackageDropdown.onCreated ->
@operation = new ReactiveVar null
Template.programPackageDropdown.helpers
operation: ->
tpl = Template.instance()
tpl.operation.get()
dstWorkspaces: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['workspace', 'programs']}
dstRegistries: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['programRegistry']}
Template.programPackageDropdown.events
'click .js-add-to-workspace': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.operation.set 'Adding...'
pdat1 = Template.parentData(1)
srcrepo = pdat1.repo
entry = Template.currentData()
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
entries: [{sha1: entry.sha1}]
commitId: pdat1.commitId
dst:
ownerName: @owner
repoName: @name
NogFiles.call.addProgram opts, (err, res) ->
if err
tpl.operation.set null
return defaultErrorHandler err
tpl.operation.set 'Added'
clearOp = -> tpl.operation.set null
setTimeout clearOp, 1000
'click .js-add-to-registry': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.operation.set 'adding'
pdat1 = Template.parentData(1)
srcrepo = pdat1.repo
entry = Template.currentData()
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
sha1: entry.sha1
path: entry.treePath
commitId: pdat1.commitId
dst:
ownerName: @owner
repoName: @name
NogFlow.call.addProgramToRegistry opts, (err, res) ->
if err
tpl.operation.set null
return defaultErrorHandler err
tpl.operation.set 'added'
clearOp = -> tpl.operation.set null
setTimeout clearOp, 1000
# `resolveImgSrc()` calls the server to create an S3 link, which is cached
# locally. XXX: Consider factoring-out to a package with nog content helpers.
imgSrcs = new ReactiveDict()
NogContent.resolveImgSrc = (pathParams) ->
hash = EJSON.stringify pathParams
src = imgSrcs.get(hash)
now = new Date()
if not src? or now > src.expire
expire = new Date()
expire.setSeconds(expire.getSeconds() + 600)
src = {isPlaceholder: true, expire, href: 'https://placehold.it/1x1.png'}
imgSrcs.set(hash, src)
Meteor.call 'resolveImgSrc', pathParams, (err, href) ->
if href
src.isPlaceholder = false
src.href = href
imgSrcs.set hash, src
return src
Template.objectReprGeneric.helpers
blobHref: ->
unless (blob = @last.content.blob)?
return
if blob == NULL_SHA1
return
if (blobdoc = NogContent.blobs.findOne(blob))?
fileSize = asXiBUnit(blobdoc.size)
else
fileSize = null
return {
blob
name: @last.content.name
fileSize
}
content: ->
@last.content.meta.content
previewSrc: ->
if not (blob = @last.content.meta.preview?.blob)?
return null
NogContent.resolveImgSrc {
ownerName: @repo.owner
repoName: @repo.name
name: @last.content.meta.preview.type ? 'png'
blob
}
Template.objectReprProgramParams.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.objectReprProgramParams.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
paramsJSON: ->
params = @last.content.meta.program.params
EJSON.stringify params, {indent: true, canonical: true}
Template.objectReprProgramParams.events
'click .js-save-params': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-params').text()
try
params = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(params, @last.content.meta.program.params)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
params
}
tpl.action.set 'Saving...'
Session.set({'blockProgramRunButton': 'Saving'})
NogFlow.call.updateProgramParams opts, (err, res) =>
Session.set({'blockProgramRunButton': null})
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
if (ar = @actionRedirect)?
FlowRouter.go ar
else
FlowRouter.go routerPath('repoObject', res)
Template.objectReprProgramRuntime.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.objectReprProgramRuntime.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
runtimeJSON: ->
runtime = @last.content.meta.program.runtime ? {}
EJSON.stringify runtime, {indent: true, canonical: true}
Template.objectReprProgramRuntime.events
'click .js-save-runtime': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-runtime').text()
try
runtime = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(runtime, @last.content.meta.program.runtime)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
runtime
}
tpl.action.set 'Saving...'
NogFlow.call.updateProgramRuntime opts, (err, res) =>
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
if (ar = @actionRedirect)?
FlowRouter.go ar
else
FlowRouter.go routerPath('repoObject', res)
Template.metaView.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.metaView.events
'click .js-toggle-raw-meta': (ev, tpl) ->
ev.preventDefault()
'click .js-toggle-editing-meta': (ev) ->
ev.preventDefault()
Session.set('isRawMetaEditing', !Session.get('isRawMetaEditing'))
'click .js-save-meta': (ev) ->
ev.preventDefault()
tpl = Template.instance()
text = tpl.$('.js-meta-text').text()
try
proposed = JSON.parse text
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
old = @last.content.meta
if (e = NogFlow.metaChangeViolation(old, proposed))?
tpl.inputError.set e
return
tpl.inputError.set null
if _.isEqual(old, proposed)
return
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
meta: proposed
}
tpl.action.set 'Saving...'
NogFlow.call.setMeta opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.metaView.helpers
isEditing: -> Session.get('isRawMetaEditing')
inputError: ->
tpl = Template.instance()
tpl.inputError.get()
action: ->
tpl = Template.instance()
tpl.action.get()
meta: ->
EJSON.stringify @last.content.meta, {indent: true, canonical: true}
mayModify: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
Template.jobInfo.onCreated ->
@subs = new ReactiveVar []
@autorun =>
subs = []
dat = Template.currentData()
if (jobId = dat.last.content.meta?.job?.id)?
subs.push subsCache.subscribe 'jobStatus', [jobId]
@subs.set subs
Template.jobInfo.helpers
isReady: ->
tpl = Template.instance()
_.all tpl.subs.get(), (s) -> s.ready()
job: ->
unless (id = @last.content.meta?.job?.id)?
return null
NogExec.jobs.findOne({'data.jobId': id})
progressBarClass: ->
switch @status
when 'completed' then 'progress-bar-success'
when 'failed' then 'progress-bar-danger'
else null
progressPct: ->
Math.round(@progress.percent)
showProgressPct: ->
@progress.percent >= 15
# `jobExecutionRepo` returns an href to the repo to which the job results
# will be posted.
jobExecutionRepo: ->
pdat = Template.parentData()
thisRepo = "#{pdat.repo.owner}/#{pdat.repo.name}"
jobRepo = @data.workspaceRepo
if jobRepo == thisRepo
return null
[ownerName, repoName] = jobRepo.split('/')
{refTreePath} = pdat
href = routerPath 'repoTree', {ownerName, repoName, refTreePath}
return {
fullName: jobRepo
href
}
failure: ->
if @failures?.length
{
reason: (f.reason for f in @failures).join('. ')
}
else if @status == 'cancelled'
{
reason: 'Cancelled due to lack of progress.'
}
else
null
# FIXME: Notice that master has updated causes flickering.
Template.uploadToDatalist.events
'change .js-upload-files': (e) ->
e.preventDefault()
dat = Template.currentData()
for f in e.target.files
id = NogBlob.uploadFile f, (err, res) ->
if err
return defaultErrorHandler err
opts = {
ownerName: dat.repo.owner
repoName: dat.repo.name
numericPath: dat.numericPath
name: res.filename
blob: res.sha1
}
_id = res._id
NogFiles.call.addBlobToDatalist opts, (err, res) ->
if err
return defaultErrorHandler err
cleanup = -> NogBlob.files.remove _id
setTimeout cleanup, 1000
clearStable()
Template.uploadToDatalist.helpers
uploads: -> NogBlob.files.find()
Template.uploadToDatalist.helpers _.pick(
NogBlob.fileHelpers, 'name', 'progressWidth', 'uploadCompleteClass',
'sha1Progress', 'sha1', 'haveSha1'
)
Template.treeReprRegistryProgram.helpers
name: ->
@last.content.name
authors: ->
as = @last.content.meta.package?.authors ? []
(a.name for a in as).join(', ')
latestVersion: ->
entryContent(@last.content.entries[0])?.name
resolvedReadme: ->
{repo, refTreePath} = @
NogContent.resolveRefTreePath repo, refTreePath + '/index!0/README.md'
Template.treeReprWorkspaceProgram.helpers
mayRunProgram: -> mayModifyRepo @repo
name: ->
@last.content.name
latestVersion: ->
entryContent(@last.content.entries[0])?.name
resolvedReadme: ->
{repo, refTreePath} = @
NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/index!0/README.md'
)
resolvedParams: ->
{repo, refTreePath} = @
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/params'
)
unless resolved?
return
# Redirect 'Save Parameter' back to here.
resolved.actionRedirect = routerPath 'repoTree', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedRuntime: ->
{repo, refTreePath} = @
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/runtime'
)
unless resolved?
return
# Redirect 'Save Runtime Setting' back to here.
resolved.actionRedirect = routerPath 'repoTree', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
Template.treeReprWorkspaceProgramRunButton.onCreated ->
@action = new ReactiveVar()
Template.treeReprWorkspaceProgramRunButton.helpers
action: -> Template.instance().action.get()
blocked: -> Session.get('blockProgramRunButton')
Template.treeReprWorkspaceProgramRunButton.events
'click .js-run': (ev) ->
ev.preventDefault()
opts = {
ownerName: @repo.owner
repoName: @repo.name
commitId: @commit._id
sha1: @last.content._id
}
tpl = Template.instance()
tpl.action.set 'Submitting Job...'
NogFlow.call.runProgram opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
FlowRouter.go routerPath('repoTree', res)
versionString = (v) ->
if v.major?
"#{v.major}.#{v.minor}.#{v.patch}"
else if v.date?
v.date
else if v.sha1?
v.sha1
else
'unknown'
upstreamVersionsCache = new ReactiveDict
getLatestUpstreamVersion = (origin) ->
[ownerName, repoName] = origin.repoFullName.split('/')
unless (repo = NogContent.repos.findOne {owner: ownerName, name: repoName})?
return null
fixedOrigin = {
ownerName
repoName,
packageName: origin.name
commitId: repo.refs['branches/master']
}
cacheKey = EJSON.stringify fixedOrigin, {canonical: true}
ver = upstreamVersionsCache.get cacheKey
unless _.isUndefined(ver)
return ver
getVersion = (opts) ->
NogFlow.call.getPackageVersion opts, (err, res) ->
if err
console.log 'Failed to get version', opts, err
return
key = <KEY>.stringify _.pick(
res, 'ownerName', 'repoName', 'packageName', 'commitId'
), {
canonical: true
}
upstreamVersionsCache.set key, res.version
getVersion {ownerName, repoName, packageName: origin.name}
return null
Template.treeReprWorkspaceProgramDeps.helpers
mayUpdateDep: -> mayModifyRepo Template.parentData().repo
deps: ->
latest = entryContent(@last.content.entries[0])
if latest
pkg = latest.meta.package
deps = {}
for d in pkg.dependencies
deps[d.name] = d
for f in pkg.frozen
version = versionString(f)
dep = {
name: f.name
version
sha1: f.sha1
}
if (origin = deps[f.name])?
upstream = getLatestUpstreamVersion origin
if upstream?
dep.upstreamVersion = versionString upstream
dep.upstreamSha1 = upstream.sha1
dep.isUpdateAvailable = (
dep.upstreamVersion? and version != dep.upstreamVersion
)
[ownerName, repoName] = origin.repoFullName.split('/')
dep.origin = {
ownerName
repoName
name: origin.repoFullName
href: '' +
'/' + origin.repoFullName +
'/tree/master/programs/' + origin.name
}
dep
Template.treeReprWorkspaceProgramDepsUpdateButton.onCreated ->
@action = new ReactiveVar()
Template.treeReprWorkspaceProgramDepsUpdateButton.helpers
action: -> Template.instance().action.get()
Template.treeReprWorkspaceProgramDepsUpdateButton.events
'click .js-update-dep': (ev) ->
ev.preventDefault()
tpl = Template.instance()
pdat = Template.parentData()
opts =
ownerName: pdat.repo.owner
repoName: pdat.repo.name
commitId: pdat.commitId
package:
numericPath: pdat.numericPath
dependency:
name: @name
oldSha1: @sha1
newSha1: @upstreamSha1
origin:
ownerName: @origin.ownerName
repoName: @origin.repoName
tpl.action.set 'Updating...'
NogFlow.call.updatePackageDependency opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
| true | {defaultErrorHandler} = NogError
{asXiBUnit} = NogFmt
routerPath = (route, opts) -> FlowRouter.path route, opts
NULL_SHA1 = '0000000000000000000000000000000000000000'
if (c = NogApp?.subsCache)?
console.log 'Using main subs cache'
subsCache = c
else
subsCache = new SubsCache()
iskind = (entry, kind) -> _.isObject(entry.meta[kind])
iskindDatalist = (tree) -> iskind tree, 'datalist'
iskindPrograms = (tree) -> iskind tree, 'programs'
iskindJob = (tree) -> iskind tree, 'job'
iskindPackage = (tree) -> iskind tree, 'package'
iskindWorkspace = (tree) -> iskind tree, 'workspace'
iskindProgramRegistry = (tree) -> iskind tree, 'programRegistry'
iskindCatalog = (tree) -> iskind tree, 'catalog'
mayModifyRepo = (repo) ->
aopts = {ownerName: repo.owner, repoName: repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
entryContent = (e) ->
if e.type == 'object'
NogContent.objects.findOne e.sha1
else if e.type == 'tree'
NogContent.trees.findOne e.sha1
else
e
# Register entry representations: object reprs and tree reprs separately.
# XXX: The nog-flow-related representation should perhaps be moved to
# nog-repr-flow, where code could be shared to implement nog-file views, in
# case such views become relevant.
Meteor.startup ->
NogTree.registerEntryRepr
selector: (ctx) ->
unless ctx.last.type == 'object'
return null
content = ctx.last.content
name = content.name
if name == 'params' and iskind(content, 'program')
'objectReprProgramParams'
else if name == 'runtime' and iskind(content, 'program')
'objectReprProgramRuntime'
else
null
isWorkspaceProgramTree = (ctx) ->
(
ctx.contentPath.length == 2 and
iskindWorkspace(ctx.tree.content) and
iskindPrograms(ctx.contentPath[0].content) and
iskindPackage(ctx.last.content)
)
isRegistryProgramTree = (ctx) ->
(
ctx.contentPath.length == 2 and
iskindProgramRegistry(ctx.tree.content) and
iskindPrograms(ctx.contentPath[0].content) and
iskindPackage(ctx.last.content)
)
Meteor.startup ->
NogTree.registerEntryRepr
selector: (ctx) ->
unless ctx.last.type == 'tree'
return null
content = ctx.last.content
if iskindDatalist content
'treeReprDatalist'
else if isWorkspaceProgramTree ctx
'treeReprWorkspaceProgram'
else if isRegistryProgramTree ctx
'treeReprRegistryProgram'
else
null
# Provide a file scope function to reset the stable commit from anywhere until
# we have a better solution. A possible solution would be to put the stable
# commit into the query part of the URL. We rely on the URL for hrefs anyway.
# There can only be a single instance of treeContent at a time. So we can
# simply use the global state directly.
treeContentInstance = null
clearStable = ->
unless treeContentInstance
return
treeContentInstance.commitId.set null
Template.tree.helpers
ownerName: -> FlowRouter.getParam('ownerName')
repoName: -> FlowRouter.getParam('repoName')
treeCtx: ->
{
ownerName: FlowRouter.getParam('ownerName')
repoName: FlowRouter.getParam('repoName')
refTreePath: FlowRouter.getParam('refTreePath')
}
# Manage subscriptions explicitly in order to use `SubsCache`.
# `template.autorun` will automatically terminate when the template is
# destroyed and subscriptions inside an autorun will be automatically stopped,
# so it is nearly as good as `template.subscribe`. But we cannot use the
# template helper `Template.subscriptionsReady`, so we manage subscriptions in
# `subs` and provide the helper `isReady`. `subs` must be reactive in order to
# rerun `isReady` when the subscriptions change.
Template.treeContent.onCreated ->
treeContentInstance = @
@contextKey = null
@commitId = new ReactiveVar null
@subs = new ReactiveVar []
unless (ownerName = FlowRouter.getParam('ownerName'))?
return
unless (repoName = FlowRouter.getParam('repoName'))?
return
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
repoId = repo._id
NogRepoSettings.call.addToRecentRepos {repoId}, (err, res) ->
if err
return defaultErrorHandler err
@autorun =>
subs = []
subs.push subsCache.subscribe 'targetDatalists'
subs.push subsCache.subscribe 'targetProgramWorkspaces'
subs.push subsCache.subscribe 'targetProgramRegistries'
data = Template.currentData()
ownerName = data.ownerName
repoName = data.repoName
refTreePath = data.refTreePath
subs.push subsCache.subscribe 'repoWithRefTreePath',
repo:
owner: ownerName
name: repoName
refTreePath: refTreePath
@subs.set subs
repo = NogContent.repos.findOne {owner: ownerName, name: repoName}
unless repo?
return
unless (resolved = NogContent.resolveRefTreePath repo, refTreePath)?
return
# Reset stable commit id if the repo or ref changes.
key = [ownerPI:KEY:<KEY>END_PI resolved.ref].PI:KEY:<KEY>END_PI
if key != @contextKey
@contextKey = key
@commitId.set null
# Do not capture the commit id when browsing by id, since there cannot be
# updates.
if resolved.refType is 'id'
@commitId.set null
return
# When browsing by branch name, capture the current commit id for the
# change warning.
if not (@commitId.get())?
{commitId} = resolved
@commitId.set commitId
Template.treeContent.events
'click .js-latest': (ev, tpl) ->
ev.preventDefault()
tpl.commitId.set null
'click .js-previous': (ev, tpl) ->
ev.preventDefault()
params =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: tpl.commitId.get() + '/' + @treePath
if @last.type is 'tree'
FlowRouter.go 'repoTree', params
else
FlowRouter.go 'repoObject', params
Template.treeContent.helpers
isReady: ->
tpl = Template.instance()
_.all tpl.subs.get(), (s) -> s.ready()
reprTemplate: ->
NogTree.selectEntryRepr(@) ? 'entryReprDefault'
failResolveReason: ->
tpl = Template.instance()
ownerName = @ownerName
repoName = @repoName
sel = {owner: ownerName, name: repoName}
if NogContent.repos.findOne sel
return {pathResolveFailed: true}
sel = {oldFullNames: "#{ownerName}/#{repoName}"}
if (r = NogContent.repos.findOne sel)?
return {repoIsRenamed: true, newFullName: r.fullName}
return {repoIsUnknown: true}
resolvedPath: ->
tpl = Template.instance()
ownerName = @ownerName
repoName = @repoName
repoSel = {owner: ownerName, name: repoName}
unless (repo = NogContent.repos.findOne repoSel)?
return null
refTreePath = @refTreePath
NogContent.resolveRefTreePath repo, refTreePath
refHasChanged: ->
tpl = Template.instance()
prev = tpl.commitId.get()
(prev? and @commitId != prev)
rootHref: ->
href = routerPath 'repoTree',
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @ref
{href, name: @repo.name}
pathHrefs: ->
[initial..., last] = @namePath
hrefs = []
path = ''
for name in initial
path += "/#{name}"
hrefs.push
name: name
href: routerPath 'repoTree',
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @ref + path
if last?
hrefs.push {name: last}
hrefs
viewerInfo: ->
ownerName = @ownerName
repoName = @repoName
if (repo = NogContent.repos.findOne({owner: ownerName, name: repoName}))?
if (commit = NogContent.commits.findOne(repo.refs['branches/master']))?
if (tree = NogContent.trees.findOne(commit.tree))?
refTreePath = FlowRouter.getParam('refTreePath') ? ''
resolved = NogContent.resolveRefTreePath repo, refTreePath
{
fullName: repo.fullName
type: resolved.last.type
treePath: refTreePath.replace(/^master\/?/,'')
iskindWorkspace: iskindWorkspace(tree)
currentIsTechnical: true
iskindCatalog: iskindCatalog(tree)
}
Template.entryReprDefault.helpers
isTree: ->
@last.type is 'tree'
isObject: ->
@last.type is 'object'
Template.treeEntriesWithInlineMarkdown.helpers
resolvedInlineObject: ->
{repo, refTreePath} = @
for p in ['index.md', 'README.md', 'summary.md', 'report.md']
if (child = NogContent.resolveRefTreePath repo, refTreePath + '/' + p)?
return child
return null
Template.treeReprDatalist.helpers
mayUpload: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
# Manage the active info tab as global session state to maintain it when
# browsing to other repos.
#
# See <http://getbootstrap.com/javascript/#tabs-events>
Session.setDefault 'treeInfoTabs.current', 'summary'
Template.treeInfoTabs.events
'shown.bs.tab': (ev) ->
tabId = $(ev.target).attr('href')[1..]
Session.set 'treeInfoTabs.current', tabId
Template.treeInfoTabs.helpers
description: -> @last.content.meta.description
summaryActive: -> treeInfoTabsActive 'summary'
metaActive: -> treeInfoTabsActive 'meta'
historyActive: -> treeInfoTabsActive 'history'
iskindJob: -> iskindJob @last.content
treeInfoTabsActive = (tabId) ->
if Session.equals 'treeInfoTabs.current', tabId
'active'
else
null
Template.commitInfo.helpers
commitHref: ->
routeParams =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: @commit._id
return {
subject: @commit.subject
shortId: @commit._id[0...10]
href: routerPath 'repoTree', routeParams
}
author: ->
@commit.authors[0]
authorRelDate: ->
@commit.authorDate.fromNow()
Template.refDropdown.helpers
titlePrefix: ->
switch @refType
when 'id' then 'commit'
when 'branch' then 'branch'
title: ->
switch @refType
when 'id' then @ref[0...10]
when 'branch' then @ref
isIdRef: -> @refType == 'id'
entries: ->
routeName = switch @last.type
when 'object' then 'repoObject'
when 'tree' then 'repoTree'
routeParams =
ownerName: @repo.owner
repoName: @repo.name
for refName of @repo.refs
[ty, name...] = refName.split '/'
{
name: name.join('/')
href: routerPath routeName, _.extend routeParams, {
refTreePath: [name, @namePath...].join('/')
}
}
hasKindChild = (tree, kind) ->
for e in tree.entries
e = entryContent(e)
if iskind e, kind
return true
return false
Template.workspaceActions.helpers
addMenuItems: ->
items = [
{name: 'Datalist', kind: 'datalist'}
{name: 'Programs', kind: 'programs'}
{name: 'Log', kind: 'log'}
]
for i in items
if hasKindChild @last.content, i.kind
i.disabled = 'disabled'
items
Template.workspaceActions.events
'click .js-add': (ev) ->
ev.preventDefault()
repo = Template.parentData(0).repo
opts =
ownerName: repo.owner
repoName: repo.name
kind: @kind
NogFlow.call.addWorkspaceKindTree opts, (err, res) ->
if err
return defaultErrorHandler err
Template.treeEntries.onCreated ->
@isEditing = new ReactiveVar(false)
editingCacheKey = null
@isSelected = new ReactiveDict()
@action = new ReactiveVar()
@editNames = new ReactiveDict()
@isModifiedName = new ReactiveDict()
@selectEntry = (idx) =>
@isSelected.set(idx, true)
@deselectEntry = (idx) =>
@isSelected.set(idx, false)
@selectAllEntries = (n) =>
for i in [0...n]
@selectEntry i
@deselectAllEntries = (n) =>
for i in [0...n]
@deselectEntry i
@clearAllEditNames = (n) =>
for i in [0...n]
@editNames.set(i, null)
@isModifiedName.set(i, false)
@autorun =>
# Stop editing and clear selection when navigating to a different path.
dat = Template.currentData()
ownerName = dat.repo.owner
repoName = dat.repo.name
editingCacheKey = [ownerName, repoName, dat.refTreePath].join('/')
if editingCacheKey != @editingCacheKey
@isEditing.set false
@deselectAllEntries dat.last.content.entries.length
@clearAllEditNames dat.last.content.entries.length
@editingCacheKey = editingCacheKey
Template.treeEntries.helpers
action: ->
tpl = Template.instance()
tpl.action.get()
isEditing: ->
tpl = Template.instance()
return tpl.isEditing.get()
isWorkspaceProgram: ->
pdat = Template.parentData(1)
return (
iskindWorkspace(pdat.tree.content) and
iskindPrograms(pdat.last.content) and
iskindPackage(@content)
)
isProgramPackage: ->
parent = Template.parentData(1).last.content
return (iskindPrograms(parent) and iskindPackage(@content))
# Rules for data dropdown:
#
# - Do not show it in a program registry.
# - Do not show it at the first level of a workspace.
# - Do not show it in the `programs` subtree of a workspace.
# - Show it everywhere in generic repos.
#
shouldShowDataEntryDropdown: ->
pdat = Template.currentData()
if iskindProgramRegistry(pdat.tree.content)
return false
if iskindWorkspace(pdat.tree.content)
if pdat.contentPath.length < 1
return false
if iskindPrograms(pdat.contentPath[0].content)
return false
return true
mayModify: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
isEntryNameModified: ->
tpl = Template.instance()
tpl.isModifiedName.get(@index)
isAnyEntryNameModified: ->
tpl = Template.instance()
nEntries = @last.content.entries.length
for i in [0...nEntries]
if tpl.isModifiedName.get(i)
return true
return false
entries: ->
tpl = Template.instance()
pathParams =
ownerName: @repo.owner
repoName: @repo.name
refTreePath: [@ref, @namePath...].join('/')
# hrefs default to names, and use `index!` only if necessary to
# disambiguate identical names. `usedNames` tracks the names that have
# been used. If a name is encountered again, `index!` is used instead.
usedNames = {}
for e, idx in @last.content.entries
switch e.type
when 'object'
content = NogContent.objects.findOne(e.sha1)
icon = 'file'
routeName = 'repoObject'
when 'tree'
content = NogContent.trees.findOne(e.sha1)
icon = 'folder-close'
routeName = 'repoTree'
if content
name = content.name
if usedNames[name]?
tail = "index!#{idx}"
else
tail = name
usedNames[name] = true
routeParams = _.clone pathParams
routeParams.refTreePath += '/' + tail
treePath = @treePath + '/' + tail
{
name
icon
href: routerPath routeName, routeParams
description: content.meta.description
type: e.type
sha1: e.sha1
treePath
content
index: idx
isSelected: tpl.isSelected.get(idx)
}
Template.treeEntries.events
'click .js-toggle-entry': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.isSelected.set(@index, !tpl.isSelected.get(@index))
if tpl.isSelected.get(@index)
tpl.isEditing.set(true)
else
pdat = Template.parentData(0)
nEntries = pdat.last.content.entries.length
tpl.isEditing.set(false)
for i in [0...nEntries]
if tpl.isSelected.get(i)
tpl.isEditing.set(true)
if !tpl.isEditing.get()
tpl.clearAllEditNames @last.content.entries.length
'click .js-select-all': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.selectAllEntries @last.content.entries.length
tpl.isEditing.set(true)
'click .js-deselect-all': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.deselectAllEntries @last.content.entries.length
tpl.isEditing.set(false)
tpl.clearAllEditNames @last.content.entries.length
'click .js-delete': (ev) ->
ev.preventDefault()
tpl = Template.instance()
nEntries = @last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
children.push(i)
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
children
}
tpl.action.set 'deleting'
NogFiles.call.deleteChildren opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
clearStable()
'keyup .js-name-val': (ev) ->
val = $(ev.target).text()
tpl = Template.instance()
isModified = (val != @name)
tpl.editNames.set(@index, val)
tpl.isModifiedName.set(@index, isModified)
'click .js-rename': (ev) ->
ev.preventDefault()
tpl = Template.instance()
nEntries = @last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isModifiedName.get(i)
children.push
index: i
newName: tpl.editNames.get(i)
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
children
}
tpl.action.set 'renaming'
NogFiles.call.renameChildren opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
clearStable()
'click .js-starred': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
alert 'starred datalist not yet implemented'
# The event is emitted by `dataEntryDropdown` but handled here, since it
# requires the selection.
'click .js-add-to': (ev) ->
ev.preventDefault()
tpl = Template.instance()
dat = Template.currentData()
nEntries = dat.last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
entry = dat.last.content.entries[i]
children.push
type: entry.type
sha1: entry.sha1
tpl.action.set 'adding'
srcrepo = dat.repo
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
commitId: dat.commitId
entries: children
dst:
ownerName: @owner
repoName: @name
NogFiles.call.addToDatalist opts, (err, res) ->
if err
tpl.action.set null
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
# Don't clearStable(), since entries are usually added to another repo.
# We warn the user if the current repo gets modified.
tpl.action.set 'added'
clearOp = -> tpl.action.set null
setTimeout clearOp, 1000
'click .js-new-datalist': (ev) ->
ev.preventDefault()
ev.stopImmediatePropagation()
tpl = Template.instance()
tpl.$('.js-new-datalist-modal').modal()
# The event is emitted by `dataEntryDropdown` but handled here, since it
# requires the selection.
'click .js-create-and-add': (ev) ->
tpl = Template.instance()
dat = Template.currentData()
nEntries = dat.last.content.entries.length
children = []
for i in [0...nEntries]
if tpl.isSelected.get(i)
entry = dat.last.content.entries[i]
children.push
type: entry.type
sha1: entry.sha1
name = tpl.$('.js-new-repo-name').val()
name = sanitizedRepoName name
tpl.action.set 'creating'
srcrepo = dat.repo
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
commitId: dat.commitId
entries: children
dst:
create: true
ownerName: Meteor.user().username
repoName: name
NogFiles.call.addToDatalist opts, (err, res) ->
tpl.$('.js-new-datalist-modal').modal('hide')
if err
tpl.action.set null
return defaultErrorHandler err
tpl.deselectAllEntries nEntries
tpl.clearAllEditNames nEntries
# Don't clearStable(), since entries are usually added to another repo.
# We warn the user if the current repo gets modified.
tpl.action.set 'created and added'
clearOp = -> tpl.action.set null
setTimeout clearOp, 1000
Template.treeEntriesAddFolder.onCreated ->
@inputIsEmpty = new ReactiveVar true
Template.treeEntriesAddFolder.helpers
inputIsEmpty: ->
tpl = Template.instance()
tpl.inputIsEmpty.get()
Template.treeEntriesAddFolder.events
'click .js-addFolder-start': (ev) ->
tpl = Template.instance()
tpl.$('.js-addFolder-modal').modal()
'keyup .js-addFolder-name': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-addFolder-name').val()
if name != ""
tpl.inputIsEmpty.set false
else
tpl.inputIsEmpty.set true
'click .js-addFolder-complete': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-addFolder-name').val()
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
folderName: name
}
NogFiles.call.addSubtree opts, (err, res) ->
if err
return defaultErrorHandler err
tpl.$('.js-addFolder-modal').modal('hide')
suggestRepoNameForEntry = (e) ->
parts = []
if (study = e.meta.study)?
parts.push study
if (specimen = e.meta.specimen)?
parts.push specimen
if parts.length == 0
parts.push e.name.split('.')[0]
parts.join('_')
sanitizedRepoName = (n) ->
n = n.replace /[^a-zA-Z0-9._-]/g, '_'
n = n.replace /__+/g, '__'
n
Template.dataEntryDropdown.helpers
dstWorkspaces: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['workspace', 'datalist']}
Template.newDatalistModal.onCreated ->
@inputIsEmpty = new ReactiveVar true
Template.newDatalistModal.events
'keyup .js-new-repo-name': (ev) ->
tpl = Template.instance()
name = tpl.$('.js-new-repo-name').val()
if name != ""
tpl.inputIsEmpty.set false
else
tpl.inputIsEmpty.set true
Template.newDatalistModal.helpers
inputIsEmpty: ->
tpl = Template.instance()
tpl.inputIsEmpty.get()
Template.programPackageDropdown.onCreated ->
@operation = new ReactiveVar null
Template.programPackageDropdown.helpers
operation: ->
tpl = Template.instance()
tpl.operation.get()
dstWorkspaces: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['workspace', 'programs']}
dstRegistries: ->
NogContent.repos.find
ownerId: Meteor.userId()
kinds: {$all: ['programRegistry']}
Template.programPackageDropdown.events
'click .js-add-to-workspace': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.operation.set 'Adding...'
pdat1 = Template.parentData(1)
srcrepo = pdat1.repo
entry = Template.currentData()
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
entries: [{sha1: entry.sha1}]
commitId: pdat1.commitId
dst:
ownerName: @owner
repoName: @name
NogFiles.call.addProgram opts, (err, res) ->
if err
tpl.operation.set null
return defaultErrorHandler err
tpl.operation.set 'Added'
clearOp = -> tpl.operation.set null
setTimeout clearOp, 1000
'click .js-add-to-registry': (ev) ->
ev.preventDefault()
tpl = Template.instance()
tpl.operation.set 'adding'
pdat1 = Template.parentData(1)
srcrepo = pdat1.repo
entry = Template.currentData()
opts =
src:
ownerName: srcrepo.owner
repoName: srcrepo.name
sha1: entry.sha1
path: entry.treePath
commitId: pdat1.commitId
dst:
ownerName: @owner
repoName: @name
NogFlow.call.addProgramToRegistry opts, (err, res) ->
if err
tpl.operation.set null
return defaultErrorHandler err
tpl.operation.set 'added'
clearOp = -> tpl.operation.set null
setTimeout clearOp, 1000
# `resolveImgSrc()` calls the server to create an S3 link, which is cached
# locally. XXX: Consider factoring-out to a package with nog content helpers.
imgSrcs = new ReactiveDict()
NogContent.resolveImgSrc = (pathParams) ->
hash = EJSON.stringify pathParams
src = imgSrcs.get(hash)
now = new Date()
if not src? or now > src.expire
expire = new Date()
expire.setSeconds(expire.getSeconds() + 600)
src = {isPlaceholder: true, expire, href: 'https://placehold.it/1x1.png'}
imgSrcs.set(hash, src)
Meteor.call 'resolveImgSrc', pathParams, (err, href) ->
if href
src.isPlaceholder = false
src.href = href
imgSrcs.set hash, src
return src
Template.objectReprGeneric.helpers
blobHref: ->
unless (blob = @last.content.blob)?
return
if blob == NULL_SHA1
return
if (blobdoc = NogContent.blobs.findOne(blob))?
fileSize = asXiBUnit(blobdoc.size)
else
fileSize = null
return {
blob
name: @last.content.name
fileSize
}
content: ->
@last.content.meta.content
previewSrc: ->
if not (blob = @last.content.meta.preview?.blob)?
return null
NogContent.resolveImgSrc {
ownerName: @repo.owner
repoName: @repo.name
name: @last.content.meta.preview.type ? 'png'
blob
}
Template.objectReprProgramParams.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.objectReprProgramParams.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
paramsJSON: ->
params = @last.content.meta.program.params
EJSON.stringify params, {indent: true, canonical: true}
Template.objectReprProgramParams.events
'click .js-save-params': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-params').text()
try
params = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(params, @last.content.meta.program.params)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
params
}
tpl.action.set 'Saving...'
Session.set({'blockProgramRunButton': 'Saving'})
NogFlow.call.updateProgramParams opts, (err, res) =>
Session.set({'blockProgramRunButton': null})
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
if (ar = @actionRedirect)?
FlowRouter.go ar
else
FlowRouter.go routerPath('repoObject', res)
Template.objectReprProgramRuntime.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.objectReprProgramRuntime.helpers
mayModify: -> mayModifyRepo @repo
action: -> Template.instance().action.get()
inputError: -> Template.instance().inputError.get()
runtimeJSON: ->
runtime = @last.content.meta.program.runtime ? {}
EJSON.stringify runtime, {indent: true, canonical: true}
Template.objectReprProgramRuntime.events
'click .js-save-runtime': (ev) ->
ev.preventDefault()
tpl = Template.instance()
val = tpl.$('.js-runtime').text()
try
runtime = JSON.parse val
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
if _.isEqual(runtime, @last.content.meta.program.runtime)
tpl.inputError.set 'Parameters unchanged.'
return
tpl.inputError.set null
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
runtime
}
tpl.action.set 'Saving...'
NogFlow.call.updateProgramRuntime opts, (err, res) =>
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
if (ar = @actionRedirect)?
FlowRouter.go ar
else
FlowRouter.go routerPath('repoObject', res)
Template.metaView.onCreated ->
@inputError = new ReactiveVar()
@action = new ReactiveVar()
Template.metaView.events
'click .js-toggle-raw-meta': (ev, tpl) ->
ev.preventDefault()
'click .js-toggle-editing-meta': (ev) ->
ev.preventDefault()
Session.set('isRawMetaEditing', !Session.get('isRawMetaEditing'))
'click .js-save-meta': (ev) ->
ev.preventDefault()
tpl = Template.instance()
text = tpl.$('.js-meta-text').text()
try
proposed = JSON.parse text
catch err
msg = "Failed to parse JSON: #{err.message}."
tpl.inputError.set msg
return
old = @last.content.meta
if (e = NogFlow.metaChangeViolation(old, proposed))?
tpl.inputError.set e
return
tpl.inputError.set null
if _.isEqual(old, proposed)
return
opts = {
ownerName: @repo.owner
repoName: @repo.name
numericPath: @numericPath
commitId: @commit._id
meta: proposed
}
tpl.action.set 'Saving...'
NogFlow.call.setMeta opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
Template.metaView.helpers
isEditing: -> Session.get('isRawMetaEditing')
inputError: ->
tpl = Template.instance()
tpl.inputError.get()
action: ->
tpl = Template.instance()
tpl.action.get()
meta: ->
EJSON.stringify @last.content.meta, {indent: true, canonical: true}
mayModify: ->
aopts = {ownerName: @repo.owner, repoName: @repo.name}
NogAccess.testAccess 'nog-content/modify', aopts
Template.jobInfo.onCreated ->
@subs = new ReactiveVar []
@autorun =>
subs = []
dat = Template.currentData()
if (jobId = dat.last.content.meta?.job?.id)?
subs.push subsCache.subscribe 'jobStatus', [jobId]
@subs.set subs
Template.jobInfo.helpers
isReady: ->
tpl = Template.instance()
_.all tpl.subs.get(), (s) -> s.ready()
job: ->
unless (id = @last.content.meta?.job?.id)?
return null
NogExec.jobs.findOne({'data.jobId': id})
progressBarClass: ->
switch @status
when 'completed' then 'progress-bar-success'
when 'failed' then 'progress-bar-danger'
else null
progressPct: ->
Math.round(@progress.percent)
showProgressPct: ->
@progress.percent >= 15
# `jobExecutionRepo` returns an href to the repo to which the job results
# will be posted.
jobExecutionRepo: ->
pdat = Template.parentData()
thisRepo = "#{pdat.repo.owner}/#{pdat.repo.name}"
jobRepo = @data.workspaceRepo
if jobRepo == thisRepo
return null
[ownerName, repoName] = jobRepo.split('/')
{refTreePath} = pdat
href = routerPath 'repoTree', {ownerName, repoName, refTreePath}
return {
fullName: jobRepo
href
}
failure: ->
if @failures?.length
{
reason: (f.reason for f in @failures).join('. ')
}
else if @status == 'cancelled'
{
reason: 'Cancelled due to lack of progress.'
}
else
null
# FIXME: Notice that master has updated causes flickering.
Template.uploadToDatalist.events
'change .js-upload-files': (e) ->
e.preventDefault()
dat = Template.currentData()
for f in e.target.files
id = NogBlob.uploadFile f, (err, res) ->
if err
return defaultErrorHandler err
opts = {
ownerName: dat.repo.owner
repoName: dat.repo.name
numericPath: dat.numericPath
name: res.filename
blob: res.sha1
}
_id = res._id
NogFiles.call.addBlobToDatalist opts, (err, res) ->
if err
return defaultErrorHandler err
cleanup = -> NogBlob.files.remove _id
setTimeout cleanup, 1000
clearStable()
Template.uploadToDatalist.helpers
uploads: -> NogBlob.files.find()
Template.uploadToDatalist.helpers _.pick(
NogBlob.fileHelpers, 'name', 'progressWidth', 'uploadCompleteClass',
'sha1Progress', 'sha1', 'haveSha1'
)
Template.treeReprRegistryProgram.helpers
name: ->
@last.content.name
authors: ->
as = @last.content.meta.package?.authors ? []
(a.name for a in as).join(', ')
latestVersion: ->
entryContent(@last.content.entries[0])?.name
resolvedReadme: ->
{repo, refTreePath} = @
NogContent.resolveRefTreePath repo, refTreePath + '/index!0/README.md'
Template.treeReprWorkspaceProgram.helpers
mayRunProgram: -> mayModifyRepo @repo
name: ->
@last.content.name
latestVersion: ->
entryContent(@last.content.entries[0])?.name
resolvedReadme: ->
{repo, refTreePath} = @
NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/index!0/README.md'
)
resolvedParams: ->
{repo, refTreePath} = @
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/params'
)
unless resolved?
return
# Redirect 'Save Parameter' back to here.
resolved.actionRedirect = routerPath 'repoTree', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
resolvedRuntime: ->
{repo, refTreePath} = @
resolved = NogContent.resolveRefTreePath(
repo, refTreePath + '/index!0/runtime'
)
unless resolved?
return
# Redirect 'Save Runtime Setting' back to here.
resolved.actionRedirect = routerPath 'repoTree', {
ownerName: repo.owner
repoName: repo.name
refTreePath
}
resolved
Template.treeReprWorkspaceProgramRunButton.onCreated ->
@action = new ReactiveVar()
Template.treeReprWorkspaceProgramRunButton.helpers
action: -> Template.instance().action.get()
blocked: -> Session.get('blockProgramRunButton')
Template.treeReprWorkspaceProgramRunButton.events
'click .js-run': (ev) ->
ev.preventDefault()
opts = {
ownerName: @repo.owner
repoName: @repo.name
commitId: @commit._id
sha1: @last.content._id
}
tpl = Template.instance()
tpl.action.set 'Submitting Job...'
NogFlow.call.runProgram opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
clearStable()
FlowRouter.go routerPath('repoTree', res)
versionString = (v) ->
if v.major?
"#{v.major}.#{v.minor}.#{v.patch}"
else if v.date?
v.date
else if v.sha1?
v.sha1
else
'unknown'
upstreamVersionsCache = new ReactiveDict
getLatestUpstreamVersion = (origin) ->
[ownerName, repoName] = origin.repoFullName.split('/')
unless (repo = NogContent.repos.findOne {owner: ownerName, name: repoName})?
return null
fixedOrigin = {
ownerName
repoName,
packageName: origin.name
commitId: repo.refs['branches/master']
}
cacheKey = EJSON.stringify fixedOrigin, {canonical: true}
ver = upstreamVersionsCache.get cacheKey
unless _.isUndefined(ver)
return ver
getVersion = (opts) ->
NogFlow.call.getPackageVersion opts, (err, res) ->
if err
console.log 'Failed to get version', opts, err
return
key = PI:KEY:<KEY>END_PI.stringify _.pick(
res, 'ownerName', 'repoName', 'packageName', 'commitId'
), {
canonical: true
}
upstreamVersionsCache.set key, res.version
getVersion {ownerName, repoName, packageName: origin.name}
return null
Template.treeReprWorkspaceProgramDeps.helpers
mayUpdateDep: -> mayModifyRepo Template.parentData().repo
deps: ->
latest = entryContent(@last.content.entries[0])
if latest
pkg = latest.meta.package
deps = {}
for d in pkg.dependencies
deps[d.name] = d
for f in pkg.frozen
version = versionString(f)
dep = {
name: f.name
version
sha1: f.sha1
}
if (origin = deps[f.name])?
upstream = getLatestUpstreamVersion origin
if upstream?
dep.upstreamVersion = versionString upstream
dep.upstreamSha1 = upstream.sha1
dep.isUpdateAvailable = (
dep.upstreamVersion? and version != dep.upstreamVersion
)
[ownerName, repoName] = origin.repoFullName.split('/')
dep.origin = {
ownerName
repoName
name: origin.repoFullName
href: '' +
'/' + origin.repoFullName +
'/tree/master/programs/' + origin.name
}
dep
Template.treeReprWorkspaceProgramDepsUpdateButton.onCreated ->
@action = new ReactiveVar()
Template.treeReprWorkspaceProgramDepsUpdateButton.helpers
action: -> Template.instance().action.get()
Template.treeReprWorkspaceProgramDepsUpdateButton.events
'click .js-update-dep': (ev) ->
ev.preventDefault()
tpl = Template.instance()
pdat = Template.parentData()
opts =
ownerName: pdat.repo.owner
repoName: pdat.repo.name
commitId: pdat.commitId
package:
numericPath: pdat.numericPath
dependency:
name: @name
oldSha1: @sha1
newSha1: @upstreamSha1
origin:
ownerName: @origin.ownerName
repoName: @origin.repoName
tpl.action.set 'Updating...'
NogFlow.call.updatePackageDependency opts, (err, res) ->
tpl.action.set null
if err
return defaultErrorHandler err
|
[
{
"context": "ploadcare.jQuery\n\nwindow.UPLOADCARE_PUBLIC_KEY = 'demopublickey'\nwindow.UPLOADCARE_URL_BASE = 'https://up",
"end": 400,
"score": 0.6086395978927612,
"start": 395,
"tag": "KEY",
"value": "demop"
},
{
"context": "0.uploadcare.com'\nwindow.UPLOADCARE_PUSHER_KEY = 'c0d50edd02144b749006'\nwindow.UPLOADCARE_SOCIAL_BASE = 'https://social.",
"end": 532,
"score": 0.9991298317909241,
"start": 512,
"tag": "KEY",
"value": "c0d50edd02144b749006"
}
] | test/dummy/spec/javascripts/spec.js.coffee | fossabot/uploadcare-widget | 1 | # This pulls in all your specs from the javascripts directory into Jasmine:
#
# = require uploadcare/build/uploadcare.full
# = require_self
# = require ./utils
# = require mock-objects/manager
# = require_tree ./
# = require_tree ./fixtures/data
# FIXME: tests should use uploadcare.__exports like regular dev env.
window.$ = window.jQuery = uploadcare.jQuery
window.UPLOADCARE_PUBLIC_KEY = 'demopublickey'
window.UPLOADCARE_URL_BASE = 'https://upload.staging0.uploadcare.com'
window.UPLOADCARE_PUSHER_KEY = 'c0d50edd02144b749006'
window.UPLOADCARE_SOCIAL_BASE = 'https://social.staging0.uploadcare.com/'
window.UPLOADCARE_CDN_BASE = 'http://staging0.ucarecdn.com/'
window.UPLOADCARE_SCRIPT_BASE = '/assets/uploadcare/'
jasmine.ns = (path, cb) ->
node = jasmine
for part in path.split '.' when part
node = node[part] or= {}
cb node
afterEach ->
jasmine.mocks.clear()
| 171515 | # This pulls in all your specs from the javascripts directory into Jasmine:
#
# = require uploadcare/build/uploadcare.full
# = require_self
# = require ./utils
# = require mock-objects/manager
# = require_tree ./
# = require_tree ./fixtures/data
# FIXME: tests should use uploadcare.__exports like regular dev env.
window.$ = window.jQuery = uploadcare.jQuery
window.UPLOADCARE_PUBLIC_KEY = '<KEY>ublickey'
window.UPLOADCARE_URL_BASE = 'https://upload.staging0.uploadcare.com'
window.UPLOADCARE_PUSHER_KEY = '<KEY>'
window.UPLOADCARE_SOCIAL_BASE = 'https://social.staging0.uploadcare.com/'
window.UPLOADCARE_CDN_BASE = 'http://staging0.ucarecdn.com/'
window.UPLOADCARE_SCRIPT_BASE = '/assets/uploadcare/'
jasmine.ns = (path, cb) ->
node = jasmine
for part in path.split '.' when part
node = node[part] or= {}
cb node
afterEach ->
jasmine.mocks.clear()
| true | # This pulls in all your specs from the javascripts directory into Jasmine:
#
# = require uploadcare/build/uploadcare.full
# = require_self
# = require ./utils
# = require mock-objects/manager
# = require_tree ./
# = require_tree ./fixtures/data
# FIXME: tests should use uploadcare.__exports like regular dev env.
window.$ = window.jQuery = uploadcare.jQuery
window.UPLOADCARE_PUBLIC_KEY = 'PI:KEY:<KEY>END_PIublickey'
window.UPLOADCARE_URL_BASE = 'https://upload.staging0.uploadcare.com'
window.UPLOADCARE_PUSHER_KEY = 'PI:KEY:<KEY>END_PI'
window.UPLOADCARE_SOCIAL_BASE = 'https://social.staging0.uploadcare.com/'
window.UPLOADCARE_CDN_BASE = 'http://staging0.ucarecdn.com/'
window.UPLOADCARE_SCRIPT_BASE = '/assets/uploadcare/'
jasmine.ns = (path, cb) ->
node = jasmine
for part in path.split '.' when part
node = node[part] or= {}
cb node
afterEach ->
jasmine.mocks.clear()
|
[
{
"context": " = '<p>Illustration by <a href=\"http://artsy.net\">Tomi Um</a>.</p>'\n @props = {\n html: @postscr",
"end": 2159,
"score": 0.9971120953559875,
"start": 2152,
"tag": "NAME",
"value": "Tomi Um"
}
] | src/client/components/rich_text/test/components/paragraph.test.coffee | craigspaeth/positron | 0 | benv = require 'benv'
{ resolve } = require 'path'
sinon = require 'sinon'
React = require 'react'
ReactDOM = require 'react-dom'
ReactTestUtils = require 'react-dom/test-utils'
ReactDOMServer = require 'react-dom/server'
Draft = require 'draft-js'
{ EditorState, Modifier } = require 'draft-js'
r =
find: ReactTestUtils.findRenderedDOMComponentWithClass
simulate: ReactTestUtils.Simulate
describe 'Rich Text: Paragraph', ->
beforeEach (done) ->
benv.setup =>
benv.expose
$: benv.require 'jquery'
window.jQuery = $
global.Node = window.Node
global.Element = window.Element
global.HTMLElement = window.HTMLElement
global.document = window.document
window.getSelection = sinon.stub().returns(
isCollapsed: false
getRangeAt: sinon.stub().returns(
getClientRects: sinon.stub.returns([{
bottom: 170
height: 25
left: 425
right: 525
top: 145
width: 95
}])
)
)
window.matchMedia = sinon.stub().returns(
{
matches: false
addListener: sinon.stub()
removeListener: sinon.stub()
}
)
@Paragraph = benv.require resolve __dirname, '../../components/paragraph'
@Paragraph.__set__ 'Modifier', Modifier
@Paragraph.__set__ 'EditorState', EditorState
Config = require '../../utils/config.js'
@Paragraph.__set__ 'Config', Config
{ TextNav } = benv.require(
resolve(__dirname, '../../components/text_nav')
)
@Paragraph.__set__ 'TextNav', TextNav
{ TextInputUrl } = benv.require(
resolve(__dirname, '../../components/input_url')
)
@Paragraph.__set__ 'TextInputUrl', TextInputUrl
@Paragraph.__set__ 'stickyControlsBox', sinon.stub().returns {top: 20, left: 40}
@Paragraph.__set__ 'stripGoogleStyles', @stripGoogleStyles = sinon.stub().returns('<p>hello</p><p>here again.</p>')
@leadParagraph = '<p>Here is the <em>lead</em> paragraph for <b>this</b> article.</p>'
@postscript = '<p>Illustration by <a href="http://artsy.net">Tomi Um</a>.</p>'
@props = {
html: @postscript
placeholder: 'Postscript (optional)'
onChange: sinon.stub()
linked: true
}
@component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], => setTimeout =>
@component.stickyControlsBox = sinon.stub().returns {top: 20, left: 40}
@component.state.editorState.getSelection().isCollapsed = sinon.stub().returns false
selection = @component.state.editorState.getSelection()
newSelection = selection.merge({
anchorKey: @component.state.editorState.getCurrentContent().getFirstBlock().key
anchorOffset: 0
focusKey: @component.state.editorState.getCurrentContent().getFirstBlock().key
focusOffset: 12
})
newEditorState = EditorState.acceptSelection(@component.state.editorState, newSelection)
@component.onChange newEditorState
done()
afterEach ->
benv.teardown()
describe 'Render', ->
it 'Shows a placeholder if provided and empty', ->
component = ReactDOMServer.renderToString React.createElement(@Paragraph, @props)
$(component).text().should.containEql 'Postscript (optional)'
it 'Renders existing html', ->
$(ReactDOM.findDOMNode(@component)).text().should.containEql 'Illustration by Tomi Um.'
it 'Renders existing link entities', ->
$(ReactDOM.findDOMNode(@component)).html().should.containEql '<a href="http://artsy.net/">'
describe 'On change', ->
it 'Sets the editorState and html on change', ->
@component.setState = sinon.stub()
r.simulate.click r.find @component, 'rich-text--paragraph__input'
@component.setState.args[1][0].editorState.should.be.ok
@component.setState.args[1][0].html.should.be.ok
it 'Calls props.onChange if content has changed', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('italic')
@component.props.onChange.called.should.eql true
it 'Does not call props.onChange if content has not changed', ->
@component.setState = sinon.stub()
r.simulate.click r.find @component, 'rich-text--paragraph__input'
@component.props.onChange.called.should.eql false
@component.setState.called.should.eql true
describe 'Key commands', ->
it 'Can toggle bold styles', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('bold')
@component.setState.args[0][0].html.should.containEql '<strong>Illustration</strong>'
it 'Does not toggle bold if type is caption', ->
@props.linked = null
@props.type = 'caption'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
component.setState = sinon.stub()
component.handleKeyCommand('bold')
component.setState.called.should.eql false
it 'Can toggle italic styles', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('italic')
@component.setState.args[0][0].html.should.containEql '<em>Illustration</em>'
it 'Does not toggle italic if type is postscript', ->
@props.linked = null
@props.type = 'postscript'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
component.setState = sinon.stub()
component.handleKeyCommand('italic')
component.setState.called.should.eql false
it 'Can toggle a link prompt', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('link-prompt')
@component.setState.args[0][0].selectionTarget.should.eql { top: 20, left: 40 }
@component.setState.args[0][0].showUrlInput.should.eql true
describe 'Nav', ->
it 'Prints Italic and Bold buttons by default', ->
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="italic">I</button><button class="bold">B</button>'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="link">'
it 'Shows correct buttons if type unspecified and linked is true', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
$(ReactDOM.findDOMNode(@component)).html().should.containEql(
'<button class="italic">I</button><button class="bold">B</button><button class="link">'
)
it 'Does not show italic if type is postscript', ->
@props.linked = null
@props.type = 'postscript'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
component.setState = sinon.stub()
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="bold">B</button><button class="link">'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="italic">I</button>'
it 'Does not show bold if type is caption', ->
@props.linked = null
@props.type = 'caption'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
component.setState = sinon.stub()
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="italic">I</button><button class="link">'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="bold">B</button>'
it 'Can toggle bold styles', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'bold'
@component.setState.args[0][0].html.should.containEql '<strong>Illustration</strong>'
it 'Can toggle italic styles', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'italic'
@component.setState.args[0][0].html.should.containEql '<em>Illustration</em>'
it 'Can toggle a link prompt', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'link'
@component.setState.args[0][0].selectionTarget.should.eql { top: 20, left: 40 }
@component.setState.args[0][0].showUrlInput.should.eql true
describe 'Links', ->
it '#hasLinks returns true if props.linked', ->
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#hasLinks returns true if type is postscript', ->
@props.type = 'postscript'
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#hasLinks returns true if type is caption', ->
@props.type = 'caption'
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#confirmLink can save a link as html', ->
@component.confirmLink('http://artsy.net')
(@component.state.html.match(/<a href=/g) || []).length.should.eql 2
describe 'Linebreaks', ->
it 'allows linebreaks by default', ->
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
$(ReactDOM.findDOMNode(component)).find('.public-DraftStyleDefault-block').length.should.eql 2
it 'strips linebreaks if props.stripLinebreaks', ->
@props.stripLinebreaks = true
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
$(ReactDOM.findDOMNode(component)).find('.public-DraftStyleDefault-block').length.should.eql 1
it 'interrupts key command for linebreak if props.stripLinebreaks', ->
@props.stripLinebreaks = true
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
keyResponse = component.handleKeyCommand('split-block')
keyResponse.should.eql 'handled'
describe '#onPaste', ->
it 'calls stripGoogleStyles', ->
@component.onChange = sinon.stub()
@component.onPaste('hello here again.', '<p>hello</p><p>here again.</p>')
@stripGoogleStyles.called.should.eql true
it 'calls standardizeSpacing', ->
@Paragraph.__set__ 'standardizeSpacing', standardizeSpacing = sinon.stub().returns('<p>hello</p><p>here again.</p>')
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0]
component.onChange = sinon.stub()
component.onPaste('hello here again.', '<p>hello</p><p>here again.</p>')
standardizeSpacing.called.should.eql true
| 128404 | benv = require 'benv'
{ resolve } = require 'path'
sinon = require 'sinon'
React = require 'react'
ReactDOM = require 'react-dom'
ReactTestUtils = require 'react-dom/test-utils'
ReactDOMServer = require 'react-dom/server'
Draft = require 'draft-js'
{ EditorState, Modifier } = require 'draft-js'
r =
find: ReactTestUtils.findRenderedDOMComponentWithClass
simulate: ReactTestUtils.Simulate
describe 'Rich Text: Paragraph', ->
beforeEach (done) ->
benv.setup =>
benv.expose
$: benv.require 'jquery'
window.jQuery = $
global.Node = window.Node
global.Element = window.Element
global.HTMLElement = window.HTMLElement
global.document = window.document
window.getSelection = sinon.stub().returns(
isCollapsed: false
getRangeAt: sinon.stub().returns(
getClientRects: sinon.stub.returns([{
bottom: 170
height: 25
left: 425
right: 525
top: 145
width: 95
}])
)
)
window.matchMedia = sinon.stub().returns(
{
matches: false
addListener: sinon.stub()
removeListener: sinon.stub()
}
)
@Paragraph = benv.require resolve __dirname, '../../components/paragraph'
@Paragraph.__set__ 'Modifier', Modifier
@Paragraph.__set__ 'EditorState', EditorState
Config = require '../../utils/config.js'
@Paragraph.__set__ 'Config', Config
{ TextNav } = benv.require(
resolve(__dirname, '../../components/text_nav')
)
@Paragraph.__set__ 'TextNav', TextNav
{ TextInputUrl } = benv.require(
resolve(__dirname, '../../components/input_url')
)
@Paragraph.__set__ 'TextInputUrl', TextInputUrl
@Paragraph.__set__ 'stickyControlsBox', sinon.stub().returns {top: 20, left: 40}
@Paragraph.__set__ 'stripGoogleStyles', @stripGoogleStyles = sinon.stub().returns('<p>hello</p><p>here again.</p>')
@leadParagraph = '<p>Here is the <em>lead</em> paragraph for <b>this</b> article.</p>'
@postscript = '<p>Illustration by <a href="http://artsy.net"><NAME></a>.</p>'
@props = {
html: @postscript
placeholder: 'Postscript (optional)'
onChange: sinon.stub()
linked: true
}
@component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], => setTimeout =>
@component.stickyControlsBox = sinon.stub().returns {top: 20, left: 40}
@component.state.editorState.getSelection().isCollapsed = sinon.stub().returns false
selection = @component.state.editorState.getSelection()
newSelection = selection.merge({
anchorKey: @component.state.editorState.getCurrentContent().getFirstBlock().key
anchorOffset: 0
focusKey: @component.state.editorState.getCurrentContent().getFirstBlock().key
focusOffset: 12
})
newEditorState = EditorState.acceptSelection(@component.state.editorState, newSelection)
@component.onChange newEditorState
done()
afterEach ->
benv.teardown()
describe 'Render', ->
it 'Shows a placeholder if provided and empty', ->
component = ReactDOMServer.renderToString React.createElement(@Paragraph, @props)
$(component).text().should.containEql 'Postscript (optional)'
it 'Renders existing html', ->
$(ReactDOM.findDOMNode(@component)).text().should.containEql 'Illustration by Tomi Um.'
it 'Renders existing link entities', ->
$(ReactDOM.findDOMNode(@component)).html().should.containEql '<a href="http://artsy.net/">'
describe 'On change', ->
it 'Sets the editorState and html on change', ->
@component.setState = sinon.stub()
r.simulate.click r.find @component, 'rich-text--paragraph__input'
@component.setState.args[1][0].editorState.should.be.ok
@component.setState.args[1][0].html.should.be.ok
it 'Calls props.onChange if content has changed', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('italic')
@component.props.onChange.called.should.eql true
it 'Does not call props.onChange if content has not changed', ->
@component.setState = sinon.stub()
r.simulate.click r.find @component, 'rich-text--paragraph__input'
@component.props.onChange.called.should.eql false
@component.setState.called.should.eql true
describe 'Key commands', ->
it 'Can toggle bold styles', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('bold')
@component.setState.args[0][0].html.should.containEql '<strong>Illustration</strong>'
it 'Does not toggle bold if type is caption', ->
@props.linked = null
@props.type = 'caption'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
component.setState = sinon.stub()
component.handleKeyCommand('bold')
component.setState.called.should.eql false
it 'Can toggle italic styles', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('italic')
@component.setState.args[0][0].html.should.containEql '<em>Illustration</em>'
it 'Does not toggle italic if type is postscript', ->
@props.linked = null
@props.type = 'postscript'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
component.setState = sinon.stub()
component.handleKeyCommand('italic')
component.setState.called.should.eql false
it 'Can toggle a link prompt', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('link-prompt')
@component.setState.args[0][0].selectionTarget.should.eql { top: 20, left: 40 }
@component.setState.args[0][0].showUrlInput.should.eql true
describe 'Nav', ->
it 'Prints Italic and Bold buttons by default', ->
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="italic">I</button><button class="bold">B</button>'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="link">'
it 'Shows correct buttons if type unspecified and linked is true', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
$(ReactDOM.findDOMNode(@component)).html().should.containEql(
'<button class="italic">I</button><button class="bold">B</button><button class="link">'
)
it 'Does not show italic if type is postscript', ->
@props.linked = null
@props.type = 'postscript'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
component.setState = sinon.stub()
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="bold">B</button><button class="link">'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="italic">I</button>'
it 'Does not show bold if type is caption', ->
@props.linked = null
@props.type = 'caption'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
component.setState = sinon.stub()
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="italic">I</button><button class="link">'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="bold">B</button>'
it 'Can toggle bold styles', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'bold'
@component.setState.args[0][0].html.should.containEql '<strong>Illustration</strong>'
it 'Can toggle italic styles', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'italic'
@component.setState.args[0][0].html.should.containEql '<em>Illustration</em>'
it 'Can toggle a link prompt', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'link'
@component.setState.args[0][0].selectionTarget.should.eql { top: 20, left: 40 }
@component.setState.args[0][0].showUrlInput.should.eql true
describe 'Links', ->
it '#hasLinks returns true if props.linked', ->
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#hasLinks returns true if type is postscript', ->
@props.type = 'postscript'
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#hasLinks returns true if type is caption', ->
@props.type = 'caption'
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#confirmLink can save a link as html', ->
@component.confirmLink('http://artsy.net')
(@component.state.html.match(/<a href=/g) || []).length.should.eql 2
describe 'Linebreaks', ->
it 'allows linebreaks by default', ->
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
$(ReactDOM.findDOMNode(component)).find('.public-DraftStyleDefault-block').length.should.eql 2
it 'strips linebreaks if props.stripLinebreaks', ->
@props.stripLinebreaks = true
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
$(ReactDOM.findDOMNode(component)).find('.public-DraftStyleDefault-block').length.should.eql 1
it 'interrupts key command for linebreak if props.stripLinebreaks', ->
@props.stripLinebreaks = true
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
keyResponse = component.handleKeyCommand('split-block')
keyResponse.should.eql 'handled'
describe '#onPaste', ->
it 'calls stripGoogleStyles', ->
@component.onChange = sinon.stub()
@component.onPaste('hello here again.', '<p>hello</p><p>here again.</p>')
@stripGoogleStyles.called.should.eql true
it 'calls standardizeSpacing', ->
@Paragraph.__set__ 'standardizeSpacing', standardizeSpacing = sinon.stub().returns('<p>hello</p><p>here again.</p>')
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0]
component.onChange = sinon.stub()
component.onPaste('hello here again.', '<p>hello</p><p>here again.</p>')
standardizeSpacing.called.should.eql true
| true | benv = require 'benv'
{ resolve } = require 'path'
sinon = require 'sinon'
React = require 'react'
ReactDOM = require 'react-dom'
ReactTestUtils = require 'react-dom/test-utils'
ReactDOMServer = require 'react-dom/server'
Draft = require 'draft-js'
{ EditorState, Modifier } = require 'draft-js'
r =
find: ReactTestUtils.findRenderedDOMComponentWithClass
simulate: ReactTestUtils.Simulate
describe 'Rich Text: Paragraph', ->
beforeEach (done) ->
benv.setup =>
benv.expose
$: benv.require 'jquery'
window.jQuery = $
global.Node = window.Node
global.Element = window.Element
global.HTMLElement = window.HTMLElement
global.document = window.document
window.getSelection = sinon.stub().returns(
isCollapsed: false
getRangeAt: sinon.stub().returns(
getClientRects: sinon.stub.returns([{
bottom: 170
height: 25
left: 425
right: 525
top: 145
width: 95
}])
)
)
window.matchMedia = sinon.stub().returns(
{
matches: false
addListener: sinon.stub()
removeListener: sinon.stub()
}
)
@Paragraph = benv.require resolve __dirname, '../../components/paragraph'
@Paragraph.__set__ 'Modifier', Modifier
@Paragraph.__set__ 'EditorState', EditorState
Config = require '../../utils/config.js'
@Paragraph.__set__ 'Config', Config
{ TextNav } = benv.require(
resolve(__dirname, '../../components/text_nav')
)
@Paragraph.__set__ 'TextNav', TextNav
{ TextInputUrl } = benv.require(
resolve(__dirname, '../../components/input_url')
)
@Paragraph.__set__ 'TextInputUrl', TextInputUrl
@Paragraph.__set__ 'stickyControlsBox', sinon.stub().returns {top: 20, left: 40}
@Paragraph.__set__ 'stripGoogleStyles', @stripGoogleStyles = sinon.stub().returns('<p>hello</p><p>here again.</p>')
@leadParagraph = '<p>Here is the <em>lead</em> paragraph for <b>this</b> article.</p>'
@postscript = '<p>Illustration by <a href="http://artsy.net">PI:NAME:<NAME>END_PI</a>.</p>'
@props = {
html: @postscript
placeholder: 'Postscript (optional)'
onChange: sinon.stub()
linked: true
}
@component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], => setTimeout =>
@component.stickyControlsBox = sinon.stub().returns {top: 20, left: 40}
@component.state.editorState.getSelection().isCollapsed = sinon.stub().returns false
selection = @component.state.editorState.getSelection()
newSelection = selection.merge({
anchorKey: @component.state.editorState.getCurrentContent().getFirstBlock().key
anchorOffset: 0
focusKey: @component.state.editorState.getCurrentContent().getFirstBlock().key
focusOffset: 12
})
newEditorState = EditorState.acceptSelection(@component.state.editorState, newSelection)
@component.onChange newEditorState
done()
afterEach ->
benv.teardown()
describe 'Render', ->
it 'Shows a placeholder if provided and empty', ->
component = ReactDOMServer.renderToString React.createElement(@Paragraph, @props)
$(component).text().should.containEql 'Postscript (optional)'
it 'Renders existing html', ->
$(ReactDOM.findDOMNode(@component)).text().should.containEql 'Illustration by Tomi Um.'
it 'Renders existing link entities', ->
$(ReactDOM.findDOMNode(@component)).html().should.containEql '<a href="http://artsy.net/">'
describe 'On change', ->
it 'Sets the editorState and html on change', ->
@component.setState = sinon.stub()
r.simulate.click r.find @component, 'rich-text--paragraph__input'
@component.setState.args[1][0].editorState.should.be.ok
@component.setState.args[1][0].html.should.be.ok
it 'Calls props.onChange if content has changed', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('italic')
@component.props.onChange.called.should.eql true
it 'Does not call props.onChange if content has not changed', ->
@component.setState = sinon.stub()
r.simulate.click r.find @component, 'rich-text--paragraph__input'
@component.props.onChange.called.should.eql false
@component.setState.called.should.eql true
describe 'Key commands', ->
it 'Can toggle bold styles', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('bold')
@component.setState.args[0][0].html.should.containEql '<strong>Illustration</strong>'
it 'Does not toggle bold if type is caption', ->
@props.linked = null
@props.type = 'caption'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
component.setState = sinon.stub()
component.handleKeyCommand('bold')
component.setState.called.should.eql false
it 'Can toggle italic styles', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('italic')
@component.setState.args[0][0].html.should.containEql '<em>Illustration</em>'
it 'Does not toggle italic if type is postscript', ->
@props.linked = null
@props.type = 'postscript'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
component.setState = sinon.stub()
component.handleKeyCommand('italic')
component.setState.called.should.eql false
it 'Can toggle a link prompt', ->
@component.setState = sinon.stub()
@component.handleKeyCommand('link-prompt')
@component.setState.args[0][0].selectionTarget.should.eql { top: 20, left: 40 }
@component.setState.args[0][0].showUrlInput.should.eql true
describe 'Nav', ->
it 'Prints Italic and Bold buttons by default', ->
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="italic">I</button><button class="bold">B</button>'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="link">'
it 'Shows correct buttons if type unspecified and linked is true', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
$(ReactDOM.findDOMNode(@component)).html().should.containEql(
'<button class="italic">I</button><button class="bold">B</button><button class="link">'
)
it 'Does not show italic if type is postscript', ->
@props.linked = null
@props.type = 'postscript'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
component.setState = sinon.stub()
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="bold">B</button><button class="link">'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="italic">I</button>'
it 'Does not show bold if type is caption', ->
@props.linked = null
@props.type = 'caption'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
r.simulate.mouseUp r.find component, 'rich-text--paragraph__input'
component.setState = sinon.stub()
$(ReactDOM.findDOMNode(component)).html().should.containEql '<button class="italic">I</button><button class="link">'
$(ReactDOM.findDOMNode(component)).html().should.not.containEql '<button class="bold">B</button>'
it 'Can toggle bold styles', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'bold'
@component.setState.args[0][0].html.should.containEql '<strong>Illustration</strong>'
it 'Can toggle italic styles', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'italic'
@component.setState.args[0][0].html.should.containEql '<em>Illustration</em>'
it 'Can toggle a link prompt', ->
r.simulate.mouseUp r.find @component, 'rich-text--paragraph__input'
@component.setState = sinon.stub()
r.simulate.mouseDown r.find @component, 'link'
@component.setState.args[0][0].selectionTarget.should.eql { top: 20, left: 40 }
@component.setState.args[0][0].showUrlInput.should.eql true
describe 'Links', ->
it '#hasLinks returns true if props.linked', ->
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#hasLinks returns true if type is postscript', ->
@props.type = 'postscript'
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#hasLinks returns true if type is caption', ->
@props.type = 'caption'
@props.linked = null
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
haslinks = component.hasLinks()
haslinks.should.eql true
it '#confirmLink can save a link as html', ->
@component.confirmLink('http://artsy.net')
(@component.state.html.match(/<a href=/g) || []).length.should.eql 2
describe 'Linebreaks', ->
it 'allows linebreaks by default', ->
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
$(ReactDOM.findDOMNode(component)).find('.public-DraftStyleDefault-block').length.should.eql 2
it 'strips linebreaks if props.stripLinebreaks', ->
@props.stripLinebreaks = true
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
$(ReactDOM.findDOMNode(component)).find('.public-DraftStyleDefault-block').length.should.eql 1
it 'interrupts key command for linebreak if props.stripLinebreaks', ->
@props.stripLinebreaks = true
@props.html = '<p>Here one paragraph.</p><p>Here is second paragraph</p>'
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0], =>
keyResponse = component.handleKeyCommand('split-block')
keyResponse.should.eql 'handled'
describe '#onPaste', ->
it 'calls stripGoogleStyles', ->
@component.onChange = sinon.stub()
@component.onPaste('hello here again.', '<p>hello</p><p>here again.</p>')
@stripGoogleStyles.called.should.eql true
it 'calls standardizeSpacing', ->
@Paragraph.__set__ 'standardizeSpacing', standardizeSpacing = sinon.stub().returns('<p>hello</p><p>here again.</p>')
component = ReactDOM.render React.createElement(@Paragraph, @props), (@$el = $ "<div></div>")[0]
component.onChange = sinon.stub()
component.onPaste('hello here again.', '<p>hello</p><p>here again.</p>')
standardizeSpacing.called.should.eql true
|
[
{
"context": ".json.httpAuth.username\n\t\tpage.settings.password = tests.json.httpAuth.password\n\n\tmethod = \"GET\"\n\tif !!test",
"end": 1047,
"score": 0.7691437005996704,
"start": 1042,
"tag": "PASSWORD",
"value": "tests"
},
{
"context": "uth.username\n\t\tpage.settings.password = tests.json.httpAuth.password\n\n\tmethod = \"GET\"\n\tif !!test.meth",
"end": 1052,
"score": 0.5535557270050049,
"start": 1052,
"tag": "PASSWORD",
"value": ""
},
{
"context": "ame\n\t\tpage.settings.password = tests.json.httpAuth.password\n\n\tmethod = \"GET\"\n\tif !!test.method\n\t\tmethod = tes",
"end": 1070,
"score": 0.8955628275871277,
"start": 1062,
"tag": "PASSWORD",
"value": "password"
}
] | duvel.coffee | nsteenv/duvel.js | 1 | fs = require "fs"
system = require "system"
webpage = require "webpage"
renderPath = "."
authenticityToken = ""
tests = {}
runTests = ->
tests.index++
test = tests.json.routes.shift()
if !test
tests.endDate = new Date()
console.log "[" + Math.round(tests.endDate.getTime() - tests.runDate.getTime()) + "ms] " + tests.file.match(/\/([a-z0-9_]+).json$/)[1] + " finished"
phantom.exit 0
renderUrl test
renderUrl = (test) ->
page = webpage.create()
page.viewportSize = if test.viewportSize then test.viewportSize else { width: 1024, height: 768 }
page.settings.userAgent = "Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7";
page.onError = (msg, trace) ->
console.log "[JS Error] : #{msg}"
console.log "--------------------"
for idx, item of trace
console.log "#{item.function} #{item.file} : #{item.line}"
console.log "--------------------"
if !!tests.json.httpAuth
page.settings.userName = tests.json.httpAuth.username
page.settings.password = tests.json.httpAuth.password
method = "GET"
if !!test.method
method = test.method
data = ""
if !!test.data
data += "#{key}=#{value}&" for key, value of test.data
if !!authenticityToken
data += "authenticityToken=#{authenticityToken}"
testUrl = tests.baseUrl + test.route
if method == "GET" && data
testUrl += "? #{data}"
startDate = new Date()
page.open testUrl, method, data, (status) ->
openDate = new Date()
console.log "[" + Math.round(openDate.getTime() - startDate.getTime()) + "ms] #{method} #{testUrl}"
authenticityToken = page.evaluate ->
if document.getElementsByName("authenticityToken").length > 0
return document.getElementsByName("authenticityToken")[0].value
if !!test.script
# page.includeJs "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js",
eval("page.evaluate(function(){"+test.script+"});")
fileName = renderPath + "/" + tests.file.match(/\/([a-z0-9_]+).json$/)[1] + "/"
fileName += tests.index + test.route.replace(/[\/\*\|\;]/g,"_") + "_#{method}.png"
setTimeout(
->
if status == "success"
if !test.ignore
page.render(fileName)
renderDate = new Date()
console.log "[" + Math.round(renderDate.getTime() - openDate.getTime()) + "ms] Render #{fileName}"
else
console.log "Error opening: #{testUrl}"
console.log "Status: #{status}"
endDate = new Date()
setTimeout runTests, 10
page.close()
console.log "[" + Math.round((endDate.getTime() - startDate.getTime())) + "ms] #{fileName} finished"
, if test.wait then test.wait else 1)
run = ->
if !!phantom.args[0] && !!phantom.args[1]
tests.runDate = new Date()
tests.baseUrl = phantom.args[0]
tests.file = phantom.args[1]
tests.index = 0;
if !!phantom.args[2]
renderPath = phantom.args[2]
try
console.log "Reading tests routes from file: #{tests.file}"
tests.json = JSON.parse(fs.read(tests.file))
catch e
console.log "Could not read file #{tests.file}:\n" + e
phantom.exit 1
runTests()
else
console.log "Usage: phantomjs capture.coffee <baseUrl> <testFile> [renderPath] [--debug]"
phantom.exit 1
run() | 89668 | fs = require "fs"
system = require "system"
webpage = require "webpage"
renderPath = "."
authenticityToken = ""
tests = {}
runTests = ->
tests.index++
test = tests.json.routes.shift()
if !test
tests.endDate = new Date()
console.log "[" + Math.round(tests.endDate.getTime() - tests.runDate.getTime()) + "ms] " + tests.file.match(/\/([a-z0-9_]+).json$/)[1] + " finished"
phantom.exit 0
renderUrl test
renderUrl = (test) ->
page = webpage.create()
page.viewportSize = if test.viewportSize then test.viewportSize else { width: 1024, height: 768 }
page.settings.userAgent = "Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7";
page.onError = (msg, trace) ->
console.log "[JS Error] : #{msg}"
console.log "--------------------"
for idx, item of trace
console.log "#{item.function} #{item.file} : #{item.line}"
console.log "--------------------"
if !!tests.json.httpAuth
page.settings.userName = tests.json.httpAuth.username
page.settings.password = <PASSWORD>.json<PASSWORD>.httpAuth.<PASSWORD>
method = "GET"
if !!test.method
method = test.method
data = ""
if !!test.data
data += "#{key}=#{value}&" for key, value of test.data
if !!authenticityToken
data += "authenticityToken=#{authenticityToken}"
testUrl = tests.baseUrl + test.route
if method == "GET" && data
testUrl += "? #{data}"
startDate = new Date()
page.open testUrl, method, data, (status) ->
openDate = new Date()
console.log "[" + Math.round(openDate.getTime() - startDate.getTime()) + "ms] #{method} #{testUrl}"
authenticityToken = page.evaluate ->
if document.getElementsByName("authenticityToken").length > 0
return document.getElementsByName("authenticityToken")[0].value
if !!test.script
# page.includeJs "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js",
eval("page.evaluate(function(){"+test.script+"});")
fileName = renderPath + "/" + tests.file.match(/\/([a-z0-9_]+).json$/)[1] + "/"
fileName += tests.index + test.route.replace(/[\/\*\|\;]/g,"_") + "_#{method}.png"
setTimeout(
->
if status == "success"
if !test.ignore
page.render(fileName)
renderDate = new Date()
console.log "[" + Math.round(renderDate.getTime() - openDate.getTime()) + "ms] Render #{fileName}"
else
console.log "Error opening: #{testUrl}"
console.log "Status: #{status}"
endDate = new Date()
setTimeout runTests, 10
page.close()
console.log "[" + Math.round((endDate.getTime() - startDate.getTime())) + "ms] #{fileName} finished"
, if test.wait then test.wait else 1)
run = ->
if !!phantom.args[0] && !!phantom.args[1]
tests.runDate = new Date()
tests.baseUrl = phantom.args[0]
tests.file = phantom.args[1]
tests.index = 0;
if !!phantom.args[2]
renderPath = phantom.args[2]
try
console.log "Reading tests routes from file: #{tests.file}"
tests.json = JSON.parse(fs.read(tests.file))
catch e
console.log "Could not read file #{tests.file}:\n" + e
phantom.exit 1
runTests()
else
console.log "Usage: phantomjs capture.coffee <baseUrl> <testFile> [renderPath] [--debug]"
phantom.exit 1
run() | true | fs = require "fs"
system = require "system"
webpage = require "webpage"
renderPath = "."
authenticityToken = ""
tests = {}
runTests = ->
tests.index++
test = tests.json.routes.shift()
if !test
tests.endDate = new Date()
console.log "[" + Math.round(tests.endDate.getTime() - tests.runDate.getTime()) + "ms] " + tests.file.match(/\/([a-z0-9_]+).json$/)[1] + " finished"
phantom.exit 0
renderUrl test
renderUrl = (test) ->
page = webpage.create()
page.viewportSize = if test.viewportSize then test.viewportSize else { width: 1024, height: 768 }
page.settings.userAgent = "Mozilla/5.0 (Windows NT 6.0; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7";
page.onError = (msg, trace) ->
console.log "[JS Error] : #{msg}"
console.log "--------------------"
for idx, item of trace
console.log "#{item.function} #{item.file} : #{item.line}"
console.log "--------------------"
if !!tests.json.httpAuth
page.settings.userName = tests.json.httpAuth.username
page.settings.password = PI:PASSWORD:<PASSWORD>END_PI.jsonPI:PASSWORD:<PASSWORD>END_PI.httpAuth.PI:PASSWORD:<PASSWORD>END_PI
method = "GET"
if !!test.method
method = test.method
data = ""
if !!test.data
data += "#{key}=#{value}&" for key, value of test.data
if !!authenticityToken
data += "authenticityToken=#{authenticityToken}"
testUrl = tests.baseUrl + test.route
if method == "GET" && data
testUrl += "? #{data}"
startDate = new Date()
page.open testUrl, method, data, (status) ->
openDate = new Date()
console.log "[" + Math.round(openDate.getTime() - startDate.getTime()) + "ms] #{method} #{testUrl}"
authenticityToken = page.evaluate ->
if document.getElementsByName("authenticityToken").length > 0
return document.getElementsByName("authenticityToken")[0].value
if !!test.script
# page.includeJs "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js",
eval("page.evaluate(function(){"+test.script+"});")
fileName = renderPath + "/" + tests.file.match(/\/([a-z0-9_]+).json$/)[1] + "/"
fileName += tests.index + test.route.replace(/[\/\*\|\;]/g,"_") + "_#{method}.png"
setTimeout(
->
if status == "success"
if !test.ignore
page.render(fileName)
renderDate = new Date()
console.log "[" + Math.round(renderDate.getTime() - openDate.getTime()) + "ms] Render #{fileName}"
else
console.log "Error opening: #{testUrl}"
console.log "Status: #{status}"
endDate = new Date()
setTimeout runTests, 10
page.close()
console.log "[" + Math.round((endDate.getTime() - startDate.getTime())) + "ms] #{fileName} finished"
, if test.wait then test.wait else 1)
run = ->
if !!phantom.args[0] && !!phantom.args[1]
tests.runDate = new Date()
tests.baseUrl = phantom.args[0]
tests.file = phantom.args[1]
tests.index = 0;
if !!phantom.args[2]
renderPath = phantom.args[2]
try
console.log "Reading tests routes from file: #{tests.file}"
tests.json = JSON.parse(fs.read(tests.file))
catch e
console.log "Could not read file #{tests.file}:\n" + e
phantom.exit 1
runTests()
else
console.log "Usage: phantomjs capture.coffee <baseUrl> <testFile> [renderPath] [--debug]"
phantom.exit 1
run() |
[
{
"context": "save', ->\n jysperm = new User\n name: 'jysperm'\n token:\n code: '03b9a5f0d18bc6b6",
"end": 368,
"score": 0.9997127652168274,
"start": 361,
"tag": "USERNAME",
"value": "jysperm"
},
{
"context": " name: 'jysperm'\n token:\n code: '03b9a5f0d18bc6b6'\n\n jysperm.token.should.be.instanceof Token\n",
"end": 418,
"score": 0.994843602180481,
"start": 402,
"tag": "KEY",
"value": "03b9a5f0d18bc6b6"
},
{
"context": "en\n jysperm.token.getCode().should.be.equal '03b9a5f0d18bc6b6'\n jysperm.token._id.should.be.exists\n\n ",
"end": 531,
"score": 0.9723303914070129,
"start": 515,
"tag": "KEY",
"value": "03b9a5f0d18bc6b6"
},
{
"context": "ument', ->\n token = new Token\n code: '03b9a5f0d18bc6b6'\n\n User.create\n name: 'jysperm'\n ",
"end": 748,
"score": 0.9895145297050476,
"start": 732,
"tag": "KEY",
"value": "03b9a5f0d18bc6b6"
},
{
"context": "b9a5f0d18bc6b6'\n\n User.create\n name: 'jysperm'\n token: token\n . then (jysperm) ->\n ",
"end": 791,
"score": 0.99972003698349,
"start": 784,
"tag": "USERNAME",
"value": "jysperm"
},
{
"context": "\n jysperm.token.getCode().should.be.equal '03b9a5f0d18bc6b6'\n jysperm.token._id.should.be.exists\n\n ",
"end": 954,
"score": 0.9926213622093201,
"start": 938,
"tag": "KEY",
"value": "03b9a5f0d18bc6b6"
},
{
"context": "fail', (done) ->\n User.create\n name: 'jysperm'\n token:\n code: 1024\n , (err",
"end": 1088,
"score": 0.9997200965881348,
"start": 1081,
"tag": "USERNAME",
"value": "jysperm"
},
{
"context": "ment', (done) ->\n User.create\n name: 'jysperm'\n , (err) ->\n err.should.be.match /to",
"end": 1292,
"score": 0.9997214674949646,
"start": 1285,
"tag": "USERNAME",
"value": "jysperm"
},
{
"context": "te document', ->\n User.create\n name: 'jysperm'\n token:\n code: '03b9a5f0d18bc6b6",
"end": 1465,
"score": 0.9997196197509766,
"start": 1458,
"tag": "USERNAME",
"value": "jysperm"
},
{
"context": " name: 'jysperm'\n token:\n code: '03b9a5f0d18bc6b6'\n .then (jysperm) ->\n jysperm.token.u",
"end": 1515,
"score": 0.9927902817726135,
"start": 1499,
"tag": "KEY",
"value": "03b9a5f0d18bc6b6"
},
{
"context": "fy document', ->\n User.create\n name: 'jysperm'\n token:\n code: '03b9a5f0d18bc6b6",
"end": 1902,
"score": 0.9996575713157654,
"start": 1895,
"tag": "USERNAME",
"value": "jysperm"
},
{
"context": " name: 'jysperm'\n token:\n code: '03b9a5f0d18bc6b6'\n .then (jysperm) ->\n jysperm.token.m",
"end": 1952,
"score": 0.9007718563079834,
"start": 1936,
"tag": "KEY",
"value": "03b9a5f0d18bc6b6"
},
{
"context": "ve document', ->\n User.create\n name: 'jysperm'\n token:\n code: '03b9a5f0d18bc6b6",
"end": 2227,
"score": 0.9996290802955627,
"start": 2220,
"tag": "USERNAME",
"value": "jysperm"
},
{
"context": " name: 'jysperm'\n token:\n code: '03b9a5f0d18bc6b6'\n .then (jysperm) ->\n jysperm.token.r",
"end": 2277,
"score": 0.9054041504859924,
"start": 2261,
"tag": "KEY",
"value": "03b9a5f0d18bc6b6"
}
] | test/embedded.document.test.coffee | jysperm/Mabolo | 33 | describe 'embedded.document', ->
mabolo = new Mabolo mongodb_uri
Token = mabolo.model 'Token',
code: String
Token::getCode = ->
return @code
User = mabolo.model 'User',
name: String
token:
required: true
type: Token
describe 'create document', ->
it 'construct and save', ->
jysperm = new User
name: 'jysperm'
token:
code: '03b9a5f0d18bc6b6'
jysperm.token.should.be.instanceof Token
jysperm.token.getCode().should.be.equal '03b9a5f0d18bc6b6'
jysperm.token._id.should.be.exists
jysperm.toObject().token.should.not.instanceof Token
return jysperm.save()
it 'create document', ->
token = new Token
code: '03b9a5f0d18bc6b6'
User.create
name: 'jysperm'
token: token
. then (jysperm) ->
jysperm.token.should.be.instanceof Token
jysperm.token.getCode().should.be.equal '03b9a5f0d18bc6b6'
jysperm.token._id.should.be.exists
it 'create when validating fail', (done) ->
User.create
name: 'jysperm'
token:
code: 1024
, (err) ->
err.should.be.match /code/
done()
it 'create when missing embedded document', (done) ->
User.create
name: 'jysperm'
, (err) ->
err.should.be.match /token/
done()
describe 'update document', ->
it 'update document', ->
User.create
name: 'jysperm'
token:
code: '03b9a5f0d18bc6b6'
.then (jysperm) ->
jysperm.token.update
$set:
code: 'updated'
.then (token) ->
token.code.should.be.equal 'updated'
User.findById(jysperm._id).then (jysperm) ->
jysperm.token.code.should.be.equal 'updated'
describe 'modify document', ->
it 'modify document', ->
User.create
name: 'jysperm'
token:
code: '03b9a5f0d18bc6b6'
.then (jysperm) ->
jysperm.token.modify ->
jysperm.token.code = 'updated'
.then (token) ->
token.code.should.be.equal 'updated'
describe 'remove document', ->
it 'remove document', ->
User.create
name: 'jysperm'
token:
code: '03b9a5f0d18bc6b6'
.then (jysperm) ->
jysperm.token.remove().then ->
expect(jysperm.token).to.not.exists
User.findById(jysperm._id).then (jysperm) ->
expect(jysperm.token).to.not.exists
| 180544 | describe 'embedded.document', ->
mabolo = new Mabolo mongodb_uri
Token = mabolo.model 'Token',
code: String
Token::getCode = ->
return @code
User = mabolo.model 'User',
name: String
token:
required: true
type: Token
describe 'create document', ->
it 'construct and save', ->
jysperm = new User
name: 'jysperm'
token:
code: '<KEY>'
jysperm.token.should.be.instanceof Token
jysperm.token.getCode().should.be.equal '<KEY>'
jysperm.token._id.should.be.exists
jysperm.toObject().token.should.not.instanceof Token
return jysperm.save()
it 'create document', ->
token = new Token
code: '<KEY>'
User.create
name: 'jysperm'
token: token
. then (jysperm) ->
jysperm.token.should.be.instanceof Token
jysperm.token.getCode().should.be.equal '<KEY>'
jysperm.token._id.should.be.exists
it 'create when validating fail', (done) ->
User.create
name: 'jysperm'
token:
code: 1024
, (err) ->
err.should.be.match /code/
done()
it 'create when missing embedded document', (done) ->
User.create
name: 'jysperm'
, (err) ->
err.should.be.match /token/
done()
describe 'update document', ->
it 'update document', ->
User.create
name: 'jysperm'
token:
code: '<KEY>'
.then (jysperm) ->
jysperm.token.update
$set:
code: 'updated'
.then (token) ->
token.code.should.be.equal 'updated'
User.findById(jysperm._id).then (jysperm) ->
jysperm.token.code.should.be.equal 'updated'
describe 'modify document', ->
it 'modify document', ->
User.create
name: 'jysperm'
token:
code: '<KEY>'
.then (jysperm) ->
jysperm.token.modify ->
jysperm.token.code = 'updated'
.then (token) ->
token.code.should.be.equal 'updated'
describe 'remove document', ->
it 'remove document', ->
User.create
name: 'jysperm'
token:
code: '<KEY>'
.then (jysperm) ->
jysperm.token.remove().then ->
expect(jysperm.token).to.not.exists
User.findById(jysperm._id).then (jysperm) ->
expect(jysperm.token).to.not.exists
| true | describe 'embedded.document', ->
mabolo = new Mabolo mongodb_uri
Token = mabolo.model 'Token',
code: String
Token::getCode = ->
return @code
User = mabolo.model 'User',
name: String
token:
required: true
type: Token
describe 'create document', ->
it 'construct and save', ->
jysperm = new User
name: 'jysperm'
token:
code: 'PI:KEY:<KEY>END_PI'
jysperm.token.should.be.instanceof Token
jysperm.token.getCode().should.be.equal 'PI:KEY:<KEY>END_PI'
jysperm.token._id.should.be.exists
jysperm.toObject().token.should.not.instanceof Token
return jysperm.save()
it 'create document', ->
token = new Token
code: 'PI:KEY:<KEY>END_PI'
User.create
name: 'jysperm'
token: token
. then (jysperm) ->
jysperm.token.should.be.instanceof Token
jysperm.token.getCode().should.be.equal 'PI:KEY:<KEY>END_PI'
jysperm.token._id.should.be.exists
it 'create when validating fail', (done) ->
User.create
name: 'jysperm'
token:
code: 1024
, (err) ->
err.should.be.match /code/
done()
it 'create when missing embedded document', (done) ->
User.create
name: 'jysperm'
, (err) ->
err.should.be.match /token/
done()
describe 'update document', ->
it 'update document', ->
User.create
name: 'jysperm'
token:
code: 'PI:KEY:<KEY>END_PI'
.then (jysperm) ->
jysperm.token.update
$set:
code: 'updated'
.then (token) ->
token.code.should.be.equal 'updated'
User.findById(jysperm._id).then (jysperm) ->
jysperm.token.code.should.be.equal 'updated'
describe 'modify document', ->
it 'modify document', ->
User.create
name: 'jysperm'
token:
code: 'PI:KEY:<KEY>END_PI'
.then (jysperm) ->
jysperm.token.modify ->
jysperm.token.code = 'updated'
.then (token) ->
token.code.should.be.equal 'updated'
describe 'remove document', ->
it 'remove document', ->
User.create
name: 'jysperm'
token:
code: 'PI:KEY:<KEY>END_PI'
.then (jysperm) ->
jysperm.token.remove().then ->
expect(jysperm.token).to.not.exists
User.findById(jysperm._id).then (jysperm) ->
expect(jysperm.token).to.not.exists
|
[
{
"context": "der()\n\n view.$el.find('input[name=name]').val('New Name')\n view.$el.find('select[name=category]').val(",
"end": 2181,
"score": 0.9710872173309326,
"start": 2173,
"tag": "NAME",
"value": "New Name"
},
{
"context": "pect(model.set).toHaveBeenCalledWith\n name: 'New Name'\n category_id: '11'\n account_id: 123\n ",
"end": 2405,
"score": 0.987543523311615,
"start": 2397,
"tag": "NAME",
"value": "New Name"
},
{
"context": "l = new DotLedger.Models.SortingRule\n name: 'Foobar'\n category_id: '22'\n tag_list: 'Foo, Ba",
"end": 2629,
"score": 0.8875681757926941,
"start": 2623,
"tag": "NAME",
"value": "Foobar"
}
] | spec/javascripts/dot_ledger/views/sorted_transactions/form_spec.js.coffee | timobleeker/dotledger | 0 | describe "DotLedger.Views.SortedTransactions.Form", ->
createView = (model = new DotLedger.Models.SortedTransaction())->
categories = new DotLedger.Collections.Categories [
{
id: 11
name: 'Category One'
type: 'Essential'
}
{
id: 22
name: 'Category Two'
type: 'Flexible'
}
{
id: 33
name: 'Category Three'
type: 'Income'
}
{
id: 44
name: 'Transfer In'
type: 'Transfer'
}
]
transaction = new DotLedger.Models.Transaction
search: 'Some Search'
account_id: 123
id: 345
view = new DotLedger.Views.SortedTransactions.Form
model: model
transaction: transaction
categories: categories
view
it "should be defined", ->
expect(DotLedger.Views.SortedTransactions.Form).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.SortedTransactions.Form).toUseTemplate('sorted_transactions/form')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the form fields", ->
view = createView().render()
expect(view.$el).toContainElement('input[name=name]')
expect(view.$el).toContainElement('select[name=category]')
expect(view.$el).toContainElement('option[value=11]')
expect(view.$el).toContainElement('option[value=22]')
expect(view.$el).toContainElement('option[value=33]')
expect(view.$el).toContainElement('option[value=44]')
expect(view.$el).toContainElement('optgroup[label=Essential]')
expect(view.$el).toContainElement('optgroup[label=Flexible]')
expect(view.$el).toContainElement('optgroup[label=Income]')
expect(view.$el).toContainElement('optgroup[label=Transfer]')
expect(view.$el).toContainElement('input[name=tags]')
it "renders the heading", ->
view = createView().render()
expect(view.$el).toHaveText(/Sort Transaction/)
it "should set the values on the model when update is called", ->
model = new DotLedger.Models.SortedTransaction()
view = createView(model).render()
view.$el.find('input[name=name]').val('New Name')
view.$el.find('select[name=category]').val('11')
view.$el.find('input[name=tags]').val('Foo, Bar, Baz')
spyOn(model, 'set')
view.update()
expect(model.set).toHaveBeenCalledWith
name: 'New Name'
category_id: '11'
account_id: 123
transaction_id: 345
tags: 'Foo, Bar, Baz'
it "renders the form fields with the model values", ->
model = new DotLedger.Models.SortingRule
name: 'Foobar'
category_id: '22'
tag_list: 'Foo, Bar, Baz'
view = createView(model).render()
expect(view.$el.find('input[name=name]')).toHaveValue('Foobar')
expect(view.$el.find('select[name=category]')).toHaveValue('22')
expect(view.$el.find('input[name=tags]')).toHaveValue('Foo, Bar, Baz')
| 151768 | describe "DotLedger.Views.SortedTransactions.Form", ->
createView = (model = new DotLedger.Models.SortedTransaction())->
categories = new DotLedger.Collections.Categories [
{
id: 11
name: 'Category One'
type: 'Essential'
}
{
id: 22
name: 'Category Two'
type: 'Flexible'
}
{
id: 33
name: 'Category Three'
type: 'Income'
}
{
id: 44
name: 'Transfer In'
type: 'Transfer'
}
]
transaction = new DotLedger.Models.Transaction
search: 'Some Search'
account_id: 123
id: 345
view = new DotLedger.Views.SortedTransactions.Form
model: model
transaction: transaction
categories: categories
view
it "should be defined", ->
expect(DotLedger.Views.SortedTransactions.Form).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.SortedTransactions.Form).toUseTemplate('sorted_transactions/form')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the form fields", ->
view = createView().render()
expect(view.$el).toContainElement('input[name=name]')
expect(view.$el).toContainElement('select[name=category]')
expect(view.$el).toContainElement('option[value=11]')
expect(view.$el).toContainElement('option[value=22]')
expect(view.$el).toContainElement('option[value=33]')
expect(view.$el).toContainElement('option[value=44]')
expect(view.$el).toContainElement('optgroup[label=Essential]')
expect(view.$el).toContainElement('optgroup[label=Flexible]')
expect(view.$el).toContainElement('optgroup[label=Income]')
expect(view.$el).toContainElement('optgroup[label=Transfer]')
expect(view.$el).toContainElement('input[name=tags]')
it "renders the heading", ->
view = createView().render()
expect(view.$el).toHaveText(/Sort Transaction/)
it "should set the values on the model when update is called", ->
model = new DotLedger.Models.SortedTransaction()
view = createView(model).render()
view.$el.find('input[name=name]').val('<NAME>')
view.$el.find('select[name=category]').val('11')
view.$el.find('input[name=tags]').val('Foo, Bar, Baz')
spyOn(model, 'set')
view.update()
expect(model.set).toHaveBeenCalledWith
name: '<NAME>'
category_id: '11'
account_id: 123
transaction_id: 345
tags: 'Foo, Bar, Baz'
it "renders the form fields with the model values", ->
model = new DotLedger.Models.SortingRule
name: '<NAME>'
category_id: '22'
tag_list: 'Foo, Bar, Baz'
view = createView(model).render()
expect(view.$el.find('input[name=name]')).toHaveValue('Foobar')
expect(view.$el.find('select[name=category]')).toHaveValue('22')
expect(view.$el.find('input[name=tags]')).toHaveValue('Foo, Bar, Baz')
| true | describe "DotLedger.Views.SortedTransactions.Form", ->
createView = (model = new DotLedger.Models.SortedTransaction())->
categories = new DotLedger.Collections.Categories [
{
id: 11
name: 'Category One'
type: 'Essential'
}
{
id: 22
name: 'Category Two'
type: 'Flexible'
}
{
id: 33
name: 'Category Three'
type: 'Income'
}
{
id: 44
name: 'Transfer In'
type: 'Transfer'
}
]
transaction = new DotLedger.Models.Transaction
search: 'Some Search'
account_id: 123
id: 345
view = new DotLedger.Views.SortedTransactions.Form
model: model
transaction: transaction
categories: categories
view
it "should be defined", ->
expect(DotLedger.Views.SortedTransactions.Form).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.SortedTransactions.Form).toUseTemplate('sorted_transactions/form')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the form fields", ->
view = createView().render()
expect(view.$el).toContainElement('input[name=name]')
expect(view.$el).toContainElement('select[name=category]')
expect(view.$el).toContainElement('option[value=11]')
expect(view.$el).toContainElement('option[value=22]')
expect(view.$el).toContainElement('option[value=33]')
expect(view.$el).toContainElement('option[value=44]')
expect(view.$el).toContainElement('optgroup[label=Essential]')
expect(view.$el).toContainElement('optgroup[label=Flexible]')
expect(view.$el).toContainElement('optgroup[label=Income]')
expect(view.$el).toContainElement('optgroup[label=Transfer]')
expect(view.$el).toContainElement('input[name=tags]')
it "renders the heading", ->
view = createView().render()
expect(view.$el).toHaveText(/Sort Transaction/)
it "should set the values on the model when update is called", ->
model = new DotLedger.Models.SortedTransaction()
view = createView(model).render()
view.$el.find('input[name=name]').val('PI:NAME:<NAME>END_PI')
view.$el.find('select[name=category]').val('11')
view.$el.find('input[name=tags]').val('Foo, Bar, Baz')
spyOn(model, 'set')
view.update()
expect(model.set).toHaveBeenCalledWith
name: 'PI:NAME:<NAME>END_PI'
category_id: '11'
account_id: 123
transaction_id: 345
tags: 'Foo, Bar, Baz'
it "renders the form fields with the model values", ->
model = new DotLedger.Models.SortingRule
name: 'PI:NAME:<NAME>END_PI'
category_id: '22'
tag_list: 'Foo, Bar, Baz'
view = createView(model).render()
expect(view.$el.find('input[name=name]')).toHaveValue('Foobar')
expect(view.$el.find('select[name=category]')).toHaveValue('22')
expect(view.$el.find('input[name=tags]')).toHaveValue('Foo, Bar, Baz')
|
[
{
"context": ".\n# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/\n\n$(document).ready(() =>",
"end": 202,
"score": 0.9059174656867981,
"start": 193,
"tag": "USERNAME",
"value": "jashkenas"
},
{
"context": "eScript in this file: http://jashkenas.github.com/coffee-script/\n\n$(document).ready(() =>\n @event_manager = ne",
"end": 227,
"score": 0.9299864768981934,
"start": 214,
"tag": "USERNAME",
"value": "coffee-script"
},
{
"context": "s_id:\"#pattern-defs\",\n element_key:\"pattern_id\"})\n\n @gradientItemsView = new GradientPanelVie",
"end": 2043,
"score": 0.9592996835708618,
"start": 2041,
"tag": "KEY",
"value": "id"
},
{
"context": "efs_id:\"#filter-defs\",\n element_key:\"filter_id\"})\n\n @filterItemsView.setTemplate(_.template('",
"end": 2469,
"score": 0.9845091104507446,
"start": 2467,
"tag": "KEY",
"value": "id"
}
] | coffee/main.coffee | hi104/rapen | 8 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
$(document).ready(() =>
@event_manager = new EventManager()
@cloneControlView = new CloneControlView({
el: $("#clone-control-view"),
line_wrapper: $("#clone-select-line-views"),
select_el: $("#clone-selected-view"),
manager:@event_manager
})
@event_manager.setControl(@cloneControlView)
@SvgCanvasBase = new SvgCanvas({
el: $("#svg-canvas-base"),
control: @cloneControlView,
mainCanvas: $("#svg-canvas")[0],
manager: @event_manager
})
@event_manager.setCanvas(@SvgCanvasBase)
@cloneControlView.setCanvas(@SvgCanvasBase)
@svgPathControl = new SvgPathControlView(el:$("#path-control-panel"))
@inspectorListView = new InspectorListView({
control: @cloneControlView,
item_list: SvgCanvasBase.item_list
})
@inspectorDragAndDrop = new InspectorDragAndDrop()
$("#inspector-list").append(@inspectorListView.el)
@SvgCanvasBase.bind("onZoom", (e) =>
canvas_transform = $(@SvgCanvasBase.mainCanvas).attr("transform")
$(grid_view.el).attr("stroke-width", 0.5 * (1 / SvgCanvasBase.zoomValue))
$(grid_view.el).attr("transform", canvas_transform)
$("#clone-control-view-wapper").attr("transform", canvas_transform)
cloneControlView.render()
svgPathControl.render()
)
@SvgItems = new SvgItemList
@SvgItemToolView = new SvgItemToolView({model:@SvgItems, el:$("#svg-item-list"), canvas:SvgCanvasBase})
for svg in SvgSample
do (svg) ->
SvgItems.add(new SvgItem(name:"item", contents:svg))
@patternItemsView = new PatternPanelView({
model:new SvgItemList,
el:$("#pattern-items"),
control:cloneControlView,
defs_id:"#pattern-defs",
element_key:"pattern_id"})
@gradientItemsView = new GradientPanelView({
model:new SvgItemList,
el:$("#gradient-items"),
control:cloneControlView,
defs_id:"#gradient-defs",
element_key:"gradient_id"})
@filterItemsView = new FilterPanelView({
model:new SvgItemList,
el:$("#filter-items"),
control:cloneControlView,
defs_id:"#filter-defs",
element_key:"filter_id"})
@filterItemsView.setTemplate(_.template('<rect x="10" y="10" filter="url(#{{element_id}})" fill="white" width="30" height="30"></rect>'))
@gradientItemsView.loadFile("partial/gradient_defs.html")
@patternItemsView.loadFile("partial/pattern_defs.html")
@filterItemsView.loadFile("partial/filter_defs.html")
@orderControl = new ZOrderControl(canvas:@SvgCanvasBase)
@orderControl.bind("onMove", () => inspectorListView.sortByIndex())
$("#export-button").click((e)-> SvgExport())
$("#open-file-button").click((e)->
$("#fileModal").modal()
)
$("#open-image-file-button").click((e)->
$("#imageFileModal").modal()
)
@grid_setting = new GridSetting(width:800, height:600, grid_size:10, visible:true)
@grid_view = new SvgGridView(model:@grid_setting, el:$("#svg-canvas-grid"), width:800, height:600)
@grid_view.render()
@grid_setting_view = new GridSettingView(model:@grid_setting, el:$("#grid-setting"))
@grid_setting_view.render()
@open_file_view = new OpenFileView(el:$("#fileModal"))
@open_image_file_view = new OpenImageFileView(el:$("#imageFileModal"))
@contextMenu = new ContextMenuView(el:$("#svg-canvas-base"))
@snap_line_view = new SnapLineView(el:$("#snap-line-view"))
@snap_item_view = new SnapItemView(el:$("#snap-item-view"))
$('#panel-tabs a').click((e)->
e.preventDefault()
$(this).tab('show')
)
event_manager.setMode('control')
mode_view = new ModeView(
el: $("#mode-btn-group"),
manager: event_manager
)
mode_view.render()
@undo_redo_view = new UndoRedoView(
el: $('#undo-redo-view'),
stack: GLOBAL.commandService.command_stack
)
undo_redo_view.render()
for i in _.map(_.range(1, 30), (e) -> 0.1 * e )
temp = _.template('<option value="{{val}}" {{option}}> {{name}}</option>')
option = ""
e = Math.round(i*100)
if(e == 100)
option = "selected"
$("#zoom-control").append temp(option:option, name: e + "%", val: i)
$("#zoom-control").change((e) =>
SvgCanvasBase.zoom($("#zoom-control").val(), { x: 400, y:300}, false)
)
key("backspace, delete", (e) =>
e.preventDefault();
SvgCanvasBase.deleteSelectedItem()
)
key("c", (e) => event_manager.setMode('control'))
key("t", (e) => event_manager.setMode('text'))
key("v", (e) => event_manager.setMode('path'))
key("g", (e) => event_manager.setMode('grad'))
move_item_position = (pos) =>
if cloneControlView.item_list.length > 0
cloneControlView.getControlItem().move(pos)
move_keys =
[{key:"up", x:0, y:-1},
{key:"down", x:0, y:1},
{key:"right", x:1, y:0},
{key:"left", x:-1, y:0}]
for move in move_keys
do (move) =>
key(move.key, (e) =>
move_item_position({x:move.x, y:move.y})
e.preventDefault()
)
$("#gradient-rotate").knob({
"change": (v) =>
el = cloneControlView.firstOriginalItem().el
bbox = el.getBBox()
id = $(el).attr("id") + "-grad"
cx = bbox.width/2
cy = bbox.height/2
attr = "rotate(" + v + ")"
$("#" + id)[0].setAttributeNS(null, "gradientTransform", attr)
});
update_pattern = () =>
el = cloneControlView.firstOriginalItem().el
bbox = el.getBBox()
id = $(el).attr("id") + "-pattern"
cx = bbox.width/2
cy = bbox.height/2
v = $("#pattern-rotate").val()
scale = Math.pow($( "#pattern-slider" ).slider( "value" )/25, 2)
attr = "rotate(#{v}, #{cx}, #{cy}) scale(#{scale})"
$("#" + id)[0].setAttributeNS(null, "patternTransform", attr)
$("#pattern-rotate").knob({
"change": (v) =>
update_pattern()
});
$("#pattern-slider").slider({
slide: ( event, ui ) =>
update_pattern()
});
$('#grid-check').click((e) =>
if $('#grid-check')[0].checked then grid_view.show() else grid_view.hide()
);
$(".navbar-fixed-top").hide();
$(".container-fluid").css("padding-top", "0px");
$("#add-folder-button").click((e) ->
SvgCanvasBase.addFolder()
)
$("#delete-item-button").click((e) ->
SvgCanvasBase.deleteSelectedItem()
)
initPropertyEdit()
cloneControlView.hide()
)
@excutePathBoolean = (operate) =>
if cloneControlView.item_list.length == 2
item1 = cloneControlView.item_list.at(0).get("origin_model")
item2 = cloneControlView.item_list.at(1).get("origin_model")
path1 = new paper.CompoundPath()
path2 = new paper.CompoundPath()
paperMatrix = (sm) => new paper.Matrix(sm.a, sm.b, sm.c, sm.d, sm.e, sm.f)
path1.setPathData($(item1.el).attr("d"))
path2.setPathData($(item2.el).attr("d"))
path1.transform(paperMatrix(item1.getLocalMatrix()))
path2.transform(paperMatrix(item2.getLocalMatrix()))
#all path set clockwise
for path in [path1, path2]
for child in path._children
if (not child.isClockwise())
child.reverse()
path = path2[operate](path1)
if _(["exclude", "divide"]).contains(operate)
# path type is paper.Group
path._children.forEach((item) =>
path_el = item1.el.cloneNode(true)
$(path_el).attr({
"d": item.getPathData(),
"fill-rule": "evenodd",
"transform": "",
"id": ""
})
SvgCanvasBase.addElement(path_el)
)
SvgCanvasBase.removeItem(item1)
SvgCanvasBase.removeItem(item2)
cloneControlView.clear()
else
item1.attr({
"d": path.getPathData(),
"fill-rule": "evenodd",
"transform": ""
})
SvgCanvasBase.removeItem(item2)
cloneControlView.setItems([item1])
@propertyEditSet = {}
@initPropertyEdit = () ->
propertyEditSet = new PropertyEditSetView(el:$("#property-table"))
for attr in ["fill-spe", "stroke-spe"]
do (attr) ->
prop = attr
$("#property-edit-#{attr}").spectrum({
showPalette: true,
showSelectionPalette: true,
maxPaletteSize: 10,
palette:[["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]],
change: (color) ->
propertyEditSet.prop_views[prop.replace("-spe", "")].update(color.toHexString())
})
cloneControlView.bind("onChangeList", (control) =>
if cloneControlView.isOneItem()
item = cloneControlView.firstOriginalItem()
propertyEditSet.bindElement(item)
#set color spectrum
for attr in ["fill-spe", "stroke-spe"]
do (attr) ->
$("#property-edit-#{attr}").spectrum("set",$(item.el).attr(attr.replace("-spe", "")))
else
propertyEditSet.clear()
)
@SvgExport = () =>
(new SvgExporter).toSvg($("#svg-canvas-wrap")[0], "svgfile", "width=600, height=400")
@GLOBAL = @GLOBAL || {}
@GLOBAL.commandService = new CommandService()
| 98883 | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
$(document).ready(() =>
@event_manager = new EventManager()
@cloneControlView = new CloneControlView({
el: $("#clone-control-view"),
line_wrapper: $("#clone-select-line-views"),
select_el: $("#clone-selected-view"),
manager:@event_manager
})
@event_manager.setControl(@cloneControlView)
@SvgCanvasBase = new SvgCanvas({
el: $("#svg-canvas-base"),
control: @cloneControlView,
mainCanvas: $("#svg-canvas")[0],
manager: @event_manager
})
@event_manager.setCanvas(@SvgCanvasBase)
@cloneControlView.setCanvas(@SvgCanvasBase)
@svgPathControl = new SvgPathControlView(el:$("#path-control-panel"))
@inspectorListView = new InspectorListView({
control: @cloneControlView,
item_list: SvgCanvasBase.item_list
})
@inspectorDragAndDrop = new InspectorDragAndDrop()
$("#inspector-list").append(@inspectorListView.el)
@SvgCanvasBase.bind("onZoom", (e) =>
canvas_transform = $(@SvgCanvasBase.mainCanvas).attr("transform")
$(grid_view.el).attr("stroke-width", 0.5 * (1 / SvgCanvasBase.zoomValue))
$(grid_view.el).attr("transform", canvas_transform)
$("#clone-control-view-wapper").attr("transform", canvas_transform)
cloneControlView.render()
svgPathControl.render()
)
@SvgItems = new SvgItemList
@SvgItemToolView = new SvgItemToolView({model:@SvgItems, el:$("#svg-item-list"), canvas:SvgCanvasBase})
for svg in SvgSample
do (svg) ->
SvgItems.add(new SvgItem(name:"item", contents:svg))
@patternItemsView = new PatternPanelView({
model:new SvgItemList,
el:$("#pattern-items"),
control:cloneControlView,
defs_id:"#pattern-defs",
element_key:"pattern_<KEY>"})
@gradientItemsView = new GradientPanelView({
model:new SvgItemList,
el:$("#gradient-items"),
control:cloneControlView,
defs_id:"#gradient-defs",
element_key:"gradient_id"})
@filterItemsView = new FilterPanelView({
model:new SvgItemList,
el:$("#filter-items"),
control:cloneControlView,
defs_id:"#filter-defs",
element_key:"filter_<KEY>"})
@filterItemsView.setTemplate(_.template('<rect x="10" y="10" filter="url(#{{element_id}})" fill="white" width="30" height="30"></rect>'))
@gradientItemsView.loadFile("partial/gradient_defs.html")
@patternItemsView.loadFile("partial/pattern_defs.html")
@filterItemsView.loadFile("partial/filter_defs.html")
@orderControl = new ZOrderControl(canvas:@SvgCanvasBase)
@orderControl.bind("onMove", () => inspectorListView.sortByIndex())
$("#export-button").click((e)-> SvgExport())
$("#open-file-button").click((e)->
$("#fileModal").modal()
)
$("#open-image-file-button").click((e)->
$("#imageFileModal").modal()
)
@grid_setting = new GridSetting(width:800, height:600, grid_size:10, visible:true)
@grid_view = new SvgGridView(model:@grid_setting, el:$("#svg-canvas-grid"), width:800, height:600)
@grid_view.render()
@grid_setting_view = new GridSettingView(model:@grid_setting, el:$("#grid-setting"))
@grid_setting_view.render()
@open_file_view = new OpenFileView(el:$("#fileModal"))
@open_image_file_view = new OpenImageFileView(el:$("#imageFileModal"))
@contextMenu = new ContextMenuView(el:$("#svg-canvas-base"))
@snap_line_view = new SnapLineView(el:$("#snap-line-view"))
@snap_item_view = new SnapItemView(el:$("#snap-item-view"))
$('#panel-tabs a').click((e)->
e.preventDefault()
$(this).tab('show')
)
event_manager.setMode('control')
mode_view = new ModeView(
el: $("#mode-btn-group"),
manager: event_manager
)
mode_view.render()
@undo_redo_view = new UndoRedoView(
el: $('#undo-redo-view'),
stack: GLOBAL.commandService.command_stack
)
undo_redo_view.render()
for i in _.map(_.range(1, 30), (e) -> 0.1 * e )
temp = _.template('<option value="{{val}}" {{option}}> {{name}}</option>')
option = ""
e = Math.round(i*100)
if(e == 100)
option = "selected"
$("#zoom-control").append temp(option:option, name: e + "%", val: i)
$("#zoom-control").change((e) =>
SvgCanvasBase.zoom($("#zoom-control").val(), { x: 400, y:300}, false)
)
key("backspace, delete", (e) =>
e.preventDefault();
SvgCanvasBase.deleteSelectedItem()
)
key("c", (e) => event_manager.setMode('control'))
key("t", (e) => event_manager.setMode('text'))
key("v", (e) => event_manager.setMode('path'))
key("g", (e) => event_manager.setMode('grad'))
move_item_position = (pos) =>
if cloneControlView.item_list.length > 0
cloneControlView.getControlItem().move(pos)
move_keys =
[{key:"up", x:0, y:-1},
{key:"down", x:0, y:1},
{key:"right", x:1, y:0},
{key:"left", x:-1, y:0}]
for move in move_keys
do (move) =>
key(move.key, (e) =>
move_item_position({x:move.x, y:move.y})
e.preventDefault()
)
$("#gradient-rotate").knob({
"change": (v) =>
el = cloneControlView.firstOriginalItem().el
bbox = el.getBBox()
id = $(el).attr("id") + "-grad"
cx = bbox.width/2
cy = bbox.height/2
attr = "rotate(" + v + ")"
$("#" + id)[0].setAttributeNS(null, "gradientTransform", attr)
});
update_pattern = () =>
el = cloneControlView.firstOriginalItem().el
bbox = el.getBBox()
id = $(el).attr("id") + "-pattern"
cx = bbox.width/2
cy = bbox.height/2
v = $("#pattern-rotate").val()
scale = Math.pow($( "#pattern-slider" ).slider( "value" )/25, 2)
attr = "rotate(#{v}, #{cx}, #{cy}) scale(#{scale})"
$("#" + id)[0].setAttributeNS(null, "patternTransform", attr)
$("#pattern-rotate").knob({
"change": (v) =>
update_pattern()
});
$("#pattern-slider").slider({
slide: ( event, ui ) =>
update_pattern()
});
$('#grid-check').click((e) =>
if $('#grid-check')[0].checked then grid_view.show() else grid_view.hide()
);
$(".navbar-fixed-top").hide();
$(".container-fluid").css("padding-top", "0px");
$("#add-folder-button").click((e) ->
SvgCanvasBase.addFolder()
)
$("#delete-item-button").click((e) ->
SvgCanvasBase.deleteSelectedItem()
)
initPropertyEdit()
cloneControlView.hide()
)
@excutePathBoolean = (operate) =>
if cloneControlView.item_list.length == 2
item1 = cloneControlView.item_list.at(0).get("origin_model")
item2 = cloneControlView.item_list.at(1).get("origin_model")
path1 = new paper.CompoundPath()
path2 = new paper.CompoundPath()
paperMatrix = (sm) => new paper.Matrix(sm.a, sm.b, sm.c, sm.d, sm.e, sm.f)
path1.setPathData($(item1.el).attr("d"))
path2.setPathData($(item2.el).attr("d"))
path1.transform(paperMatrix(item1.getLocalMatrix()))
path2.transform(paperMatrix(item2.getLocalMatrix()))
#all path set clockwise
for path in [path1, path2]
for child in path._children
if (not child.isClockwise())
child.reverse()
path = path2[operate](path1)
if _(["exclude", "divide"]).contains(operate)
# path type is paper.Group
path._children.forEach((item) =>
path_el = item1.el.cloneNode(true)
$(path_el).attr({
"d": item.getPathData(),
"fill-rule": "evenodd",
"transform": "",
"id": ""
})
SvgCanvasBase.addElement(path_el)
)
SvgCanvasBase.removeItem(item1)
SvgCanvasBase.removeItem(item2)
cloneControlView.clear()
else
item1.attr({
"d": path.getPathData(),
"fill-rule": "evenodd",
"transform": ""
})
SvgCanvasBase.removeItem(item2)
cloneControlView.setItems([item1])
@propertyEditSet = {}
@initPropertyEdit = () ->
propertyEditSet = new PropertyEditSetView(el:$("#property-table"))
for attr in ["fill-spe", "stroke-spe"]
do (attr) ->
prop = attr
$("#property-edit-#{attr}").spectrum({
showPalette: true,
showSelectionPalette: true,
maxPaletteSize: 10,
palette:[["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]],
change: (color) ->
propertyEditSet.prop_views[prop.replace("-spe", "")].update(color.toHexString())
})
cloneControlView.bind("onChangeList", (control) =>
if cloneControlView.isOneItem()
item = cloneControlView.firstOriginalItem()
propertyEditSet.bindElement(item)
#set color spectrum
for attr in ["fill-spe", "stroke-spe"]
do (attr) ->
$("#property-edit-#{attr}").spectrum("set",$(item.el).attr(attr.replace("-spe", "")))
else
propertyEditSet.clear()
)
@SvgExport = () =>
(new SvgExporter).toSvg($("#svg-canvas-wrap")[0], "svgfile", "width=600, height=400")
@GLOBAL = @GLOBAL || {}
@GLOBAL.commandService = new CommandService()
| true | # Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
$(document).ready(() =>
@event_manager = new EventManager()
@cloneControlView = new CloneControlView({
el: $("#clone-control-view"),
line_wrapper: $("#clone-select-line-views"),
select_el: $("#clone-selected-view"),
manager:@event_manager
})
@event_manager.setControl(@cloneControlView)
@SvgCanvasBase = new SvgCanvas({
el: $("#svg-canvas-base"),
control: @cloneControlView,
mainCanvas: $("#svg-canvas")[0],
manager: @event_manager
})
@event_manager.setCanvas(@SvgCanvasBase)
@cloneControlView.setCanvas(@SvgCanvasBase)
@svgPathControl = new SvgPathControlView(el:$("#path-control-panel"))
@inspectorListView = new InspectorListView({
control: @cloneControlView,
item_list: SvgCanvasBase.item_list
})
@inspectorDragAndDrop = new InspectorDragAndDrop()
$("#inspector-list").append(@inspectorListView.el)
@SvgCanvasBase.bind("onZoom", (e) =>
canvas_transform = $(@SvgCanvasBase.mainCanvas).attr("transform")
$(grid_view.el).attr("stroke-width", 0.5 * (1 / SvgCanvasBase.zoomValue))
$(grid_view.el).attr("transform", canvas_transform)
$("#clone-control-view-wapper").attr("transform", canvas_transform)
cloneControlView.render()
svgPathControl.render()
)
@SvgItems = new SvgItemList
@SvgItemToolView = new SvgItemToolView({model:@SvgItems, el:$("#svg-item-list"), canvas:SvgCanvasBase})
for svg in SvgSample
do (svg) ->
SvgItems.add(new SvgItem(name:"item", contents:svg))
@patternItemsView = new PatternPanelView({
model:new SvgItemList,
el:$("#pattern-items"),
control:cloneControlView,
defs_id:"#pattern-defs",
element_key:"pattern_PI:KEY:<KEY>END_PI"})
@gradientItemsView = new GradientPanelView({
model:new SvgItemList,
el:$("#gradient-items"),
control:cloneControlView,
defs_id:"#gradient-defs",
element_key:"gradient_id"})
@filterItemsView = new FilterPanelView({
model:new SvgItemList,
el:$("#filter-items"),
control:cloneControlView,
defs_id:"#filter-defs",
element_key:"filter_PI:KEY:<KEY>END_PI"})
@filterItemsView.setTemplate(_.template('<rect x="10" y="10" filter="url(#{{element_id}})" fill="white" width="30" height="30"></rect>'))
@gradientItemsView.loadFile("partial/gradient_defs.html")
@patternItemsView.loadFile("partial/pattern_defs.html")
@filterItemsView.loadFile("partial/filter_defs.html")
@orderControl = new ZOrderControl(canvas:@SvgCanvasBase)
@orderControl.bind("onMove", () => inspectorListView.sortByIndex())
$("#export-button").click((e)-> SvgExport())
$("#open-file-button").click((e)->
$("#fileModal").modal()
)
$("#open-image-file-button").click((e)->
$("#imageFileModal").modal()
)
@grid_setting = new GridSetting(width:800, height:600, grid_size:10, visible:true)
@grid_view = new SvgGridView(model:@grid_setting, el:$("#svg-canvas-grid"), width:800, height:600)
@grid_view.render()
@grid_setting_view = new GridSettingView(model:@grid_setting, el:$("#grid-setting"))
@grid_setting_view.render()
@open_file_view = new OpenFileView(el:$("#fileModal"))
@open_image_file_view = new OpenImageFileView(el:$("#imageFileModal"))
@contextMenu = new ContextMenuView(el:$("#svg-canvas-base"))
@snap_line_view = new SnapLineView(el:$("#snap-line-view"))
@snap_item_view = new SnapItemView(el:$("#snap-item-view"))
$('#panel-tabs a').click((e)->
e.preventDefault()
$(this).tab('show')
)
event_manager.setMode('control')
mode_view = new ModeView(
el: $("#mode-btn-group"),
manager: event_manager
)
mode_view.render()
@undo_redo_view = new UndoRedoView(
el: $('#undo-redo-view'),
stack: GLOBAL.commandService.command_stack
)
undo_redo_view.render()
for i in _.map(_.range(1, 30), (e) -> 0.1 * e )
temp = _.template('<option value="{{val}}" {{option}}> {{name}}</option>')
option = ""
e = Math.round(i*100)
if(e == 100)
option = "selected"
$("#zoom-control").append temp(option:option, name: e + "%", val: i)
$("#zoom-control").change((e) =>
SvgCanvasBase.zoom($("#zoom-control").val(), { x: 400, y:300}, false)
)
key("backspace, delete", (e) =>
e.preventDefault();
SvgCanvasBase.deleteSelectedItem()
)
key("c", (e) => event_manager.setMode('control'))
key("t", (e) => event_manager.setMode('text'))
key("v", (e) => event_manager.setMode('path'))
key("g", (e) => event_manager.setMode('grad'))
move_item_position = (pos) =>
if cloneControlView.item_list.length > 0
cloneControlView.getControlItem().move(pos)
move_keys =
[{key:"up", x:0, y:-1},
{key:"down", x:0, y:1},
{key:"right", x:1, y:0},
{key:"left", x:-1, y:0}]
for move in move_keys
do (move) =>
key(move.key, (e) =>
move_item_position({x:move.x, y:move.y})
e.preventDefault()
)
$("#gradient-rotate").knob({
"change": (v) =>
el = cloneControlView.firstOriginalItem().el
bbox = el.getBBox()
id = $(el).attr("id") + "-grad"
cx = bbox.width/2
cy = bbox.height/2
attr = "rotate(" + v + ")"
$("#" + id)[0].setAttributeNS(null, "gradientTransform", attr)
});
update_pattern = () =>
el = cloneControlView.firstOriginalItem().el
bbox = el.getBBox()
id = $(el).attr("id") + "-pattern"
cx = bbox.width/2
cy = bbox.height/2
v = $("#pattern-rotate").val()
scale = Math.pow($( "#pattern-slider" ).slider( "value" )/25, 2)
attr = "rotate(#{v}, #{cx}, #{cy}) scale(#{scale})"
$("#" + id)[0].setAttributeNS(null, "patternTransform", attr)
$("#pattern-rotate").knob({
"change": (v) =>
update_pattern()
});
$("#pattern-slider").slider({
slide: ( event, ui ) =>
update_pattern()
});
$('#grid-check').click((e) =>
if $('#grid-check')[0].checked then grid_view.show() else grid_view.hide()
);
$(".navbar-fixed-top").hide();
$(".container-fluid").css("padding-top", "0px");
$("#add-folder-button").click((e) ->
SvgCanvasBase.addFolder()
)
$("#delete-item-button").click((e) ->
SvgCanvasBase.deleteSelectedItem()
)
initPropertyEdit()
cloneControlView.hide()
)
@excutePathBoolean = (operate) =>
if cloneControlView.item_list.length == 2
item1 = cloneControlView.item_list.at(0).get("origin_model")
item2 = cloneControlView.item_list.at(1).get("origin_model")
path1 = new paper.CompoundPath()
path2 = new paper.CompoundPath()
paperMatrix = (sm) => new paper.Matrix(sm.a, sm.b, sm.c, sm.d, sm.e, sm.f)
path1.setPathData($(item1.el).attr("d"))
path2.setPathData($(item2.el).attr("d"))
path1.transform(paperMatrix(item1.getLocalMatrix()))
path2.transform(paperMatrix(item2.getLocalMatrix()))
#all path set clockwise
for path in [path1, path2]
for child in path._children
if (not child.isClockwise())
child.reverse()
path = path2[operate](path1)
if _(["exclude", "divide"]).contains(operate)
# path type is paper.Group
path._children.forEach((item) =>
path_el = item1.el.cloneNode(true)
$(path_el).attr({
"d": item.getPathData(),
"fill-rule": "evenodd",
"transform": "",
"id": ""
})
SvgCanvasBase.addElement(path_el)
)
SvgCanvasBase.removeItem(item1)
SvgCanvasBase.removeItem(item2)
cloneControlView.clear()
else
item1.attr({
"d": path.getPathData(),
"fill-rule": "evenodd",
"transform": ""
})
SvgCanvasBase.removeItem(item2)
cloneControlView.setItems([item1])
@propertyEditSet = {}
@initPropertyEdit = () ->
propertyEditSet = new PropertyEditSetView(el:$("#property-table"))
for attr in ["fill-spe", "stroke-spe"]
do (attr) ->
prop = attr
$("#property-edit-#{attr}").spectrum({
showPalette: true,
showSelectionPalette: true,
maxPaletteSize: 10,
palette:[["#000","#444","#666","#999","#ccc","#eee","#f3f3f3","#fff"],["#f00","#f90","#ff0","#0f0","#0ff","#00f","#90f","#f0f"],["#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#cfe2f3","#d9d2e9","#ead1dc"],["#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#9fc5e8","#b4a7d6","#d5a6bd"],["#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6fa8dc","#8e7cc3","#c27ba0"],["#c00","#e69138","#f1c232","#6aa84f","#45818e","#3d85c6","#674ea7","#a64d79"],["#900","#b45f06","#bf9000","#38761d","#134f5c","#0b5394","#351c75","#741b47"],["#600","#783f04","#7f6000","#274e13","#0c343d","#073763","#20124d","#4c1130"]],
change: (color) ->
propertyEditSet.prop_views[prop.replace("-spe", "")].update(color.toHexString())
})
cloneControlView.bind("onChangeList", (control) =>
if cloneControlView.isOneItem()
item = cloneControlView.firstOriginalItem()
propertyEditSet.bindElement(item)
#set color spectrum
for attr in ["fill-spe", "stroke-spe"]
do (attr) ->
$("#property-edit-#{attr}").spectrum("set",$(item.el).attr(attr.replace("-spe", "")))
else
propertyEditSet.clear()
)
@SvgExport = () =>
(new SvgExporter).toSvg($("#svg-canvas-wrap")[0], "svgfile", "width=600, height=400")
@GLOBAL = @GLOBAL || {}
@GLOBAL.commandService = new CommandService()
|
[
{
"context": "e results of the compilation\ninstanceUniqueKey = '44564699550419906'\nbase_dir = 'tmp/debug'\n\ndocjson = JSON.parse(fs.",
"end": 540,
"score": 0.9997010827064514,
"start": 523,
"tag": "KEY",
"value": "44564699550419906"
}
] | e2e-tests/debug-compiled.coffee | mehrdad-shokri/pagedraw | 3,213 | require('../coffeescript-register-web')
fs = require 'fs'
_l = require 'lodash'
path = require 'path'
{writeFiles, setupReactEnv, compileProjectForInstanceBlock} = require('./create-react-env.coffee')
{Doc} = require('../src/doc')
{InstanceBlock} = require('../src/blocks/instance-block')
## Running this is gonna set up the compiled environment for the instance block with key instanceUniqueKey
# in base_dir. Running npm start in base_dir should let you visualize the results of the compilation
instanceUniqueKey = '44564699550419906'
base_dir = 'tmp/debug'
docjson = JSON.parse(fs.readFileSync('../test-data/e2e-tests/doctotest.json', 'utf8'))
doc = Doc.deserialize(docjson)
instanceBlock = _l.find(doc.blocks, (block) -> block.uniqueKey == instanceUniqueKey)
if _l.isEmpty(instanceBlock)
throw new Error('instanceBlock not found')
files = compileProjectForInstanceBlock(instanceBlock)
writeFiles(base_dir, files)
| 128705 | require('../coffeescript-register-web')
fs = require 'fs'
_l = require 'lodash'
path = require 'path'
{writeFiles, setupReactEnv, compileProjectForInstanceBlock} = require('./create-react-env.coffee')
{Doc} = require('../src/doc')
{InstanceBlock} = require('../src/blocks/instance-block')
## Running this is gonna set up the compiled environment for the instance block with key instanceUniqueKey
# in base_dir. Running npm start in base_dir should let you visualize the results of the compilation
instanceUniqueKey = '<KEY>'
base_dir = 'tmp/debug'
docjson = JSON.parse(fs.readFileSync('../test-data/e2e-tests/doctotest.json', 'utf8'))
doc = Doc.deserialize(docjson)
instanceBlock = _l.find(doc.blocks, (block) -> block.uniqueKey == instanceUniqueKey)
if _l.isEmpty(instanceBlock)
throw new Error('instanceBlock not found')
files = compileProjectForInstanceBlock(instanceBlock)
writeFiles(base_dir, files)
| true | require('../coffeescript-register-web')
fs = require 'fs'
_l = require 'lodash'
path = require 'path'
{writeFiles, setupReactEnv, compileProjectForInstanceBlock} = require('./create-react-env.coffee')
{Doc} = require('../src/doc')
{InstanceBlock} = require('../src/blocks/instance-block')
## Running this is gonna set up the compiled environment for the instance block with key instanceUniqueKey
# in base_dir. Running npm start in base_dir should let you visualize the results of the compilation
instanceUniqueKey = 'PI:KEY:<KEY>END_PI'
base_dir = 'tmp/debug'
docjson = JSON.parse(fs.readFileSync('../test-data/e2e-tests/doctotest.json', 'utf8'))
doc = Doc.deserialize(docjson)
instanceBlock = _l.find(doc.blocks, (block) -> block.uniqueKey == instanceUniqueKey)
if _l.isEmpty(instanceBlock)
throw new Error('instanceBlock not found')
files = compileProjectForInstanceBlock(instanceBlock)
writeFiles(base_dir, files)
|
[
{
"context": ")\n\n @stubSession =\n user:\n email: \"stub@user\"\n\n @scope = $rootScope.$new()\n @controller ",
"end": 837,
"score": 0.9395336508750916,
"start": 828,
"tag": "EMAIL",
"value": "stub@user"
},
{
"context": "e if method was called', () =>\n testEmail = 'test@test.ts'\n\n @stubDataService.inviteFriend.and.returnV",
"end": 3070,
"score": 0.999596893787384,
"start": 3058,
"tag": "EMAIL",
"value": "test@test.ts"
},
{
"context": "rom server is negative', () =>\n testEmail = 'test@test.ts'\n testError =\n data: 'test error'\n\n ",
"end": 3650,
"score": 0.9998334050178528,
"start": 3638,
"tag": "EMAIL",
"value": "test@test.ts"
},
{
"context": "ue(@$q.when())\n\n @controller.changePassword(\"new_password\", \"new_password\")\n\n @$rootScope.$digest()\n\n ",
"end": 4570,
"score": 0.994838297367096,
"start": 4558,
"tag": "PASSWORD",
"value": "new_password"
},
{
"context": " @controller.changePassword(\"new_password\", \"new_password\")\n\n @$rootScope.$digest()\n\n expect(@stu",
"end": 4586,
"score": 0.9981374144554138,
"start": 4574,
"tag": "PASSWORD",
"value": "new_password"
},
{
"context": "ice.changePassword).toHaveBeenCalledWith(\"test\", \"new_password\")\n\n expect(@stubState.reload).toHaveBeenCall",
"end": 4786,
"score": 0.9955560564994812,
"start": 4774,
"tag": "PASSWORD",
"value": "new_password"
},
{
"context": "ue(@$q.when())\n\n @controller.changePassword(\"new_password\", \"incorrect_new_password\")\n\n @$rootScope.$d",
"end": 5301,
"score": 0.9967878460884094,
"start": 5289,
"tag": "PASSWORD",
"value": "new_password"
},
{
"context": " @controller.changePassword(\"new_password\", \"incorrect_new_password\")\n\n @$rootScope.$digest()\n\n it 'should se",
"end": 5327,
"score": 0.9975074529647827,
"start": 5305,
"tag": "PASSWORD",
"value": "incorrect_new_password"
},
{
"context": " p.promise\n\n @controller.changePassword(\"new_password\", \"new_password\")\n\n @$rootScope.$digest()\n\n ",
"end": 5780,
"score": 0.9924988746643066,
"start": 5768,
"tag": "PASSWORD",
"value": "new_password"
},
{
"context": " @controller.changePassword(\"new_password\", \"new_password\")\n\n @$rootScope.$digest()\n\n expect(@stu",
"end": 5796,
"score": 0.9969019889831543,
"start": 5784,
"tag": "PASSWORD",
"value": "new_password"
},
{
"context": "ice.changePassword).toHaveBeenCalledWith(\"test\", \"new_password\")\n\n expect(@stubAlertsService.showAlert).toH",
"end": 5996,
"score": 0.9964756965637207,
"start": 5984,
"tag": "PASSWORD",
"value": "new_password"
}
] | src/app/pages/settings/pages.settings.spec.coffee | pavelkuchin/tracktrains-ui | 0 | describe 'PagesSettingsCtrl', () ->
beforeEach(module('trackSeatsApp'))
beforeEach(inject((@$rootScope, $controller, $httpBackend, @ALERTS_TYPE, @$q) =>
$httpBackend.when('GET', '/v1/user/session/').respond({})
$httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html')
.respond({})
@stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert'])
@stubAlertsService.TYPE = @ALERTS_TYPE
@stubDialogsService = jasmine.createSpyObj('DialogsService', [
'confirmation',
'confirmationWithPassword'
])
@stubDataService = jasmine.createSpyObj('DataService', [
'deleteAccount',
'inviteFriend',
'changePassword'
])
@stubState = jasmine.createSpyObj('$state', [
'reload'
])
@stubSession =
user:
email: "stub@user"
@scope = $rootScope.$new()
@controller = $controller('PagesSettingsCtrl',
$scope: @scope
AlertsService: @stubAlertsService
DataService: @stubDataService
DialogsService: @stubDialogsService
session: @stubSession
$state: @stubState
)
))
describe 'controller.deleteAccount', () =>
it 'should send a request to server, perform a logout and shows a message if method was calles
and dialog was confirmed', () =>
@stubDialogsService.confirmation.and.returnValue(@$q.when())
@stubDataService.deleteAccount.and.returnValue(@$q.when())
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
expect(@stubDataService.deleteAccount).toHaveBeenCalledWith(@stubSession.user)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Your account has been permanently removed. It was great to have you with us!"
@ALERTS_TYPE.SUCCESS
)
it 'should not send a request to server if method was calles but a dialog was not confirmed', () =>
@stubDialogsService.confirmation.and.callFake(() =>
p = @$q.defer()
p.reject('')
p.promise
)
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
it 'should show error message if method was called and confirmed but request to server was failed', () =>
@stubDialogsService.confirmation.and.returnValue(@$q.when())
@stubDataService.deleteAccount.and.callFake(() =>
p = @$q.defer()
p.reject('')
p.promise
)
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
expect(@stubDataService.deleteAccount).toHaveBeenCalledWith(@stubSession.user)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Something went wrong. Please try later."
@ALERTS_TYPE.ERROR
)
describe 'controller.inviteFriend', () =>
it 'should send a request to add a friend and shows a success message if method was called', () =>
testEmail = 'test@test.ts'
@stubDataService.inviteFriend.and.returnValue(@$q.when())
@controller.inviteFriend(testEmail)
@$rootScope.$digest()
expect(@stubDataService.inviteFriend).toHaveBeenCalledWith(testEmail)
expect(@stubState.reload).toHaveBeenCalled()
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"An invitation letter has been sent for #{testEmail}",
@ALERTS_TYPE.SUCCESS,
3000
)
it 'should show a fault message if method was called but result from server is negative', () =>
testEmail = 'test@test.ts'
testError =
data: 'test error'
@stubDataService.inviteFriend.and.callFake () =>
p = @$q.defer()
p.reject(testError)
p.promise
@controller.inviteFriend(testEmail)
@$rootScope.$digest()
expect(@stubDataService.inviteFriend).toHaveBeenCalledWith(testEmail)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"An invitation letter has not been sent because of '#{testError.data}'"
@ALERTS_TYPE.ERROR
)
describe 'controller.changePassword', () =>
it 'should send a request to change a password and shows a message if user enter
a new password and confirmed his action by enter the current password', () =>
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.returnValue(@$q.when())
@controller.changePassword("new_password", "new_password")
@$rootScope.$digest()
expect(@stubDialogsService.confirmationWithPassword).toHaveBeenCalled()
expect(@stubDataService.changePassword).toHaveBeenCalledWith("test", "new_password")
expect(@stubState.reload).toHaveBeenCalled()
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Password has been changed.",
@ALERTS_TYPE.SUCCESS,
3000
)
it 'should not send a request to change the password if origin and confiramtion are different', () =>
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.returnValue(@$q.when())
@controller.changePassword("new_password", "incorrect_new_password")
@$rootScope.$digest()
it 'should send a request to change the password and if result is fail then error message should appear', () =>
testError =
data: "testError"
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.callFake () =>
p = @$q.defer()
p.reject(testError)
p.promise
@controller.changePassword("new_password", "new_password")
@$rootScope.$digest()
expect(@stubDialogsService.confirmationWithPassword).toHaveBeenCalled()
expect(@stubDataService.changePassword).toHaveBeenCalledWith("test", "new_password")
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Password has not been changed because of '#{testError.data}'"
@ALERTS_TYPE.ERROR
)
describe 'controller.getValidationClass', () =>
it 'should return nothing if field is clear (not dirty)', () =>
fakeField =
$dirty: false
$error: {}
result = @controller.getValidationClass(fakeField)
expect(result).toBeUndefined()
it 'should return "has-success" class if field is durty and $error object is clear', () =>
fakeField =
$dirty: true
$error: {}
result = @controller.getValidationClass(fakeField)
expect(result).toEqual(["has-success"])
it 'should return "has-error" class if field is durty and $error object is not clear', () =>
fakeField =
$dirty: true
$error:
testError: true
result = @controller.getValidationClass(fakeField)
expect(result).toEqual(["has-error"])
| 133955 | describe 'PagesSettingsCtrl', () ->
beforeEach(module('trackSeatsApp'))
beforeEach(inject((@$rootScope, $controller, $httpBackend, @ALERTS_TYPE, @$q) =>
$httpBackend.when('GET', '/v1/user/session/').respond({})
$httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html')
.respond({})
@stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert'])
@stubAlertsService.TYPE = @ALERTS_TYPE
@stubDialogsService = jasmine.createSpyObj('DialogsService', [
'confirmation',
'confirmationWithPassword'
])
@stubDataService = jasmine.createSpyObj('DataService', [
'deleteAccount',
'inviteFriend',
'changePassword'
])
@stubState = jasmine.createSpyObj('$state', [
'reload'
])
@stubSession =
user:
email: "<EMAIL>"
@scope = $rootScope.$new()
@controller = $controller('PagesSettingsCtrl',
$scope: @scope
AlertsService: @stubAlertsService
DataService: @stubDataService
DialogsService: @stubDialogsService
session: @stubSession
$state: @stubState
)
))
describe 'controller.deleteAccount', () =>
it 'should send a request to server, perform a logout and shows a message if method was calles
and dialog was confirmed', () =>
@stubDialogsService.confirmation.and.returnValue(@$q.when())
@stubDataService.deleteAccount.and.returnValue(@$q.when())
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
expect(@stubDataService.deleteAccount).toHaveBeenCalledWith(@stubSession.user)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Your account has been permanently removed. It was great to have you with us!"
@ALERTS_TYPE.SUCCESS
)
it 'should not send a request to server if method was calles but a dialog was not confirmed', () =>
@stubDialogsService.confirmation.and.callFake(() =>
p = @$q.defer()
p.reject('')
p.promise
)
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
it 'should show error message if method was called and confirmed but request to server was failed', () =>
@stubDialogsService.confirmation.and.returnValue(@$q.when())
@stubDataService.deleteAccount.and.callFake(() =>
p = @$q.defer()
p.reject('')
p.promise
)
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
expect(@stubDataService.deleteAccount).toHaveBeenCalledWith(@stubSession.user)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Something went wrong. Please try later."
@ALERTS_TYPE.ERROR
)
describe 'controller.inviteFriend', () =>
it 'should send a request to add a friend and shows a success message if method was called', () =>
testEmail = '<EMAIL>'
@stubDataService.inviteFriend.and.returnValue(@$q.when())
@controller.inviteFriend(testEmail)
@$rootScope.$digest()
expect(@stubDataService.inviteFriend).toHaveBeenCalledWith(testEmail)
expect(@stubState.reload).toHaveBeenCalled()
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"An invitation letter has been sent for #{testEmail}",
@ALERTS_TYPE.SUCCESS,
3000
)
it 'should show a fault message if method was called but result from server is negative', () =>
testEmail = '<EMAIL>'
testError =
data: 'test error'
@stubDataService.inviteFriend.and.callFake () =>
p = @$q.defer()
p.reject(testError)
p.promise
@controller.inviteFriend(testEmail)
@$rootScope.$digest()
expect(@stubDataService.inviteFriend).toHaveBeenCalledWith(testEmail)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"An invitation letter has not been sent because of '#{testError.data}'"
@ALERTS_TYPE.ERROR
)
describe 'controller.changePassword', () =>
it 'should send a request to change a password and shows a message if user enter
a new password and confirmed his action by enter the current password', () =>
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.returnValue(@$q.when())
@controller.changePassword("<PASSWORD>", "<PASSWORD>")
@$rootScope.$digest()
expect(@stubDialogsService.confirmationWithPassword).toHaveBeenCalled()
expect(@stubDataService.changePassword).toHaveBeenCalledWith("test", "<PASSWORD>")
expect(@stubState.reload).toHaveBeenCalled()
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Password has been changed.",
@ALERTS_TYPE.SUCCESS,
3000
)
it 'should not send a request to change the password if origin and confiramtion are different', () =>
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.returnValue(@$q.when())
@controller.changePassword("<PASSWORD>", "<PASSWORD>")
@$rootScope.$digest()
it 'should send a request to change the password and if result is fail then error message should appear', () =>
testError =
data: "testError"
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.callFake () =>
p = @$q.defer()
p.reject(testError)
p.promise
@controller.changePassword("<PASSWORD>", "<PASSWORD>")
@$rootScope.$digest()
expect(@stubDialogsService.confirmationWithPassword).toHaveBeenCalled()
expect(@stubDataService.changePassword).toHaveBeenCalledWith("test", "<PASSWORD>")
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Password has not been changed because of '#{testError.data}'"
@ALERTS_TYPE.ERROR
)
describe 'controller.getValidationClass', () =>
it 'should return nothing if field is clear (not dirty)', () =>
fakeField =
$dirty: false
$error: {}
result = @controller.getValidationClass(fakeField)
expect(result).toBeUndefined()
it 'should return "has-success" class if field is durty and $error object is clear', () =>
fakeField =
$dirty: true
$error: {}
result = @controller.getValidationClass(fakeField)
expect(result).toEqual(["has-success"])
it 'should return "has-error" class if field is durty and $error object is not clear', () =>
fakeField =
$dirty: true
$error:
testError: true
result = @controller.getValidationClass(fakeField)
expect(result).toEqual(["has-error"])
| true | describe 'PagesSettingsCtrl', () ->
beforeEach(module('trackSeatsApp'))
beforeEach(inject((@$rootScope, $controller, $httpBackend, @ALERTS_TYPE, @$q) =>
$httpBackend.when('GET', '/v1/user/session/').respond({})
$httpBackend.when('GET', 'app/pages/landing/pages.landing.template.html')
.respond({})
@stubAlertsService = jasmine.createSpyObj('AlertsService', ['showAlert'])
@stubAlertsService.TYPE = @ALERTS_TYPE
@stubDialogsService = jasmine.createSpyObj('DialogsService', [
'confirmation',
'confirmationWithPassword'
])
@stubDataService = jasmine.createSpyObj('DataService', [
'deleteAccount',
'inviteFriend',
'changePassword'
])
@stubState = jasmine.createSpyObj('$state', [
'reload'
])
@stubSession =
user:
email: "PI:EMAIL:<EMAIL>END_PI"
@scope = $rootScope.$new()
@controller = $controller('PagesSettingsCtrl',
$scope: @scope
AlertsService: @stubAlertsService
DataService: @stubDataService
DialogsService: @stubDialogsService
session: @stubSession
$state: @stubState
)
))
describe 'controller.deleteAccount', () =>
it 'should send a request to server, perform a logout and shows a message if method was calles
and dialog was confirmed', () =>
@stubDialogsService.confirmation.and.returnValue(@$q.when())
@stubDataService.deleteAccount.and.returnValue(@$q.when())
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
expect(@stubDataService.deleteAccount).toHaveBeenCalledWith(@stubSession.user)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Your account has been permanently removed. It was great to have you with us!"
@ALERTS_TYPE.SUCCESS
)
it 'should not send a request to server if method was calles but a dialog was not confirmed', () =>
@stubDialogsService.confirmation.and.callFake(() =>
p = @$q.defer()
p.reject('')
p.promise
)
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
it 'should show error message if method was called and confirmed but request to server was failed', () =>
@stubDialogsService.confirmation.and.returnValue(@$q.when())
@stubDataService.deleteAccount.and.callFake(() =>
p = @$q.defer()
p.reject('')
p.promise
)
@controller.deleteAccount()
@$rootScope.$digest()
expect(@stubDialogsService.confirmation).toHaveBeenCalled()
expect(@stubDataService.deleteAccount).toHaveBeenCalledWith(@stubSession.user)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Something went wrong. Please try later."
@ALERTS_TYPE.ERROR
)
describe 'controller.inviteFriend', () =>
it 'should send a request to add a friend and shows a success message if method was called', () =>
testEmail = 'PI:EMAIL:<EMAIL>END_PI'
@stubDataService.inviteFriend.and.returnValue(@$q.when())
@controller.inviteFriend(testEmail)
@$rootScope.$digest()
expect(@stubDataService.inviteFriend).toHaveBeenCalledWith(testEmail)
expect(@stubState.reload).toHaveBeenCalled()
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"An invitation letter has been sent for #{testEmail}",
@ALERTS_TYPE.SUCCESS,
3000
)
it 'should show a fault message if method was called but result from server is negative', () =>
testEmail = 'PI:EMAIL:<EMAIL>END_PI'
testError =
data: 'test error'
@stubDataService.inviteFriend.and.callFake () =>
p = @$q.defer()
p.reject(testError)
p.promise
@controller.inviteFriend(testEmail)
@$rootScope.$digest()
expect(@stubDataService.inviteFriend).toHaveBeenCalledWith(testEmail)
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"An invitation letter has not been sent because of '#{testError.data}'"
@ALERTS_TYPE.ERROR
)
describe 'controller.changePassword', () =>
it 'should send a request to change a password and shows a message if user enter
a new password and confirmed his action by enter the current password', () =>
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.returnValue(@$q.when())
@controller.changePassword("PI:PASSWORD:<PASSWORD>END_PI", "PI:PASSWORD:<PASSWORD>END_PI")
@$rootScope.$digest()
expect(@stubDialogsService.confirmationWithPassword).toHaveBeenCalled()
expect(@stubDataService.changePassword).toHaveBeenCalledWith("test", "PI:PASSWORD:<PASSWORD>END_PI")
expect(@stubState.reload).toHaveBeenCalled()
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Password has been changed.",
@ALERTS_TYPE.SUCCESS,
3000
)
it 'should not send a request to change the password if origin and confiramtion are different', () =>
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.returnValue(@$q.when())
@controller.changePassword("PI:PASSWORD:<PASSWORD>END_PI", "PI:PASSWORD:<PASSWORD>END_PI")
@$rootScope.$digest()
it 'should send a request to change the password and if result is fail then error message should appear', () =>
testError =
data: "testError"
@stubDialogsService.confirmationWithPassword.and.returnValue(@$q.when('test'))
@stubDataService.changePassword.and.callFake () =>
p = @$q.defer()
p.reject(testError)
p.promise
@controller.changePassword("PI:PASSWORD:<PASSWORD>END_PI", "PI:PASSWORD:<PASSWORD>END_PI")
@$rootScope.$digest()
expect(@stubDialogsService.confirmationWithPassword).toHaveBeenCalled()
expect(@stubDataService.changePassword).toHaveBeenCalledWith("test", "PI:PASSWORD:<PASSWORD>END_PI")
expect(@stubAlertsService.showAlert).toHaveBeenCalledWith(
"Password has not been changed because of '#{testError.data}'"
@ALERTS_TYPE.ERROR
)
describe 'controller.getValidationClass', () =>
it 'should return nothing if field is clear (not dirty)', () =>
fakeField =
$dirty: false
$error: {}
result = @controller.getValidationClass(fakeField)
expect(result).toBeUndefined()
it 'should return "has-success" class if field is durty and $error object is clear', () =>
fakeField =
$dirty: true
$error: {}
result = @controller.getValidationClass(fakeField)
expect(result).toEqual(["has-success"])
it 'should return "has-error" class if field is durty and $error object is not clear', () =>
fakeField =
$dirty: true
$error:
testError: true
result = @controller.getValidationClass(fakeField)
expect(result).toEqual(["has-error"])
|
[
{
"context": ".ready()\n\n\t\tselector =\n\t\t\tspace: spaceId\n\t\t\tkey: 'contacts_no_force_phone_users'\n\n\t\treturn db.space_settings.find(selector)",
"end": 238,
"score": 0.9930775761604309,
"start": 209,
"tag": "KEY",
"value": "contacts_no_force_phone_users"
}
] | creator/packages/steedos-creator/server/publications/contacts_no_force_phone_users.coffee | yicone/steedos-platform | 42 |
if Meteor.isServer
Meteor.publish 'contacts_no_force_phone_users', (spaceId)->
unless this.userId
return this.ready()
unless spaceId
return this.ready()
selector =
space: spaceId
key: 'contacts_no_force_phone_users'
return db.space_settings.find(selector) | 51108 |
if Meteor.isServer
Meteor.publish 'contacts_no_force_phone_users', (spaceId)->
unless this.userId
return this.ready()
unless spaceId
return this.ready()
selector =
space: spaceId
key: '<KEY>'
return db.space_settings.find(selector) | true |
if Meteor.isServer
Meteor.publish 'contacts_no_force_phone_users', (spaceId)->
unless this.userId
return this.ready()
unless spaceId
return this.ready()
selector =
space: spaceId
key: 'PI:KEY:<KEY>END_PI'
return db.space_settings.find(selector) |
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9983450770378113,
"start": 16,
"tag": "NAME",
"value": "Konode"
}
] | src/persist/collectionMethods.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# This module implements the core operations of the persistent object store.
#
# The Persist package generates an API based on the data models it is
# configured with. Within that API, there is an interface for each collection
# (e.g. `persist.clientFiles` or `persist.metrics`). That interface is called
# a Collection API, i.e. an API for a specific collection.
#
# The `createCollectionApi` function generates an API for a single collection
# based on a data model (and some additional information such as the current
# session). The `persist/apiBuilder` module uses this function on every data
# model definition.
Async = require 'async'
Joi = require 'joi'
Imm = require 'immutable'
Moment = require 'moment'
{
IOError
IdSchema
ObjectNotFoundError
TimestampFormat
generateId
} = require './utils'
joiValidationOptions = Object.freeze {
# I would like to set this to false, but Joi doesn't seem to support date
# string validation without convert: true
convert: true
# Any properties that are not required must be explicitly marked optional.
presence: 'required'
}
# Create an API based on the specified model definition.
#
# session: a Session object
# eventBus: the EventBus to which object mutation events should be dispatched
# context: a List of model definitions. Each model definition is an ancestor
# of this collection, ordered from outermost (i.e. top-level) to innermost.
#
# Example:
# Imm.List([clientFileModelDef, progNoteModelDef])
#
# modelDef: the data model definition that defines this collection
createCollectionApi = (backend, session, eventBus, context, modelDef) ->
# Define a series of methods that this collection API will (or might) contain.
# These methods correspond to what is documented in the wiki.
# See the wiki for instructions on their use.
create = (obj, cb) ->
# The object hasn't been created yet, so it shouldn't have any of these
# metadata fields. If it does, it probably indicates a bug.
if obj.has('id')
cb new Error "new objects cannot already have an ID"
return
if obj.has('revisionId')
cb new Error "new objects cannot already have a revision ID"
return
# We allow explicit metadata for development purposes, such as seeding.
# This is commented out for now, to prevent the application failing here
# when trying to import data that might somehow still have these metadata properties attached
# (which get overwritten here anyway)
# if process.env.NODE_ENV isnt 'development'
# if obj.has('author')
# cb new Error "new objects cannot already have an author"
# return
# if obj.has('timestamp')
# cb new Error "new objects cannot already have a timestamp"
# return
# if obj.has('authorDisplayName')
# cb new Error "new objects cannot already have a displayName"
# return
# Add metadata fields
obj = obj
.set 'id', generateId()
.set 'revisionId', generateId()
.set 'author', obj.get('author') or session.userName
.set 'authorDisplayName', session.displayName or session.userName
.set 'timestamp', obj.get('timestamp') or Moment().format(TimestampFormat)
# Validate object before passing to backend
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
process.nextTick ->
cb validation.error
return
backend.createObject Imm.fromJS(validation.value), context, modelDef, (err) ->
if err
cb err
return
# Return a copy of the newly created object, complete with metadata
cb null, obj
list = (contextualIds..., cb) ->
contextualIds = Imm.List(contextualIds)
# API user must provide IDs for each of the ancestor objects,
# otherwise, we don't know where to look
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.listObjectsInCollection contextualIds, context, modelDef, (err, headers) ->
if err
cb err
return
cb null, headers
read = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
# API user must provide enough IDs to figure out where this collection
# is located.
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.readObject contextualIds, id, context, modelDef, (err, obj) ->
if err
cb err
return
# Validate against the collection's schema
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
cb validation.error
return
cb null, Imm.fromJS validation.value
createRevision = (obj, cb) ->
# The object should already have been created, so it should already
# have an ID.
unless obj.has('id')
cb new Error "missing property 'id'"
return
objId = obj.get('id')
# Add the relevant metadata fields
obj = obj
.set 'revisionId', generateId()
.set 'author', session.userName
.set 'authorDisplayName', session.displayName or session.userName
.set 'timestamp', Moment().format(TimestampFormat)
# Validate object before passing to backend
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
process.nextTick ->
cb validation.error
return
backend.createObjectRevision Imm.fromJS(validation.value), context, modelDef, (err) ->
if err
cb err
return
cb null, obj
listRevisions = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
# Need enough context to locate this object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.listObjectRevisions contextualIds, id, context, modelDef, cb
readRevisions = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
cb new Error "readRevisions must be provided a callback"
return
# Need enough information to determine where this object's collection
# is located
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
# List all of this object's revisions
listRevisions contextualIds.toArray()..., id, (err, revisions) ->
if err
cb err
return
# Read the revisions one-by-one
Async.map revisions.toArray(), (rev, cb) ->
readRevision contextualIds.toArray()..., id, rev.get('revisionId'), cb
, (err, results) ->
if err
cb err
return
cb null, Imm.List(results)
readLatestRevisions = (contextualIds..., id, maxRevisionCount, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
throw new Error "readLatestRevisions must be provided a callback"
# Need object IDs of any ancestor objects in order to locate this
# object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
if maxRevisionCount < 0
cb new Error "maxRevisionCount must be >= 0"
return
# We could theoretically optimize for maxRevisionCount=0 here.
# However, this would cause requests for non-existant objects to succeed.
# List all of the object's revisions
listRevisions contextualIds.toArray()..., id, (err, revisions) ->
if err
cb err
return
# Only access the most recent revisions
revisions = revisions.takeLast maxRevisionCount
# Read only those revisions
Async.map revisions.toArray(), (rev, cb) ->
readRevision contextualIds.toArray()..., id, rev.get('revisionId'), cb
, (err, results) ->
if err
cb err
return
cb null, Imm.List(results)
readRevision = (contextualIds..., id, revisionId, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
throw new Error "readLatestRevisions must be provided a callback"
# Need object IDs of any ancestor objects in order to locate this
# object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.readObjectRevision contextualIds, id, revisionId, context, modelDef, (err, obj) ->
if err
cb err
return
# Validate against the collection's schema
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
cb validation.error
return
cb null, Imm.fromJS validation.value
# Build and return the actual collection API, using the previously defined methods
result = {
create,
list,
}
if modelDef.isMutable
# Only mutable collections have methods related to revisions
result.createRevision = createRevision
result.listRevisions = listRevisions
result.readRevisions = readRevisions
result.readLatestRevisions = readLatestRevisions
else
# Immutable collections just get the basic read method
result.read = read
return result
# Add metadata fields to object schema
prepareSchema = (schema, context) ->
# The schema can be an array of possible schemas
# (see Joi documentation)
if Array.isArray schema
return (prepareSchema(subschema, context) for subschema in schema)
# We assume at this point that schema is a Joi.object()
newKeys = {
id: IdSchema
revisionId: IdSchema
timestamp: Joi.date().format(TimestampFormat).raw()
author: Joi.string().regex(/^[a-zA-Z0-9_-]+$/)
authorDisplayName: Joi.string().allow('').optional()
}
# Each context type needs its own ID field
context.forEach (contextDef) ->
# Add another entry to newKeys
typeName = contextDef.name
newKeys[typeName + 'Id'] = IdSchema
# Extend the original set of permissible keys
return schema.keys(newKeys)
module.exports = {
createCollectionApi
}
| 214803 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# This module implements the core operations of the persistent object store.
#
# The Persist package generates an API based on the data models it is
# configured with. Within that API, there is an interface for each collection
# (e.g. `persist.clientFiles` or `persist.metrics`). That interface is called
# a Collection API, i.e. an API for a specific collection.
#
# The `createCollectionApi` function generates an API for a single collection
# based on a data model (and some additional information such as the current
# session). The `persist/apiBuilder` module uses this function on every data
# model definition.
Async = require 'async'
Joi = require 'joi'
Imm = require 'immutable'
Moment = require 'moment'
{
IOError
IdSchema
ObjectNotFoundError
TimestampFormat
generateId
} = require './utils'
joiValidationOptions = Object.freeze {
# I would like to set this to false, but Joi doesn't seem to support date
# string validation without convert: true
convert: true
# Any properties that are not required must be explicitly marked optional.
presence: 'required'
}
# Create an API based on the specified model definition.
#
# session: a Session object
# eventBus: the EventBus to which object mutation events should be dispatched
# context: a List of model definitions. Each model definition is an ancestor
# of this collection, ordered from outermost (i.e. top-level) to innermost.
#
# Example:
# Imm.List([clientFileModelDef, progNoteModelDef])
#
# modelDef: the data model definition that defines this collection
createCollectionApi = (backend, session, eventBus, context, modelDef) ->
# Define a series of methods that this collection API will (or might) contain.
# These methods correspond to what is documented in the wiki.
# See the wiki for instructions on their use.
create = (obj, cb) ->
# The object hasn't been created yet, so it shouldn't have any of these
# metadata fields. If it does, it probably indicates a bug.
if obj.has('id')
cb new Error "new objects cannot already have an ID"
return
if obj.has('revisionId')
cb new Error "new objects cannot already have a revision ID"
return
# We allow explicit metadata for development purposes, such as seeding.
# This is commented out for now, to prevent the application failing here
# when trying to import data that might somehow still have these metadata properties attached
# (which get overwritten here anyway)
# if process.env.NODE_ENV isnt 'development'
# if obj.has('author')
# cb new Error "new objects cannot already have an author"
# return
# if obj.has('timestamp')
# cb new Error "new objects cannot already have a timestamp"
# return
# if obj.has('authorDisplayName')
# cb new Error "new objects cannot already have a displayName"
# return
# Add metadata fields
obj = obj
.set 'id', generateId()
.set 'revisionId', generateId()
.set 'author', obj.get('author') or session.userName
.set 'authorDisplayName', session.displayName or session.userName
.set 'timestamp', obj.get('timestamp') or Moment().format(TimestampFormat)
# Validate object before passing to backend
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
process.nextTick ->
cb validation.error
return
backend.createObject Imm.fromJS(validation.value), context, modelDef, (err) ->
if err
cb err
return
# Return a copy of the newly created object, complete with metadata
cb null, obj
list = (contextualIds..., cb) ->
contextualIds = Imm.List(contextualIds)
# API user must provide IDs for each of the ancestor objects,
# otherwise, we don't know where to look
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.listObjectsInCollection contextualIds, context, modelDef, (err, headers) ->
if err
cb err
return
cb null, headers
read = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
# API user must provide enough IDs to figure out where this collection
# is located.
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.readObject contextualIds, id, context, modelDef, (err, obj) ->
if err
cb err
return
# Validate against the collection's schema
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
cb validation.error
return
cb null, Imm.fromJS validation.value
createRevision = (obj, cb) ->
# The object should already have been created, so it should already
# have an ID.
unless obj.has('id')
cb new Error "missing property 'id'"
return
objId = obj.get('id')
# Add the relevant metadata fields
obj = obj
.set 'revisionId', generateId()
.set 'author', session.userName
.set 'authorDisplayName', session.displayName or session.userName
.set 'timestamp', Moment().format(TimestampFormat)
# Validate object before passing to backend
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
process.nextTick ->
cb validation.error
return
backend.createObjectRevision Imm.fromJS(validation.value), context, modelDef, (err) ->
if err
cb err
return
cb null, obj
listRevisions = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
# Need enough context to locate this object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.listObjectRevisions contextualIds, id, context, modelDef, cb
readRevisions = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
cb new Error "readRevisions must be provided a callback"
return
# Need enough information to determine where this object's collection
# is located
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
# List all of this object's revisions
listRevisions contextualIds.toArray()..., id, (err, revisions) ->
if err
cb err
return
# Read the revisions one-by-one
Async.map revisions.toArray(), (rev, cb) ->
readRevision contextualIds.toArray()..., id, rev.get('revisionId'), cb
, (err, results) ->
if err
cb err
return
cb null, Imm.List(results)
readLatestRevisions = (contextualIds..., id, maxRevisionCount, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
throw new Error "readLatestRevisions must be provided a callback"
# Need object IDs of any ancestor objects in order to locate this
# object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
if maxRevisionCount < 0
cb new Error "maxRevisionCount must be >= 0"
return
# We could theoretically optimize for maxRevisionCount=0 here.
# However, this would cause requests for non-existant objects to succeed.
# List all of the object's revisions
listRevisions contextualIds.toArray()..., id, (err, revisions) ->
if err
cb err
return
# Only access the most recent revisions
revisions = revisions.takeLast maxRevisionCount
# Read only those revisions
Async.map revisions.toArray(), (rev, cb) ->
readRevision contextualIds.toArray()..., id, rev.get('revisionId'), cb
, (err, results) ->
if err
cb err
return
cb null, Imm.List(results)
readRevision = (contextualIds..., id, revisionId, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
throw new Error "readLatestRevisions must be provided a callback"
# Need object IDs of any ancestor objects in order to locate this
# object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.readObjectRevision contextualIds, id, revisionId, context, modelDef, (err, obj) ->
if err
cb err
return
# Validate against the collection's schema
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
cb validation.error
return
cb null, Imm.fromJS validation.value
# Build and return the actual collection API, using the previously defined methods
result = {
create,
list,
}
if modelDef.isMutable
# Only mutable collections have methods related to revisions
result.createRevision = createRevision
result.listRevisions = listRevisions
result.readRevisions = readRevisions
result.readLatestRevisions = readLatestRevisions
else
# Immutable collections just get the basic read method
result.read = read
return result
# Add metadata fields to object schema
prepareSchema = (schema, context) ->
# The schema can be an array of possible schemas
# (see Joi documentation)
if Array.isArray schema
return (prepareSchema(subschema, context) for subschema in schema)
# We assume at this point that schema is a Joi.object()
newKeys = {
id: IdSchema
revisionId: IdSchema
timestamp: Joi.date().format(TimestampFormat).raw()
author: Joi.string().regex(/^[a-zA-Z0-9_-]+$/)
authorDisplayName: Joi.string().allow('').optional()
}
# Each context type needs its own ID field
context.forEach (contextDef) ->
# Add another entry to newKeys
typeName = contextDef.name
newKeys[typeName + 'Id'] = IdSchema
# Extend the original set of permissible keys
return schema.keys(newKeys)
module.exports = {
createCollectionApi
}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
# This module implements the core operations of the persistent object store.
#
# The Persist package generates an API based on the data models it is
# configured with. Within that API, there is an interface for each collection
# (e.g. `persist.clientFiles` or `persist.metrics`). That interface is called
# a Collection API, i.e. an API for a specific collection.
#
# The `createCollectionApi` function generates an API for a single collection
# based on a data model (and some additional information such as the current
# session). The `persist/apiBuilder` module uses this function on every data
# model definition.
Async = require 'async'
Joi = require 'joi'
Imm = require 'immutable'
Moment = require 'moment'
{
IOError
IdSchema
ObjectNotFoundError
TimestampFormat
generateId
} = require './utils'
joiValidationOptions = Object.freeze {
# I would like to set this to false, but Joi doesn't seem to support date
# string validation without convert: true
convert: true
# Any properties that are not required must be explicitly marked optional.
presence: 'required'
}
# Create an API based on the specified model definition.
#
# session: a Session object
# eventBus: the EventBus to which object mutation events should be dispatched
# context: a List of model definitions. Each model definition is an ancestor
# of this collection, ordered from outermost (i.e. top-level) to innermost.
#
# Example:
# Imm.List([clientFileModelDef, progNoteModelDef])
#
# modelDef: the data model definition that defines this collection
createCollectionApi = (backend, session, eventBus, context, modelDef) ->
# Define a series of methods that this collection API will (or might) contain.
# These methods correspond to what is documented in the wiki.
# See the wiki for instructions on their use.
create = (obj, cb) ->
# The object hasn't been created yet, so it shouldn't have any of these
# metadata fields. If it does, it probably indicates a bug.
if obj.has('id')
cb new Error "new objects cannot already have an ID"
return
if obj.has('revisionId')
cb new Error "new objects cannot already have a revision ID"
return
# We allow explicit metadata for development purposes, such as seeding.
# This is commented out for now, to prevent the application failing here
# when trying to import data that might somehow still have these metadata properties attached
# (which get overwritten here anyway)
# if process.env.NODE_ENV isnt 'development'
# if obj.has('author')
# cb new Error "new objects cannot already have an author"
# return
# if obj.has('timestamp')
# cb new Error "new objects cannot already have a timestamp"
# return
# if obj.has('authorDisplayName')
# cb new Error "new objects cannot already have a displayName"
# return
# Add metadata fields
obj = obj
.set 'id', generateId()
.set 'revisionId', generateId()
.set 'author', obj.get('author') or session.userName
.set 'authorDisplayName', session.displayName or session.userName
.set 'timestamp', obj.get('timestamp') or Moment().format(TimestampFormat)
# Validate object before passing to backend
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
process.nextTick ->
cb validation.error
return
backend.createObject Imm.fromJS(validation.value), context, modelDef, (err) ->
if err
cb err
return
# Return a copy of the newly created object, complete with metadata
cb null, obj
list = (contextualIds..., cb) ->
contextualIds = Imm.List(contextualIds)
# API user must provide IDs for each of the ancestor objects,
# otherwise, we don't know where to look
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.listObjectsInCollection contextualIds, context, modelDef, (err, headers) ->
if err
cb err
return
cb null, headers
read = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
# API user must provide enough IDs to figure out where this collection
# is located.
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.readObject contextualIds, id, context, modelDef, (err, obj) ->
if err
cb err
return
# Validate against the collection's schema
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
cb validation.error
return
cb null, Imm.fromJS validation.value
createRevision = (obj, cb) ->
# The object should already have been created, so it should already
# have an ID.
unless obj.has('id')
cb new Error "missing property 'id'"
return
objId = obj.get('id')
# Add the relevant metadata fields
obj = obj
.set 'revisionId', generateId()
.set 'author', session.userName
.set 'authorDisplayName', session.displayName or session.userName
.set 'timestamp', Moment().format(TimestampFormat)
# Validate object before passing to backend
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
process.nextTick ->
cb validation.error
return
backend.createObjectRevision Imm.fromJS(validation.value), context, modelDef, (err) ->
if err
cb err
return
cb null, obj
listRevisions = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
# Need enough context to locate this object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.listObjectRevisions contextualIds, id, context, modelDef, cb
readRevisions = (contextualIds..., id, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
cb new Error "readRevisions must be provided a callback"
return
# Need enough information to determine where this object's collection
# is located
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
# List all of this object's revisions
listRevisions contextualIds.toArray()..., id, (err, revisions) ->
if err
cb err
return
# Read the revisions one-by-one
Async.map revisions.toArray(), (rev, cb) ->
readRevision contextualIds.toArray()..., id, rev.get('revisionId'), cb
, (err, results) ->
if err
cb err
return
cb null, Imm.List(results)
readLatestRevisions = (contextualIds..., id, maxRevisionCount, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
throw new Error "readLatestRevisions must be provided a callback"
# Need object IDs of any ancestor objects in order to locate this
# object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
if maxRevisionCount < 0
cb new Error "maxRevisionCount must be >= 0"
return
# We could theoretically optimize for maxRevisionCount=0 here.
# However, this would cause requests for non-existant objects to succeed.
# List all of the object's revisions
listRevisions contextualIds.toArray()..., id, (err, revisions) ->
if err
cb err
return
# Only access the most recent revisions
revisions = revisions.takeLast maxRevisionCount
# Read only those revisions
Async.map revisions.toArray(), (rev, cb) ->
readRevision contextualIds.toArray()..., id, rev.get('revisionId'), cb
, (err, results) ->
if err
cb err
return
cb null, Imm.List(results)
readRevision = (contextualIds..., id, revisionId, cb) ->
contextualIds = Imm.List(contextualIds)
unless cb
throw new Error "readLatestRevisions must be provided a callback"
# Need object IDs of any ancestor objects in order to locate this
# object's collection
if contextualIds.size isnt context.size
cb new Error "wrong number of arguments"
return
backend.readObjectRevision contextualIds, id, revisionId, context, modelDef, (err, obj) ->
if err
cb err
return
# Validate against the collection's schema
schema = prepareSchema modelDef.schema, context
validation = Joi.validate obj.toJS(), schema, joiValidationOptions
if validation.error?
cb validation.error
return
cb null, Imm.fromJS validation.value
# Build and return the actual collection API, using the previously defined methods
result = {
create,
list,
}
if modelDef.isMutable
# Only mutable collections have methods related to revisions
result.createRevision = createRevision
result.listRevisions = listRevisions
result.readRevisions = readRevisions
result.readLatestRevisions = readLatestRevisions
else
# Immutable collections just get the basic read method
result.read = read
return result
# Add metadata fields to object schema
prepareSchema = (schema, context) ->
# The schema can be an array of possible schemas
# (see Joi documentation)
if Array.isArray schema
return (prepareSchema(subschema, context) for subschema in schema)
# We assume at this point that schema is a Joi.object()
newKeys = {
id: IdSchema
revisionId: IdSchema
timestamp: Joi.date().format(TimestampFormat).raw()
author: Joi.string().regex(/^[a-zA-Z0-9_-]+$/)
authorDisplayName: Joi.string().allow('').optional()
}
# Each context type needs its own ID field
context.forEach (contextDef) ->
# Add another entry to newKeys
typeName = contextDef.name
newKeys[typeName + 'Id'] = IdSchema
# Extend the original set of permissible keys
return schema.keys(newKeys)
module.exports = {
createCollectionApi
}
|
[
{
"context": "s\n addresses:\n patterns: [\n {\n # \"John Doe\" <john.doe@example.com>\n name: 'meta.email",
"end": 455,
"score": 0.9997892379760742,
"start": 447,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "es:\n patterns: [\n {\n # \"John Doe\" <john.doe@example.com>\n name: 'meta.email-address.eml'\n m",
"end": 478,
"score": 0.999923050403595,
"start": 458,
"tag": "EMAIL",
"value": "john.doe@example.com"
},
{
"context": "efinition.tag.end.eml\"\n }\n {\n # \"John Doe\" <john.doe@example.com>\n name: 'meta",
"end": 1052,
"score": 0.9998303651809692,
"start": 1044,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "end.eml\"\n }\n {\n # \"John Doe\" <john.doe@example.com>\n name: 'meta.email-address.eml'\n ",
"end": 1078,
"score": 0.9999182820320129,
"start": 1058,
"tag": "EMAIL",
"value": "john.doe@example.com"
},
{
"context": ".definition.tag.end.eml\"\n }\n {\n # John <john.doe@example.com>\n name: 'meta.email-",
"end": 1654,
"score": 0.9998195767402649,
"start": 1650,
"tag": "NAME",
"value": "John"
},
{
"context": "tion.tag.end.eml\"\n }\n {\n # John <john.doe@example.com>\n name: 'meta.email-address.eml'\n m",
"end": 1676,
"score": 0.9999253153800964,
"start": 1656,
"tag": "EMAIL",
"value": "john.doe@example.com"
},
{
"context": ".definition.tag.end.eml\"\n }\n {\n # John <john.doe@example.com>\n name: 'meta.",
"end": 2105,
"score": 0.99983811378479,
"start": 2101,
"tag": "NAME",
"value": "John"
},
{
"context": "n.tag.end.eml\"\n }\n {\n # John <john.doe@example.com>\n name: 'meta.email-address.eml'\n ",
"end": 2130,
"score": 0.9999207854270935,
"start": 2110,
"tag": "EMAIL",
"value": "john.doe@example.com"
},
{
"context": "nition.tag.end.eml\"\n }\n {\n # <john.doe@example.com>\n match: '(<)([-a-zA-Z0-9.+_]+@[-a-z",
"end": 2588,
"score": 0.9999246001243591,
"start": 2568,
"tag": "EMAIL",
"value": "john.doe@example.com"
},
{
"context": "efinition.tag.end.eml\"\n }\n {\n # <john.doe@example.com>\n match: '(<?)([-a-zA-Z0-9.+_]+@[-a-zA-Z0-",
"end": 2890,
"score": 0.9999257326126099,
"start": 2870,
"tag": "EMAIL",
"value": "john.doe@example.com"
}
] | grammars/language-eml.cson | mariozaizar/language-eml | 6 | scopeName: 'text.eml.basic'
name: 'Email (EML)'
fileTypes: ['eml', 'msg', 'mbx', 'mbox']
patterns: [
{include: "#addresses"}
{include: "#headers"}
{include: "#boundary"}
{include: "#encodedWord"}
{include: "#encodingTypes"}
{include: "#uuid"}
{include: "#base64"}
{include: "#html"}
{include: "#quote"}
{include: "#ipv4"}
{include: "#ipv6"}
]
repository:
# Email addresses
addresses:
patterns: [
{
# "John Doe" <john.doe@example.com>
name: 'meta.email-address.eml'
match: """(?ix)
((") [-a-zA-Z0-9.\\x20+_]+ (")) \\s*
((<) [-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+ (>))
"""
captures:
1: name: "string.quoted.double.author-name.eml"
2: name: "punctuation.definition.string.begin.eml"
3: name: "punctuation.definition.string.end.eml"
4: name: "constant.other.author-address.eml"
5: name: "punctuation.definition.tag.begin.eml"
6: name: "punctuation.definition.tag.end.eml"
}
{
# "John Doe" <john.doe@example.com>
name: 'meta.email-address.eml'
match: """(?ix)
((") [-a-zA-Z0-9.\\ +_]+ (")) \\s*
((<) [-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+ (>))
"""
captures:
1: name: "string.quoted.double.author-name.eml"
2: name: "punctuation.definition.string.begin.eml"
3: name: "punctuation.definition.string.end.eml"
4: name: "constant.other.author-address.eml"
5: name: "punctuation.definition.tag.begin.eml"
6: name: "punctuation.definition.tag.end.eml"
}
{
# John <john.doe@example.com>
name: 'meta.email-address.eml'
match: """(?ix)
([-a-zZ-Z0-9.+_]+) \\s*
(<)([-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+)(>)
"""
captures:
1: name: "string.unquoted.author-name.eml"
2: name: "punctuation.definition.tag.begin.eml"
3: name: "constant.other.author-address.eml"
4: name: "punctuation.definition.tag.end.eml"
}
{
# John <john.doe@example.com>
name: 'meta.email-address.eml'
match: """(?ix)
([-a-zZ-Z0-9.+_]+) \\s*
(<)([-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+)(>)
"""
captures:
1: name: "string.unquoted.author-name.eml"
2: name: "punctuation.definition.tag.begin.eml"
3: name: "constant.other.author-address.eml"
4: name: "punctuation.definition.tag.end.eml"
}
{
# <john.doe@example.com>
match: '(<)([-a-zA-Z0-9.+_]+@[-a-zA-Z0-9.]+)(>)'
captures:
1: name: "punctuation.definition.tag.begin.eml"
2: name: "constant.other.author-address.eml"
3: name: "punctuation.definition.tag.end.eml"
}
{
# <john.doe@example.com>
match: '(<?)([-a-zA-Z0-9.+_]+@[-a-zA-Z0-9.]+)(>?)'
captures:
1: name: "punctuation.definition.tag.begin.eml"
2: name: "constant.other.author-address.eml"
3: name: "punctuation.definition.tag.end.eml"
}
]
# Content-Transfer-Encoding: base64
base64:
name: 'text.eml.encoded'
match: """(?x) ^
(?:[A-Za-z0-9+/]{4})+
(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
"""
# Multipart MIME
boundary:
name: 'meta.multi-part.chunk.eml'
begin: '^(--(?!>).*)'
end: '^(?=\\1)'
beginCaptures:
0: name: 'keyword.control.boundary.eml'
patterns: [{
# Content-Type: text/html;
name: 'meta.embedded.html.eml'
begin: '^(?i)(Content-Type:)\\s*(text/html(?=[\\s;+]).*)'
end: '^(?=--(?!>))'
patterns: [
{include: '#boundaryHeaders'}
{include: 'text.html.basic'}
]
contentName: 'meta.embedded.html'
beginCaptures:
1: patterns: [include: '#headers']
2: patterns: [include: '$self']
},{
# Content-Type: text/plain;
name: 'meta.embedded.text.eml'
begin: '^(?i)(Content-Type:)\\s*((?!text/html(?=[\\s;+]))\\S+.*)'
end: '^(?=--(?!>))'
contentName: 'markup.raw.html'
beginCaptures:
1: patterns: [include: '#headers']
2: patterns: [include: '$self']
patterns: [include: '#boundaryHeaders']
},{
# Other headers unrelated to content-type
include: '$self'
}]
# Additional headers following Content-Type, but before body
boundaryHeaders:
begin: '\\G'
end: '^(?=\\s*)$'
patterns: [include: '$self']
# Single-part MIME (Content-Type: text/html)
html:
name: 'meta.single.html.eml'
begin: '(?xi)^\<html(.*)\>$'
end: '(?xi)^\<\/html\>$'
patterns: [
{include: 'text.html.basic'},
{include: '$self'}
]
# Header fields
headers:
captures:
1: name: 'variable.header.name.eml'
2: name: 'punctuation.separator.dictionary.key-value.colon.eml'
match: '''(?xi) ^
( archived-at
| cc
| content-type
| date
| envelope-from
| from
| in-reply-to
| mail-from
| message-id
| precedence
| references
| reply-to
| return-path
| sender
| subject
| to
| x-cmae-virus
| \\d*zendesk\\d*
| [^:]*resent-[^:]*
| x-[^:]*
| [A-Z][a-zA-Z0-9-]*
) (:)
'''
# Encoded-words (https://www.ietf.org/rfc/rfc2047.txt)
encodedWord:
name: 'keyword.control.encoded-word.eml'
match: '(?i)=\\?utf-8\\?B\\?(.*)\\?='
# IPv4
ipv4:
name: 'variable.other.ipv4.eml'
match: '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
# IPv6
ipv6:
name: 'variable.other.eml'
match: '''(?x)
( ([0-9a-fA-F]{1,4}:){7} [0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,4} :[0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,6} :[0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,7} :
| ([0-9a-fA-F]{1,4}:){1,5} (:[0-9a-fA-F]{1,4}){1,2}
| ([0-9a-fA-F]{1,4}:){1,4} (:[0-9a-fA-F]{1,4}){1,3}
| ([0-9a-fA-F]{1,4}:){1,3} (:[0-9a-fA-F]{1,4}){1,4}
| ([0-9a-fA-F]{1,4}:){1,2} (:[0-9a-fA-F]{1,4}){1,5}
| [0-9a-fA-F]{1,4} :((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)
| fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]+
| ::(ffff(:0{1,4})?:)? ((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])
| ([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])
)
'''
# Quoted Text
quote:
name: 'markup.quote.line.eml'
begin: '^[|>]'
end: '$'
beginCaptures:
0: name: 'punctuation.definition.comment.quote.eml'
# Specials
encodingTypes:
name: 'keyword.operator.special.eml'
match: '''(?xi)
( base64
| multipart\\/.*:
| image\\/.*;
| text\\/.*
| boundary=.*
)
'''
# UUID
uuid:
name: 'constant.other.uuid.eml'
match: '''(?x)
( [0-9a-fA-F]{32}
| [0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}
)
'''
| 67937 | scopeName: 'text.eml.basic'
name: 'Email (EML)'
fileTypes: ['eml', 'msg', 'mbx', 'mbox']
patterns: [
{include: "#addresses"}
{include: "#headers"}
{include: "#boundary"}
{include: "#encodedWord"}
{include: "#encodingTypes"}
{include: "#uuid"}
{include: "#base64"}
{include: "#html"}
{include: "#quote"}
{include: "#ipv4"}
{include: "#ipv6"}
]
repository:
# Email addresses
addresses:
patterns: [
{
# "<NAME>" <<EMAIL>>
name: 'meta.email-address.eml'
match: """(?ix)
((") [-a-zA-Z0-9.\\x20+_]+ (")) \\s*
((<) [-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+ (>))
"""
captures:
1: name: "string.quoted.double.author-name.eml"
2: name: "punctuation.definition.string.begin.eml"
3: name: "punctuation.definition.string.end.eml"
4: name: "constant.other.author-address.eml"
5: name: "punctuation.definition.tag.begin.eml"
6: name: "punctuation.definition.tag.end.eml"
}
{
# "<NAME>" <<EMAIL>>
name: 'meta.email-address.eml'
match: """(?ix)
((") [-a-zA-Z0-9.\\ +_]+ (")) \\s*
((<) [-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+ (>))
"""
captures:
1: name: "string.quoted.double.author-name.eml"
2: name: "punctuation.definition.string.begin.eml"
3: name: "punctuation.definition.string.end.eml"
4: name: "constant.other.author-address.eml"
5: name: "punctuation.definition.tag.begin.eml"
6: name: "punctuation.definition.tag.end.eml"
}
{
# <NAME> <<EMAIL>>
name: 'meta.email-address.eml'
match: """(?ix)
([-a-zZ-Z0-9.+_]+) \\s*
(<)([-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+)(>)
"""
captures:
1: name: "string.unquoted.author-name.eml"
2: name: "punctuation.definition.tag.begin.eml"
3: name: "constant.other.author-address.eml"
4: name: "punctuation.definition.tag.end.eml"
}
{
# <NAME> <<EMAIL>>
name: 'meta.email-address.eml'
match: """(?ix)
([-a-zZ-Z0-9.+_]+) \\s*
(<)([-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+)(>)
"""
captures:
1: name: "string.unquoted.author-name.eml"
2: name: "punctuation.definition.tag.begin.eml"
3: name: "constant.other.author-address.eml"
4: name: "punctuation.definition.tag.end.eml"
}
{
# <<EMAIL>>
match: '(<)([-a-zA-Z0-9.+_]+@[-a-zA-Z0-9.]+)(>)'
captures:
1: name: "punctuation.definition.tag.begin.eml"
2: name: "constant.other.author-address.eml"
3: name: "punctuation.definition.tag.end.eml"
}
{
# <<EMAIL>>
match: '(<?)([-a-zA-Z0-9.+_]+@[-a-zA-Z0-9.]+)(>?)'
captures:
1: name: "punctuation.definition.tag.begin.eml"
2: name: "constant.other.author-address.eml"
3: name: "punctuation.definition.tag.end.eml"
}
]
# Content-Transfer-Encoding: base64
base64:
name: 'text.eml.encoded'
match: """(?x) ^
(?:[A-Za-z0-9+/]{4})+
(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
"""
# Multipart MIME
boundary:
name: 'meta.multi-part.chunk.eml'
begin: '^(--(?!>).*)'
end: '^(?=\\1)'
beginCaptures:
0: name: 'keyword.control.boundary.eml'
patterns: [{
# Content-Type: text/html;
name: 'meta.embedded.html.eml'
begin: '^(?i)(Content-Type:)\\s*(text/html(?=[\\s;+]).*)'
end: '^(?=--(?!>))'
patterns: [
{include: '#boundaryHeaders'}
{include: 'text.html.basic'}
]
contentName: 'meta.embedded.html'
beginCaptures:
1: patterns: [include: '#headers']
2: patterns: [include: '$self']
},{
# Content-Type: text/plain;
name: 'meta.embedded.text.eml'
begin: '^(?i)(Content-Type:)\\s*((?!text/html(?=[\\s;+]))\\S+.*)'
end: '^(?=--(?!>))'
contentName: 'markup.raw.html'
beginCaptures:
1: patterns: [include: '#headers']
2: patterns: [include: '$self']
patterns: [include: '#boundaryHeaders']
},{
# Other headers unrelated to content-type
include: '$self'
}]
# Additional headers following Content-Type, but before body
boundaryHeaders:
begin: '\\G'
end: '^(?=\\s*)$'
patterns: [include: '$self']
# Single-part MIME (Content-Type: text/html)
html:
name: 'meta.single.html.eml'
begin: '(?xi)^\<html(.*)\>$'
end: '(?xi)^\<\/html\>$'
patterns: [
{include: 'text.html.basic'},
{include: '$self'}
]
# Header fields
headers:
captures:
1: name: 'variable.header.name.eml'
2: name: 'punctuation.separator.dictionary.key-value.colon.eml'
match: '''(?xi) ^
( archived-at
| cc
| content-type
| date
| envelope-from
| from
| in-reply-to
| mail-from
| message-id
| precedence
| references
| reply-to
| return-path
| sender
| subject
| to
| x-cmae-virus
| \\d*zendesk\\d*
| [^:]*resent-[^:]*
| x-[^:]*
| [A-Z][a-zA-Z0-9-]*
) (:)
'''
# Encoded-words (https://www.ietf.org/rfc/rfc2047.txt)
encodedWord:
name: 'keyword.control.encoded-word.eml'
match: '(?i)=\\?utf-8\\?B\\?(.*)\\?='
# IPv4
ipv4:
name: 'variable.other.ipv4.eml'
match: '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
# IPv6
ipv6:
name: 'variable.other.eml'
match: '''(?x)
( ([0-9a-fA-F]{1,4}:){7} [0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,4} :[0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,6} :[0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,7} :
| ([0-9a-fA-F]{1,4}:){1,5} (:[0-9a-fA-F]{1,4}){1,2}
| ([0-9a-fA-F]{1,4}:){1,4} (:[0-9a-fA-F]{1,4}){1,3}
| ([0-9a-fA-F]{1,4}:){1,3} (:[0-9a-fA-F]{1,4}){1,4}
| ([0-9a-fA-F]{1,4}:){1,2} (:[0-9a-fA-F]{1,4}){1,5}
| [0-9a-fA-F]{1,4} :((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)
| fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]+
| ::(ffff(:0{1,4})?:)? ((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])
| ([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])
)
'''
# Quoted Text
quote:
name: 'markup.quote.line.eml'
begin: '^[|>]'
end: '$'
beginCaptures:
0: name: 'punctuation.definition.comment.quote.eml'
# Specials
encodingTypes:
name: 'keyword.operator.special.eml'
match: '''(?xi)
( base64
| multipart\\/.*:
| image\\/.*;
| text\\/.*
| boundary=.*
)
'''
# UUID
uuid:
name: 'constant.other.uuid.eml'
match: '''(?x)
( [0-9a-fA-F]{32}
| [0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}
)
'''
| true | scopeName: 'text.eml.basic'
name: 'Email (EML)'
fileTypes: ['eml', 'msg', 'mbx', 'mbox']
patterns: [
{include: "#addresses"}
{include: "#headers"}
{include: "#boundary"}
{include: "#encodedWord"}
{include: "#encodingTypes"}
{include: "#uuid"}
{include: "#base64"}
{include: "#html"}
{include: "#quote"}
{include: "#ipv4"}
{include: "#ipv6"}
]
repository:
# Email addresses
addresses:
patterns: [
{
# "PI:NAME:<NAME>END_PI" <PI:EMAIL:<EMAIL>END_PI>
name: 'meta.email-address.eml'
match: """(?ix)
((") [-a-zA-Z0-9.\\x20+_]+ (")) \\s*
((<) [-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+ (>))
"""
captures:
1: name: "string.quoted.double.author-name.eml"
2: name: "punctuation.definition.string.begin.eml"
3: name: "punctuation.definition.string.end.eml"
4: name: "constant.other.author-address.eml"
5: name: "punctuation.definition.tag.begin.eml"
6: name: "punctuation.definition.tag.end.eml"
}
{
# "PI:NAME:<NAME>END_PI" <PI:EMAIL:<EMAIL>END_PI>
name: 'meta.email-address.eml'
match: """(?ix)
((") [-a-zA-Z0-9.\\ +_]+ (")) \\s*
((<) [-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+ (>))
"""
captures:
1: name: "string.quoted.double.author-name.eml"
2: name: "punctuation.definition.string.begin.eml"
3: name: "punctuation.definition.string.end.eml"
4: name: "constant.other.author-address.eml"
5: name: "punctuation.definition.tag.begin.eml"
6: name: "punctuation.definition.tag.end.eml"
}
{
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
name: 'meta.email-address.eml'
match: """(?ix)
([-a-zZ-Z0-9.+_]+) \\s*
(<)([-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+)(>)
"""
captures:
1: name: "string.unquoted.author-name.eml"
2: name: "punctuation.definition.tag.begin.eml"
3: name: "constant.other.author-address.eml"
4: name: "punctuation.definition.tag.end.eml"
}
{
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
name: 'meta.email-address.eml'
match: """(?ix)
([-a-zZ-Z0-9.+_]+) \\s*
(<)([-a-zA-Z0-9.]+@[-a-zA-Z0-9.]+)(>)
"""
captures:
1: name: "string.unquoted.author-name.eml"
2: name: "punctuation.definition.tag.begin.eml"
3: name: "constant.other.author-address.eml"
4: name: "punctuation.definition.tag.end.eml"
}
{
# <PI:EMAIL:<EMAIL>END_PI>
match: '(<)([-a-zA-Z0-9.+_]+@[-a-zA-Z0-9.]+)(>)'
captures:
1: name: "punctuation.definition.tag.begin.eml"
2: name: "constant.other.author-address.eml"
3: name: "punctuation.definition.tag.end.eml"
}
{
# <PI:EMAIL:<EMAIL>END_PI>
match: '(<?)([-a-zA-Z0-9.+_]+@[-a-zA-Z0-9.]+)(>?)'
captures:
1: name: "punctuation.definition.tag.begin.eml"
2: name: "constant.other.author-address.eml"
3: name: "punctuation.definition.tag.end.eml"
}
]
# Content-Transfer-Encoding: base64
base64:
name: 'text.eml.encoded'
match: """(?x) ^
(?:[A-Za-z0-9+/]{4})+
(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
"""
# Multipart MIME
boundary:
name: 'meta.multi-part.chunk.eml'
begin: '^(--(?!>).*)'
end: '^(?=\\1)'
beginCaptures:
0: name: 'keyword.control.boundary.eml'
patterns: [{
# Content-Type: text/html;
name: 'meta.embedded.html.eml'
begin: '^(?i)(Content-Type:)\\s*(text/html(?=[\\s;+]).*)'
end: '^(?=--(?!>))'
patterns: [
{include: '#boundaryHeaders'}
{include: 'text.html.basic'}
]
contentName: 'meta.embedded.html'
beginCaptures:
1: patterns: [include: '#headers']
2: patterns: [include: '$self']
},{
# Content-Type: text/plain;
name: 'meta.embedded.text.eml'
begin: '^(?i)(Content-Type:)\\s*((?!text/html(?=[\\s;+]))\\S+.*)'
end: '^(?=--(?!>))'
contentName: 'markup.raw.html'
beginCaptures:
1: patterns: [include: '#headers']
2: patterns: [include: '$self']
patterns: [include: '#boundaryHeaders']
},{
# Other headers unrelated to content-type
include: '$self'
}]
# Additional headers following Content-Type, but before body
boundaryHeaders:
begin: '\\G'
end: '^(?=\\s*)$'
patterns: [include: '$self']
# Single-part MIME (Content-Type: text/html)
html:
name: 'meta.single.html.eml'
begin: '(?xi)^\<html(.*)\>$'
end: '(?xi)^\<\/html\>$'
patterns: [
{include: 'text.html.basic'},
{include: '$self'}
]
# Header fields
headers:
captures:
1: name: 'variable.header.name.eml'
2: name: 'punctuation.separator.dictionary.key-value.colon.eml'
match: '''(?xi) ^
( archived-at
| cc
| content-type
| date
| envelope-from
| from
| in-reply-to
| mail-from
| message-id
| precedence
| references
| reply-to
| return-path
| sender
| subject
| to
| x-cmae-virus
| \\d*zendesk\\d*
| [^:]*resent-[^:]*
| x-[^:]*
| [A-Z][a-zA-Z0-9-]*
) (:)
'''
# Encoded-words (https://www.ietf.org/rfc/rfc2047.txt)
encodedWord:
name: 'keyword.control.encoded-word.eml'
match: '(?i)=\\?utf-8\\?B\\?(.*)\\?='
# IPv4
ipv4:
name: 'variable.other.ipv4.eml'
match: '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
# IPv6
ipv6:
name: 'variable.other.eml'
match: '''(?x)
( ([0-9a-fA-F]{1,4}:){7} [0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,4} :[0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,6} :[0-9a-fA-F]{1,4}
| ([0-9a-fA-F]{1,4}:){1,7} :
| ([0-9a-fA-F]{1,4}:){1,5} (:[0-9a-fA-F]{1,4}){1,2}
| ([0-9a-fA-F]{1,4}:){1,4} (:[0-9a-fA-F]{1,4}){1,3}
| ([0-9a-fA-F]{1,4}:){1,3} (:[0-9a-fA-F]{1,4}){1,4}
| ([0-9a-fA-F]{1,4}:){1,2} (:[0-9a-fA-F]{1,4}){1,5}
| [0-9a-fA-F]{1,4} :((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)
| fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]+
| ::(ffff(:0{1,4})?:)? ((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])
| ([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1?[0-9])?[0-9])\\.){3}(25[0-5]|(2[0-4]|1?[0-9])?[0-9])
)
'''
# Quoted Text
quote:
name: 'markup.quote.line.eml'
begin: '^[|>]'
end: '$'
beginCaptures:
0: name: 'punctuation.definition.comment.quote.eml'
# Specials
encodingTypes:
name: 'keyword.operator.special.eml'
match: '''(?xi)
( base64
| multipart\\/.*:
| image\\/.*;
| text\\/.*
| boundary=.*
)
'''
# UUID
uuid:
name: 'constant.other.uuid.eml'
match: '''(?x)
( [0-9a-fA-F]{32}
| [0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}
)
'''
|
[
{
"context": "=================================\n# Copyright 2014 Hatio, Lab.\n# Licensed under The MIT License\n# http",
"end": 63,
"score": 0.6281068921089172,
"start": 62,
"tag": "NAME",
"value": "H"
}
] | src/command/CommandMove.coffee | heartyoh/infopik | 0 | # ==========================================
# Copyright 2014 Hatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'../Command'
], (dou, Command) ->
"use strict"
class CommandMove extends Command
execute: ->
to = @params.to
model = @params.model
view = @params.view
@i_model = model.getContainer().indexOf(model)
@i_view = view.getZIndex()
switch to
when 'FORWARD'
view.moveUp()
model.moveForward()
when 'BACKWARD'
view.moveDown()
model.moveBackward()
when 'FRONT'
view.moveToTop()
model.moveToFront()
when 'BACK'
view.moveToBottom()
model.moveToBack()
layer = view.getLayer()
layer.draw() if layer
unexecute: ->
to = @params.to
model = @params.model
view = @params.view
view.setZIndex(@i_view)
model.moveAt(@i_model)
layer = view.getLayer()
layer.draw() if layer
| 54 | # ==========================================
# Copyright 2014 <NAME>atio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'../Command'
], (dou, Command) ->
"use strict"
class CommandMove extends Command
execute: ->
to = @params.to
model = @params.model
view = @params.view
@i_model = model.getContainer().indexOf(model)
@i_view = view.getZIndex()
switch to
when 'FORWARD'
view.moveUp()
model.moveForward()
when 'BACKWARD'
view.moveDown()
model.moveBackward()
when 'FRONT'
view.moveToTop()
model.moveToFront()
when 'BACK'
view.moveToBottom()
model.moveToBack()
layer = view.getLayer()
layer.draw() if layer
unexecute: ->
to = @params.to
model = @params.model
view = @params.view
view.setZIndex(@i_view)
model.moveAt(@i_model)
layer = view.getLayer()
layer.draw() if layer
| true | # ==========================================
# Copyright 2014 PI:NAME:<NAME>END_PIatio, Lab.
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
# ==========================================
define [
'dou'
'../Command'
], (dou, Command) ->
"use strict"
class CommandMove extends Command
execute: ->
to = @params.to
model = @params.model
view = @params.view
@i_model = model.getContainer().indexOf(model)
@i_view = view.getZIndex()
switch to
when 'FORWARD'
view.moveUp()
model.moveForward()
when 'BACKWARD'
view.moveDown()
model.moveBackward()
when 'FRONT'
view.moveToTop()
model.moveToFront()
when 'BACK'
view.moveToBottom()
model.moveToBack()
layer = view.getLayer()
layer.draw() if layer
unexecute: ->
to = @params.to
model = @params.model
view = @params.view
view.setZIndex(@i_view)
model.moveAt(@i_model)
layer = view.getLayer()
layer.draw() if layer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.