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": "stream DNS server to send requests to\", default: \"8.8.8.8\"}\n .option \"p\", { alias: \"port\", demand: false", "end": 695, "score": 0.9997676014900208, "start": 688, "tag": "IP_ADDRESS", "value": "8.8.8.8" }, { "context": "lp\"\n .example \"simple-dns-proxy www.test.com:A:127.0.0.1\", \"Resolve www.test.com to 127.0.0.1\"\n .exampl", "end": 1307, "score": 0.9997673034667969, "start": 1298, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "w.test.com:A:127.0.0.1\", \"Resolve www.test.com to 127.0.0.1\"\n .example \"simple-dns-proxy *.test.com:A:127.", "end": 1344, "score": 0.9997829794883728, "start": 1335, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": ".0.1\"\n .example \"simple-dns-proxy *.test.com:A:127.0.0.1\", \"Resolve *.test.com to 127.0.0.1\"\n .epilog \"", "end": 1399, "score": 0.9997686743736267, "start": 1390, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "y *.test.com:A:127.0.0.1\", \"Resolve *.test.com to 127.0.0.1\"\n .epilog \"Copyright 2015 Arturo Arévalo\"\n ", "end": 1434, "score": 0.9996329545974731, "start": 1425, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "test.com to 127.0.0.1\"\n .epilog \"Copyright 2015 Arturo Arévalo\"\n .argv\n\n\n\n\nDnsServer = require \"./dns-server\"", "end": 1478, "score": 0.9998934268951416, "start": 1464, "tag": "NAME", "value": "Arturo Arévalo" } ]
src/index.iced
sajad-sadra/simple-dns-proxy
9
options = require "yargs" .usage """ Usage: simple-dns-proxy <dns-record> [-u <upstream server>] [-p <port>] DESCRIPTION A simple DNS proxy which allows to locally resolve some domain names or patterns and forward the rest of them to an upstream, real DNS server. SECURITY By default, it tries to bind to the standard DNS port (53). If you run it under the root account, additional security can be obtained using the -U and -G options. """ .command "dns-record", "DNS record to resolve" .option "u", { alias: "upstream", demand: false, requiresArg: true, describe: "Upstream DNS server to send requests to", default: "8.8.8.8"} .option "p", { alias: "port", demand: false, requiresArg: true, describe: "Port to bind the DNS service", default: 53} .option "a", { alias: "admin-port", demand: false, requiresArg: true, describe: "Port to bind the HTTP administation interface (0 = disabled)", default: 5380} .option "U", { alias: "uid", demand:false, requiresArg: true, describe: "uid/username to set upon execution" } .option "G", { alias: "gid", demand:false, requiresArg: true, describe: "gid/groupname to set upon execution" } .help "?" .alias "?", "help" .example "simple-dns-proxy www.test.com:A:127.0.0.1", "Resolve www.test.com to 127.0.0.1" .example "simple-dns-proxy *.test.com:A:127.0.0.1", "Resolve *.test.com to 127.0.0.1" .epilog "Copyright 2015 Arturo Arévalo" .argv DnsServer = require "./dns-server" dnsServer = new DnsServer options dnsServer.addTextEntry entry for entry in options._ dnsServer.start()
183659
options = require "yargs" .usage """ Usage: simple-dns-proxy <dns-record> [-u <upstream server>] [-p <port>] DESCRIPTION A simple DNS proxy which allows to locally resolve some domain names or patterns and forward the rest of them to an upstream, real DNS server. SECURITY By default, it tries to bind to the standard DNS port (53). If you run it under the root account, additional security can be obtained using the -U and -G options. """ .command "dns-record", "DNS record to resolve" .option "u", { alias: "upstream", demand: false, requiresArg: true, describe: "Upstream DNS server to send requests to", default: "8.8.8.8"} .option "p", { alias: "port", demand: false, requiresArg: true, describe: "Port to bind the DNS service", default: 53} .option "a", { alias: "admin-port", demand: false, requiresArg: true, describe: "Port to bind the HTTP administation interface (0 = disabled)", default: 5380} .option "U", { alias: "uid", demand:false, requiresArg: true, describe: "uid/username to set upon execution" } .option "G", { alias: "gid", demand:false, requiresArg: true, describe: "gid/groupname to set upon execution" } .help "?" .alias "?", "help" .example "simple-dns-proxy www.test.com:A:127.0.0.1", "Resolve www.test.com to 127.0.0.1" .example "simple-dns-proxy *.test.com:A:127.0.0.1", "Resolve *.test.com to 127.0.0.1" .epilog "Copyright 2015 <NAME>" .argv DnsServer = require "./dns-server" dnsServer = new DnsServer options dnsServer.addTextEntry entry for entry in options._ dnsServer.start()
true
options = require "yargs" .usage """ Usage: simple-dns-proxy <dns-record> [-u <upstream server>] [-p <port>] DESCRIPTION A simple DNS proxy which allows to locally resolve some domain names or patterns and forward the rest of them to an upstream, real DNS server. SECURITY By default, it tries to bind to the standard DNS port (53). If you run it under the root account, additional security can be obtained using the -U and -G options. """ .command "dns-record", "DNS record to resolve" .option "u", { alias: "upstream", demand: false, requiresArg: true, describe: "Upstream DNS server to send requests to", default: "8.8.8.8"} .option "p", { alias: "port", demand: false, requiresArg: true, describe: "Port to bind the DNS service", default: 53} .option "a", { alias: "admin-port", demand: false, requiresArg: true, describe: "Port to bind the HTTP administation interface (0 = disabled)", default: 5380} .option "U", { alias: "uid", demand:false, requiresArg: true, describe: "uid/username to set upon execution" } .option "G", { alias: "gid", demand:false, requiresArg: true, describe: "gid/groupname to set upon execution" } .help "?" .alias "?", "help" .example "simple-dns-proxy www.test.com:A:127.0.0.1", "Resolve www.test.com to 127.0.0.1" .example "simple-dns-proxy *.test.com:A:127.0.0.1", "Resolve *.test.com to 127.0.0.1" .epilog "Copyright 2015 PI:NAME:<NAME>END_PI" .argv DnsServer = require "./dns-server" dnsServer = new DnsServer options dnsServer.addTextEntry entry for entry in options._ dnsServer.start()
[ { "context": "= new jsSHA(\"SHA-1\", 'TEXT')\n shaObj.setHMACKey 'lttmlttm', 'TEXT'\n shaObj.update url\n hmac = shaObj.getH", "end": 6951, "score": 0.8939019441604614, "start": 6943, "tag": "KEY", "value": "lttmlttm" } ]
src/js/lttm.coffee
nekottyo/lttm-crx
0
atwhoOptions = at: "!" tpl: '<li class="lttm" data-value="![${alt}](${imageUrl})"><img src="${imagePreviewUrl}" /></li>' limit: 80 display_timeout: 1000 search_key: null callbacks: matcher: (flag, subtext) -> regexp = new XRegExp("(\\s+|^)" + flag + "([\\p{L}_-]+)$", "gi") match = regexp.exec(subtext) return null unless match and match.length >= 2 match[2] remote_filter: (query, callback) -> return unless query kind = query[0].toLowerCase() query = query.slice(1) switch when kind is "l" if location.protocol == "https:" url = 'https://lttm-ssl.herokuapp.com/lgtm' else url = 'http://www.lgtm.in/g' task1 = $.getJSON(url + '?' + Math.random()).then() task2 = $.getJSON(url + '?' + Math.random()).then() task3 = $.getJSON(url + '?' + Math.random()).then() $.when(task1, task2, task3).then (a, b, c) -> images = _.map([ a[0] b[0] c[0] ], (data) -> imageUrl = data.actualImageUrl name: imageUrl imageUrl: imageUrl imagePreviewUrl: previewUrl(imageUrl) alt: "LGTM" ) callback images when kind is "t" if query $.getJSON "https://d942scftf40wm.cloudfront.net/search.json", q: query , (data) -> images = [] $.each data, (k, v) -> url = "https://img.tiqav.com/" + v.id + "." + v.ext images.push name: url imageUrl: url imagePreviewUrl: previewUrl(url) alt: "tiqav" callback images when kind is "m" $.getJSON chrome.extension.getURL("/config/meigens.json"), (data) -> boys = [] if query boys = _.filter(data, (n) -> (n.title and n.title.indexOf(query) > -1) or (n.body and n.body.indexOf(query) > -1) ) else boys = _.sample(data, 30) images = [] $.each boys, (k, v) -> image = v.image.replace('http://', 'https://') images.push name: image imageUrl: image imagePreviewUrl: previewUrl(image) alt: "ミサワ" callback images when kind is "i" $.getJSON chrome.extension.getURL("/config/irasutoya.json"), (data) -> illustrations = [] if query illustrations = _.filter(data, (n) -> (n.title?.indexOf(query) > -1) || (n.description?.indexOf(query) > -1) || (n.categories && n.categories.join().indexOf(query) > -1) ) else illustrations = _.sample(data, 30) images = [] $.each illustrations, (k, v) -> image_url = v.image_url.replace('http://', 'https://') images.push name: image_url imageUrl: image_url imagePreviewUrl: previewUrl(image_url) alt: v.title callback images when kind is 's' $.getJSON chrome.extension.getURL("/config/sushi_list.json"), (data) -> sushiList = [] if query sushiList = _.filter(data, (sushi) -> !!_.find(sushi.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else sushiList = data images = [] _.each(sushiList, (sushi) -> images.push name: sushi.url imageUrl: sushi.url imagePreviewUrl: sushi.url alt: "寿司ゆき:#{sushi.keywords[0]}" ) callback images when kind is 'j' $.getJSON chrome.extension.getURL("/config/js_girls.json"), (data) -> js_girls = [] if query js_girls = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else js_girls = data images = [] _.each(js_girls, (js_girl) -> images.push name: js_girl.url imageUrl: js_girl.url imagePreviewUrl: js_girl.url alt: "JS Girls:#{js_girl.keywords[0]}" ) callback images when kind is 'n' $.getJSON chrome.extension.getURL("/config/engineer_homeru_neko.json"), (data) -> source = [] if query source = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) > -1 ) ) else source = data images = [] _.each(source, (item) -> images.push name: item.url imageUrl: item.url imagePreviewUrl: item.url alt: "エンジニアを褒めるネコ:#{item.keywords[0]}" ) callback images when kind is 'd' $.getJSON chrome.extension.getURL("/config/decomoji.json"), (data) -> decomojis = [] if query decomojis = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else decomojis = data images = [] _.each(decomojis, (decomoji) -> images.push name: decomoji.url imageUrl: decomoji.url imagePreviewUrl: decomoji.url alt: ":#{decomoji.keywords[0]}" ) callback images when kind is 'r' $.getJSON chrome.extension.getURL("/config/sushidot.json"), (data) -> sushidots = [] if query sushidots = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else sushidots = data images = [] _.each(sushidots, (sushidot) -> images.push name: sushidot.url imageUrl: sushidot.url imagePreviewUrl: sushidot.url alt: ":#{sushidot.keywords[0]}" ) callback images previewUrl = (url) -> return url if location.protocol == "http:" return url if url.indexOf('https:') == 0 shaObj = new jsSHA("SHA-1", 'TEXT') shaObj.setHMACKey 'lttmlttm', 'TEXT' shaObj.update url hmac = shaObj.getHMAC('HEX') "https://lttmcamo.herokuapp.com/#{hmac}?url=#{url}" $(document).on 'focusin', (ev) -> $this = $ ev.target return unless $this.is 'textarea' $this.atwho atwhoOptions $(document).on 'keyup.atwhoInner', (ev) -> setTimeout -> $currentItem = $('.atwho-view .cur') return if $currentItem.length == 0 $parent = $($currentItem.parents('.atwho-view')[0]) offset = Math.floor($currentItem.offset().top - $parent.offset().top) - 1 if (offset < 0) || (offset > 250) setTimeout -> offset = Math.floor($currentItem.offset().top - $parent.offset().top) - 1 row = Math.floor(offset / 150) $parent.scrollTop($parent.scrollTop() + row * 150 - 75) , 100
57349
atwhoOptions = at: "!" tpl: '<li class="lttm" data-value="![${alt}](${imageUrl})"><img src="${imagePreviewUrl}" /></li>' limit: 80 display_timeout: 1000 search_key: null callbacks: matcher: (flag, subtext) -> regexp = new XRegExp("(\\s+|^)" + flag + "([\\p{L}_-]+)$", "gi") match = regexp.exec(subtext) return null unless match and match.length >= 2 match[2] remote_filter: (query, callback) -> return unless query kind = query[0].toLowerCase() query = query.slice(1) switch when kind is "l" if location.protocol == "https:" url = 'https://lttm-ssl.herokuapp.com/lgtm' else url = 'http://www.lgtm.in/g' task1 = $.getJSON(url + '?' + Math.random()).then() task2 = $.getJSON(url + '?' + Math.random()).then() task3 = $.getJSON(url + '?' + Math.random()).then() $.when(task1, task2, task3).then (a, b, c) -> images = _.map([ a[0] b[0] c[0] ], (data) -> imageUrl = data.actualImageUrl name: imageUrl imageUrl: imageUrl imagePreviewUrl: previewUrl(imageUrl) alt: "LGTM" ) callback images when kind is "t" if query $.getJSON "https://d942scftf40wm.cloudfront.net/search.json", q: query , (data) -> images = [] $.each data, (k, v) -> url = "https://img.tiqav.com/" + v.id + "." + v.ext images.push name: url imageUrl: url imagePreviewUrl: previewUrl(url) alt: "tiqav" callback images when kind is "m" $.getJSON chrome.extension.getURL("/config/meigens.json"), (data) -> boys = [] if query boys = _.filter(data, (n) -> (n.title and n.title.indexOf(query) > -1) or (n.body and n.body.indexOf(query) > -1) ) else boys = _.sample(data, 30) images = [] $.each boys, (k, v) -> image = v.image.replace('http://', 'https://') images.push name: image imageUrl: image imagePreviewUrl: previewUrl(image) alt: "ミサワ" callback images when kind is "i" $.getJSON chrome.extension.getURL("/config/irasutoya.json"), (data) -> illustrations = [] if query illustrations = _.filter(data, (n) -> (n.title?.indexOf(query) > -1) || (n.description?.indexOf(query) > -1) || (n.categories && n.categories.join().indexOf(query) > -1) ) else illustrations = _.sample(data, 30) images = [] $.each illustrations, (k, v) -> image_url = v.image_url.replace('http://', 'https://') images.push name: image_url imageUrl: image_url imagePreviewUrl: previewUrl(image_url) alt: v.title callback images when kind is 's' $.getJSON chrome.extension.getURL("/config/sushi_list.json"), (data) -> sushiList = [] if query sushiList = _.filter(data, (sushi) -> !!_.find(sushi.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else sushiList = data images = [] _.each(sushiList, (sushi) -> images.push name: sushi.url imageUrl: sushi.url imagePreviewUrl: sushi.url alt: "寿司ゆき:#{sushi.keywords[0]}" ) callback images when kind is 'j' $.getJSON chrome.extension.getURL("/config/js_girls.json"), (data) -> js_girls = [] if query js_girls = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else js_girls = data images = [] _.each(js_girls, (js_girl) -> images.push name: js_girl.url imageUrl: js_girl.url imagePreviewUrl: js_girl.url alt: "JS Girls:#{js_girl.keywords[0]}" ) callback images when kind is 'n' $.getJSON chrome.extension.getURL("/config/engineer_homeru_neko.json"), (data) -> source = [] if query source = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) > -1 ) ) else source = data images = [] _.each(source, (item) -> images.push name: item.url imageUrl: item.url imagePreviewUrl: item.url alt: "エンジニアを褒めるネコ:#{item.keywords[0]}" ) callback images when kind is 'd' $.getJSON chrome.extension.getURL("/config/decomoji.json"), (data) -> decomojis = [] if query decomojis = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else decomojis = data images = [] _.each(decomojis, (decomoji) -> images.push name: decomoji.url imageUrl: decomoji.url imagePreviewUrl: decomoji.url alt: ":#{decomoji.keywords[0]}" ) callback images when kind is 'r' $.getJSON chrome.extension.getURL("/config/sushidot.json"), (data) -> sushidots = [] if query sushidots = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else sushidots = data images = [] _.each(sushidots, (sushidot) -> images.push name: sushidot.url imageUrl: sushidot.url imagePreviewUrl: sushidot.url alt: ":#{sushidot.keywords[0]}" ) callback images previewUrl = (url) -> return url if location.protocol == "http:" return url if url.indexOf('https:') == 0 shaObj = new jsSHA("SHA-1", 'TEXT') shaObj.setHMACKey '<KEY>', 'TEXT' shaObj.update url hmac = shaObj.getHMAC('HEX') "https://lttmcamo.herokuapp.com/#{hmac}?url=#{url}" $(document).on 'focusin', (ev) -> $this = $ ev.target return unless $this.is 'textarea' $this.atwho atwhoOptions $(document).on 'keyup.atwhoInner', (ev) -> setTimeout -> $currentItem = $('.atwho-view .cur') return if $currentItem.length == 0 $parent = $($currentItem.parents('.atwho-view')[0]) offset = Math.floor($currentItem.offset().top - $parent.offset().top) - 1 if (offset < 0) || (offset > 250) setTimeout -> offset = Math.floor($currentItem.offset().top - $parent.offset().top) - 1 row = Math.floor(offset / 150) $parent.scrollTop($parent.scrollTop() + row * 150 - 75) , 100
true
atwhoOptions = at: "!" tpl: '<li class="lttm" data-value="![${alt}](${imageUrl})"><img src="${imagePreviewUrl}" /></li>' limit: 80 display_timeout: 1000 search_key: null callbacks: matcher: (flag, subtext) -> regexp = new XRegExp("(\\s+|^)" + flag + "([\\p{L}_-]+)$", "gi") match = regexp.exec(subtext) return null unless match and match.length >= 2 match[2] remote_filter: (query, callback) -> return unless query kind = query[0].toLowerCase() query = query.slice(1) switch when kind is "l" if location.protocol == "https:" url = 'https://lttm-ssl.herokuapp.com/lgtm' else url = 'http://www.lgtm.in/g' task1 = $.getJSON(url + '?' + Math.random()).then() task2 = $.getJSON(url + '?' + Math.random()).then() task3 = $.getJSON(url + '?' + Math.random()).then() $.when(task1, task2, task3).then (a, b, c) -> images = _.map([ a[0] b[0] c[0] ], (data) -> imageUrl = data.actualImageUrl name: imageUrl imageUrl: imageUrl imagePreviewUrl: previewUrl(imageUrl) alt: "LGTM" ) callback images when kind is "t" if query $.getJSON "https://d942scftf40wm.cloudfront.net/search.json", q: query , (data) -> images = [] $.each data, (k, v) -> url = "https://img.tiqav.com/" + v.id + "." + v.ext images.push name: url imageUrl: url imagePreviewUrl: previewUrl(url) alt: "tiqav" callback images when kind is "m" $.getJSON chrome.extension.getURL("/config/meigens.json"), (data) -> boys = [] if query boys = _.filter(data, (n) -> (n.title and n.title.indexOf(query) > -1) or (n.body and n.body.indexOf(query) > -1) ) else boys = _.sample(data, 30) images = [] $.each boys, (k, v) -> image = v.image.replace('http://', 'https://') images.push name: image imageUrl: image imagePreviewUrl: previewUrl(image) alt: "ミサワ" callback images when kind is "i" $.getJSON chrome.extension.getURL("/config/irasutoya.json"), (data) -> illustrations = [] if query illustrations = _.filter(data, (n) -> (n.title?.indexOf(query) > -1) || (n.description?.indexOf(query) > -1) || (n.categories && n.categories.join().indexOf(query) > -1) ) else illustrations = _.sample(data, 30) images = [] $.each illustrations, (k, v) -> image_url = v.image_url.replace('http://', 'https://') images.push name: image_url imageUrl: image_url imagePreviewUrl: previewUrl(image_url) alt: v.title callback images when kind is 's' $.getJSON chrome.extension.getURL("/config/sushi_list.json"), (data) -> sushiList = [] if query sushiList = _.filter(data, (sushi) -> !!_.find(sushi.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else sushiList = data images = [] _.each(sushiList, (sushi) -> images.push name: sushi.url imageUrl: sushi.url imagePreviewUrl: sushi.url alt: "寿司ゆき:#{sushi.keywords[0]}" ) callback images when kind is 'j' $.getJSON chrome.extension.getURL("/config/js_girls.json"), (data) -> js_girls = [] if query js_girls = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else js_girls = data images = [] _.each(js_girls, (js_girl) -> images.push name: js_girl.url imageUrl: js_girl.url imagePreviewUrl: js_girl.url alt: "JS Girls:#{js_girl.keywords[0]}" ) callback images when kind is 'n' $.getJSON chrome.extension.getURL("/config/engineer_homeru_neko.json"), (data) -> source = [] if query source = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) > -1 ) ) else source = data images = [] _.each(source, (item) -> images.push name: item.url imageUrl: item.url imagePreviewUrl: item.url alt: "エンジニアを褒めるネコ:#{item.keywords[0]}" ) callback images when kind is 'd' $.getJSON chrome.extension.getURL("/config/decomoji.json"), (data) -> decomojis = [] if query decomojis = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else decomojis = data images = [] _.each(decomojis, (decomoji) -> images.push name: decomoji.url imageUrl: decomoji.url imagePreviewUrl: decomoji.url alt: ":#{decomoji.keywords[0]}" ) callback images when kind is 'r' $.getJSON chrome.extension.getURL("/config/sushidot.json"), (data) -> sushidots = [] if query sushidots = _.filter(data, (js_girl) -> !!_.find(js_girl.keywords, (keyword) -> keyword.indexOf(query) == 0 ) ) else sushidots = data images = [] _.each(sushidots, (sushidot) -> images.push name: sushidot.url imageUrl: sushidot.url imagePreviewUrl: sushidot.url alt: ":#{sushidot.keywords[0]}" ) callback images previewUrl = (url) -> return url if location.protocol == "http:" return url if url.indexOf('https:') == 0 shaObj = new jsSHA("SHA-1", 'TEXT') shaObj.setHMACKey 'PI:KEY:<KEY>END_PI', 'TEXT' shaObj.update url hmac = shaObj.getHMAC('HEX') "https://lttmcamo.herokuapp.com/#{hmac}?url=#{url}" $(document).on 'focusin', (ev) -> $this = $ ev.target return unless $this.is 'textarea' $this.atwho atwhoOptions $(document).on 'keyup.atwhoInner', (ev) -> setTimeout -> $currentItem = $('.atwho-view .cur') return if $currentItem.length == 0 $parent = $($currentItem.parents('.atwho-view')[0]) offset = Math.floor($currentItem.offset().top - $parent.offset().top) - 1 if (offset < 0) || (offset > 250) setTimeout -> offset = Math.floor($currentItem.offset().top - $parent.offset().top) - 1 row = Math.floor(offset / 150) $parent.scrollTop($parent.scrollTop() + row * 150 - 75) , 100
[ { "context": "\n\t\t@user =\n\t\t\t_id: ObjectId()\n\t\t\temail: @email = \"USER@example.com\"\n\t\t\tfirst_name: \"bob\"\n\t\t\tlast_name: \"brown\"\n\t\t\tre", "end": 1488, "score": 0.999919593334198, "start": 1472, "tag": "EMAIL", "value": "USER@example.com" }, { "context": "mail: @email = \"USER@example.com\"\n\t\t\tfirst_name: \"bob\"\n\t\t\tlast_name: \"brown\"\n\t\t\treferal_id: 1234\n\t\t\tisA", "end": 1509, "score": 0.9997984766960144, "start": 1506, "tag": "NAME", "value": "bob" }, { "context": "@example.com\"\n\t\t\tfirst_name: \"bob\"\n\t\t\tlast_name: \"brown\"\n\t\t\treferal_id: 1234\n\t\t\tisAdmin: false\n\t\t@passwor", "end": 1531, "score": 0.9997413754463196, "start": 1526, "tag": "NAME", "value": "brown" }, { "context": "referal_id: 1234\n\t\t\tisAdmin: false\n\t\t@password = \"banana\"\n\t\t@req = new MockRequest()\n\t\t@res = new MockResp", "end": 1592, "score": 0.9990037679672241, "start": 1586, "tag": "PASSWORD", "value": "banana" }, { "context": "ch ->\n\t\t\t@user = {\n\t\t\t\t_id: 'id'\n\t\t\t\tfirst_name: 'a'\n\t\t\t\tlast_name: 'b'\n\t\t\t\temail: 'c'\n\t\t\t}\n\t\t\t", "end": 2592, "score": 0.998247504234314, "start": 2591, "tag": "NAME", "value": "a" }, { "context": "\t\t\t_id: 'id'\n\t\t\t\tfirst_name: 'a'\n\t\t\t\tlast_name: 'b'\n\t\t\t\temail: 'c'\n\t\t\t}\n\t\t\t@req.session.passpor", "end": 2612, "score": 0.9801362752914429, "start": 2611, "tag": "NAME", "value": "b" }, { "context": "\t\t\t\tfirst_name: 'new_first_name'\n\t\t\t\tlast_name: 'b'\n\t\t\t\temail: 'new_email'\n\t\t\t}\n\t\t\texpect(@req.", "end": 2948, "score": 0.9965682029724121, "start": 2947, "tag": "NAME", "value": "b" }, { "context": "\t\t@req.session = @session = {\n\t\t\t\tpassport: {user: @user},\n\t\t\t\tpostLoginRedirect: \"/path/to/redir/to\"\n", "end": 3300, "score": 0.5438186526298523, "start": 3300, "tag": "USERNAME", "value": "" }, { "context": "ll)\n\t\t\t@req.session = @session = {passport: {user: @user}}\n\t\t\t@req.session =\n\t\t\t\tpassport: {user: {_id: \"o", "end": 5935, "score": 0.9909188151359558, "start": 5930, "tag": "USERNAME", "value": "@user" }, { "context": "(2)\n\t\t\t@req.body =\n\t\t\t\temail: @email\n\t\t\t\tpassword: @password\n\t\t\t\tsession:\n\t\t\t\t\tpostLoginRedirect: \"/path/to/re", "end": 8025, "score": 0.9978693127632141, "start": 8016, "tag": "PASSWORD", "value": "@password" }, { "context": "->\n\t\t\t\t@AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true\n\n\t\t\tit \"sh", "end": 9182, "score": 0.7998468279838562, "start": 9178, "tag": "USERNAME", "value": "user" }, { "context": "nd\", ->\n\t\t\t\t@UserHandler.setupLoginData.calledWith(@user).should.equal true\n\n\t\t\tit \"should establish the u", "end": 9328, "score": 0.9621933102607727, "start": 9323, "tag": "USERNAME", "value": "@user" }, { "context": "the user's session\", ->\n\t\t\t\t@cb.calledWith(null, @user).should.equal true\n\n\t\t\tit \"should set res.session", "end": 9427, "score": 0.5582261085510254, "start": 9423, "tag": "USERNAME", "value": "user" }, { "context": "Controller._recordSuccessfulLogin\n\t\t\t\t\t.calledWith(@user._id)\n\t\t\t\t\t.should.equal true\n\n\t\t\tit \"should tell ", "end": 9667, "score": 0.9715712070465088, "start": 9662, "tag": "USERNAME", "value": "@user" }, { "context": "\t.calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), \"successful log in\")\n\t\t\t\t\t.should", "end": 9995, "score": 0.9040976762771606, "start": 9990, "tag": "USERNAME", "value": "@user" }, { "context": "\t\t\t\t@AnalyticsManager.recordEvent\n\t\t\t\t\t.calledWith(@user._id, \"user-logged-in\")\n\t\t\t\t\t.should.equal true\n\n\t", "end": 10155, "score": 0.8990789651870728, "start": 10150, "tag": "USERNAME", "value": "@user" }, { "context": "\t\t@user_id = \"2134\"\n\t\t\t@req.session.user =\n\t\t\t\t_id:@user_id\n\t\t\tresult = @AuthenticationController.getLoggedIn", "end": 11437, "score": 0.9099652767181396, "start": 11429, "tag": "USERNAME", "value": "@user_id" }, { "context": "session = {\n\t\t\t\tpassport: {\n\t\t\t\t\tuser: {\n\t\t\t\t\t\t_id:@user_id\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t \t}\n\t\t\tresult = @AuthenticationCon", "end": 11678, "score": 0.7495087385177612, "start": 11670, "tag": "USERNAME", "value": "@user_id" }, { "context": "reLogin\", ->\n\t\tbeforeEach ->\n\t\t\t@user =\n\t\t\t\t_id: \"user-id-123\"\n\t\t\t\temail: \"user@sharelatex.com\"\n\t\t\t@middleware ", "end": 12354, "score": 0.8717488646507263, "start": 12343, "tag": "USERNAME", "value": "user-id-123" }, { "context": " ->\n\t\t\t@user =\n\t\t\t\t_id: \"user-id-123\"\n\t\t\t\temail: \"user@sharelatex.com\"\n\t\t\t@middleware = @AuthenticationController.requi", "end": 12387, "score": 0.9999246001243591, "start": 12368, "tag": "EMAIL", "value": "user@sharelatex.com" }, { "context": "\t\t@req.session =\n\t\t\t\t\tuser: @user = {\n\t\t\t\t\t\t_id: \"user-id-123\"\n\t\t\t\t\t\temail: \"user@sharelatex.com\"\n\t\t\t\t\t}", "end": 12565, "score": 0.6303861737251282, "start": 12561, "tag": "USERNAME", "value": "user" }, { "context": "ession =\n\t\t\t\t\tuser: @user = {\n\t\t\t\t\t\t_id: \"user-id-123\"\n\t\t\t\t\t\temail: \"user@sharelatex.com\"\n\t\t\t\t\t}\n\t\t\t\t@m", "end": 12572, "score": 0.8095169067382812, "start": 12569, "tag": "USERNAME", "value": "123" }, { "context": " @user = {\n\t\t\t\t\t\t_id: \"user-id-123\"\n\t\t\t\t\t\temail: \"user@sharelatex.com\"\n\t\t\t\t\t}\n\t\t\t\t@middleware(@req, @res, @next)\n\n\t\t\tit", "end": 12607, "score": 0.999924898147583, "start": 12588, "tag": "EMAIL", "value": "user@sharelatex.com" } ]
test/UnitTests/coffee/Authentication/AuthenticationControllerTests.coffee
HasanSanli/web-sharelatex
0
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationController.js" SandboxedModule = require('sandboxed-module') events = require "events" tk = require("timekeeper") MockRequest = require("../helpers/MockRequest") MockResponse = require("../helpers/MockResponse") ObjectId = require("mongojs").ObjectId describe "AuthenticationController", -> beforeEach -> @AuthenticationController = SandboxedModule.require modulePath, requires: "./AuthenticationManager": @AuthenticationManager = {} "../User/UserGetter" : @UserGetter = {} "../User/UserUpdater" : @UserUpdater = {} "metrics-sharelatex": @Metrics = { inc: sinon.stub() } "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() } "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() } "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() } "settings-sharelatex": {} "passport": @passport = authenticate: sinon.stub().returns(sinon.stub()) "../User/UserSessionsManager": @UserSessionsManager = trackSession: sinon.stub() untrackSession: sinon.stub() revokeAllUserSessions: sinon.stub().callsArgWith(1, null) @user = _id: ObjectId() email: @email = "USER@example.com" first_name: "bob" last_name: "brown" referal_id: 1234 isAdmin: false @password = "banana" @req = new MockRequest() @res = new MockResponse() @callback = @next = sinon.stub() tk.freeze(Date.now()) afterEach -> tk.reset() describe 'isUserLoggedIn', () -> beforeEach -> @stub = sinon.stub(@AuthenticationController, 'getLoggedInUserId') afterEach -> @stub.restore() it 'should do the right thing in all cases', () -> @AuthenticationController.getLoggedInUserId.returns('some_id') expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal true @AuthenticationController.getLoggedInUserId.returns(null) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(false) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(undefined) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false describe 'setInSessionUser', () -> beforeEach -> @user = { _id: 'id' first_name: 'a' last_name: 'b' email: 'c' } @req.session.passport = {user: @user} @req.session.user = @user it 'should update the right properties', () -> @AuthenticationController.setInSessionUser(@req, {first_name: 'new_first_name', email: 'new_email'}) expectedUser = { _id: 'id' first_name: 'new_first_name' last_name: 'b' email: 'new_email' } expect(@req.session.passport.user).to.deep.equal(expectedUser) expect(@req.session.user).to.deep.equal(expectedUser) describe 'passportLogin', -> beforeEach -> @info = null @req.login = sinon.stub().callsArgWith(1, null) @res.json = sinon.stub() @req.session = @session = { passport: {user: @user}, postLoginRedirect: "/path/to/redir/to" } @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @passport.authenticate.callsArgWith(1, null, @user, @info) it 'should call passport.authenticate', () -> @AuthenticationController.passportLogin @req, @res, @next @passport.authenticate.callCount.should.equal 1 describe 'when authenticate produces an error', -> beforeEach -> @err = new Error('woops') @passport.authenticate.callsArgWith(1, @err) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true describe 'when authenticate produces a user', -> beforeEach -> @req.session.postLoginRedirect = 'some_redirect' @passport.authenticate.callsArgWith(1, null, @user, @info) afterEach -> delete @req.session.postLoginRedirect it 'should call req.login', () -> @AuthenticationController.passportLogin @req, @res, @next @req.login.callCount.should.equal 1 @req.login.calledWith(@user).should.equal true it 'should send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({redir: 'some_redirect'}).should.equal true describe 'when session.save produces an error', () -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true it 'should not return json', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 0 describe 'when authenticate does not produce a user', -> beforeEach -> @info = {text: 'a', type: 'b'} @passport.authenticate.callsArgWith(1, null, false, @info) it 'should not call req.login', () -> @AuthenticationController.passportLogin @req, @res, @next @req.login.callCount.should.equal 0 it 'should not send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({message: @info}).should.equal true expect(@res.json.lastCall.args[0].redir?).to.equal false describe 'afterLoginSessionSetup', -> beforeEach -> @req.login = sinon.stub().callsArgWith(1, null) @req.session = @session = {passport: {user: @user}} @req.session = passport: {user: {_id: "one"}} @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @UserSessionsManager.trackSession = sinon.stub() @call = (callback) => @AuthenticationController.afterLoginSessionSetup @req, @user, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.equal null done() it 'should call req.login', (done) -> @call (err) => @req.login.callCount.should.equal 1 done() it 'should call req.session.save', (done) -> @call (err) => @req.session.save.callCount.should.equal 1 done() it 'should call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 1 done() describe 'when req.session.save produces an error', -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.not.be.oneOf [null, undefined] expect(err).to.be.instanceof Error done() it 'should not call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 0 done() describe 'getSessionUser', -> it 'should get the user object from session', -> @req.session = passport: user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} it 'should work with legacy sessions', -> @req.session = user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} describe "doPassportLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2) @req.body = email: @email password: @password session: postLoginRedirect: "/path/to/redir/to" @cb = sinon.stub() describe "when the users rate limit", -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false) it "should block the request if the limit has been exceeded", (done)-> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, null).should.equal true done() describe 'when the user is authenticated', -> beforeEach -> @cb = sinon.stub() @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user) @req.sessionID = Math.random() @AnalyticsManager.identifyUser = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should attempt to authorise the user", -> @AuthenticationManager.authenticate .calledWith(email: @email.toLowerCase(), @password) .should.equal true it "should call identifyUser", -> @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true it "should setup the user data in the background", -> @UserHandler.setupLoginData.calledWith(@user).should.equal true it "should establish the user's session", -> @cb.calledWith(null, @user).should.equal true it "should set res.session.justLoggedIn", -> @req.session.justLoggedIn.should.equal true it "should record the successful login", -> @AuthenticationController._recordSuccessfulLogin .calledWith(@user._id) .should.equal true it "should tell the rate limiter that there was a success for that email", -> @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true it "should log the successful login", -> @logger.log .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in") .should.equal true it "should track the login event", -> @AnalyticsManager.recordEvent .calledWith(@user._id, "user-logged-in") .should.equal true describe 'when the user is not authenticated', -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null) @cb = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should not establish the login", -> @cb.callCount.should.equal 1 @cb.calledWith(null, false) # @res.body.should.exist expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type'] # message: # text: 'Your email or password were incorrect. Please try again', # type: 'error' it "should not setup the user data in the background", -> @UserHandler.setupLoginData.called.should.equal false it "should record a failed login", -> @AuthenticationController._recordFailedLogin.called.should.equal true it "should log the failed login", -> @logger.log .calledWith(email: @email.toLowerCase(), "failed log in") .should.equal true describe "getLoggedInUserId", -> beforeEach -> @req = session :{} it "should return the user id from the session", ()-> @user_id = "2134" @req.session.user = _id:@user_id result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it 'should return user for passport session', () -> @user_id = "2134" @req.session = { passport: { user: { _id:@user_id } } } result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it "should return null if there is no user on the session", ()-> result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no session", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no req", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null describe "requireLogin", -> beforeEach -> @user = _id: "user-id-123" email: "user@sharelatex.com" @middleware = @AuthenticationController.requireLogin() describe "when the user is logged in", -> beforeEach -> @req.session = user: @user = { _id: "user-id-123" email: "user@sharelatex.com" } @middleware(@req, @res, @next) it "should call the next method in the chain", -> @next.called.should.equal true describe "when the user is not logged in", -> beforeEach -> @req.session = {} @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() @req.query = {} @middleware(@req, @res, @next) it "should redirect to the register or login page", -> @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true describe "requireGlobalLogin", -> beforeEach -> @req.headers = {} @AuthenticationController.httpAuth = sinon.stub() @_setRedirect = sinon.spy(@AuthenticationController, '_setRedirectInSession') afterEach -> @_setRedirect.restore() describe "with white listed url", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with white listed url and a query string", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @req.url = "/login?query=something" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with http auth", -> beforeEach -> @req.headers["authorization"] = "Mock Basic Auth" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should pass the request onto httpAuth", -> @AuthenticationController.httpAuth .calledWith(@req, @res, @next) .should.equal true describe "with a user session", -> beforeEach -> @req.session = user: {"mock": "user", "_id": "some_id"} @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with no login credentials", -> beforeEach -> @req.session = {} @AuthenticationController.requireGlobalLogin @req, @res, @next it 'should have called setRedirectInSession', -> @_setRedirect.callCount.should.equal 1 it "should redirect to the /login page", -> @res.redirectedTo.should.equal "/login" describe "_redirectToLoginOrRegisterPage", -> beforeEach -> @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false }) @req.session = {} @AuthenticationController._redirectToRegisterPage = sinon.stub() @AuthenticationController._redirectToLoginPage = sinon.stub() @req.query = {} describe "they have come directly to the url", -> beforeEach -> @req.query = {} @middleware(@req, @res, @next) it "should redirect to the login page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true describe "they have come via a templates link", -> beforeEach -> @req.query.zipUrl = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "they have been invited to a project", -> beforeEach -> @req.query.project_name = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "_redirectToRegisterPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToRegisterPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/register?extra_query=foo" it "should log out a message", -> @logger.log .calledWith(url: @url, "user not logged in so redirecting to register page") .should.equal true describe "_redirectToLoginPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToLoginPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/login?extra_query=foo" describe "_recordSuccessfulLogin", -> beforeEach -> @UserUpdater.updateUser = sinon.stub().callsArg(2) @AuthenticationController._recordSuccessfulLogin(@user._id, @callback) it "should increment the user.login.success metric", -> @Metrics.inc .calledWith("user.login.success") .should.equal true it "should update the user's login count and last logged in date", -> @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1 it "should call the callback", -> @callback.called.should.equal true describe "_recordFailedLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin(@callback) it "should increment the user.login.failed metric", -> @Metrics.inc .calledWith("user.login.failed") .should.equal true it "should call the callback", -> @callback.called.should.equal true describe '_setRedirectInSession', -> beforeEach -> @req = {session: {}} @req.path = "/somewhere" @req.query = {one: "1"} it 'should set redirect property on session', -> @AuthenticationController._setRedirectInSession(@req) expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1" it 'should set the supplied value', -> @AuthenticationController._setRedirectInSession(@req, '/somewhere/specific') expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific" describe 'with a png', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController._setRedirectInSession(@req, '/something.png') expect(@req.session.postLoginRedirect).to.equal undefined describe 'with a js path', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController._setRedirectInSession(@req, '/js/something.js') expect(@req.session.postLoginRedirect).to.equal undefined describe '_getRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should get redirect property from session', -> expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c" describe '_clearRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should remove the redirect property from session', -> @AuthenticationController._clearRedirectFromSession(@req) expect(@req.session.postLoginRedirect).to.equal undefined
52076
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationController.js" SandboxedModule = require('sandboxed-module') events = require "events" tk = require("timekeeper") MockRequest = require("../helpers/MockRequest") MockResponse = require("../helpers/MockResponse") ObjectId = require("mongojs").ObjectId describe "AuthenticationController", -> beforeEach -> @AuthenticationController = SandboxedModule.require modulePath, requires: "./AuthenticationManager": @AuthenticationManager = {} "../User/UserGetter" : @UserGetter = {} "../User/UserUpdater" : @UserUpdater = {} "metrics-sharelatex": @Metrics = { inc: sinon.stub() } "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() } "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() } "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() } "settings-sharelatex": {} "passport": @passport = authenticate: sinon.stub().returns(sinon.stub()) "../User/UserSessionsManager": @UserSessionsManager = trackSession: sinon.stub() untrackSession: sinon.stub() revokeAllUserSessions: sinon.stub().callsArgWith(1, null) @user = _id: ObjectId() email: @email = "<EMAIL>" first_name: "<NAME>" last_name: "<NAME>" referal_id: 1234 isAdmin: false @password = "<PASSWORD>" @req = new MockRequest() @res = new MockResponse() @callback = @next = sinon.stub() tk.freeze(Date.now()) afterEach -> tk.reset() describe 'isUserLoggedIn', () -> beforeEach -> @stub = sinon.stub(@AuthenticationController, 'getLoggedInUserId') afterEach -> @stub.restore() it 'should do the right thing in all cases', () -> @AuthenticationController.getLoggedInUserId.returns('some_id') expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal true @AuthenticationController.getLoggedInUserId.returns(null) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(false) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(undefined) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false describe 'setInSessionUser', () -> beforeEach -> @user = { _id: 'id' first_name: '<NAME>' last_name: '<NAME>' email: 'c' } @req.session.passport = {user: @user} @req.session.user = @user it 'should update the right properties', () -> @AuthenticationController.setInSessionUser(@req, {first_name: 'new_first_name', email: 'new_email'}) expectedUser = { _id: 'id' first_name: 'new_first_name' last_name: '<NAME>' email: 'new_email' } expect(@req.session.passport.user).to.deep.equal(expectedUser) expect(@req.session.user).to.deep.equal(expectedUser) describe 'passportLogin', -> beforeEach -> @info = null @req.login = sinon.stub().callsArgWith(1, null) @res.json = sinon.stub() @req.session = @session = { passport: {user: @user}, postLoginRedirect: "/path/to/redir/to" } @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @passport.authenticate.callsArgWith(1, null, @user, @info) it 'should call passport.authenticate', () -> @AuthenticationController.passportLogin @req, @res, @next @passport.authenticate.callCount.should.equal 1 describe 'when authenticate produces an error', -> beforeEach -> @err = new Error('woops') @passport.authenticate.callsArgWith(1, @err) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true describe 'when authenticate produces a user', -> beforeEach -> @req.session.postLoginRedirect = 'some_redirect' @passport.authenticate.callsArgWith(1, null, @user, @info) afterEach -> delete @req.session.postLoginRedirect it 'should call req.login', () -> @AuthenticationController.passportLogin @req, @res, @next @req.login.callCount.should.equal 1 @req.login.calledWith(@user).should.equal true it 'should send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({redir: 'some_redirect'}).should.equal true describe 'when session.save produces an error', () -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true it 'should not return json', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 0 describe 'when authenticate does not produce a user', -> beforeEach -> @info = {text: 'a', type: 'b'} @passport.authenticate.callsArgWith(1, null, false, @info) it 'should not call req.login', () -> @AuthenticationController.passportLogin @req, @res, @next @req.login.callCount.should.equal 0 it 'should not send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({message: @info}).should.equal true expect(@res.json.lastCall.args[0].redir?).to.equal false describe 'afterLoginSessionSetup', -> beforeEach -> @req.login = sinon.stub().callsArgWith(1, null) @req.session = @session = {passport: {user: @user}} @req.session = passport: {user: {_id: "one"}} @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @UserSessionsManager.trackSession = sinon.stub() @call = (callback) => @AuthenticationController.afterLoginSessionSetup @req, @user, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.equal null done() it 'should call req.login', (done) -> @call (err) => @req.login.callCount.should.equal 1 done() it 'should call req.session.save', (done) -> @call (err) => @req.session.save.callCount.should.equal 1 done() it 'should call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 1 done() describe 'when req.session.save produces an error', -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.not.be.oneOf [null, undefined] expect(err).to.be.instanceof Error done() it 'should not call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 0 done() describe 'getSessionUser', -> it 'should get the user object from session', -> @req.session = passport: user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} it 'should work with legacy sessions', -> @req.session = user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} describe "doPassportLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2) @req.body = email: @email password: <PASSWORD> session: postLoginRedirect: "/path/to/redir/to" @cb = sinon.stub() describe "when the users rate limit", -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false) it "should block the request if the limit has been exceeded", (done)-> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, null).should.equal true done() describe 'when the user is authenticated', -> beforeEach -> @cb = sinon.stub() @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user) @req.sessionID = Math.random() @AnalyticsManager.identifyUser = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should attempt to authorise the user", -> @AuthenticationManager.authenticate .calledWith(email: @email.toLowerCase(), @password) .should.equal true it "should call identifyUser", -> @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true it "should setup the user data in the background", -> @UserHandler.setupLoginData.calledWith(@user).should.equal true it "should establish the user's session", -> @cb.calledWith(null, @user).should.equal true it "should set res.session.justLoggedIn", -> @req.session.justLoggedIn.should.equal true it "should record the successful login", -> @AuthenticationController._recordSuccessfulLogin .calledWith(@user._id) .should.equal true it "should tell the rate limiter that there was a success for that email", -> @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true it "should log the successful login", -> @logger.log .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in") .should.equal true it "should track the login event", -> @AnalyticsManager.recordEvent .calledWith(@user._id, "user-logged-in") .should.equal true describe 'when the user is not authenticated', -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null) @cb = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should not establish the login", -> @cb.callCount.should.equal 1 @cb.calledWith(null, false) # @res.body.should.exist expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type'] # message: # text: 'Your email or password were incorrect. Please try again', # type: 'error' it "should not setup the user data in the background", -> @UserHandler.setupLoginData.called.should.equal false it "should record a failed login", -> @AuthenticationController._recordFailedLogin.called.should.equal true it "should log the failed login", -> @logger.log .calledWith(email: @email.toLowerCase(), "failed log in") .should.equal true describe "getLoggedInUserId", -> beforeEach -> @req = session :{} it "should return the user id from the session", ()-> @user_id = "2134" @req.session.user = _id:@user_id result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it 'should return user for passport session', () -> @user_id = "2134" @req.session = { passport: { user: { _id:@user_id } } } result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it "should return null if there is no user on the session", ()-> result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no session", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no req", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null describe "requireLogin", -> beforeEach -> @user = _id: "user-id-123" email: "<EMAIL>" @middleware = @AuthenticationController.requireLogin() describe "when the user is logged in", -> beforeEach -> @req.session = user: @user = { _id: "user-id-123" email: "<EMAIL>" } @middleware(@req, @res, @next) it "should call the next method in the chain", -> @next.called.should.equal true describe "when the user is not logged in", -> beforeEach -> @req.session = {} @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() @req.query = {} @middleware(@req, @res, @next) it "should redirect to the register or login page", -> @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true describe "requireGlobalLogin", -> beforeEach -> @req.headers = {} @AuthenticationController.httpAuth = sinon.stub() @_setRedirect = sinon.spy(@AuthenticationController, '_setRedirectInSession') afterEach -> @_setRedirect.restore() describe "with white listed url", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with white listed url and a query string", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @req.url = "/login?query=something" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with http auth", -> beforeEach -> @req.headers["authorization"] = "Mock Basic Auth" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should pass the request onto httpAuth", -> @AuthenticationController.httpAuth .calledWith(@req, @res, @next) .should.equal true describe "with a user session", -> beforeEach -> @req.session = user: {"mock": "user", "_id": "some_id"} @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with no login credentials", -> beforeEach -> @req.session = {} @AuthenticationController.requireGlobalLogin @req, @res, @next it 'should have called setRedirectInSession', -> @_setRedirect.callCount.should.equal 1 it "should redirect to the /login page", -> @res.redirectedTo.should.equal "/login" describe "_redirectToLoginOrRegisterPage", -> beforeEach -> @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false }) @req.session = {} @AuthenticationController._redirectToRegisterPage = sinon.stub() @AuthenticationController._redirectToLoginPage = sinon.stub() @req.query = {} describe "they have come directly to the url", -> beforeEach -> @req.query = {} @middleware(@req, @res, @next) it "should redirect to the login page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true describe "they have come via a templates link", -> beforeEach -> @req.query.zipUrl = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "they have been invited to a project", -> beforeEach -> @req.query.project_name = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "_redirectToRegisterPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToRegisterPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/register?extra_query=foo" it "should log out a message", -> @logger.log .calledWith(url: @url, "user not logged in so redirecting to register page") .should.equal true describe "_redirectToLoginPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToLoginPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/login?extra_query=foo" describe "_recordSuccessfulLogin", -> beforeEach -> @UserUpdater.updateUser = sinon.stub().callsArg(2) @AuthenticationController._recordSuccessfulLogin(@user._id, @callback) it "should increment the user.login.success metric", -> @Metrics.inc .calledWith("user.login.success") .should.equal true it "should update the user's login count and last logged in date", -> @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1 it "should call the callback", -> @callback.called.should.equal true describe "_recordFailedLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin(@callback) it "should increment the user.login.failed metric", -> @Metrics.inc .calledWith("user.login.failed") .should.equal true it "should call the callback", -> @callback.called.should.equal true describe '_setRedirectInSession', -> beforeEach -> @req = {session: {}} @req.path = "/somewhere" @req.query = {one: "1"} it 'should set redirect property on session', -> @AuthenticationController._setRedirectInSession(@req) expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1" it 'should set the supplied value', -> @AuthenticationController._setRedirectInSession(@req, '/somewhere/specific') expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific" describe 'with a png', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController._setRedirectInSession(@req, '/something.png') expect(@req.session.postLoginRedirect).to.equal undefined describe 'with a js path', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController._setRedirectInSession(@req, '/js/something.js') expect(@req.session.postLoginRedirect).to.equal undefined describe '_getRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should get redirect property from session', -> expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c" describe '_clearRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should remove the redirect property from session', -> @AuthenticationController._clearRedirectFromSession(@req) expect(@req.session.postLoginRedirect).to.equal undefined
true
sinon = require('sinon') chai = require('chai') should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationController.js" SandboxedModule = require('sandboxed-module') events = require "events" tk = require("timekeeper") MockRequest = require("../helpers/MockRequest") MockResponse = require("../helpers/MockResponse") ObjectId = require("mongojs").ObjectId describe "AuthenticationController", -> beforeEach -> @AuthenticationController = SandboxedModule.require modulePath, requires: "./AuthenticationManager": @AuthenticationManager = {} "../User/UserGetter" : @UserGetter = {} "../User/UserUpdater" : @UserUpdater = {} "metrics-sharelatex": @Metrics = { inc: sinon.stub() } "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() } "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() } "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() } "settings-sharelatex": {} "passport": @passport = authenticate: sinon.stub().returns(sinon.stub()) "../User/UserSessionsManager": @UserSessionsManager = trackSession: sinon.stub() untrackSession: sinon.stub() revokeAllUserSessions: sinon.stub().callsArgWith(1, null) @user = _id: ObjectId() email: @email = "PI:EMAIL:<EMAIL>END_PI" first_name: "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" referal_id: 1234 isAdmin: false @password = "PI:PASSWORD:<PASSWORD>END_PI" @req = new MockRequest() @res = new MockResponse() @callback = @next = sinon.stub() tk.freeze(Date.now()) afterEach -> tk.reset() describe 'isUserLoggedIn', () -> beforeEach -> @stub = sinon.stub(@AuthenticationController, 'getLoggedInUserId') afterEach -> @stub.restore() it 'should do the right thing in all cases', () -> @AuthenticationController.getLoggedInUserId.returns('some_id') expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal true @AuthenticationController.getLoggedInUserId.returns(null) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(false) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(undefined) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false describe 'setInSessionUser', () -> beforeEach -> @user = { _id: 'id' first_name: 'PI:NAME:<NAME>END_PI' last_name: 'PI:NAME:<NAME>END_PI' email: 'c' } @req.session.passport = {user: @user} @req.session.user = @user it 'should update the right properties', () -> @AuthenticationController.setInSessionUser(@req, {first_name: 'new_first_name', email: 'new_email'}) expectedUser = { _id: 'id' first_name: 'new_first_name' last_name: 'PI:NAME:<NAME>END_PI' email: 'new_email' } expect(@req.session.passport.user).to.deep.equal(expectedUser) expect(@req.session.user).to.deep.equal(expectedUser) describe 'passportLogin', -> beforeEach -> @info = null @req.login = sinon.stub().callsArgWith(1, null) @res.json = sinon.stub() @req.session = @session = { passport: {user: @user}, postLoginRedirect: "/path/to/redir/to" } @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @passport.authenticate.callsArgWith(1, null, @user, @info) it 'should call passport.authenticate', () -> @AuthenticationController.passportLogin @req, @res, @next @passport.authenticate.callCount.should.equal 1 describe 'when authenticate produces an error', -> beforeEach -> @err = new Error('woops') @passport.authenticate.callsArgWith(1, @err) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true describe 'when authenticate produces a user', -> beforeEach -> @req.session.postLoginRedirect = 'some_redirect' @passport.authenticate.callsArgWith(1, null, @user, @info) afterEach -> delete @req.session.postLoginRedirect it 'should call req.login', () -> @AuthenticationController.passportLogin @req, @res, @next @req.login.callCount.should.equal 1 @req.login.calledWith(@user).should.equal true it 'should send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({redir: 'some_redirect'}).should.equal true describe 'when session.save produces an error', () -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true it 'should not return json', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 0 describe 'when authenticate does not produce a user', -> beforeEach -> @info = {text: 'a', type: 'b'} @passport.authenticate.callsArgWith(1, null, false, @info) it 'should not call req.login', () -> @AuthenticationController.passportLogin @req, @res, @next @req.login.callCount.should.equal 0 it 'should not send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({message: @info}).should.equal true expect(@res.json.lastCall.args[0].redir?).to.equal false describe 'afterLoginSessionSetup', -> beforeEach -> @req.login = sinon.stub().callsArgWith(1, null) @req.session = @session = {passport: {user: @user}} @req.session = passport: {user: {_id: "one"}} @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @UserSessionsManager.trackSession = sinon.stub() @call = (callback) => @AuthenticationController.afterLoginSessionSetup @req, @user, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.equal null done() it 'should call req.login', (done) -> @call (err) => @req.login.callCount.should.equal 1 done() it 'should call req.session.save', (done) -> @call (err) => @req.session.save.callCount.should.equal 1 done() it 'should call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 1 done() describe 'when req.session.save produces an error', -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.not.be.oneOf [null, undefined] expect(err).to.be.instanceof Error done() it 'should not call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 0 done() describe 'getSessionUser', -> it 'should get the user object from session', -> @req.session = passport: user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} it 'should work with legacy sessions', -> @req.session = user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} describe "doPassportLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2) @req.body = email: @email password: PI:PASSWORD:<PASSWORD>END_PI session: postLoginRedirect: "/path/to/redir/to" @cb = sinon.stub() describe "when the users rate limit", -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false) it "should block the request if the limit has been exceeded", (done)-> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, null).should.equal true done() describe 'when the user is authenticated', -> beforeEach -> @cb = sinon.stub() @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user) @req.sessionID = Math.random() @AnalyticsManager.identifyUser = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should attempt to authorise the user", -> @AuthenticationManager.authenticate .calledWith(email: @email.toLowerCase(), @password) .should.equal true it "should call identifyUser", -> @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true it "should setup the user data in the background", -> @UserHandler.setupLoginData.calledWith(@user).should.equal true it "should establish the user's session", -> @cb.calledWith(null, @user).should.equal true it "should set res.session.justLoggedIn", -> @req.session.justLoggedIn.should.equal true it "should record the successful login", -> @AuthenticationController._recordSuccessfulLogin .calledWith(@user._id) .should.equal true it "should tell the rate limiter that there was a success for that email", -> @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true it "should log the successful login", -> @logger.log .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in") .should.equal true it "should track the login event", -> @AnalyticsManager.recordEvent .calledWith(@user._id, "user-logged-in") .should.equal true describe 'when the user is not authenticated', -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null) @cb = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should not establish the login", -> @cb.callCount.should.equal 1 @cb.calledWith(null, false) # @res.body.should.exist expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type'] # message: # text: 'Your email or password were incorrect. Please try again', # type: 'error' it "should not setup the user data in the background", -> @UserHandler.setupLoginData.called.should.equal false it "should record a failed login", -> @AuthenticationController._recordFailedLogin.called.should.equal true it "should log the failed login", -> @logger.log .calledWith(email: @email.toLowerCase(), "failed log in") .should.equal true describe "getLoggedInUserId", -> beforeEach -> @req = session :{} it "should return the user id from the session", ()-> @user_id = "2134" @req.session.user = _id:@user_id result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it 'should return user for passport session', () -> @user_id = "2134" @req.session = { passport: { user: { _id:@user_id } } } result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it "should return null if there is no user on the session", ()-> result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no session", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no req", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null describe "requireLogin", -> beforeEach -> @user = _id: "user-id-123" email: "PI:EMAIL:<EMAIL>END_PI" @middleware = @AuthenticationController.requireLogin() describe "when the user is logged in", -> beforeEach -> @req.session = user: @user = { _id: "user-id-123" email: "PI:EMAIL:<EMAIL>END_PI" } @middleware(@req, @res, @next) it "should call the next method in the chain", -> @next.called.should.equal true describe "when the user is not logged in", -> beforeEach -> @req.session = {} @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() @req.query = {} @middleware(@req, @res, @next) it "should redirect to the register or login page", -> @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true describe "requireGlobalLogin", -> beforeEach -> @req.headers = {} @AuthenticationController.httpAuth = sinon.stub() @_setRedirect = sinon.spy(@AuthenticationController, '_setRedirectInSession') afterEach -> @_setRedirect.restore() describe "with white listed url", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with white listed url and a query string", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @req.url = "/login?query=something" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with http auth", -> beforeEach -> @req.headers["authorization"] = "Mock Basic Auth" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should pass the request onto httpAuth", -> @AuthenticationController.httpAuth .calledWith(@req, @res, @next) .should.equal true describe "with a user session", -> beforeEach -> @req.session = user: {"mock": "user", "_id": "some_id"} @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with no login credentials", -> beforeEach -> @req.session = {} @AuthenticationController.requireGlobalLogin @req, @res, @next it 'should have called setRedirectInSession', -> @_setRedirect.callCount.should.equal 1 it "should redirect to the /login page", -> @res.redirectedTo.should.equal "/login" describe "_redirectToLoginOrRegisterPage", -> beforeEach -> @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false }) @req.session = {} @AuthenticationController._redirectToRegisterPage = sinon.stub() @AuthenticationController._redirectToLoginPage = sinon.stub() @req.query = {} describe "they have come directly to the url", -> beforeEach -> @req.query = {} @middleware(@req, @res, @next) it "should redirect to the login page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true describe "they have come via a templates link", -> beforeEach -> @req.query.zipUrl = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "they have been invited to a project", -> beforeEach -> @req.query.project_name = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "_redirectToRegisterPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToRegisterPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/register?extra_query=foo" it "should log out a message", -> @logger.log .calledWith(url: @url, "user not logged in so redirecting to register page") .should.equal true describe "_redirectToLoginPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToLoginPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/login?extra_query=foo" describe "_recordSuccessfulLogin", -> beforeEach -> @UserUpdater.updateUser = sinon.stub().callsArg(2) @AuthenticationController._recordSuccessfulLogin(@user._id, @callback) it "should increment the user.login.success metric", -> @Metrics.inc .calledWith("user.login.success") .should.equal true it "should update the user's login count and last logged in date", -> @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1 it "should call the callback", -> @callback.called.should.equal true describe "_recordFailedLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin(@callback) it "should increment the user.login.failed metric", -> @Metrics.inc .calledWith("user.login.failed") .should.equal true it "should call the callback", -> @callback.called.should.equal true describe '_setRedirectInSession', -> beforeEach -> @req = {session: {}} @req.path = "/somewhere" @req.query = {one: "1"} it 'should set redirect property on session', -> @AuthenticationController._setRedirectInSession(@req) expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1" it 'should set the supplied value', -> @AuthenticationController._setRedirectInSession(@req, '/somewhere/specific') expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific" describe 'with a png', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController._setRedirectInSession(@req, '/something.png') expect(@req.session.postLoginRedirect).to.equal undefined describe 'with a js path', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController._setRedirectInSession(@req, '/js/something.js') expect(@req.session.postLoginRedirect).to.equal undefined describe '_getRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should get redirect property from session', -> expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c" describe '_clearRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should remove the redirect property from session', -> @AuthenticationController._clearRedirectFromSession(@req) expect(@req.session.postLoginRedirect).to.equal undefined
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9995848536491394, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-writefloat.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. # # * Tests to verify we're writing floats correctly # test = (clazz) -> buffer = new clazz(8) buffer.writeFloatBE 1, 0 buffer.writeFloatLE 1, 4 ASSERT.equal 0x3f, buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0x3f, buffer[7] buffer.writeFloatBE 1 / 3, 0 buffer.writeFloatLE 1 / 3, 4 ASSERT.equal 0x3e, buffer[0] ASSERT.equal 0xaa, buffer[1] ASSERT.equal 0xaa, buffer[2] ASSERT.equal 0xab, buffer[3] ASSERT.equal 0xab, buffer[4] ASSERT.equal 0xaa, buffer[5] ASSERT.equal 0xaa, buffer[6] ASSERT.equal 0x3e, buffer[7] buffer.writeFloatBE 3.4028234663852886e+38, 0 buffer.writeFloatLE 3.4028234663852886e+38, 4 ASSERT.equal 0x7f, buffer[0] ASSERT.equal 0x7f, buffer[1] ASSERT.equal 0xff, buffer[2] ASSERT.equal 0xff, buffer[3] ASSERT.equal 0xff, buffer[4] ASSERT.equal 0xff, buffer[5] ASSERT.equal 0x7f, buffer[6] ASSERT.equal 0x7f, buffer[7] buffer.writeFloatLE 1.1754943508222875e-38, 0 buffer.writeFloatBE 1.1754943508222875e-38, 4 ASSERT.equal 0x00, buffer[0] ASSERT.equal 0x00, buffer[1] ASSERT.equal 0x80, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x80, buffer[5] ASSERT.equal 0x00, buffer[6] ASSERT.equal 0x00, buffer[7] buffer.writeFloatBE 0 * -1, 0 buffer.writeFloatLE 0 * -1, 4 ASSERT.equal 0x80, buffer[0] ASSERT.equal 0x00, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x00, buffer[6] ASSERT.equal 0x80, buffer[7] buffer.writeFloatBE Infinity, 0 buffer.writeFloatLE Infinity, 4 ASSERT.equal 0x7f, buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0x7f, buffer[7] ASSERT.equal Infinity, buffer.readFloatBE(0) ASSERT.equal Infinity, buffer.readFloatLE(4) buffer.writeFloatBE -Infinity, 0 buffer.writeFloatLE -Infinity, 4 # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0xff is buffer[0] or 0x7f is buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0xff, buffer[7] ASSERT.equal -Infinity, buffer.readFloatBE(0) ASSERT.equal -Infinity, buffer.readFloatLE(4) buffer.writeFloatBE NaN, 0 buffer.writeFloatLE NaN, 4 # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0x7f is buffer[0] or 0xff is buffer[0] # mips processors use a slightly different NaN ASSERT 0xc0 is buffer[1] or 0xbf is buffer[1] ASSERT 0x00 is buffer[2] or 0xff is buffer[2] ASSERT 0x00 is buffer[3] or 0xff is buffer[3] ASSERT 0x00 is buffer[4] or 0xff is buffer[4] ASSERT 0x00 is buffer[5] or 0xff is buffer[5] ASSERT 0xc0 is buffer[6] or 0xbf is buffer[6] # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0x7f is buffer[7] or 0xff is buffer[7] ASSERT.ok isNaN(buffer.readFloatBE(0)) ASSERT.ok isNaN(buffer.readFloatLE(4)) return common = require("../common") ASSERT = require("assert") test Buffer
211431
# 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. # # * Tests to verify we're writing floats correctly # test = (clazz) -> buffer = new clazz(8) buffer.writeFloatBE 1, 0 buffer.writeFloatLE 1, 4 ASSERT.equal 0x3f, buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0x3f, buffer[7] buffer.writeFloatBE 1 / 3, 0 buffer.writeFloatLE 1 / 3, 4 ASSERT.equal 0x3e, buffer[0] ASSERT.equal 0xaa, buffer[1] ASSERT.equal 0xaa, buffer[2] ASSERT.equal 0xab, buffer[3] ASSERT.equal 0xab, buffer[4] ASSERT.equal 0xaa, buffer[5] ASSERT.equal 0xaa, buffer[6] ASSERT.equal 0x3e, buffer[7] buffer.writeFloatBE 3.4028234663852886e+38, 0 buffer.writeFloatLE 3.4028234663852886e+38, 4 ASSERT.equal 0x7f, buffer[0] ASSERT.equal 0x7f, buffer[1] ASSERT.equal 0xff, buffer[2] ASSERT.equal 0xff, buffer[3] ASSERT.equal 0xff, buffer[4] ASSERT.equal 0xff, buffer[5] ASSERT.equal 0x7f, buffer[6] ASSERT.equal 0x7f, buffer[7] buffer.writeFloatLE 1.1754943508222875e-38, 0 buffer.writeFloatBE 1.1754943508222875e-38, 4 ASSERT.equal 0x00, buffer[0] ASSERT.equal 0x00, buffer[1] ASSERT.equal 0x80, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x80, buffer[5] ASSERT.equal 0x00, buffer[6] ASSERT.equal 0x00, buffer[7] buffer.writeFloatBE 0 * -1, 0 buffer.writeFloatLE 0 * -1, 4 ASSERT.equal 0x80, buffer[0] ASSERT.equal 0x00, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x00, buffer[6] ASSERT.equal 0x80, buffer[7] buffer.writeFloatBE Infinity, 0 buffer.writeFloatLE Infinity, 4 ASSERT.equal 0x7f, buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0x7f, buffer[7] ASSERT.equal Infinity, buffer.readFloatBE(0) ASSERT.equal Infinity, buffer.readFloatLE(4) buffer.writeFloatBE -Infinity, 0 buffer.writeFloatLE -Infinity, 4 # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0xff is buffer[0] or 0x7f is buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0xff, buffer[7] ASSERT.equal -Infinity, buffer.readFloatBE(0) ASSERT.equal -Infinity, buffer.readFloatLE(4) buffer.writeFloatBE NaN, 0 buffer.writeFloatLE NaN, 4 # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0x7f is buffer[0] or 0xff is buffer[0] # mips processors use a slightly different NaN ASSERT 0xc0 is buffer[1] or 0xbf is buffer[1] ASSERT 0x00 is buffer[2] or 0xff is buffer[2] ASSERT 0x00 is buffer[3] or 0xff is buffer[3] ASSERT 0x00 is buffer[4] or 0xff is buffer[4] ASSERT 0x00 is buffer[5] or 0xff is buffer[5] ASSERT 0xc0 is buffer[6] or 0xbf is buffer[6] # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0x7f is buffer[7] or 0xff is buffer[7] ASSERT.ok isNaN(buffer.readFloatBE(0)) ASSERT.ok isNaN(buffer.readFloatLE(4)) return common = require("../common") ASSERT = require("assert") test Buffer
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. # # * Tests to verify we're writing floats correctly # test = (clazz) -> buffer = new clazz(8) buffer.writeFloatBE 1, 0 buffer.writeFloatLE 1, 4 ASSERT.equal 0x3f, buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0x3f, buffer[7] buffer.writeFloatBE 1 / 3, 0 buffer.writeFloatLE 1 / 3, 4 ASSERT.equal 0x3e, buffer[0] ASSERT.equal 0xaa, buffer[1] ASSERT.equal 0xaa, buffer[2] ASSERT.equal 0xab, buffer[3] ASSERT.equal 0xab, buffer[4] ASSERT.equal 0xaa, buffer[5] ASSERT.equal 0xaa, buffer[6] ASSERT.equal 0x3e, buffer[7] buffer.writeFloatBE 3.4028234663852886e+38, 0 buffer.writeFloatLE 3.4028234663852886e+38, 4 ASSERT.equal 0x7f, buffer[0] ASSERT.equal 0x7f, buffer[1] ASSERT.equal 0xff, buffer[2] ASSERT.equal 0xff, buffer[3] ASSERT.equal 0xff, buffer[4] ASSERT.equal 0xff, buffer[5] ASSERT.equal 0x7f, buffer[6] ASSERT.equal 0x7f, buffer[7] buffer.writeFloatLE 1.1754943508222875e-38, 0 buffer.writeFloatBE 1.1754943508222875e-38, 4 ASSERT.equal 0x00, buffer[0] ASSERT.equal 0x00, buffer[1] ASSERT.equal 0x80, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x80, buffer[5] ASSERT.equal 0x00, buffer[6] ASSERT.equal 0x00, buffer[7] buffer.writeFloatBE 0 * -1, 0 buffer.writeFloatLE 0 * -1, 4 ASSERT.equal 0x80, buffer[0] ASSERT.equal 0x00, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x00, buffer[6] ASSERT.equal 0x80, buffer[7] buffer.writeFloatBE Infinity, 0 buffer.writeFloatLE Infinity, 4 ASSERT.equal 0x7f, buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0x7f, buffer[7] ASSERT.equal Infinity, buffer.readFloatBE(0) ASSERT.equal Infinity, buffer.readFloatLE(4) buffer.writeFloatBE -Infinity, 0 buffer.writeFloatLE -Infinity, 4 # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0xff is buffer[0] or 0x7f is buffer[0] ASSERT.equal 0x80, buffer[1] ASSERT.equal 0x00, buffer[2] ASSERT.equal 0x00, buffer[3] ASSERT.equal 0x00, buffer[4] ASSERT.equal 0x00, buffer[5] ASSERT.equal 0x80, buffer[6] ASSERT.equal 0xff, buffer[7] ASSERT.equal -Infinity, buffer.readFloatBE(0) ASSERT.equal -Infinity, buffer.readFloatLE(4) buffer.writeFloatBE NaN, 0 buffer.writeFloatLE NaN, 4 # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0x7f is buffer[0] or 0xff is buffer[0] # mips processors use a slightly different NaN ASSERT 0xc0 is buffer[1] or 0xbf is buffer[1] ASSERT 0x00 is buffer[2] or 0xff is buffer[2] ASSERT 0x00 is buffer[3] or 0xff is buffer[3] ASSERT 0x00 is buffer[4] or 0xff is buffer[4] ASSERT 0x00 is buffer[5] or 0xff is buffer[5] ASSERT 0xc0 is buffer[6] or 0xbf is buffer[6] # Darwin ia32 does the other kind of NaN. # Compiler bug. No one really cares. ASSERT 0x7f is buffer[7] or 0xff is buffer[7] ASSERT.ok isNaN(buffer.readFloatBE(0)) ASSERT.ok isNaN(buffer.readFloatLE(4)) return common = require("../common") ASSERT = require("assert") test Buffer
[ { "context": " get: sinon.stub().yields [[{id: '123', name: 'Berlin'}]]\n )\n Bloodhound.tokenizers = { obj", "end": 3106, "score": 0.8705790042877197, "start": 3100, "tag": "NAME", "value": "Berlin" }, { "context": " fixtures().tags\n { id: '123', name: 'Berlin', public: true }\n ]\n url: 'url'\n ", "end": 3753, "score": 0.9986544847488403, "start": 3747, "tag": "NAME", "value": "Berlin" }, { "context": "d @component, 'bordered-input'\n input.value = 'Berlin'\n r.simulate.change input\n @component.props", "end": 4418, "score": 0.9990416765213013, "start": 4412, "tag": "NAME", "value": "Berlin" }, { "context": "ps.searchResults.args[0][0][0].name.should.equal 'Berlin'", "end": 4593, "score": 0.9986104965209961, "start": 4587, "tag": "NAME", "value": "Berlin" } ]
src/client/components/filter_search/test/index.test.coffee
craigspaeth/positron
76
benv = require 'benv' sinon = require 'sinon' { resolve } = require 'path' fixtures = require '../../../../test/helpers/fixtures.coffee' React = require 'react' ReactDOM = require 'react-dom' ReactTestUtils = require 'react-dom/test-utils' r = find: ReactTestUtils.findRenderedDOMComponentWithClass simulate: ReactTestUtils.Simulate describe 'FilterSearch Article', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (@Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> remote: { url: '' } get: sinon.stub().yields( [[{id: '456', thumbnail_title: 'finding nemo'}]] ) ) Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } window.jQuery = $ require 'typeahead.js' FilterSearch = benv.requireWithJadeify( resolve(__dirname, '../index') [] ) ArticleList = benv.requireWithJadeify( resolve(__dirname, '../../article_list/index') [] ) FilterSearch.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'ArticleList', React.createFactory(ArticleList.ArticleList) props = { collection: [{id: '123', thumbnail_title: 'Game of Thrones', slug: 'artsy-editorial-game-of-thrones'}] url: 'url' selected: sinon.stub() checkable: true searchResults: sinon.stub() contentType: 'article' } @component = ReactDOM.render React.createElement(FilterSearch, props), (@$el = $ "<div></div>")[0], => setTimeout => sinon.stub @component, 'setState' sinon.stub @component, 'addAutocomplete' done() afterEach -> benv.teardown() it 'renders an initial set of articles', -> $(ReactDOM.findDOMNode(@component)).html().should.containEql 'Game of Thrones' $(ReactDOM.findDOMNode(@component)).html().should.containEql '/article/artsy-editorial-game-of-thrones' it 'selects the article when clicking the check button', -> r.simulate.click r.find @component, 'article-list__checkcircle' @component.props.selected.args[0][0].id.should.containEql '123' @component.props.selected.args[0][0].thumbnail_title.should.containEql 'Game of Thrones' @component.props.selected.args[0][0].slug.should.containEql 'artsy-editorial-game-of-thrones' it 'searches articles given a query', -> input = r.find @component, 'bordered-input' input.value = 'finding nemo' r.simulate.change input @component.props.searchResults.args[0][0][0].id.should.equal '456' @component.props.searchResults.args[0][0][0].thumbnail_title.should.equal 'finding nemo' describe 'FilterSearch Tag', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (@Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> remote: { url: '' } get: sinon.stub().yields [[{id: '123', name: 'Berlin'}]] ) Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } window.jQuery = $ require 'typeahead.js' FilterSearch = benv.requireWithJadeify( resolve(__dirname, '../index') [] ) TagList = benv.requireWithJadeify( resolve(__dirname, '../../tag_list/index') [] ) TagList.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'TagList', React.createFactory(TagList) props = { collection: [ fixtures().tags { id: '123', name: 'Berlin', public: true } ] url: 'url' searchResults: sinon.stub() deleteTag: sinon.stub() contentType: 'tag' } @component = ReactDOM.render React.createElement(FilterSearch, props), (@$el = $ "<div></div>")[0], => setTimeout => sinon.stub @component, 'setState' sinon.stub @component, 'addAutocomplete' done() afterEach -> benv.teardown() it 'renders an initial set of tags', -> $(ReactDOM.findDOMNode(@component)).html().should.containEql 'Show Reviews' it 'searches tags given a query', -> input = r.find @component, 'bordered-input' input.value = 'Berlin' r.simulate.change input @component.props.searchResults.args[0][0][0].id.should.equal '123' @component.props.searchResults.args[0][0][0].name.should.equal 'Berlin'
220763
benv = require 'benv' sinon = require 'sinon' { resolve } = require 'path' fixtures = require '../../../../test/helpers/fixtures.coffee' React = require 'react' ReactDOM = require 'react-dom' ReactTestUtils = require 'react-dom/test-utils' r = find: ReactTestUtils.findRenderedDOMComponentWithClass simulate: ReactTestUtils.Simulate describe 'FilterSearch Article', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (@Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> remote: { url: '' } get: sinon.stub().yields( [[{id: '456', thumbnail_title: 'finding nemo'}]] ) ) Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } window.jQuery = $ require 'typeahead.js' FilterSearch = benv.requireWithJadeify( resolve(__dirname, '../index') [] ) ArticleList = benv.requireWithJadeify( resolve(__dirname, '../../article_list/index') [] ) FilterSearch.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'ArticleList', React.createFactory(ArticleList.ArticleList) props = { collection: [{id: '123', thumbnail_title: 'Game of Thrones', slug: 'artsy-editorial-game-of-thrones'}] url: 'url' selected: sinon.stub() checkable: true searchResults: sinon.stub() contentType: 'article' } @component = ReactDOM.render React.createElement(FilterSearch, props), (@$el = $ "<div></div>")[0], => setTimeout => sinon.stub @component, 'setState' sinon.stub @component, 'addAutocomplete' done() afterEach -> benv.teardown() it 'renders an initial set of articles', -> $(ReactDOM.findDOMNode(@component)).html().should.containEql 'Game of Thrones' $(ReactDOM.findDOMNode(@component)).html().should.containEql '/article/artsy-editorial-game-of-thrones' it 'selects the article when clicking the check button', -> r.simulate.click r.find @component, 'article-list__checkcircle' @component.props.selected.args[0][0].id.should.containEql '123' @component.props.selected.args[0][0].thumbnail_title.should.containEql 'Game of Thrones' @component.props.selected.args[0][0].slug.should.containEql 'artsy-editorial-game-of-thrones' it 'searches articles given a query', -> input = r.find @component, 'bordered-input' input.value = 'finding nemo' r.simulate.change input @component.props.searchResults.args[0][0][0].id.should.equal '456' @component.props.searchResults.args[0][0][0].thumbnail_title.should.equal 'finding nemo' describe 'FilterSearch Tag', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (@Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> remote: { url: '' } get: sinon.stub().yields [[{id: '123', name: '<NAME>'}]] ) Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } window.jQuery = $ require 'typeahead.js' FilterSearch = benv.requireWithJadeify( resolve(__dirname, '../index') [] ) TagList = benv.requireWithJadeify( resolve(__dirname, '../../tag_list/index') [] ) TagList.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'TagList', React.createFactory(TagList) props = { collection: [ fixtures().tags { id: '123', name: '<NAME>', public: true } ] url: 'url' searchResults: sinon.stub() deleteTag: sinon.stub() contentType: 'tag' } @component = ReactDOM.render React.createElement(FilterSearch, props), (@$el = $ "<div></div>")[0], => setTimeout => sinon.stub @component, 'setState' sinon.stub @component, 'addAutocomplete' done() afterEach -> benv.teardown() it 'renders an initial set of tags', -> $(ReactDOM.findDOMNode(@component)).html().should.containEql 'Show Reviews' it 'searches tags given a query', -> input = r.find @component, 'bordered-input' input.value = '<NAME>' r.simulate.change input @component.props.searchResults.args[0][0][0].id.should.equal '123' @component.props.searchResults.args[0][0][0].name.should.equal '<NAME>'
true
benv = require 'benv' sinon = require 'sinon' { resolve } = require 'path' fixtures = require '../../../../test/helpers/fixtures.coffee' React = require 'react' ReactDOM = require 'react-dom' ReactTestUtils = require 'react-dom/test-utils' r = find: ReactTestUtils.findRenderedDOMComponentWithClass simulate: ReactTestUtils.Simulate describe 'FilterSearch Article', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (@Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> remote: { url: '' } get: sinon.stub().yields( [[{id: '456', thumbnail_title: 'finding nemo'}]] ) ) Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } window.jQuery = $ require 'typeahead.js' FilterSearch = benv.requireWithJadeify( resolve(__dirname, '../index') [] ) ArticleList = benv.requireWithJadeify( resolve(__dirname, '../../article_list/index') [] ) FilterSearch.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'ArticleList', React.createFactory(ArticleList.ArticleList) props = { collection: [{id: '123', thumbnail_title: 'Game of Thrones', slug: 'artsy-editorial-game-of-thrones'}] url: 'url' selected: sinon.stub() checkable: true searchResults: sinon.stub() contentType: 'article' } @component = ReactDOM.render React.createElement(FilterSearch, props), (@$el = $ "<div></div>")[0], => setTimeout => sinon.stub @component, 'setState' sinon.stub @component, 'addAutocomplete' done() afterEach -> benv.teardown() it 'renders an initial set of articles', -> $(ReactDOM.findDOMNode(@component)).html().should.containEql 'Game of Thrones' $(ReactDOM.findDOMNode(@component)).html().should.containEql '/article/artsy-editorial-game-of-thrones' it 'selects the article when clicking the check button', -> r.simulate.click r.find @component, 'article-list__checkcircle' @component.props.selected.args[0][0].id.should.containEql '123' @component.props.selected.args[0][0].thumbnail_title.should.containEql 'Game of Thrones' @component.props.selected.args[0][0].slug.should.containEql 'artsy-editorial-game-of-thrones' it 'searches articles given a query', -> input = r.find @component, 'bordered-input' input.value = 'finding nemo' r.simulate.change input @component.props.searchResults.args[0][0][0].id.should.equal '456' @component.props.searchResults.args[0][0][0].thumbnail_title.should.equal 'finding nemo' describe 'FilterSearch Tag', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require 'jquery' Bloodhound: (@Bloodhound = sinon.stub()).returns( initialize: -> ttAdapter: -> remote: { url: '' } get: sinon.stub().yields [[{id: '123', name: 'PI:NAME:<NAME>END_PI'}]] ) Bloodhound.tokenizers = { obj: { whitespace: sinon.stub() } } window.jQuery = $ require 'typeahead.js' FilterSearch = benv.requireWithJadeify( resolve(__dirname, '../index') [] ) TagList = benv.requireWithJadeify( resolve(__dirname, '../../tag_list/index') [] ) TagList.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'sd', { FORCE_URL: 'http://artsy.net' } FilterSearch.__set__ 'TagList', React.createFactory(TagList) props = { collection: [ fixtures().tags { id: '123', name: 'PI:NAME:<NAME>END_PI', public: true } ] url: 'url' searchResults: sinon.stub() deleteTag: sinon.stub() contentType: 'tag' } @component = ReactDOM.render React.createElement(FilterSearch, props), (@$el = $ "<div></div>")[0], => setTimeout => sinon.stub @component, 'setState' sinon.stub @component, 'addAutocomplete' done() afterEach -> benv.teardown() it 'renders an initial set of tags', -> $(ReactDOM.findDOMNode(@component)).html().should.containEql 'Show Reviews' it 'searches tags given a query', -> input = r.find @component, 'bordered-input' input.value = 'PI:NAME:<NAME>END_PI' r.simulate.change input @component.props.searchResults.args[0][0][0].id.should.equal '123' @component.props.searchResults.args[0][0][0].name.should.equal 'PI:NAME:<NAME>END_PI'
[ { "context": "8, 'list', [1, 2, 3] ]\n [ 9, 'object', {name: 'Egon'} ]\n [ 10, 'complex', [{name: 'Valentina'}, {n", "end": 661, "score": 0.9972453117370605, "start": 657, "tag": "NAME", "value": "Egon" }, { "context": "', {name: 'Egon'} ]\n [ 10, 'complex', [{name: 'Valentina'}, {name: 'Nadine'}, {name: 'Sven'}] ]\n ]\n\n des", "end": 705, "score": 0.999213457107544, "start": 696, "tag": "NAME", "value": "Valentina" }, { "context": " [ 10, 'complex', [{name: 'Valentina'}, {name: 'Nadine'}, {name: 'Sven'}] ]\n ]\n\n describe \"parse prese", "end": 723, "score": 0.9994735717773438, "start": 717, "tag": "NAME", "value": "Nadine" }, { "context": ", [{name: 'Valentina'}, {name: 'Nadine'}, {name: 'Sven'}] ]\n ]\n\n describe \"parse preset file\", ->\n\n ", "end": 739, "score": 0.9995696544647217, "start": 735, "tag": "NAME", "value": "Sven" } ]
test/mocha/csv.coffee
alinex/node-formatter
0
chai = require 'chai' expect = chai.expect ### eslint-env node, mocha ### fs = require 'fs' debug = require('debug') 'test:csv' chalk = require 'chalk' Table = require 'alinex-table' formatter = require '../../src/index' describe "CSV", -> file = __dirname + '/../data/format.csv' format = 'csv' example = fs.readFileSync file source = null data = [ [ 'num', 'type', 'object' ] [ 1, 'null', null ] [ 2, 'undefined', null ] [ 3, 'boolean', 1 ] [ 4, 'number', 5.6 ] [ 5, 'text', "Hello" ] [ 6, 'quotes', "Give me a \"hand up\"" ] [ 7, 'date', 128182440000 ] [ 8, 'list', [1, 2, 3] ] [ 9, 'object', {name: 'Egon'} ] [ 10, 'complex', [{name: 'Valentina'}, {name: 'Nadine'}, {name: 'Sven'}] ] ] describe "parse preset file", -> it "should get object", (cb) -> formatter.parse example, format, (err, obj) -> source = obj expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with filename", (cb) -> formatter.parse example, file, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() describe "format and parse", -> it "should reread object", (cb) -> source = data formatter.stringify source, format, (err, text) -> expect(err, 'error').to.not.exist # used to create the example file # fs.writeFile __dirname + '/../data/format.csv', text debug "result", chalk.grey text expect(typeof text, 'type of result').to.equal 'string' formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb() describe "table", -> it "should reread object", (cb) -> table = new Table data formatter.stringify table, format, (err, text) -> expect(err, 'error').to.not.exist debug "result", chalk.grey text expect(typeof text, 'type of result').to.equal 'string' formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb()
42694
chai = require 'chai' expect = chai.expect ### eslint-env node, mocha ### fs = require 'fs' debug = require('debug') 'test:csv' chalk = require 'chalk' Table = require 'alinex-table' formatter = require '../../src/index' describe "CSV", -> file = __dirname + '/../data/format.csv' format = 'csv' example = fs.readFileSync file source = null data = [ [ 'num', 'type', 'object' ] [ 1, 'null', null ] [ 2, 'undefined', null ] [ 3, 'boolean', 1 ] [ 4, 'number', 5.6 ] [ 5, 'text', "Hello" ] [ 6, 'quotes', "Give me a \"hand up\"" ] [ 7, 'date', 128182440000 ] [ 8, 'list', [1, 2, 3] ] [ 9, 'object', {name: '<NAME>'} ] [ 10, 'complex', [{name: '<NAME>'}, {name: '<NAME>'}, {name: '<NAME>'}] ] ] describe "parse preset file", -> it "should get object", (cb) -> formatter.parse example, format, (err, obj) -> source = obj expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with filename", (cb) -> formatter.parse example, file, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() describe "format and parse", -> it "should reread object", (cb) -> source = data formatter.stringify source, format, (err, text) -> expect(err, 'error').to.not.exist # used to create the example file # fs.writeFile __dirname + '/../data/format.csv', text debug "result", chalk.grey text expect(typeof text, 'type of result').to.equal 'string' formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb() describe "table", -> it "should reread object", (cb) -> table = new Table data formatter.stringify table, format, (err, text) -> expect(err, 'error').to.not.exist debug "result", chalk.grey text expect(typeof text, 'type of result').to.equal 'string' formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb()
true
chai = require 'chai' expect = chai.expect ### eslint-env node, mocha ### fs = require 'fs' debug = require('debug') 'test:csv' chalk = require 'chalk' Table = require 'alinex-table' formatter = require '../../src/index' describe "CSV", -> file = __dirname + '/../data/format.csv' format = 'csv' example = fs.readFileSync file source = null data = [ [ 'num', 'type', 'object' ] [ 1, 'null', null ] [ 2, 'undefined', null ] [ 3, 'boolean', 1 ] [ 4, 'number', 5.6 ] [ 5, 'text', "Hello" ] [ 6, 'quotes', "Give me a \"hand up\"" ] [ 7, 'date', 128182440000 ] [ 8, 'list', [1, 2, 3] ] [ 9, 'object', {name: 'PI:NAME:<NAME>END_PI'} ] [ 10, 'complex', [{name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'}] ] ] describe "parse preset file", -> it "should get object", (cb) -> formatter.parse example, format, (err, obj) -> source = obj expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() it "should work with filename", (cb) -> formatter.parse example, file, (err, obj) -> expect(err, 'error').to.not.exist expect(obj, 'object').to.deep.equal data cb() describe "format and parse", -> it "should reread object", (cb) -> source = data formatter.stringify source, format, (err, text) -> expect(err, 'error').to.not.exist # used to create the example file # fs.writeFile __dirname + '/../data/format.csv', text debug "result", chalk.grey text expect(typeof text, 'type of result').to.equal 'string' formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb() describe "table", -> it "should reread object", (cb) -> table = new Table data formatter.stringify table, format, (err, text) -> expect(err, 'error').to.not.exist debug "result", chalk.grey text expect(typeof text, 'type of result').to.equal 'string' formatter.parse text, format, (err, obj) -> expect(obj, 'reread object').to.deep.equal data cb()
[ { "context": "d, doc) ->\n return false if doc.author is 'max'\n return true\n internal:\n deny: tr", "end": 357, "score": 0.5975009799003601, "start": 354, "tag": "USERNAME", "value": "max" }, { "context": "w all', (test, next) ->\n Posts.insert name: 'test', (err) ->\n test.isUndefined err, 'err sho", "end": 1018, "score": 0.9916274547576904, "start": 1014, "tag": "NAME", "value": "test" }, { "context": ", next) ->\n id = Posts.insert\n name: 'test'\n createdAt: new Date()\n , (err) ->\n ", "end": 1216, "score": 0.9975311160087585, "start": 1212, "tag": "NAME", "value": "test" }, { "context": ", next) ->\n id = Posts.insert\n name: 'test'\n author: 'max'\n , (err) ->\n t", "end": 1587, "score": 0.9976208209991455, "start": 1583, "tag": "NAME", "value": "test" }, { "context": "osts.insert\n name: 'test'\n author: 'max'\n , (err) ->\n test.isUndefined err, '", "end": 1609, "score": 0.7653710246086121, "start": 1606, "tag": "USERNAME", "value": "max" }, { "context": "pty'\n\n Posts.update id, $set: author: 'someone else', (err) ->\n test.isNotUndefined err", "end": 1728, "score": 0.5162478685379028, "start": 1725, "tag": "USERNAME", "value": "one" }, { "context": ", next) ->\n id = Posts.insert\n name: 'test'\n internal:\n foo: 'bar'\n , (", "end": 1933, "score": 0.9951436519622803, "start": 1929, "tag": "NAME", "value": "test" }, { "context": "(test, next) ->\n Posts.insert\n name: 'test'\n hidden: 'hello'\n , (err, id) ->\n ", "end": 2172, "score": 0.9993728995323181, "start": 2168, "tag": "NAME", "value": "test" }, { "context": "(test, next) ->\n Posts.insert\n name: 'test'\n secret: 'hello'\n , (err, id) ->\n ", "end": 2484, "score": 0.9992936849594116, "start": 2480, "tag": "NAME", "value": "test" }, { "context": "est, next) ->\n Authors.insert\n name: 'test'\n secret: 'hello'\n , (err, id) ->\n ", "end": 2821, "score": 0.9994120597839355, "start": 2817, "tag": "NAME", "value": "test" } ]
tests/fieldsecurity.coffee
maximalmeteor/fieldsecurity
3
Posts = new Meteor.Collection('posts') Authors = new Meteor.Collection('authors') if Meteor.isServer FieldSecurity.setLogging true Posts.attachRules name: allow: true createdAt: allow: insert: true update: false remove: true author: allow: (userId, doc) -> return false if doc.author is 'max' return true internal: deny: true hidden: visible: false secret: visible: (selector, options) -> return options?.security?.visible Authors.attachCRUD name: create: allow: true deny: false read: true update: allow: true deny: false delete: allow: true deny: false Meteor.publish 'posts', -> Posts.find {}, security: visible: true Meteor.publish 'authors', -> Authors.find() if Meteor.isClient Meteor.subscribe 'posts', -> Tinytest.addAsync 'FieldSecurity - allow all', (test, next) -> Posts.insert name: 'test', (err) -> test.isUndefined err, 'err should be empty' next() Tinytest.addAsync 'FieldSecurity - allow only insert', (test, next) -> id = Posts.insert name: 'test' createdAt: new Date() , (err) -> test.isUndefined err, 'err should be empty' Posts.update id, $set: createdAt: new Date(), (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - allow insert with function', (test, next) -> id = Posts.insert name: 'test' author: 'max' , (err) -> test.isUndefined err, 'err should be empty' Posts.update id, $set: author: 'someone else', (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - deny all', (test, next) -> id = Posts.insert name: 'test' internal: foo: 'bar' , (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - hide field', (test, next) -> Posts.insert name: 'test' hidden: 'hello' , (err, id) -> posts = Posts.find _id: id post = posts.fetch()[0] test.isUndefined post.hidden, 'test should be empty' next() Tinytest.addAsync 'FieldSecurity - hide field with function', (test, next) -> Posts.insert name: 'test' secret: 'hello' , (err, id) -> posts = Posts.find _id: id post = posts.fetch()[0] test.equal post.secret, 'hello', 'secret should be "hello"' next() Meteor.subscribe 'authors', -> Tinytest.addAsync 'FieldSecurity - use CRUD', (test, next) -> Authors.insert name: 'test' secret: 'hello' , (err, id) -> authors = Authors.find _id: id author = authors.fetch()[0] test.equal author.secret, 'hello', 'secret should be "hello"' next()
72640
Posts = new Meteor.Collection('posts') Authors = new Meteor.Collection('authors') if Meteor.isServer FieldSecurity.setLogging true Posts.attachRules name: allow: true createdAt: allow: insert: true update: false remove: true author: allow: (userId, doc) -> return false if doc.author is 'max' return true internal: deny: true hidden: visible: false secret: visible: (selector, options) -> return options?.security?.visible Authors.attachCRUD name: create: allow: true deny: false read: true update: allow: true deny: false delete: allow: true deny: false Meteor.publish 'posts', -> Posts.find {}, security: visible: true Meteor.publish 'authors', -> Authors.find() if Meteor.isClient Meteor.subscribe 'posts', -> Tinytest.addAsync 'FieldSecurity - allow all', (test, next) -> Posts.insert name: '<NAME>', (err) -> test.isUndefined err, 'err should be empty' next() Tinytest.addAsync 'FieldSecurity - allow only insert', (test, next) -> id = Posts.insert name: '<NAME>' createdAt: new Date() , (err) -> test.isUndefined err, 'err should be empty' Posts.update id, $set: createdAt: new Date(), (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - allow insert with function', (test, next) -> id = Posts.insert name: '<NAME>' author: 'max' , (err) -> test.isUndefined err, 'err should be empty' Posts.update id, $set: author: 'someone else', (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - deny all', (test, next) -> id = Posts.insert name: '<NAME>' internal: foo: 'bar' , (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - hide field', (test, next) -> Posts.insert name: '<NAME>' hidden: 'hello' , (err, id) -> posts = Posts.find _id: id post = posts.fetch()[0] test.isUndefined post.hidden, 'test should be empty' next() Tinytest.addAsync 'FieldSecurity - hide field with function', (test, next) -> Posts.insert name: '<NAME>' secret: 'hello' , (err, id) -> posts = Posts.find _id: id post = posts.fetch()[0] test.equal post.secret, 'hello', 'secret should be "hello"' next() Meteor.subscribe 'authors', -> Tinytest.addAsync 'FieldSecurity - use CRUD', (test, next) -> Authors.insert name: '<NAME>' secret: 'hello' , (err, id) -> authors = Authors.find _id: id author = authors.fetch()[0] test.equal author.secret, 'hello', 'secret should be "hello"' next()
true
Posts = new Meteor.Collection('posts') Authors = new Meteor.Collection('authors') if Meteor.isServer FieldSecurity.setLogging true Posts.attachRules name: allow: true createdAt: allow: insert: true update: false remove: true author: allow: (userId, doc) -> return false if doc.author is 'max' return true internal: deny: true hidden: visible: false secret: visible: (selector, options) -> return options?.security?.visible Authors.attachCRUD name: create: allow: true deny: false read: true update: allow: true deny: false delete: allow: true deny: false Meteor.publish 'posts', -> Posts.find {}, security: visible: true Meteor.publish 'authors', -> Authors.find() if Meteor.isClient Meteor.subscribe 'posts', -> Tinytest.addAsync 'FieldSecurity - allow all', (test, next) -> Posts.insert name: 'PI:NAME:<NAME>END_PI', (err) -> test.isUndefined err, 'err should be empty' next() Tinytest.addAsync 'FieldSecurity - allow only insert', (test, next) -> id = Posts.insert name: 'PI:NAME:<NAME>END_PI' createdAt: new Date() , (err) -> test.isUndefined err, 'err should be empty' Posts.update id, $set: createdAt: new Date(), (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - allow insert with function', (test, next) -> id = Posts.insert name: 'PI:NAME:<NAME>END_PI' author: 'max' , (err) -> test.isUndefined err, 'err should be empty' Posts.update id, $set: author: 'someone else', (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - deny all', (test, next) -> id = Posts.insert name: 'PI:NAME:<NAME>END_PI' internal: foo: 'bar' , (err) -> test.isNotUndefined err, 'err should not be empty' next() Tinytest.addAsync 'FieldSecurity - hide field', (test, next) -> Posts.insert name: 'PI:NAME:<NAME>END_PI' hidden: 'hello' , (err, id) -> posts = Posts.find _id: id post = posts.fetch()[0] test.isUndefined post.hidden, 'test should be empty' next() Tinytest.addAsync 'FieldSecurity - hide field with function', (test, next) -> Posts.insert name: 'PI:NAME:<NAME>END_PI' secret: 'hello' , (err, id) -> posts = Posts.find _id: id post = posts.fetch()[0] test.equal post.secret, 'hello', 'secret should be "hello"' next() Meteor.subscribe 'authors', -> Tinytest.addAsync 'FieldSecurity - use CRUD', (test, next) -> Authors.insert name: 'PI:NAME:<NAME>END_PI' secret: 'hello' , (err, id) -> authors = Authors.find _id: id author = authors.fetch()[0] test.equal author.secret, 'hello', 'secret should be "hello"' next()
[ { "context": "###\n@Author: Kristinita\n@Date:\t 2017-05-02 11:44:00\n@Last Modified time: ", "end": 23, "score": 0.9997901916503906, "start": 13, "tag": "NAME", "value": "Kristinita" }, { "context": "do.github.io/gemini-scrollbar/\nhttps://github.com/noeldelgado/gemini-scrollbar/issues/46#issuecomment-374928170", "end": 293, "score": 0.9994314908981323, "start": 282, "tag": "USERNAME", "value": "noeldelgado" }, { "context": "splaying in mobile devices\n\t\t# https://github.com/noeldelgado/gemini-scrollbar#options\n\t\tforceGemini: true).cre", "end": 686, "score": 0.9989975690841675, "start": 675, "tag": "USERNAME", "value": "noeldelgado" }, { "context": "()\n\t# JQuery Lazy support —\n\t# https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103\n\t$(", "end": 889, "score": 0.9996074438095093, "start": 882, "tag": "USERNAME", "value": "eisbehr" }, { "context": "n method “update” of Gemini:\n\t\thttps://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388\n\t\th", "end": 1081, "score": 0.9996300935745239, "start": 1074, "tag": "USERNAME", "value": "eisbehr" }, { "context": "y/example_callback-functions\n\t\thttps://github.com/noeldelgado/gemini-scrollbar#basic-methods\n\t\t###\n\t\tafterLoad:", "end": 1219, "score": 0.9992631673812866, "start": 1208, "tag": "USERNAME", "value": "noeldelgado" }, { "context": "g in mobile devices\n#\t\t\t\t\t\t // https://github.com/noeldelgado/gemini-scrollbar#options\n#\t\t\t\t\t\t forceGemini: tru", "end": 2305, "score": 0.9996572732925415, "start": 2294, "tag": "USERNAME", "value": "noeldelgado" }, { "context": "JQuery Lazy support —\n#\t\t\t\t // https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103\n#\t\t", "end": 2490, "score": 0.999722421169281, "start": 2483, "tag": "USERNAME", "value": "eisbehr" }, { "context": "“update” of Gemini:\n#\t\t\t\t\t\t // https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388\n#\t\t", "end": 2707, "score": 0.9997406005859375, "start": 2700, "tag": "USERNAME", "value": "eisbehr" }, { "context": "_callback-functions\n#\t\t\t\t\t\t // https://github.com/noeldelgado/gemini-scrollbar#basic-methods\n#\t\t\t\t\t\t afterLoad:", "end": 2863, "score": 0.9996811747550964, "start": 2852, "tag": "USERNAME", "value": "noeldelgado" }, { "context": "# };\n# // Scrollbar works on resize\n# // Thanks to Alfy — https://vk.com/dark_alf\n# window.onresize = fun", "end": 3491, "score": 0.9705646634101868, "start": 3487, "tag": "NAME", "value": "Alfy" }, { "context": "ks on resize\n# // Thanks to Alfy — https://vk.com/dark_alf\n# window.onresize = function() {\n#\t\t if(window.my", "end": 3517, "score": 0.9992976188659668, "start": 3509, "tag": "USERNAME", "value": "dark_alf" } ]
themes/sashapelican/static/coffee/Gemini/GeminiAndJQueryLazy.coffee
Kristinita/KristinitaPelicanCI
0
### @Author: Kristinita @Date: 2017-05-02 11:44:00 @Last Modified time: 2018-03-24 08:49:55 ### #################### # gemini-scrollbar # #################### ### Custom scrollbar instead of native body scrollbar: https://noeldelgado.github.io/gemini-scrollbar/ https://github.com/noeldelgado/gemini-scrollbar/issues/46#issuecomment-374928170 ### internals = {} internals.initialize = -> internals.scrollbar = new GeminiScrollbar( # querySelector method — https://www.w3schools.com/jsref/met_document_queryselector.asp element: document.querySelector('body') autoshow: true # Force Gemini for correct scrollbar displaying in mobile devices # https://github.com/noeldelgado/gemini-scrollbar#options forceGemini: true).create() internals.scrollingElement = internals.scrollbar.getViewElement() internals.scrollToHash() # JQuery Lazy support — # https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103 $('.SashaLazy').Lazy appendScroll: $(internals.scrollbar.getViewElement()) ### Run method “update” of Gemini: https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388 http://jquery.eisbehr.de/lazy/example_callback-functions https://github.com/noeldelgado/gemini-scrollbar#basic-methods ### afterLoad: -> internals.scrollbar.update() return return internals.handleOrientationChange = -> internals.scrollbar.update() internals.scrollToHash() return internals.scrollToHash = -> element = undefined hash = undefined hash = location.hash if hash element = document.getElementById(hash.replace('#', '')) if element internals.scrollingElement.scrollTo 0, element.offsetTop return # Listeners window.onload = internals.initialize window.onorientationchange = internals.handleOrientationChange ################# # [DEPRECATED] ## ################# # window.onload = function() { # if (window.matchMedia("(orientation: landscape)").matches) { # // For landscape orientation # var landscapescrollbar = new GeminiScrollbar({ # // querySelector method — https://www.w3schools.com/jsref/met_document_queryselector.asp # element: document.querySelector("main"), # autoshow: true, # // Force Gemini for correct scrollbar displaying in mobile devices # // https://github.com/noeldelgado/gemini-scrollbar#options # forceGemini: true, # }).create(); # window.myscroolbar = landscapescrollbar; # // JQuery Lazy support — # // https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103 # $(".SashaLazy").Lazy({ # appendScroll: $(landscapescrollbar.getViewElement()), # // Run method “update” of Gemini: # // https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388 # // http://jquery.eisbehr.de/lazy/example_callback-functions # // https://github.com/noeldelgado/gemini-scrollbar#basic-methods # afterLoad: function() { # landscapescrollbar.update(); # } # }); # } else { # // For portrait orientation # var portraitscrollbar = new GeminiScrollbar({ # element: document.querySelector("body"), # autoshow: true, # forceGemini: true, # }).create(); # window.myscroolbar = portraitscrollbar; # $(".SashaLazy").Lazy({ # appendScroll: $(portraitscrollbar.getViewElement()), # afterLoad: function() { # portraitscrollbar.update(); # } # }); # } # }; # // Scrollbar works on resize # // Thanks to Alfy — https://vk.com/dark_alf # window.onresize = function() { # if(window.myscroolbar) # window.myscroolbar.destroy(); # window.onload(); # };
182550
### @Author: <NAME> @Date: 2017-05-02 11:44:00 @Last Modified time: 2018-03-24 08:49:55 ### #################### # gemini-scrollbar # #################### ### Custom scrollbar instead of native body scrollbar: https://noeldelgado.github.io/gemini-scrollbar/ https://github.com/noeldelgado/gemini-scrollbar/issues/46#issuecomment-374928170 ### internals = {} internals.initialize = -> internals.scrollbar = new GeminiScrollbar( # querySelector method — https://www.w3schools.com/jsref/met_document_queryselector.asp element: document.querySelector('body') autoshow: true # Force Gemini for correct scrollbar displaying in mobile devices # https://github.com/noeldelgado/gemini-scrollbar#options forceGemini: true).create() internals.scrollingElement = internals.scrollbar.getViewElement() internals.scrollToHash() # JQuery Lazy support — # https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103 $('.SashaLazy').Lazy appendScroll: $(internals.scrollbar.getViewElement()) ### Run method “update” of Gemini: https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388 http://jquery.eisbehr.de/lazy/example_callback-functions https://github.com/noeldelgado/gemini-scrollbar#basic-methods ### afterLoad: -> internals.scrollbar.update() return return internals.handleOrientationChange = -> internals.scrollbar.update() internals.scrollToHash() return internals.scrollToHash = -> element = undefined hash = undefined hash = location.hash if hash element = document.getElementById(hash.replace('#', '')) if element internals.scrollingElement.scrollTo 0, element.offsetTop return # Listeners window.onload = internals.initialize window.onorientationchange = internals.handleOrientationChange ################# # [DEPRECATED] ## ################# # window.onload = function() { # if (window.matchMedia("(orientation: landscape)").matches) { # // For landscape orientation # var landscapescrollbar = new GeminiScrollbar({ # // querySelector method — https://www.w3schools.com/jsref/met_document_queryselector.asp # element: document.querySelector("main"), # autoshow: true, # // Force Gemini for correct scrollbar displaying in mobile devices # // https://github.com/noeldelgado/gemini-scrollbar#options # forceGemini: true, # }).create(); # window.myscroolbar = landscapescrollbar; # // JQuery Lazy support — # // https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103 # $(".SashaLazy").Lazy({ # appendScroll: $(landscapescrollbar.getViewElement()), # // Run method “update” of Gemini: # // https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388 # // http://jquery.eisbehr.de/lazy/example_callback-functions # // https://github.com/noeldelgado/gemini-scrollbar#basic-methods # afterLoad: function() { # landscapescrollbar.update(); # } # }); # } else { # // For portrait orientation # var portraitscrollbar = new GeminiScrollbar({ # element: document.querySelector("body"), # autoshow: true, # forceGemini: true, # }).create(); # window.myscroolbar = portraitscrollbar; # $(".SashaLazy").Lazy({ # appendScroll: $(portraitscrollbar.getViewElement()), # afterLoad: function() { # portraitscrollbar.update(); # } # }); # } # }; # // Scrollbar works on resize # // Thanks to <NAME> — https://vk.com/dark_alf # window.onresize = function() { # if(window.myscroolbar) # window.myscroolbar.destroy(); # window.onload(); # };
true
### @Author: PI:NAME:<NAME>END_PI @Date: 2017-05-02 11:44:00 @Last Modified time: 2018-03-24 08:49:55 ### #################### # gemini-scrollbar # #################### ### Custom scrollbar instead of native body scrollbar: https://noeldelgado.github.io/gemini-scrollbar/ https://github.com/noeldelgado/gemini-scrollbar/issues/46#issuecomment-374928170 ### internals = {} internals.initialize = -> internals.scrollbar = new GeminiScrollbar( # querySelector method — https://www.w3schools.com/jsref/met_document_queryselector.asp element: document.querySelector('body') autoshow: true # Force Gemini for correct scrollbar displaying in mobile devices # https://github.com/noeldelgado/gemini-scrollbar#options forceGemini: true).create() internals.scrollingElement = internals.scrollbar.getViewElement() internals.scrollToHash() # JQuery Lazy support — # https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103 $('.SashaLazy').Lazy appendScroll: $(internals.scrollbar.getViewElement()) ### Run method “update” of Gemini: https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388 http://jquery.eisbehr.de/lazy/example_callback-functions https://github.com/noeldelgado/gemini-scrollbar#basic-methods ### afterLoad: -> internals.scrollbar.update() return return internals.handleOrientationChange = -> internals.scrollbar.update() internals.scrollToHash() return internals.scrollToHash = -> element = undefined hash = undefined hash = location.hash if hash element = document.getElementById(hash.replace('#', '')) if element internals.scrollingElement.scrollTo 0, element.offsetTop return # Listeners window.onload = internals.initialize window.onorientationchange = internals.handleOrientationChange ################# # [DEPRECATED] ## ################# # window.onload = function() { # if (window.matchMedia("(orientation: landscape)").matches) { # // For landscape orientation # var landscapescrollbar = new GeminiScrollbar({ # // querySelector method — https://www.w3schools.com/jsref/met_document_queryselector.asp # element: document.querySelector("main"), # autoshow: true, # // Force Gemini for correct scrollbar displaying in mobile devices # // https://github.com/noeldelgado/gemini-scrollbar#options # forceGemini: true, # }).create(); # window.myscroolbar = landscapescrollbar; # // JQuery Lazy support — # // https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299138103 # $(".SashaLazy").Lazy({ # appendScroll: $(landscapescrollbar.getViewElement()), # // Run method “update” of Gemini: # // https://github.com/eisbehr-/jquery.lazy/issues/88#issuecomment-299196388 # // http://jquery.eisbehr.de/lazy/example_callback-functions # // https://github.com/noeldelgado/gemini-scrollbar#basic-methods # afterLoad: function() { # landscapescrollbar.update(); # } # }); # } else { # // For portrait orientation # var portraitscrollbar = new GeminiScrollbar({ # element: document.querySelector("body"), # autoshow: true, # forceGemini: true, # }).create(); # window.myscroolbar = portraitscrollbar; # $(".SashaLazy").Lazy({ # appendScroll: $(portraitscrollbar.getViewElement()), # afterLoad: function() { # portraitscrollbar.update(); # } # }); # } # }; # // Scrollbar works on resize # // Thanks to PI:NAME:<NAME>END_PI — https://vk.com/dark_alf # window.onresize = function() { # if(window.myscroolbar) # window.myscroolbar.destroy(); # window.onload(); # };
[ { "context": "gedIn()\n # analytics?.identify localStorage['purpleUserId']\n # # segment says you 'have' to call analy", "end": 4607, "score": 0.8940093517303467, "start": 4595, "tag": "USERNAME", "value": "purpleUserId" }, { "context": "tion.\n If the problem persists, contact support@purpledelivery.com.\n \"\"\",\n (->\n navigat", "end": 7146, "score": 0.9999203681945801, "start": 7120, "tag": "EMAIL", "value": "support@purpledelivery.com" }, { "context": "rage['purpleUserId']\n token: localStorage['purpleToken']\n cred: cred\n push_platform: ", "end": 9188, "score": 0.8587313294410706, "start": 9182, "tag": "KEY", "value": "purple" }, { "context": "til.VERSION_NUMBER\n user_id: localStorage['purpleUserId']\n token: localStorage['purpleToken']\n ", "end": 26453, "score": 0.6671115756034851, "start": 26441, "tag": "USERNAME", "value": "purpleUserId" }, { "context": "rage['purpleUserId']\n token: localStorage['purpleToken']\n saved_locations: savedLocations\n h", "end": 26496, "score": 0.935533881187439, "start": 26485, "tag": "KEY", "value": "purpleToken" }, { "context": "RSION_NUMBER\n user_id: localStorage['purpleUserId']\n token: localStorage['purpleToken']\n ", "end": 35680, "score": 0.7385817766189575, "start": 35674, "tag": "USERNAME", "value": "UserId" }, { "context": "ION_NUMBER\n user_id: localStorage['purpleUserId']\n token: localStorage['purpleToken']\n ", "end": 38167, "score": 0.727619469165802, "start": 38161, "tag": "USERNAME", "value": "UserId" }, { "context": "rage['purpleUserId']\n token: localStorage['purpleToken']\n lat: @lat\n lng: @lng\n gal", "end": 42899, "score": 0.7290469408035278, "start": 42888, "tag": "KEY", "value": "purpleToken" } ]
src/app/controller/Main.coffee
Purple-Services/app
2
Ext.define 'Purple.controller.Main', extend: 'Ext.app.Controller' config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' loginForm: 'loginform' requestGasTabContainer: '#requestGasTabContainer' mapForm: 'mapform' map: '#gmap' spacerBetweenMapAndAddress: '#spacerBetweenMapAndAddress' gasPriceMapDisplay: '#gasPriceMapDisplay' requestAddressField: '#requestAddressField' requestGasButtonContainer: '#requestGasButtonContainer' requestGasButton: '#requestGasButton' autocompleteList: '#autocompleteList' requestForm: 'requestform' requestFormTirePressureCheck: '[ctype=requestFormTirePressureCheck]' requestConfirmationForm: 'requestconfirmationform' feedback: 'feedback' feedbackTextField: '[ctype=feedbackTextField]' feedbackThankYouMessage: '[ctype=feedbackThankYouMessage]' invite: 'invite' inviteTextField: '[ctype=inviteTextField]' inviteThankYouMessage: '[ctype=inviteThankYouMessage]' freeGasField: '#freeGasField' discountField: '#discountField' couponCodeField: '#couponCodeField' totalPriceField: '#totalPriceField' homeAddressContainer: '#homeAddressContainer' workAddressContainer: '#workAddressContainer' accountHomeAddress: '#accountHomeAddress' accountWorkAddress: '#accountWorkAddress' addHomeAddressContainer: '#addHomeAddressContainer' addWorkAddressContainer: '#addWorkAddressContainer' addHomeAddress: '#addHomeAddress' addWorkAddress: '#addWorkAddress' removeHomeAddressContainer: '#removeHomeAddressContainer' removeWorkAddressContainer: '#removeWorkAddressContainer' removeHomeAddress: '#removeHomeAddress' removeWorkAddress: '#removeWorkAddress' centerMapButton: '#centerMapButton' control: mapForm: recenterAtUserLoc: 'recenterAtUserLoc' changeHomeAddress: 'changeHomeAddress' changeWorkAddress: 'changeWorkAddress' map: dragstart: 'dragStart' boundchange: 'boundChanged' idle: 'idle' centerchange: 'adjustDeliveryLocByLatLng' maprender: 'initGeocoder' requestAddressField: generateSuggestions: 'generateSuggestions' addressInputMode: 'addressInputMode' showLogin: 'showLogin' initialize: 'initRequestAddressField' keyup: 'keyupRequestAddressField' focus: 'focusRequestAddressField' autocompleteList: handleAutoCompleteListTap: 'handleAutoCompleteListTap' requestGasButtonContainer: initRequestGasForm: 'requestGasButtonPressed' requestForm: backToMap: 'backToMapFromRequestForm' sendRequest: 'sendRequest' requestFormTirePressureCheck: requestFormTirePressureCheckTap: 'requestFormTirePressureCheckTap' requestConfirmationForm: backToRequestForm: 'backToRequestForm' confirmOrder: 'confirmOrder' feedback: sendFeedback: 'sendFeedback' invite: sendInvites: 'sendInvites' accountHomeAddress: initialize: 'initAccountHomeAddress' accountWorkAddress: initialize: 'initAccountWorkAddress' addHomeAddress: initialize: 'initAddHomeAddress' addWorkAddress: initialize: 'initAddWorkAddress' removeHomeAddress: initialize: 'initRemoveHomeAddress' removeWorkAddress: initialize: 'initRemoveWorkAddress' # whether or not the inital map centering has occurred yet mapInitiallyCenteredYet: no mapInited: no # only used if logged in as courier courierPingIntervalRef: null launch: -> @callParent arguments localStorage['lastCacheVersionNumber'] = util.VERSION_NUMBER # COURIER APP ONLY # Remember to comment/uncomment the setTimeout script in index.html if not localStorage['courierOnDuty']? then localStorage['courierOnDuty'] = 'no' clearTimeout window.courierReloadTimer # END COURIER APP ONLY if util.ctl('Account').isCourier() @initCourierPing() # CUSTOMER APP ONLY # if VERSION is "PROD" # GappTrack.track "882234091", "CVvTCNCIkGcQ66XXpAM", "4.00", false # ga_storage?._enableSSL() # doesn't seem to actually use SSL? # ga_storage?._setAccount 'UA-61762011-1' # ga_storage?._setDomain 'none' # ga_storage?._trackEvent 'main', 'App Launch', "Platform: #{Ext.os.name}" # analytics?.load util.SEGMENT_WRITE_KEY # if util.ctl('Account').isUserLoggedIn() # analytics?.identify localStorage['purpleUserId'] # # segment says you 'have' to call analytics.page() at some point # # it doesn't seem to actually matter though # analytics?.track 'App Launch', # platform: Ext.os.name # analytics?.page 'Map' # END OF CUSTOMER APP ONLY navigator.splashscreen?.hide() if util.ctl('Account').hasPushNotificationsSetup() # this is just a re-registering locally, not an initial setup # we don't want to do the initial setup because they may not be # logged in setTimeout (Ext.bind @setUpPushNotifications, this), 4000 @checkGoogleMaps() document.addEventListener("resume", (Ext.bind @onResume, this), false) @locationNotification = 0 @androidHighAccuracyNotificationActive = false if window.queuedDeepLinkUrl? util.handleDeepLinkUrl window.queuedDeepLinkUrl window.queuedDeepLinkUrl = null onResume: -> if util.ctl('Account').isCourier() and Ext.os.name is "iOS" cordova.plugins.diagnostic?.getLocationAuthorizationStatus( ((status) => if status isnt "authorized_always" and @locationNotification < 3 util.alert "Please make sure that the app's Location settings on your device is set to 'Always'.", 'Warning', (->) @locationNotification++ ), (=> console.log "Error getting location authorization status") ) if util.ctl('Account').isUserLoggedIn() # this is causing it to happen very often, probably want to change that # so it only happens when there is a change in user's settings @setUpPushNotifications() util.ctl('Orders').refreshOrdersAndOrdersList() @updateLatlng() checkGoogleMaps: -> if not google?.maps? currentDate = new Date() today = "#{currentDate.getMonth()}/#{currentDate.getDate()}/#{currentDate.getFullYear()}" localStorage['reloadAttempts'] ?= '0' if not localStorage['currentDate']? or today isnt localStorage['currentDate'] localStorage['currentDate'] = today localStorage['reloadAttempts'] = '0' analytics?.track 'Google Maps Failed to Load' if localStorage['reloadAttempts'] isnt '3' localStorage['reloadAttempts'] = (parseInt(localStorage['reloadAttempts']) + 1).toString() navigator.splashscreen?.show() window.location.reload() else util.confirm( 'Connection Problem', """ Please try restarting the application. If the problem persists, contact support@purpledelivery.com. """, (-> navigator.splashscreen.show() window.location.reload()), null, 'Reload', 'Ignore' ) setUpPushNotifications: (alertIfDisabled) -> if Ext.os.name is "iOS" or Ext.os.name is "Android" if alertIfDisabled @pushNotificationEnabled = false setTimeout (=> if not @pushNotificationEnabled navigator.notification.alert 'Your push notifications are turned off. If you want to receive order updates, you can turn them on in your phone settings.', (->), "Reminder" ), 1500 pushPlugin = PushNotification.init ios: alert: true badge: true sound: true android: senderID: util.GCM_SENDER_ID pushPlugin.on 'registration', (data) => @registerDeviceForPushNotifications( data.registrationId, (if Ext.os.name is "iOS" then "apns" else "gcm") ) pushPlugin.on 'notification', (data) => util.alert data.message, "Notification", (->) util.ctl('Orders').loadOrdersList( true, util.ctl('Orders').refreshOrder ) pushPlugin.on 'error', (e) => if VERSION is "LOCAL" or VERSION is "DEV" alert e.message else #chrome/testing @pushNotificationEnabled = true # This is happening pretty often: initial setup and then any app start # and logins. Need to look into this later. I want to make sure it is # registered but I don't think we need to call add-sns ajax so often. registerDeviceForPushNotifications: (cred, pushPlatform = "apns") -> @pushNotificationEnabled = true # cred for APNS (apple) is the device token # for GCM (android) it is regid Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/add-sns" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] cred: cred push_platform: pushPlatform headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserHasPushNotificationsSetUp'] = "true" else util.alert response.message, "Error", (->) failure: (response_obj) -> console.log response_obj checkAndroidLocationSettings: -> if Ext.os.name is 'Android' if util.ctl('Account').isCourier() or @locationNotification < 1 cordova.plugins.diagnostic?.getLocationMode( ((locationMode) => if locationMode isnt 'high_accuracy' and @androidHighAccuracyNotificationActive is false @androidHighAccuracyNotificationActive = true cordova.plugins.locationAccuracy.request( (=> @androidHighAccuracyNotificationActive = false window.location.reload()), (=> @androidHighAccuracyNotificationActive = false if not util.ctl('Account').isCourier() @centerUsingIpAddress() util.alert "Certain features of the application may not work properly. Please restart the application and enable high accuracy to use all the features.", "Location Settings", (->) ), cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY ) @locationNotification++ ), (=> console.log 'Diagnostics plugin error') ) updateLatlng: -> @checkAndroidLocationSettings() @updateLatlngBusy ?= no if not @updateLatlngBusy @updateLatlngBusy = yes navigator.geolocation?.getCurrentPosition( ((position) => @positionAccuracy = position.coords.accuracy @geolocationAllowed = true @lat = position.coords.latitude @lng = position.coords.longitude if not @mapInitiallyCenteredYet and @mapInited @mapInitiallyCenteredYet = true @recenterAtUserLoc() @updateLatlngBusy = no ), (=> # console.log "GPS failure callback called" if not @geolocationAllowed? or @geolocationAllowed is true @centerUsingIpAddress() @geolocationAllowed = false if not localStorage['gps_not_allowed_event_sent']? analytics?.track 'GPS Not Allowed' localStorage['gps_not_allowed_event_sent'] = 'yes' @updateLatlngBusy = no), {maximumAge: 0, enableHighAccuracy: true} ) centerUsingIpAddress: -> # This works but cannot be used for commercial purposes unless we pay for it. Currently exploring other options. # Ext.Ajax.request # url: "http://ip-api.com/json" # headers: # 'Content-Type': 'application/json' # timeout: 5000 # method: 'GET' # scope: this # success: (response_obj) -> # response = Ext.JSON.decode response_obj.responseText # @getMap().getMap().setCenter( # new google.maps.LatLng response.lat, response.lon # ) # failure: (response_obj) -> @getMap().getMap().setCenter( new google.maps.LatLng 34.0507177, -118.43757779999999 ) initGeocoder: -> # this is called on maprender, so let's make sure we have user loc centered @updateLatlng() if google? and google.maps? and @getMap()? @geocoder = new google.maps.Geocoder() @placesService = new google.maps.places.PlacesService @getMap().getMap() @mapInited = true else util.alert "Internet connection problem. Please try closing the app and restarting it.", "Connection Error", (->) dragStart: -> @lastDragStart = new Date().getTime() / 1000 @getRequestGasButton().setDisabled yes @getCenterMapButton().hide() boundChanged: -> @getRequestGasButton().setDisabled yes idle: -> currentTime = new Date().getTime() / 1000 if currentTime - @lastDragStart > 0.3 @getCenterMapButton().show() adjustDeliveryLocByLatLng: -> center = @getMap().getMap().getCenter() # might want to send actual @deliveryLocLat = center.lat() @deliveryLocLng = center.lng() @updateDeliveryLocAddressByLatLng @deliveryLocLat, @deliveryLocLng updateMapWithAddressComponents: (address) -> @deliveryAddressZipCode = null if address[0]?['address_components']? addressComponents = address[0]['address_components'] streetAddress = "#{addressComponents[0]['short_name']} #{addressComponents[1]['short_name']}" @getRequestAddressField().setValue streetAddress # find the address component that contains the zip code for c in addressComponents for t in c.types if t is "postal_code" @deliveryAddressZipCode = c['short_name'] if not localStorage['gps_not_allowed_event_sent'] and not localStorage['first_launch_loc_sent']? # this means that this is the zip code of the location # where they first launched the app and they allowed GPS analytics?.track 'First Launch Location', street_address: streetAddress zip_code: @deliveryAddressZipCode localStorage['first_launch_loc_sent'] = 'yes' @busyGettingGasPrice ?= no if not @busyGettingGasPrice @busyGettingGasPrice = yes Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}dispatch/gas-prices" params: Ext.JSON.encode version: util.VERSION_NUMBER zip_code: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> @getRequestGasButton().setDisabled no response = Ext.JSON.decode response_obj.responseText if response.success prices = response.gas_prices Ext.get('gas-price-unavailable').setStyle {display: 'none'} Ext.get('gas-price-display').setStyle {display: 'block'} Ext.get('gas-price-display-87').setText( "$#{util.centsToDollars prices["87"]}" ) Ext.get('gas-price-display-91').setText( "$#{util.centsToDollars prices["91"]}" ) else Ext.get('gas-price-display').setStyle {display: 'none'} Ext.get('gas-price-unavailable').setStyle {display: 'block'} Ext.get('gas-price-unavailable').setText( response.message ) @busyGettingGasPrice = no failure: (response_obj) -> @busyGettingGasPrice = no if not @deliveryAddressZipCode @adjustDeliveryLocByLatLng() updateDeliveryLocAddressByLatLng: (lat, lng) -> if @bypassUpdateDeliveryLocAddressByLatLng? and @bypassUpdateDeliveryLocAddressByLatLng @bypassUpdateDeliveryLocAddressByLatLng = false return else latlng = new google.maps.LatLng lat, lng @geocoder?.geocode {'latLng': latlng}, (results, status) => if @geocodeTimeout? clearTimeout @geocodeTimeout @geocodeTimeout = null if status is google.maps.GeocoderStatus.OK if not @getMap().isHidden() @updateMapWithAddressComponents(results) else @geocodeTimeout = setTimeout (=> @updateDeliveryLocAddressByLatLng lat, lng ), 1000 mapMode: -> if @getMap().isHidden() @hideAllSavedLoc() @getMap().show() @getCenterMapButton().show() @getSpacerBetweenMapAndAddress().show() @getGasPriceMapDisplay().show() @getRequestGasButtonContainer().show() @getRequestAddressField().disable() @getRequestAddressField().setValue("Updating Location...") analytics?.page 'Map' recenterAtUserLoc: (showAlertIfUnavailable = false, centerMapButtonPressed = false) -> if centerMapButtonPressed Ext.Viewport.setMasked xtype: 'loadmask' message: '' navigator.geolocation?.getCurrentPosition( ((position) => @lat = position.coords.latitude @lng = position.coords.longitude @getMap().getMap().setCenter( new google.maps.LatLng @lat, @lng ) Ext.Viewport.setMasked false ), (=> Ext.Viewport.setMasked false if showAlertIfUnavailable util.alert "To use the current location button, please allow geolocation for Purple in your phone's settings.", "Current Location Unavailable", (->) ), {maximumAge: 0, enableHighAccuracy: true} ) else @getMap().getMap().setCenter( new google.maps.LatLng @lat, @lng ) addressInputMode: -> if not @getMap().isHidden() @addressInputSubMode = '' @hideAllSavedLoc() @getMap().hide() @getSpacerBetweenMapAndAddress().hide() @getGasPriceMapDisplay().hide() @getRequestGasButtonContainer().hide() @getAutocompleteList().show() @getRequestAddressField().enable() @getRequestAddressField().focus() @showSavedLoc() util.ctl('Menu').pushOntoBackButton => @recenterAtUserLoc() @mapMode() ga_storage._trackEvent 'ui', 'Address Text Input Mode' analytics?.page 'Address Text Input Mode' editSavedLoc: -> @addressInputSubMode = '' @hideAllSavedLoc() @getAutocompleteList().show() @showSavedLoc() util.ctl('Menu').pushOntoBackButton => @recenterAtUserLoc() @mapMode() showSavedLoc: -> if localStorage['purpleUserHomeLocationName'] @getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) @getHomeAddressContainer().show() else @getAddHomeAddressContainer().show() if localStorage['purpleUserWorkLocationName'] @getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) @getWorkAddressContainer().show() else @getAddWorkAddressContainer().show() showTitles: (location) -> if @addressInputSubMode is 'home' if localStorage['purpleUserHomeLocationName'] @getRequestAddressField().setValue('Change Home Address...') else @getRequestAddressField().setValue('Add Home Address...') else if @addressInputSubMode is 'work' if localStorage['purpleUserWorkLocationName'] @getRequestAddressField().setValue('Edit Work Address...') else @getRequestAddressField().setValue('Add Work Address...') removeAddress: -> @updateSavedLocations { home: if @addressInputSubMode is 'home' displayText: '' googlePlaceId: '' else displayText: localStorage['purpleUserHomeLocationName'] googlePlaceId: localStorage['purpleUserHomePlaceId'] work: if @addressInputSubMode is 'work' displayText: '' googlePlaceId: '' else displayText: localStorage['purpleUserWorkLocationName'] googlePlaceId: localStorage['purpleUserWorkPlaceId'] }, -> util.ctl('Main').editSavedLoc() util.ctl('Menu').popOffBackButtonWithoutAction() util.ctl('Menu').popOffBackButtonWithoutAction() showRemoveButtons: (location) -> if @addressInputSubMode is 'home' and localStorage['purpleUserHomeLocationName'] @getRemoveHomeAddressContainer().show() if @addressInputSubMode is 'work' and localStorage['purpleUserWorkLocationName'] @getRemoveWorkAddressContainer().show() hideAllSavedLoc: -> @getAddWorkAddressContainer().hide() @getAddHomeAddressContainer().hide() @getAutocompleteList().hide() @getHomeAddressContainer().hide() @getWorkAddressContainer().hide() @getRemoveHomeAddressContainer().hide() @getRemoveWorkAddressContainer().hide() @getCenterMapButton().hide() @getRequestAddressField().setValue('') editAddressInputMode: -> @hideAllSavedLoc() @getAutocompleteList().show() @showRemoveButtons() @showTitles() util.ctl('Menu').pushOntoBackButton => @editSavedLoc() util.ctl('Menu').popOffBackButtonWithoutAction() generateSuggestions: -> @getRequestGasButton().setDisabled yes request = input: @getRequestAddressField().getValue() @placesAutocompleteService ?= new google.maps.places.AutocompleteService() @placesAutocompleteService.getPlacePredictions request, @populateAutocompleteList populateAutocompleteList: (predictions, status) -> if status is 'OK' suggestions = new Array() for p in predictions isAddress = p.terms[0].value is ""+parseInt(p.terms[0].value) locationName = if isAddress then p.terms[0].value + " " + p.terms[1]?.value else p.terms[0].value suggestions.push 'locationName': locationName 'locationVicinity': p.description.replace locationName+', ', '' 'locationLat': '0' 'locationLng': '0' 'placeId': p.place_id util.ctl('Main').getAutocompleteList().getStore().setData suggestions updateDeliveryLocAddressByLocArray: (loc) -> @mapMode() @getRequestAddressField().setValue loc['locationName'] util.ctl('Menu').clearBackButtonStack() # set latlng to zero just in case they press request gas before this func is # done. we don't want an old latlng to be in there that doesn't match address @deliveryLocLat = 0 @deliveryLocLng = 0 @placesService.getDetails {placeId: loc['placeId']}, (place, status) => if status is google.maps.places.PlacesServiceStatus.OK latlng = place.geometry.location # find the address component that contains the zip code for c in place.address_components for t in c.types if t is "postal_code" @deliveryAddressZipCode = c['short_name'] @deliveryLocLat = latlng.lat() @deliveryLocLng = latlng.lng() @bypassUpdateDeliveryLocAddressByLatLng = true @getMap().getMap().setCenter latlng @updateMapWithAddressComponents([place]) @getMap().getMap().setZoom 17 # else # console.log 'placesService error' + status handleAutoCompleteListTap: (loc) -> @loc = loc if @addressInputSubMode @updateAddress() @updateDeliveryLocAddressByLocArray loc changeHomeAddress: -> @addressInputSubMode = 'home' @editAddressInputMode() changeWorkAddress: -> @addressInputSubMode = 'work' @editAddressInputMode() updateAddress: -> if @addressInputSubMode is 'home' @updateSavedLocations { home: displayText: @loc['locationName'] googlePlaceId: @loc['placeId'] work: if localStorage['purpleUserWorkLocationName'] displayText: localStorage['purpleUserWorkLocationName'] googlePlaceId: localStorage['purpleUserWorkPlaceId'] else displayText: '' googlePlaceId: '' }, -> util.ctl('Main').getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) if @addressInputSubMode is 'work' @updateSavedLocations { home: if localStorage['purpleUserHomeLocationName'] displayText: localStorage['purpleUserHomeLocationName'] googlePlaceId: localStorage['purpleUserHomePlaceId'] else displayText: '' googlePlaceId: '' work: displayText: @loc['locationName'] googlePlaceId: @loc['placeId'] }, -> util.ctl('Main').getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) initAccountHomeAddress: (field) -> @getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) field.element.on 'tap', @searchHome, this initAccountWorkAddress: (field) -> @getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) field.element.on 'tap', @searchWork, this initAddWorkAddress: (field) -> field.element.on 'tap', @changeWorkAddress, this initAddHomeAddress: (field) -> field.element.on 'tap', @changeHomeAddress, this initRemoveHomeAddress: (field) -> field.element.on 'tap', @removeAddress, this initRemoveWorkAddress: (field) -> field.element.on 'tap', @removeAddress, this currentLocation: (locationName, placeId) -> {locationName: locationName, placeId: placeId} searchHome: -> @updateDeliveryLocAddressByLocArray @currentLocation(localStorage['purpleUserHomeLocationName'], localStorage['purpleUserHomePlaceId']) searchWork: -> @updateDeliveryLocAddressByLocArray @currentLocation(localStorage['purpleUserWorkLocationName'], localStorage['purpleUserWorkPlaceId']) updateSavedLocations: (savedLocations, callback) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] saved_locations: savedLocations headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserHomeLocationName'] = response.saved_locations.home.displayText localStorage['purpleUserHomePlaceId'] = response.saved_locations.home.googlePlaceId localStorage['purpleUserWorkLocationName'] = response.saved_locations.work.displayText localStorage['purpleUserWorkPlaceId'] = response.saved_locations.work.googlePlaceId callback?() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response showLogin: -> @getMainContainer().getItems().getAt(0).select 1, no, no initRequestAddressField: (textField) -> textField.element.on 'tap', => if util.ctl('Account').isUserLoggedIn() textField.setValue '' @addressInputMode() else @showLogin() true keyupRequestAddressField: (textField, event) -> textField.lastQuery ?= '' query = textField.getValue() if query isnt textField.lastQuery and query isnt '' textField.lastQuery = query if textField.genSuggTimeout? clearTimeout textField.genSuggTimeout textField.genSuggTimeout = setTimeout( @generateSuggestions(), 500 ) true focusRequestAddressField: -> @getRequestAddressField().setValue '' requestGasButtonPressed: -> deliveryLocName = @getRequestAddressField().getValue() ga_storage._trackEvent 'ui', 'Request Gas Button Pressed' analytics?.track 'Request Gas Button Pressed', address_street: deliveryLocName lat: @deliveryLocLat lng: @deliveryLocLng zip: @deliveryAddressZipCode if deliveryLocName is @getRequestAddressField().getInitialConfig().value return # just return, it hasn't loaded the location yet if not (util.ctl('Account').isUserLoggedIn() and util.ctl('Account').isCompleteAccount()) # select the Login view @showLogin() else if ( not localStorage['purpleSubscriptionId']? or localStorage['purpleSubscriptionId'] is '0' ) and ( not localStorage['purpleAdShownTimesSubscription']? or parseInt(localStorage['purpleAdShownTimesSubscription']) < 2 ) and ( Ext.os.is.Android or Ext.os.is.iOS ) and not util.ctl('Account').isManagedAccount() localStorage['purpleAdShownTimesSubscription'] ?= 0 localStorage['purpleAdShownTimesSubscription'] = ( parseInt(localStorage['purpleAdShownTimesSubscription']) + 1 ) util.ctl('Subscriptions').showAd( (=> # pass-thru callback @initRequestGasForm deliveryLocName ) (=> # active callback @getMainContainer().getItems().getAt(0).select 2, no, no util.ctl('Subscriptions').subscriptionsFieldTap() ) ) else @initRequestGasForm deliveryLocName initRequestGasForm: (deliveryLocName) -> # send to request gas form # but first get availbility from disptach system on app service Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}dispatch/availability" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] lat: @deliveryLocLat lng: @deliveryLocLng zip_code: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionLocalStorageData response util.ctl('Subscriptions').subscriptionUsage = response.user.subscription_usage availabilities = response.availabilities totalNumOfTimeOptions = availabilities.reduce (a, b) -> Object.keys(a.times).length + Object.keys(b.times).length if util.isEmpty(availabilities[0].gallon_choices) and util.isEmpty(availabilities[1].gallon_choices) or totalNumOfTimeOptions is 0 util.alert response["unavailable-reason"], "Unavailable", (->) else util.ctl('Menu').pushOntoBackButton => @backToMapFromRequestForm() @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.RequestForm', availabilities: availabilities ) @getRequestForm().setValues lat: @deliveryLocLat lng: @deliveryLocLng address_street: deliveryLocName address_zip: @deliveryAddressZipCode analytics?.page 'Order Form' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj backToMapFromRequestForm: -> @getRequestGasTabContainer().remove( @getRequestForm(), yes ) backToRequestForm: -> @getRequestGasTabContainer().setActiveItem @getRequestForm() @getRequestGasTabContainer().remove( @getRequestConfirmationForm(), yes ) sendRequest: -> # takes you to the confirmation page @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.RequestConfirmationForm' ) util.ctl('Menu').pushOntoBackButton => @backToRequestForm() vals = @getRequestForm().getValues() availabilities = @getRequestForm().config.availabilities gasType = util.ctl('Vehicles').getVehicleById(vals['vehicle']).gas_type for a in availabilities if a['octane'] is gasType availability = a break vals['gas_type'] = "" + availability.octane # should already be string though vals['gas_type_display'] = "Unleaded #{vals['gas_type']} Octane" gasPrice = availability.price_per_gallon serviceFee = ( availability.times[vals['time']]['service_fee'] + (parseInt(vals['tire_pressure_check_price']) * vals['tire_pressure_check']) ) vals['gas_price'] = "" + util.centsToDollars( gasPrice ) vals['gas_price_display'] = "$#{vals['gas_price']} x #{vals['gallons']}" vals['service_fee'] = "" + util.centsToDollars( serviceFee ) freeGallonsAvailable = parseFloat localStorage['purpleUserReferralGallons'] gallonsToSubtract = 0 if freeGallonsAvailable is 0 @getFreeGasField().hide() else # apply as much free gas as possible gallonsToSubtract = Math.min vals['gallons'], freeGallonsAvailable @getFreeGasField().setValue "- $#{vals['gas_price']} x #{gallonsToSubtract}" # it's called unaltered because it doesn't have a coupon code applied @unalteredTotalPrice = ( parseFloat(gasPrice) * (parseFloat(vals['gallons']) - gallonsToSubtract) + parseFloat(serviceFee) ) vals['total_price'] = "" + util.centsToDollars @unalteredTotalPrice vals['display_time'] = availability.times[vals['time']]['text'] vals['vehicle_id'] = vals['vehicle'] for v in util.ctl('Vehicles').vehicles if v['id'] is vals['vehicle_id'] vals['vehicle'] = "#{v.year} #{v.make} #{v.model}" break @getRequestConfirmationForm().setValues vals if not vals['tire_pressure_check'] Ext.ComponentQuery.query('#tirePressureCheckField')[0].hide() # Ext.ComponentQuery.query('#addressStreetConfirmation')[0].removeCls 'bottom-margin' if vals['special_instructions'] is '' Ext.ComponentQuery.query('#specialInstructionsConfirmationLabel')[0].hide() Ext.ComponentQuery.query('#specialInstructionsConfirmation')[0].hide() Ext.ComponentQuery.query('#addressStreetConfirmation')[0].removeCls 'bottom-margin' else Ext.ComponentQuery.query('#specialInstructionsConfirmation')[0].setHtml(vals['special_instructions']) analytics?.page 'Review Order' promptForCode: -> Ext.Msg.prompt( 'Enter Coupon Code', false, ((buttonId, text) => if buttonId is 'ok' @applyCode text Ext.select('.x-msgbox .x-input-el').setStyle('text-transform', 'none') ) ) applyCode: (code) -> vals = @getRequestConfirmationForm().getValues() vehicleId = vals['vehicle_id'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/code" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] vehicle_id: vehicleId code: code address_zip: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText analytics?.track 'Tried Coupon Code', valid: response.success coupon_code: code.toUpperCase() if response.success @getDiscountField().setValue( "- $" + util.centsToDollars(Math.abs(response.value)) ) @getCouponCodeField().setValue code totalPrice = Math.max( @unalteredTotalPrice + response.value, 0 ) @getTotalPriceField().setValue "" + util.centsToDollars(totalPrice) else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response confirmOrder: -> if not util.ctl('Account').hasDefaultPaymentMethod() and not util.ctl('Account').isManagedAccount() # select the Account view @getMainContainer().getItems().getAt(0).select 2, no, no pmCtl = util.ctl('PaymentMethods') if not pmCtl.getPaymentMethods()? pmCtl.paymentMethodFieldTap yes pmCtl.showEditPaymentMethodForm 'new', yes util.ctl('Menu').pushOntoBackButton -> pmCtl.backToPreviousPage() util.ctl('Menu').selectOption 0 pmCtl.getEditPaymentMethodForm().config.saveChangesCallback = -> pmCtl.backToPreviousPage() util.ctl('Menu').selectOption 0 else vals = @getRequestConfirmationForm().getValues() # prices are finally given in cents vals['gas_price'] = parseInt( vals['gas_price'].replace('$','').replace('.','') ) vals['service_fee'] = parseInt( vals['service_fee'].replace('$','').replace('.','') ) vals['total_price'] = parseInt( vals['total_price'].replace('$','').replace('.','') ) Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/add" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] order: vals headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['specialInstructions'] = vals['special_instructions'] util.ctl('Vehicles').specialInstructionsAutoFillPrompted = false util.ctl('Menu').selectOption 3 # Orders tab util.ctl('Orders').loadOrdersList yes @getRequestGasTabContainer().setActiveItem @getMapForm() @getRequestGasTabContainer().remove( @getRequestConfirmationForm(), yes ) @getRequestGasTabContainer().remove( @getRequestForm(), yes ) util.ctl('Menu').clearBackButtonStack() util.alert response.message, (response.message_title ? "Success"), (->) # set up push notifications if they arent set up # NOTE: This will matter less and less, now that we set up push # notifications when a user creates their account. But it's nice to # keep this here for existing users that have never ordered and # don't logout and login (which would also cause a setup) @setUpPushNotifications true else util.alert response.message, (response.message_title ? "Error"), (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response sendFeedback: -> params = version: util.VERSION_NUMBER text: @getFeedbackTextField().getValue() if util.ctl('Account').isUserLoggedIn() params['user_id'] = localStorage['purpleUserId'] params['token'] = localStorage['purpleToken'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}feedback/send" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getFeedbackTextField().setValue '' util.flashComponent @getFeedbackThankYouMessage() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response # this is legacy code? sendInvites: -> params = version: util.VERSION_NUMBER email: @getInviteTextField().getValue() if util.ctl('Account').isUserLoggedIn() params['user_id'] = localStorage['purpleUserId'] params['token'] = localStorage['purpleToken'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}invite/send" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getInviteTextField().setValue '' util.flashComponent @getInviteThankYouMessage() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response initCourierPing: -> window.plugin?.backgroundMode.enable() @gpsIntervalRef ?= setInterval (Ext.bind @updateLatlng, this), 5000 @courierPingIntervalRef ?= setInterval (Ext.bind @courierPing, this), 10000 killCourierPing: -> if @gpsIntervalRef? clearInterval @gpsIntervalRef @gpsIntervalRef = null if @courierPingIntervalRef? clearInterval @courierPingIntervalRef @courierPingIntervalRef = null courierPing: (setOnDuty, successCallback, failureCallback) -> @courierPingBusy ?= no if @courierPingBusy and setOnDuty? setTimeout (=> @courierPing setOnDuty, successCallback, failureCallback ), 11000 else @courierPingBusy = yes params = version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] lat: @lat lng: @lng gallons: 87: localStorage['purpleCourierGallons87'] 91: localStorage['purpleCourierGallons91'] position_accuracy: @positionAccuracy if setOnDuty? params.set_on_duty = setOnDuty Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}courier/ping" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 10000 method: 'POST' scope: this success: (response_obj) -> @courierPingBusy = no response = Ext.JSON.decode response_obj.responseText if response.success if @disconnectedMessage? clearTimeout @disconnectedMessage Ext.get(document.getElementsByTagName('body')[0]).removeCls 'disconnected' @disconnectedMessage = setTimeout (-> if localStorage['courierOnDuty'] is 'yes' Ext.get(document.getElementsByTagName('body')[0]).addCls 'disconnected' ), (2 * 60 * 1000) if (response.on_duty and localStorage['courierOnDuty'] is 'no') or (not response.on_duty and localStorage['courierOnDuty'] is 'yes') localStorage['courierOnDuty'] = if response.on_duty then 'yes' else 'no' util.ctl('Menu').updateOnDutyToggle() successCallback?() else failureCallback?() util.alert response.message, (response.message_title ? "Error"), (->) failure: (response_obj) -> @courierPingBusy = no failureCallback?()
176338
Ext.define 'Purple.controller.Main', extend: 'Ext.app.Controller' config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' loginForm: 'loginform' requestGasTabContainer: '#requestGasTabContainer' mapForm: 'mapform' map: '#gmap' spacerBetweenMapAndAddress: '#spacerBetweenMapAndAddress' gasPriceMapDisplay: '#gasPriceMapDisplay' requestAddressField: '#requestAddressField' requestGasButtonContainer: '#requestGasButtonContainer' requestGasButton: '#requestGasButton' autocompleteList: '#autocompleteList' requestForm: 'requestform' requestFormTirePressureCheck: '[ctype=requestFormTirePressureCheck]' requestConfirmationForm: 'requestconfirmationform' feedback: 'feedback' feedbackTextField: '[ctype=feedbackTextField]' feedbackThankYouMessage: '[ctype=feedbackThankYouMessage]' invite: 'invite' inviteTextField: '[ctype=inviteTextField]' inviteThankYouMessage: '[ctype=inviteThankYouMessage]' freeGasField: '#freeGasField' discountField: '#discountField' couponCodeField: '#couponCodeField' totalPriceField: '#totalPriceField' homeAddressContainer: '#homeAddressContainer' workAddressContainer: '#workAddressContainer' accountHomeAddress: '#accountHomeAddress' accountWorkAddress: '#accountWorkAddress' addHomeAddressContainer: '#addHomeAddressContainer' addWorkAddressContainer: '#addWorkAddressContainer' addHomeAddress: '#addHomeAddress' addWorkAddress: '#addWorkAddress' removeHomeAddressContainer: '#removeHomeAddressContainer' removeWorkAddressContainer: '#removeWorkAddressContainer' removeHomeAddress: '#removeHomeAddress' removeWorkAddress: '#removeWorkAddress' centerMapButton: '#centerMapButton' control: mapForm: recenterAtUserLoc: 'recenterAtUserLoc' changeHomeAddress: 'changeHomeAddress' changeWorkAddress: 'changeWorkAddress' map: dragstart: 'dragStart' boundchange: 'boundChanged' idle: 'idle' centerchange: 'adjustDeliveryLocByLatLng' maprender: 'initGeocoder' requestAddressField: generateSuggestions: 'generateSuggestions' addressInputMode: 'addressInputMode' showLogin: 'showLogin' initialize: 'initRequestAddressField' keyup: 'keyupRequestAddressField' focus: 'focusRequestAddressField' autocompleteList: handleAutoCompleteListTap: 'handleAutoCompleteListTap' requestGasButtonContainer: initRequestGasForm: 'requestGasButtonPressed' requestForm: backToMap: 'backToMapFromRequestForm' sendRequest: 'sendRequest' requestFormTirePressureCheck: requestFormTirePressureCheckTap: 'requestFormTirePressureCheckTap' requestConfirmationForm: backToRequestForm: 'backToRequestForm' confirmOrder: 'confirmOrder' feedback: sendFeedback: 'sendFeedback' invite: sendInvites: 'sendInvites' accountHomeAddress: initialize: 'initAccountHomeAddress' accountWorkAddress: initialize: 'initAccountWorkAddress' addHomeAddress: initialize: 'initAddHomeAddress' addWorkAddress: initialize: 'initAddWorkAddress' removeHomeAddress: initialize: 'initRemoveHomeAddress' removeWorkAddress: initialize: 'initRemoveWorkAddress' # whether or not the inital map centering has occurred yet mapInitiallyCenteredYet: no mapInited: no # only used if logged in as courier courierPingIntervalRef: null launch: -> @callParent arguments localStorage['lastCacheVersionNumber'] = util.VERSION_NUMBER # COURIER APP ONLY # Remember to comment/uncomment the setTimeout script in index.html if not localStorage['courierOnDuty']? then localStorage['courierOnDuty'] = 'no' clearTimeout window.courierReloadTimer # END COURIER APP ONLY if util.ctl('Account').isCourier() @initCourierPing() # CUSTOMER APP ONLY # if VERSION is "PROD" # GappTrack.track "882234091", "CVvTCNCIkGcQ66XXpAM", "4.00", false # ga_storage?._enableSSL() # doesn't seem to actually use SSL? # ga_storage?._setAccount 'UA-61762011-1' # ga_storage?._setDomain 'none' # ga_storage?._trackEvent 'main', 'App Launch', "Platform: #{Ext.os.name}" # analytics?.load util.SEGMENT_WRITE_KEY # if util.ctl('Account').isUserLoggedIn() # analytics?.identify localStorage['purpleUserId'] # # segment says you 'have' to call analytics.page() at some point # # it doesn't seem to actually matter though # analytics?.track 'App Launch', # platform: Ext.os.name # analytics?.page 'Map' # END OF CUSTOMER APP ONLY navigator.splashscreen?.hide() if util.ctl('Account').hasPushNotificationsSetup() # this is just a re-registering locally, not an initial setup # we don't want to do the initial setup because they may not be # logged in setTimeout (Ext.bind @setUpPushNotifications, this), 4000 @checkGoogleMaps() document.addEventListener("resume", (Ext.bind @onResume, this), false) @locationNotification = 0 @androidHighAccuracyNotificationActive = false if window.queuedDeepLinkUrl? util.handleDeepLinkUrl window.queuedDeepLinkUrl window.queuedDeepLinkUrl = null onResume: -> if util.ctl('Account').isCourier() and Ext.os.name is "iOS" cordova.plugins.diagnostic?.getLocationAuthorizationStatus( ((status) => if status isnt "authorized_always" and @locationNotification < 3 util.alert "Please make sure that the app's Location settings on your device is set to 'Always'.", 'Warning', (->) @locationNotification++ ), (=> console.log "Error getting location authorization status") ) if util.ctl('Account').isUserLoggedIn() # this is causing it to happen very often, probably want to change that # so it only happens when there is a change in user's settings @setUpPushNotifications() util.ctl('Orders').refreshOrdersAndOrdersList() @updateLatlng() checkGoogleMaps: -> if not google?.maps? currentDate = new Date() today = "#{currentDate.getMonth()}/#{currentDate.getDate()}/#{currentDate.getFullYear()}" localStorage['reloadAttempts'] ?= '0' if not localStorage['currentDate']? or today isnt localStorage['currentDate'] localStorage['currentDate'] = today localStorage['reloadAttempts'] = '0' analytics?.track 'Google Maps Failed to Load' if localStorage['reloadAttempts'] isnt '3' localStorage['reloadAttempts'] = (parseInt(localStorage['reloadAttempts']) + 1).toString() navigator.splashscreen?.show() window.location.reload() else util.confirm( 'Connection Problem', """ Please try restarting the application. If the problem persists, contact <EMAIL>. """, (-> navigator.splashscreen.show() window.location.reload()), null, 'Reload', 'Ignore' ) setUpPushNotifications: (alertIfDisabled) -> if Ext.os.name is "iOS" or Ext.os.name is "Android" if alertIfDisabled @pushNotificationEnabled = false setTimeout (=> if not @pushNotificationEnabled navigator.notification.alert 'Your push notifications are turned off. If you want to receive order updates, you can turn them on in your phone settings.', (->), "Reminder" ), 1500 pushPlugin = PushNotification.init ios: alert: true badge: true sound: true android: senderID: util.GCM_SENDER_ID pushPlugin.on 'registration', (data) => @registerDeviceForPushNotifications( data.registrationId, (if Ext.os.name is "iOS" then "apns" else "gcm") ) pushPlugin.on 'notification', (data) => util.alert data.message, "Notification", (->) util.ctl('Orders').loadOrdersList( true, util.ctl('Orders').refreshOrder ) pushPlugin.on 'error', (e) => if VERSION is "LOCAL" or VERSION is "DEV" alert e.message else #chrome/testing @pushNotificationEnabled = true # This is happening pretty often: initial setup and then any app start # and logins. Need to look into this later. I want to make sure it is # registered but I don't think we need to call add-sns ajax so often. registerDeviceForPushNotifications: (cred, pushPlatform = "apns") -> @pushNotificationEnabled = true # cred for APNS (apple) is the device token # for GCM (android) it is regid Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/add-sns" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['<KEY>Token'] cred: cred push_platform: pushPlatform headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserHasPushNotificationsSetUp'] = "true" else util.alert response.message, "Error", (->) failure: (response_obj) -> console.log response_obj checkAndroidLocationSettings: -> if Ext.os.name is 'Android' if util.ctl('Account').isCourier() or @locationNotification < 1 cordova.plugins.diagnostic?.getLocationMode( ((locationMode) => if locationMode isnt 'high_accuracy' and @androidHighAccuracyNotificationActive is false @androidHighAccuracyNotificationActive = true cordova.plugins.locationAccuracy.request( (=> @androidHighAccuracyNotificationActive = false window.location.reload()), (=> @androidHighAccuracyNotificationActive = false if not util.ctl('Account').isCourier() @centerUsingIpAddress() util.alert "Certain features of the application may not work properly. Please restart the application and enable high accuracy to use all the features.", "Location Settings", (->) ), cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY ) @locationNotification++ ), (=> console.log 'Diagnostics plugin error') ) updateLatlng: -> @checkAndroidLocationSettings() @updateLatlngBusy ?= no if not @updateLatlngBusy @updateLatlngBusy = yes navigator.geolocation?.getCurrentPosition( ((position) => @positionAccuracy = position.coords.accuracy @geolocationAllowed = true @lat = position.coords.latitude @lng = position.coords.longitude if not @mapInitiallyCenteredYet and @mapInited @mapInitiallyCenteredYet = true @recenterAtUserLoc() @updateLatlngBusy = no ), (=> # console.log "GPS failure callback called" if not @geolocationAllowed? or @geolocationAllowed is true @centerUsingIpAddress() @geolocationAllowed = false if not localStorage['gps_not_allowed_event_sent']? analytics?.track 'GPS Not Allowed' localStorage['gps_not_allowed_event_sent'] = 'yes' @updateLatlngBusy = no), {maximumAge: 0, enableHighAccuracy: true} ) centerUsingIpAddress: -> # This works but cannot be used for commercial purposes unless we pay for it. Currently exploring other options. # Ext.Ajax.request # url: "http://ip-api.com/json" # headers: # 'Content-Type': 'application/json' # timeout: 5000 # method: 'GET' # scope: this # success: (response_obj) -> # response = Ext.JSON.decode response_obj.responseText # @getMap().getMap().setCenter( # new google.maps.LatLng response.lat, response.lon # ) # failure: (response_obj) -> @getMap().getMap().setCenter( new google.maps.LatLng 34.0507177, -118.43757779999999 ) initGeocoder: -> # this is called on maprender, so let's make sure we have user loc centered @updateLatlng() if google? and google.maps? and @getMap()? @geocoder = new google.maps.Geocoder() @placesService = new google.maps.places.PlacesService @getMap().getMap() @mapInited = true else util.alert "Internet connection problem. Please try closing the app and restarting it.", "Connection Error", (->) dragStart: -> @lastDragStart = new Date().getTime() / 1000 @getRequestGasButton().setDisabled yes @getCenterMapButton().hide() boundChanged: -> @getRequestGasButton().setDisabled yes idle: -> currentTime = new Date().getTime() / 1000 if currentTime - @lastDragStart > 0.3 @getCenterMapButton().show() adjustDeliveryLocByLatLng: -> center = @getMap().getMap().getCenter() # might want to send actual @deliveryLocLat = center.lat() @deliveryLocLng = center.lng() @updateDeliveryLocAddressByLatLng @deliveryLocLat, @deliveryLocLng updateMapWithAddressComponents: (address) -> @deliveryAddressZipCode = null if address[0]?['address_components']? addressComponents = address[0]['address_components'] streetAddress = "#{addressComponents[0]['short_name']} #{addressComponents[1]['short_name']}" @getRequestAddressField().setValue streetAddress # find the address component that contains the zip code for c in addressComponents for t in c.types if t is "postal_code" @deliveryAddressZipCode = c['short_name'] if not localStorage['gps_not_allowed_event_sent'] and not localStorage['first_launch_loc_sent']? # this means that this is the zip code of the location # where they first launched the app and they allowed GPS analytics?.track 'First Launch Location', street_address: streetAddress zip_code: @deliveryAddressZipCode localStorage['first_launch_loc_sent'] = 'yes' @busyGettingGasPrice ?= no if not @busyGettingGasPrice @busyGettingGasPrice = yes Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}dispatch/gas-prices" params: Ext.JSON.encode version: util.VERSION_NUMBER zip_code: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> @getRequestGasButton().setDisabled no response = Ext.JSON.decode response_obj.responseText if response.success prices = response.gas_prices Ext.get('gas-price-unavailable').setStyle {display: 'none'} Ext.get('gas-price-display').setStyle {display: 'block'} Ext.get('gas-price-display-87').setText( "$#{util.centsToDollars prices["87"]}" ) Ext.get('gas-price-display-91').setText( "$#{util.centsToDollars prices["91"]}" ) else Ext.get('gas-price-display').setStyle {display: 'none'} Ext.get('gas-price-unavailable').setStyle {display: 'block'} Ext.get('gas-price-unavailable').setText( response.message ) @busyGettingGasPrice = no failure: (response_obj) -> @busyGettingGasPrice = no if not @deliveryAddressZipCode @adjustDeliveryLocByLatLng() updateDeliveryLocAddressByLatLng: (lat, lng) -> if @bypassUpdateDeliveryLocAddressByLatLng? and @bypassUpdateDeliveryLocAddressByLatLng @bypassUpdateDeliveryLocAddressByLatLng = false return else latlng = new google.maps.LatLng lat, lng @geocoder?.geocode {'latLng': latlng}, (results, status) => if @geocodeTimeout? clearTimeout @geocodeTimeout @geocodeTimeout = null if status is google.maps.GeocoderStatus.OK if not @getMap().isHidden() @updateMapWithAddressComponents(results) else @geocodeTimeout = setTimeout (=> @updateDeliveryLocAddressByLatLng lat, lng ), 1000 mapMode: -> if @getMap().isHidden() @hideAllSavedLoc() @getMap().show() @getCenterMapButton().show() @getSpacerBetweenMapAndAddress().show() @getGasPriceMapDisplay().show() @getRequestGasButtonContainer().show() @getRequestAddressField().disable() @getRequestAddressField().setValue("Updating Location...") analytics?.page 'Map' recenterAtUserLoc: (showAlertIfUnavailable = false, centerMapButtonPressed = false) -> if centerMapButtonPressed Ext.Viewport.setMasked xtype: 'loadmask' message: '' navigator.geolocation?.getCurrentPosition( ((position) => @lat = position.coords.latitude @lng = position.coords.longitude @getMap().getMap().setCenter( new google.maps.LatLng @lat, @lng ) Ext.Viewport.setMasked false ), (=> Ext.Viewport.setMasked false if showAlertIfUnavailable util.alert "To use the current location button, please allow geolocation for Purple in your phone's settings.", "Current Location Unavailable", (->) ), {maximumAge: 0, enableHighAccuracy: true} ) else @getMap().getMap().setCenter( new google.maps.LatLng @lat, @lng ) addressInputMode: -> if not @getMap().isHidden() @addressInputSubMode = '' @hideAllSavedLoc() @getMap().hide() @getSpacerBetweenMapAndAddress().hide() @getGasPriceMapDisplay().hide() @getRequestGasButtonContainer().hide() @getAutocompleteList().show() @getRequestAddressField().enable() @getRequestAddressField().focus() @showSavedLoc() util.ctl('Menu').pushOntoBackButton => @recenterAtUserLoc() @mapMode() ga_storage._trackEvent 'ui', 'Address Text Input Mode' analytics?.page 'Address Text Input Mode' editSavedLoc: -> @addressInputSubMode = '' @hideAllSavedLoc() @getAutocompleteList().show() @showSavedLoc() util.ctl('Menu').pushOntoBackButton => @recenterAtUserLoc() @mapMode() showSavedLoc: -> if localStorage['purpleUserHomeLocationName'] @getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) @getHomeAddressContainer().show() else @getAddHomeAddressContainer().show() if localStorage['purpleUserWorkLocationName'] @getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) @getWorkAddressContainer().show() else @getAddWorkAddressContainer().show() showTitles: (location) -> if @addressInputSubMode is 'home' if localStorage['purpleUserHomeLocationName'] @getRequestAddressField().setValue('Change Home Address...') else @getRequestAddressField().setValue('Add Home Address...') else if @addressInputSubMode is 'work' if localStorage['purpleUserWorkLocationName'] @getRequestAddressField().setValue('Edit Work Address...') else @getRequestAddressField().setValue('Add Work Address...') removeAddress: -> @updateSavedLocations { home: if @addressInputSubMode is 'home' displayText: '' googlePlaceId: '' else displayText: localStorage['purpleUserHomeLocationName'] googlePlaceId: localStorage['purpleUserHomePlaceId'] work: if @addressInputSubMode is 'work' displayText: '' googlePlaceId: '' else displayText: localStorage['purpleUserWorkLocationName'] googlePlaceId: localStorage['purpleUserWorkPlaceId'] }, -> util.ctl('Main').editSavedLoc() util.ctl('Menu').popOffBackButtonWithoutAction() util.ctl('Menu').popOffBackButtonWithoutAction() showRemoveButtons: (location) -> if @addressInputSubMode is 'home' and localStorage['purpleUserHomeLocationName'] @getRemoveHomeAddressContainer().show() if @addressInputSubMode is 'work' and localStorage['purpleUserWorkLocationName'] @getRemoveWorkAddressContainer().show() hideAllSavedLoc: -> @getAddWorkAddressContainer().hide() @getAddHomeAddressContainer().hide() @getAutocompleteList().hide() @getHomeAddressContainer().hide() @getWorkAddressContainer().hide() @getRemoveHomeAddressContainer().hide() @getRemoveWorkAddressContainer().hide() @getCenterMapButton().hide() @getRequestAddressField().setValue('') editAddressInputMode: -> @hideAllSavedLoc() @getAutocompleteList().show() @showRemoveButtons() @showTitles() util.ctl('Menu').pushOntoBackButton => @editSavedLoc() util.ctl('Menu').popOffBackButtonWithoutAction() generateSuggestions: -> @getRequestGasButton().setDisabled yes request = input: @getRequestAddressField().getValue() @placesAutocompleteService ?= new google.maps.places.AutocompleteService() @placesAutocompleteService.getPlacePredictions request, @populateAutocompleteList populateAutocompleteList: (predictions, status) -> if status is 'OK' suggestions = new Array() for p in predictions isAddress = p.terms[0].value is ""+parseInt(p.terms[0].value) locationName = if isAddress then p.terms[0].value + " " + p.terms[1]?.value else p.terms[0].value suggestions.push 'locationName': locationName 'locationVicinity': p.description.replace locationName+', ', '' 'locationLat': '0' 'locationLng': '0' 'placeId': p.place_id util.ctl('Main').getAutocompleteList().getStore().setData suggestions updateDeliveryLocAddressByLocArray: (loc) -> @mapMode() @getRequestAddressField().setValue loc['locationName'] util.ctl('Menu').clearBackButtonStack() # set latlng to zero just in case they press request gas before this func is # done. we don't want an old latlng to be in there that doesn't match address @deliveryLocLat = 0 @deliveryLocLng = 0 @placesService.getDetails {placeId: loc['placeId']}, (place, status) => if status is google.maps.places.PlacesServiceStatus.OK latlng = place.geometry.location # find the address component that contains the zip code for c in place.address_components for t in c.types if t is "postal_code" @deliveryAddressZipCode = c['short_name'] @deliveryLocLat = latlng.lat() @deliveryLocLng = latlng.lng() @bypassUpdateDeliveryLocAddressByLatLng = true @getMap().getMap().setCenter latlng @updateMapWithAddressComponents([place]) @getMap().getMap().setZoom 17 # else # console.log 'placesService error' + status handleAutoCompleteListTap: (loc) -> @loc = loc if @addressInputSubMode @updateAddress() @updateDeliveryLocAddressByLocArray loc changeHomeAddress: -> @addressInputSubMode = 'home' @editAddressInputMode() changeWorkAddress: -> @addressInputSubMode = 'work' @editAddressInputMode() updateAddress: -> if @addressInputSubMode is 'home' @updateSavedLocations { home: displayText: @loc['locationName'] googlePlaceId: @loc['placeId'] work: if localStorage['purpleUserWorkLocationName'] displayText: localStorage['purpleUserWorkLocationName'] googlePlaceId: localStorage['purpleUserWorkPlaceId'] else displayText: '' googlePlaceId: '' }, -> util.ctl('Main').getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) if @addressInputSubMode is 'work' @updateSavedLocations { home: if localStorage['purpleUserHomeLocationName'] displayText: localStorage['purpleUserHomeLocationName'] googlePlaceId: localStorage['purpleUserHomePlaceId'] else displayText: '' googlePlaceId: '' work: displayText: @loc['locationName'] googlePlaceId: @loc['placeId'] }, -> util.ctl('Main').getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) initAccountHomeAddress: (field) -> @getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) field.element.on 'tap', @searchHome, this initAccountWorkAddress: (field) -> @getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) field.element.on 'tap', @searchWork, this initAddWorkAddress: (field) -> field.element.on 'tap', @changeWorkAddress, this initAddHomeAddress: (field) -> field.element.on 'tap', @changeHomeAddress, this initRemoveHomeAddress: (field) -> field.element.on 'tap', @removeAddress, this initRemoveWorkAddress: (field) -> field.element.on 'tap', @removeAddress, this currentLocation: (locationName, placeId) -> {locationName: locationName, placeId: placeId} searchHome: -> @updateDeliveryLocAddressByLocArray @currentLocation(localStorage['purpleUserHomeLocationName'], localStorage['purpleUserHomePlaceId']) searchWork: -> @updateDeliveryLocAddressByLocArray @currentLocation(localStorage['purpleUserWorkLocationName'], localStorage['purpleUserWorkPlaceId']) updateSavedLocations: (savedLocations, callback) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['<KEY>'] saved_locations: savedLocations headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserHomeLocationName'] = response.saved_locations.home.displayText localStorage['purpleUserHomePlaceId'] = response.saved_locations.home.googlePlaceId localStorage['purpleUserWorkLocationName'] = response.saved_locations.work.displayText localStorage['purpleUserWorkPlaceId'] = response.saved_locations.work.googlePlaceId callback?() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response showLogin: -> @getMainContainer().getItems().getAt(0).select 1, no, no initRequestAddressField: (textField) -> textField.element.on 'tap', => if util.ctl('Account').isUserLoggedIn() textField.setValue '' @addressInputMode() else @showLogin() true keyupRequestAddressField: (textField, event) -> textField.lastQuery ?= '' query = textField.getValue() if query isnt textField.lastQuery and query isnt '' textField.lastQuery = query if textField.genSuggTimeout? clearTimeout textField.genSuggTimeout textField.genSuggTimeout = setTimeout( @generateSuggestions(), 500 ) true focusRequestAddressField: -> @getRequestAddressField().setValue '' requestGasButtonPressed: -> deliveryLocName = @getRequestAddressField().getValue() ga_storage._trackEvent 'ui', 'Request Gas Button Pressed' analytics?.track 'Request Gas Button Pressed', address_street: deliveryLocName lat: @deliveryLocLat lng: @deliveryLocLng zip: @deliveryAddressZipCode if deliveryLocName is @getRequestAddressField().getInitialConfig().value return # just return, it hasn't loaded the location yet if not (util.ctl('Account').isUserLoggedIn() and util.ctl('Account').isCompleteAccount()) # select the Login view @showLogin() else if ( not localStorage['purpleSubscriptionId']? or localStorage['purpleSubscriptionId'] is '0' ) and ( not localStorage['purpleAdShownTimesSubscription']? or parseInt(localStorage['purpleAdShownTimesSubscription']) < 2 ) and ( Ext.os.is.Android or Ext.os.is.iOS ) and not util.ctl('Account').isManagedAccount() localStorage['purpleAdShownTimesSubscription'] ?= 0 localStorage['purpleAdShownTimesSubscription'] = ( parseInt(localStorage['purpleAdShownTimesSubscription']) + 1 ) util.ctl('Subscriptions').showAd( (=> # pass-thru callback @initRequestGasForm deliveryLocName ) (=> # active callback @getMainContainer().getItems().getAt(0).select 2, no, no util.ctl('Subscriptions').subscriptionsFieldTap() ) ) else @initRequestGasForm deliveryLocName initRequestGasForm: (deliveryLocName) -> # send to request gas form # but first get availbility from disptach system on app service Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}dispatch/availability" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] lat: @deliveryLocLat lng: @deliveryLocLng zip_code: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionLocalStorageData response util.ctl('Subscriptions').subscriptionUsage = response.user.subscription_usage availabilities = response.availabilities totalNumOfTimeOptions = availabilities.reduce (a, b) -> Object.keys(a.times).length + Object.keys(b.times).length if util.isEmpty(availabilities[0].gallon_choices) and util.isEmpty(availabilities[1].gallon_choices) or totalNumOfTimeOptions is 0 util.alert response["unavailable-reason"], "Unavailable", (->) else util.ctl('Menu').pushOntoBackButton => @backToMapFromRequestForm() @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.RequestForm', availabilities: availabilities ) @getRequestForm().setValues lat: @deliveryLocLat lng: @deliveryLocLng address_street: deliveryLocName address_zip: @deliveryAddressZipCode analytics?.page 'Order Form' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj backToMapFromRequestForm: -> @getRequestGasTabContainer().remove( @getRequestForm(), yes ) backToRequestForm: -> @getRequestGasTabContainer().setActiveItem @getRequestForm() @getRequestGasTabContainer().remove( @getRequestConfirmationForm(), yes ) sendRequest: -> # takes you to the confirmation page @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.RequestConfirmationForm' ) util.ctl('Menu').pushOntoBackButton => @backToRequestForm() vals = @getRequestForm().getValues() availabilities = @getRequestForm().config.availabilities gasType = util.ctl('Vehicles').getVehicleById(vals['vehicle']).gas_type for a in availabilities if a['octane'] is gasType availability = a break vals['gas_type'] = "" + availability.octane # should already be string though vals['gas_type_display'] = "Unleaded #{vals['gas_type']} Octane" gasPrice = availability.price_per_gallon serviceFee = ( availability.times[vals['time']]['service_fee'] + (parseInt(vals['tire_pressure_check_price']) * vals['tire_pressure_check']) ) vals['gas_price'] = "" + util.centsToDollars( gasPrice ) vals['gas_price_display'] = "$#{vals['gas_price']} x #{vals['gallons']}" vals['service_fee'] = "" + util.centsToDollars( serviceFee ) freeGallonsAvailable = parseFloat localStorage['purpleUserReferralGallons'] gallonsToSubtract = 0 if freeGallonsAvailable is 0 @getFreeGasField().hide() else # apply as much free gas as possible gallonsToSubtract = Math.min vals['gallons'], freeGallonsAvailable @getFreeGasField().setValue "- $#{vals['gas_price']} x #{gallonsToSubtract}" # it's called unaltered because it doesn't have a coupon code applied @unalteredTotalPrice = ( parseFloat(gasPrice) * (parseFloat(vals['gallons']) - gallonsToSubtract) + parseFloat(serviceFee) ) vals['total_price'] = "" + util.centsToDollars @unalteredTotalPrice vals['display_time'] = availability.times[vals['time']]['text'] vals['vehicle_id'] = vals['vehicle'] for v in util.ctl('Vehicles').vehicles if v['id'] is vals['vehicle_id'] vals['vehicle'] = "#{v.year} #{v.make} #{v.model}" break @getRequestConfirmationForm().setValues vals if not vals['tire_pressure_check'] Ext.ComponentQuery.query('#tirePressureCheckField')[0].hide() # Ext.ComponentQuery.query('#addressStreetConfirmation')[0].removeCls 'bottom-margin' if vals['special_instructions'] is '' Ext.ComponentQuery.query('#specialInstructionsConfirmationLabel')[0].hide() Ext.ComponentQuery.query('#specialInstructionsConfirmation')[0].hide() Ext.ComponentQuery.query('#addressStreetConfirmation')[0].removeCls 'bottom-margin' else Ext.ComponentQuery.query('#specialInstructionsConfirmation')[0].setHtml(vals['special_instructions']) analytics?.page 'Review Order' promptForCode: -> Ext.Msg.prompt( 'Enter Coupon Code', false, ((buttonId, text) => if buttonId is 'ok' @applyCode text Ext.select('.x-msgbox .x-input-el').setStyle('text-transform', 'none') ) ) applyCode: (code) -> vals = @getRequestConfirmationForm().getValues() vehicleId = vals['vehicle_id'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/code" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] vehicle_id: vehicleId code: code address_zip: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText analytics?.track 'Tried Coupon Code', valid: response.success coupon_code: code.toUpperCase() if response.success @getDiscountField().setValue( "- $" + util.centsToDollars(Math.abs(response.value)) ) @getCouponCodeField().setValue code totalPrice = Math.max( @unalteredTotalPrice + response.value, 0 ) @getTotalPriceField().setValue "" + util.centsToDollars(totalPrice) else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response confirmOrder: -> if not util.ctl('Account').hasDefaultPaymentMethod() and not util.ctl('Account').isManagedAccount() # select the Account view @getMainContainer().getItems().getAt(0).select 2, no, no pmCtl = util.ctl('PaymentMethods') if not pmCtl.getPaymentMethods()? pmCtl.paymentMethodFieldTap yes pmCtl.showEditPaymentMethodForm 'new', yes util.ctl('Menu').pushOntoBackButton -> pmCtl.backToPreviousPage() util.ctl('Menu').selectOption 0 pmCtl.getEditPaymentMethodForm().config.saveChangesCallback = -> pmCtl.backToPreviousPage() util.ctl('Menu').selectOption 0 else vals = @getRequestConfirmationForm().getValues() # prices are finally given in cents vals['gas_price'] = parseInt( vals['gas_price'].replace('$','').replace('.','') ) vals['service_fee'] = parseInt( vals['service_fee'].replace('$','').replace('.','') ) vals['total_price'] = parseInt( vals['total_price'].replace('$','').replace('.','') ) Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/add" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] order: vals headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['specialInstructions'] = vals['special_instructions'] util.ctl('Vehicles').specialInstructionsAutoFillPrompted = false util.ctl('Menu').selectOption 3 # Orders tab util.ctl('Orders').loadOrdersList yes @getRequestGasTabContainer().setActiveItem @getMapForm() @getRequestGasTabContainer().remove( @getRequestConfirmationForm(), yes ) @getRequestGasTabContainer().remove( @getRequestForm(), yes ) util.ctl('Menu').clearBackButtonStack() util.alert response.message, (response.message_title ? "Success"), (->) # set up push notifications if they arent set up # NOTE: This will matter less and less, now that we set up push # notifications when a user creates their account. But it's nice to # keep this here for existing users that have never ordered and # don't logout and login (which would also cause a setup) @setUpPushNotifications true else util.alert response.message, (response.message_title ? "Error"), (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response sendFeedback: -> params = version: util.VERSION_NUMBER text: @getFeedbackTextField().getValue() if util.ctl('Account').isUserLoggedIn() params['user_id'] = localStorage['purpleUserId'] params['token'] = localStorage['purpleToken'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}feedback/send" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getFeedbackTextField().setValue '' util.flashComponent @getFeedbackThankYouMessage() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response # this is legacy code? sendInvites: -> params = version: util.VERSION_NUMBER email: @getInviteTextField().getValue() if util.ctl('Account').isUserLoggedIn() params['user_id'] = localStorage['purpleUserId'] params['token'] = localStorage['purpleToken'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}invite/send" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getInviteTextField().setValue '' util.flashComponent @getInviteThankYouMessage() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response initCourierPing: -> window.plugin?.backgroundMode.enable() @gpsIntervalRef ?= setInterval (Ext.bind @updateLatlng, this), 5000 @courierPingIntervalRef ?= setInterval (Ext.bind @courierPing, this), 10000 killCourierPing: -> if @gpsIntervalRef? clearInterval @gpsIntervalRef @gpsIntervalRef = null if @courierPingIntervalRef? clearInterval @courierPingIntervalRef @courierPingIntervalRef = null courierPing: (setOnDuty, successCallback, failureCallback) -> @courierPingBusy ?= no if @courierPingBusy and setOnDuty? setTimeout (=> @courierPing setOnDuty, successCallback, failureCallback ), 11000 else @courierPingBusy = yes params = version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['<KEY>'] lat: @lat lng: @lng gallons: 87: localStorage['purpleCourierGallons87'] 91: localStorage['purpleCourierGallons91'] position_accuracy: @positionAccuracy if setOnDuty? params.set_on_duty = setOnDuty Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}courier/ping" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 10000 method: 'POST' scope: this success: (response_obj) -> @courierPingBusy = no response = Ext.JSON.decode response_obj.responseText if response.success if @disconnectedMessage? clearTimeout @disconnectedMessage Ext.get(document.getElementsByTagName('body')[0]).removeCls 'disconnected' @disconnectedMessage = setTimeout (-> if localStorage['courierOnDuty'] is 'yes' Ext.get(document.getElementsByTagName('body')[0]).addCls 'disconnected' ), (2 * 60 * 1000) if (response.on_duty and localStorage['courierOnDuty'] is 'no') or (not response.on_duty and localStorage['courierOnDuty'] is 'yes') localStorage['courierOnDuty'] = if response.on_duty then 'yes' else 'no' util.ctl('Menu').updateOnDutyToggle() successCallback?() else failureCallback?() util.alert response.message, (response.message_title ? "Error"), (->) failure: (response_obj) -> @courierPingBusy = no failureCallback?()
true
Ext.define 'Purple.controller.Main', extend: 'Ext.app.Controller' config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' loginForm: 'loginform' requestGasTabContainer: '#requestGasTabContainer' mapForm: 'mapform' map: '#gmap' spacerBetweenMapAndAddress: '#spacerBetweenMapAndAddress' gasPriceMapDisplay: '#gasPriceMapDisplay' requestAddressField: '#requestAddressField' requestGasButtonContainer: '#requestGasButtonContainer' requestGasButton: '#requestGasButton' autocompleteList: '#autocompleteList' requestForm: 'requestform' requestFormTirePressureCheck: '[ctype=requestFormTirePressureCheck]' requestConfirmationForm: 'requestconfirmationform' feedback: 'feedback' feedbackTextField: '[ctype=feedbackTextField]' feedbackThankYouMessage: '[ctype=feedbackThankYouMessage]' invite: 'invite' inviteTextField: '[ctype=inviteTextField]' inviteThankYouMessage: '[ctype=inviteThankYouMessage]' freeGasField: '#freeGasField' discountField: '#discountField' couponCodeField: '#couponCodeField' totalPriceField: '#totalPriceField' homeAddressContainer: '#homeAddressContainer' workAddressContainer: '#workAddressContainer' accountHomeAddress: '#accountHomeAddress' accountWorkAddress: '#accountWorkAddress' addHomeAddressContainer: '#addHomeAddressContainer' addWorkAddressContainer: '#addWorkAddressContainer' addHomeAddress: '#addHomeAddress' addWorkAddress: '#addWorkAddress' removeHomeAddressContainer: '#removeHomeAddressContainer' removeWorkAddressContainer: '#removeWorkAddressContainer' removeHomeAddress: '#removeHomeAddress' removeWorkAddress: '#removeWorkAddress' centerMapButton: '#centerMapButton' control: mapForm: recenterAtUserLoc: 'recenterAtUserLoc' changeHomeAddress: 'changeHomeAddress' changeWorkAddress: 'changeWorkAddress' map: dragstart: 'dragStart' boundchange: 'boundChanged' idle: 'idle' centerchange: 'adjustDeliveryLocByLatLng' maprender: 'initGeocoder' requestAddressField: generateSuggestions: 'generateSuggestions' addressInputMode: 'addressInputMode' showLogin: 'showLogin' initialize: 'initRequestAddressField' keyup: 'keyupRequestAddressField' focus: 'focusRequestAddressField' autocompleteList: handleAutoCompleteListTap: 'handleAutoCompleteListTap' requestGasButtonContainer: initRequestGasForm: 'requestGasButtonPressed' requestForm: backToMap: 'backToMapFromRequestForm' sendRequest: 'sendRequest' requestFormTirePressureCheck: requestFormTirePressureCheckTap: 'requestFormTirePressureCheckTap' requestConfirmationForm: backToRequestForm: 'backToRequestForm' confirmOrder: 'confirmOrder' feedback: sendFeedback: 'sendFeedback' invite: sendInvites: 'sendInvites' accountHomeAddress: initialize: 'initAccountHomeAddress' accountWorkAddress: initialize: 'initAccountWorkAddress' addHomeAddress: initialize: 'initAddHomeAddress' addWorkAddress: initialize: 'initAddWorkAddress' removeHomeAddress: initialize: 'initRemoveHomeAddress' removeWorkAddress: initialize: 'initRemoveWorkAddress' # whether or not the inital map centering has occurred yet mapInitiallyCenteredYet: no mapInited: no # only used if logged in as courier courierPingIntervalRef: null launch: -> @callParent arguments localStorage['lastCacheVersionNumber'] = util.VERSION_NUMBER # COURIER APP ONLY # Remember to comment/uncomment the setTimeout script in index.html if not localStorage['courierOnDuty']? then localStorage['courierOnDuty'] = 'no' clearTimeout window.courierReloadTimer # END COURIER APP ONLY if util.ctl('Account').isCourier() @initCourierPing() # CUSTOMER APP ONLY # if VERSION is "PROD" # GappTrack.track "882234091", "CVvTCNCIkGcQ66XXpAM", "4.00", false # ga_storage?._enableSSL() # doesn't seem to actually use SSL? # ga_storage?._setAccount 'UA-61762011-1' # ga_storage?._setDomain 'none' # ga_storage?._trackEvent 'main', 'App Launch', "Platform: #{Ext.os.name}" # analytics?.load util.SEGMENT_WRITE_KEY # if util.ctl('Account').isUserLoggedIn() # analytics?.identify localStorage['purpleUserId'] # # segment says you 'have' to call analytics.page() at some point # # it doesn't seem to actually matter though # analytics?.track 'App Launch', # platform: Ext.os.name # analytics?.page 'Map' # END OF CUSTOMER APP ONLY navigator.splashscreen?.hide() if util.ctl('Account').hasPushNotificationsSetup() # this is just a re-registering locally, not an initial setup # we don't want to do the initial setup because they may not be # logged in setTimeout (Ext.bind @setUpPushNotifications, this), 4000 @checkGoogleMaps() document.addEventListener("resume", (Ext.bind @onResume, this), false) @locationNotification = 0 @androidHighAccuracyNotificationActive = false if window.queuedDeepLinkUrl? util.handleDeepLinkUrl window.queuedDeepLinkUrl window.queuedDeepLinkUrl = null onResume: -> if util.ctl('Account').isCourier() and Ext.os.name is "iOS" cordova.plugins.diagnostic?.getLocationAuthorizationStatus( ((status) => if status isnt "authorized_always" and @locationNotification < 3 util.alert "Please make sure that the app's Location settings on your device is set to 'Always'.", 'Warning', (->) @locationNotification++ ), (=> console.log "Error getting location authorization status") ) if util.ctl('Account').isUserLoggedIn() # this is causing it to happen very often, probably want to change that # so it only happens when there is a change in user's settings @setUpPushNotifications() util.ctl('Orders').refreshOrdersAndOrdersList() @updateLatlng() checkGoogleMaps: -> if not google?.maps? currentDate = new Date() today = "#{currentDate.getMonth()}/#{currentDate.getDate()}/#{currentDate.getFullYear()}" localStorage['reloadAttempts'] ?= '0' if not localStorage['currentDate']? or today isnt localStorage['currentDate'] localStorage['currentDate'] = today localStorage['reloadAttempts'] = '0' analytics?.track 'Google Maps Failed to Load' if localStorage['reloadAttempts'] isnt '3' localStorage['reloadAttempts'] = (parseInt(localStorage['reloadAttempts']) + 1).toString() navigator.splashscreen?.show() window.location.reload() else util.confirm( 'Connection Problem', """ Please try restarting the application. If the problem persists, contact PI:EMAIL:<EMAIL>END_PI. """, (-> navigator.splashscreen.show() window.location.reload()), null, 'Reload', 'Ignore' ) setUpPushNotifications: (alertIfDisabled) -> if Ext.os.name is "iOS" or Ext.os.name is "Android" if alertIfDisabled @pushNotificationEnabled = false setTimeout (=> if not @pushNotificationEnabled navigator.notification.alert 'Your push notifications are turned off. If you want to receive order updates, you can turn them on in your phone settings.', (->), "Reminder" ), 1500 pushPlugin = PushNotification.init ios: alert: true badge: true sound: true android: senderID: util.GCM_SENDER_ID pushPlugin.on 'registration', (data) => @registerDeviceForPushNotifications( data.registrationId, (if Ext.os.name is "iOS" then "apns" else "gcm") ) pushPlugin.on 'notification', (data) => util.alert data.message, "Notification", (->) util.ctl('Orders').loadOrdersList( true, util.ctl('Orders').refreshOrder ) pushPlugin.on 'error', (e) => if VERSION is "LOCAL" or VERSION is "DEV" alert e.message else #chrome/testing @pushNotificationEnabled = true # This is happening pretty often: initial setup and then any app start # and logins. Need to look into this later. I want to make sure it is # registered but I don't think we need to call add-sns ajax so often. registerDeviceForPushNotifications: (cred, pushPlatform = "apns") -> @pushNotificationEnabled = true # cred for APNS (apple) is the device token # for GCM (android) it is regid Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/add-sns" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['PI:KEY:<KEY>END_PIToken'] cred: cred push_platform: pushPlatform headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserHasPushNotificationsSetUp'] = "true" else util.alert response.message, "Error", (->) failure: (response_obj) -> console.log response_obj checkAndroidLocationSettings: -> if Ext.os.name is 'Android' if util.ctl('Account').isCourier() or @locationNotification < 1 cordova.plugins.diagnostic?.getLocationMode( ((locationMode) => if locationMode isnt 'high_accuracy' and @androidHighAccuracyNotificationActive is false @androidHighAccuracyNotificationActive = true cordova.plugins.locationAccuracy.request( (=> @androidHighAccuracyNotificationActive = false window.location.reload()), (=> @androidHighAccuracyNotificationActive = false if not util.ctl('Account').isCourier() @centerUsingIpAddress() util.alert "Certain features of the application may not work properly. Please restart the application and enable high accuracy to use all the features.", "Location Settings", (->) ), cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY ) @locationNotification++ ), (=> console.log 'Diagnostics plugin error') ) updateLatlng: -> @checkAndroidLocationSettings() @updateLatlngBusy ?= no if not @updateLatlngBusy @updateLatlngBusy = yes navigator.geolocation?.getCurrentPosition( ((position) => @positionAccuracy = position.coords.accuracy @geolocationAllowed = true @lat = position.coords.latitude @lng = position.coords.longitude if not @mapInitiallyCenteredYet and @mapInited @mapInitiallyCenteredYet = true @recenterAtUserLoc() @updateLatlngBusy = no ), (=> # console.log "GPS failure callback called" if not @geolocationAllowed? or @geolocationAllowed is true @centerUsingIpAddress() @geolocationAllowed = false if not localStorage['gps_not_allowed_event_sent']? analytics?.track 'GPS Not Allowed' localStorage['gps_not_allowed_event_sent'] = 'yes' @updateLatlngBusy = no), {maximumAge: 0, enableHighAccuracy: true} ) centerUsingIpAddress: -> # This works but cannot be used for commercial purposes unless we pay for it. Currently exploring other options. # Ext.Ajax.request # url: "http://ip-api.com/json" # headers: # 'Content-Type': 'application/json' # timeout: 5000 # method: 'GET' # scope: this # success: (response_obj) -> # response = Ext.JSON.decode response_obj.responseText # @getMap().getMap().setCenter( # new google.maps.LatLng response.lat, response.lon # ) # failure: (response_obj) -> @getMap().getMap().setCenter( new google.maps.LatLng 34.0507177, -118.43757779999999 ) initGeocoder: -> # this is called on maprender, so let's make sure we have user loc centered @updateLatlng() if google? and google.maps? and @getMap()? @geocoder = new google.maps.Geocoder() @placesService = new google.maps.places.PlacesService @getMap().getMap() @mapInited = true else util.alert "Internet connection problem. Please try closing the app and restarting it.", "Connection Error", (->) dragStart: -> @lastDragStart = new Date().getTime() / 1000 @getRequestGasButton().setDisabled yes @getCenterMapButton().hide() boundChanged: -> @getRequestGasButton().setDisabled yes idle: -> currentTime = new Date().getTime() / 1000 if currentTime - @lastDragStart > 0.3 @getCenterMapButton().show() adjustDeliveryLocByLatLng: -> center = @getMap().getMap().getCenter() # might want to send actual @deliveryLocLat = center.lat() @deliveryLocLng = center.lng() @updateDeliveryLocAddressByLatLng @deliveryLocLat, @deliveryLocLng updateMapWithAddressComponents: (address) -> @deliveryAddressZipCode = null if address[0]?['address_components']? addressComponents = address[0]['address_components'] streetAddress = "#{addressComponents[0]['short_name']} #{addressComponents[1]['short_name']}" @getRequestAddressField().setValue streetAddress # find the address component that contains the zip code for c in addressComponents for t in c.types if t is "postal_code" @deliveryAddressZipCode = c['short_name'] if not localStorage['gps_not_allowed_event_sent'] and not localStorage['first_launch_loc_sent']? # this means that this is the zip code of the location # where they first launched the app and they allowed GPS analytics?.track 'First Launch Location', street_address: streetAddress zip_code: @deliveryAddressZipCode localStorage['first_launch_loc_sent'] = 'yes' @busyGettingGasPrice ?= no if not @busyGettingGasPrice @busyGettingGasPrice = yes Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}dispatch/gas-prices" params: Ext.JSON.encode version: util.VERSION_NUMBER zip_code: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> @getRequestGasButton().setDisabled no response = Ext.JSON.decode response_obj.responseText if response.success prices = response.gas_prices Ext.get('gas-price-unavailable').setStyle {display: 'none'} Ext.get('gas-price-display').setStyle {display: 'block'} Ext.get('gas-price-display-87').setText( "$#{util.centsToDollars prices["87"]}" ) Ext.get('gas-price-display-91').setText( "$#{util.centsToDollars prices["91"]}" ) else Ext.get('gas-price-display').setStyle {display: 'none'} Ext.get('gas-price-unavailable').setStyle {display: 'block'} Ext.get('gas-price-unavailable').setText( response.message ) @busyGettingGasPrice = no failure: (response_obj) -> @busyGettingGasPrice = no if not @deliveryAddressZipCode @adjustDeliveryLocByLatLng() updateDeliveryLocAddressByLatLng: (lat, lng) -> if @bypassUpdateDeliveryLocAddressByLatLng? and @bypassUpdateDeliveryLocAddressByLatLng @bypassUpdateDeliveryLocAddressByLatLng = false return else latlng = new google.maps.LatLng lat, lng @geocoder?.geocode {'latLng': latlng}, (results, status) => if @geocodeTimeout? clearTimeout @geocodeTimeout @geocodeTimeout = null if status is google.maps.GeocoderStatus.OK if not @getMap().isHidden() @updateMapWithAddressComponents(results) else @geocodeTimeout = setTimeout (=> @updateDeliveryLocAddressByLatLng lat, lng ), 1000 mapMode: -> if @getMap().isHidden() @hideAllSavedLoc() @getMap().show() @getCenterMapButton().show() @getSpacerBetweenMapAndAddress().show() @getGasPriceMapDisplay().show() @getRequestGasButtonContainer().show() @getRequestAddressField().disable() @getRequestAddressField().setValue("Updating Location...") analytics?.page 'Map' recenterAtUserLoc: (showAlertIfUnavailable = false, centerMapButtonPressed = false) -> if centerMapButtonPressed Ext.Viewport.setMasked xtype: 'loadmask' message: '' navigator.geolocation?.getCurrentPosition( ((position) => @lat = position.coords.latitude @lng = position.coords.longitude @getMap().getMap().setCenter( new google.maps.LatLng @lat, @lng ) Ext.Viewport.setMasked false ), (=> Ext.Viewport.setMasked false if showAlertIfUnavailable util.alert "To use the current location button, please allow geolocation for Purple in your phone's settings.", "Current Location Unavailable", (->) ), {maximumAge: 0, enableHighAccuracy: true} ) else @getMap().getMap().setCenter( new google.maps.LatLng @lat, @lng ) addressInputMode: -> if not @getMap().isHidden() @addressInputSubMode = '' @hideAllSavedLoc() @getMap().hide() @getSpacerBetweenMapAndAddress().hide() @getGasPriceMapDisplay().hide() @getRequestGasButtonContainer().hide() @getAutocompleteList().show() @getRequestAddressField().enable() @getRequestAddressField().focus() @showSavedLoc() util.ctl('Menu').pushOntoBackButton => @recenterAtUserLoc() @mapMode() ga_storage._trackEvent 'ui', 'Address Text Input Mode' analytics?.page 'Address Text Input Mode' editSavedLoc: -> @addressInputSubMode = '' @hideAllSavedLoc() @getAutocompleteList().show() @showSavedLoc() util.ctl('Menu').pushOntoBackButton => @recenterAtUserLoc() @mapMode() showSavedLoc: -> if localStorage['purpleUserHomeLocationName'] @getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) @getHomeAddressContainer().show() else @getAddHomeAddressContainer().show() if localStorage['purpleUserWorkLocationName'] @getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) @getWorkAddressContainer().show() else @getAddWorkAddressContainer().show() showTitles: (location) -> if @addressInputSubMode is 'home' if localStorage['purpleUserHomeLocationName'] @getRequestAddressField().setValue('Change Home Address...') else @getRequestAddressField().setValue('Add Home Address...') else if @addressInputSubMode is 'work' if localStorage['purpleUserWorkLocationName'] @getRequestAddressField().setValue('Edit Work Address...') else @getRequestAddressField().setValue('Add Work Address...') removeAddress: -> @updateSavedLocations { home: if @addressInputSubMode is 'home' displayText: '' googlePlaceId: '' else displayText: localStorage['purpleUserHomeLocationName'] googlePlaceId: localStorage['purpleUserHomePlaceId'] work: if @addressInputSubMode is 'work' displayText: '' googlePlaceId: '' else displayText: localStorage['purpleUserWorkLocationName'] googlePlaceId: localStorage['purpleUserWorkPlaceId'] }, -> util.ctl('Main').editSavedLoc() util.ctl('Menu').popOffBackButtonWithoutAction() util.ctl('Menu').popOffBackButtonWithoutAction() showRemoveButtons: (location) -> if @addressInputSubMode is 'home' and localStorage['purpleUserHomeLocationName'] @getRemoveHomeAddressContainer().show() if @addressInputSubMode is 'work' and localStorage['purpleUserWorkLocationName'] @getRemoveWorkAddressContainer().show() hideAllSavedLoc: -> @getAddWorkAddressContainer().hide() @getAddHomeAddressContainer().hide() @getAutocompleteList().hide() @getHomeAddressContainer().hide() @getWorkAddressContainer().hide() @getRemoveHomeAddressContainer().hide() @getRemoveWorkAddressContainer().hide() @getCenterMapButton().hide() @getRequestAddressField().setValue('') editAddressInputMode: -> @hideAllSavedLoc() @getAutocompleteList().show() @showRemoveButtons() @showTitles() util.ctl('Menu').pushOntoBackButton => @editSavedLoc() util.ctl('Menu').popOffBackButtonWithoutAction() generateSuggestions: -> @getRequestGasButton().setDisabled yes request = input: @getRequestAddressField().getValue() @placesAutocompleteService ?= new google.maps.places.AutocompleteService() @placesAutocompleteService.getPlacePredictions request, @populateAutocompleteList populateAutocompleteList: (predictions, status) -> if status is 'OK' suggestions = new Array() for p in predictions isAddress = p.terms[0].value is ""+parseInt(p.terms[0].value) locationName = if isAddress then p.terms[0].value + " " + p.terms[1]?.value else p.terms[0].value suggestions.push 'locationName': locationName 'locationVicinity': p.description.replace locationName+', ', '' 'locationLat': '0' 'locationLng': '0' 'placeId': p.place_id util.ctl('Main').getAutocompleteList().getStore().setData suggestions updateDeliveryLocAddressByLocArray: (loc) -> @mapMode() @getRequestAddressField().setValue loc['locationName'] util.ctl('Menu').clearBackButtonStack() # set latlng to zero just in case they press request gas before this func is # done. we don't want an old latlng to be in there that doesn't match address @deliveryLocLat = 0 @deliveryLocLng = 0 @placesService.getDetails {placeId: loc['placeId']}, (place, status) => if status is google.maps.places.PlacesServiceStatus.OK latlng = place.geometry.location # find the address component that contains the zip code for c in place.address_components for t in c.types if t is "postal_code" @deliveryAddressZipCode = c['short_name'] @deliveryLocLat = latlng.lat() @deliveryLocLng = latlng.lng() @bypassUpdateDeliveryLocAddressByLatLng = true @getMap().getMap().setCenter latlng @updateMapWithAddressComponents([place]) @getMap().getMap().setZoom 17 # else # console.log 'placesService error' + status handleAutoCompleteListTap: (loc) -> @loc = loc if @addressInputSubMode @updateAddress() @updateDeliveryLocAddressByLocArray loc changeHomeAddress: -> @addressInputSubMode = 'home' @editAddressInputMode() changeWorkAddress: -> @addressInputSubMode = 'work' @editAddressInputMode() updateAddress: -> if @addressInputSubMode is 'home' @updateSavedLocations { home: displayText: @loc['locationName'] googlePlaceId: @loc['placeId'] work: if localStorage['purpleUserWorkLocationName'] displayText: localStorage['purpleUserWorkLocationName'] googlePlaceId: localStorage['purpleUserWorkPlaceId'] else displayText: '' googlePlaceId: '' }, -> util.ctl('Main').getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) if @addressInputSubMode is 'work' @updateSavedLocations { home: if localStorage['purpleUserHomeLocationName'] displayText: localStorage['purpleUserHomeLocationName'] googlePlaceId: localStorage['purpleUserHomePlaceId'] else displayText: '' googlePlaceId: '' work: displayText: @loc['locationName'] googlePlaceId: @loc['placeId'] }, -> util.ctl('Main').getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) initAccountHomeAddress: (field) -> @getAccountHomeAddress().setValue(localStorage['purpleUserHomeLocationName']) field.element.on 'tap', @searchHome, this initAccountWorkAddress: (field) -> @getAccountWorkAddress().setValue(localStorage['purpleUserWorkLocationName']) field.element.on 'tap', @searchWork, this initAddWorkAddress: (field) -> field.element.on 'tap', @changeWorkAddress, this initAddHomeAddress: (field) -> field.element.on 'tap', @changeHomeAddress, this initRemoveHomeAddress: (field) -> field.element.on 'tap', @removeAddress, this initRemoveWorkAddress: (field) -> field.element.on 'tap', @removeAddress, this currentLocation: (locationName, placeId) -> {locationName: locationName, placeId: placeId} searchHome: -> @updateDeliveryLocAddressByLocArray @currentLocation(localStorage['purpleUserHomeLocationName'], localStorage['purpleUserHomePlaceId']) searchWork: -> @updateDeliveryLocAddressByLocArray @currentLocation(localStorage['purpleUserWorkLocationName'], localStorage['purpleUserWorkPlaceId']) updateSavedLocations: (savedLocations, callback) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['PI:KEY:<KEY>END_PI'] saved_locations: savedLocations headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserHomeLocationName'] = response.saved_locations.home.displayText localStorage['purpleUserHomePlaceId'] = response.saved_locations.home.googlePlaceId localStorage['purpleUserWorkLocationName'] = response.saved_locations.work.displayText localStorage['purpleUserWorkPlaceId'] = response.saved_locations.work.googlePlaceId callback?() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response showLogin: -> @getMainContainer().getItems().getAt(0).select 1, no, no initRequestAddressField: (textField) -> textField.element.on 'tap', => if util.ctl('Account').isUserLoggedIn() textField.setValue '' @addressInputMode() else @showLogin() true keyupRequestAddressField: (textField, event) -> textField.lastQuery ?= '' query = textField.getValue() if query isnt textField.lastQuery and query isnt '' textField.lastQuery = query if textField.genSuggTimeout? clearTimeout textField.genSuggTimeout textField.genSuggTimeout = setTimeout( @generateSuggestions(), 500 ) true focusRequestAddressField: -> @getRequestAddressField().setValue '' requestGasButtonPressed: -> deliveryLocName = @getRequestAddressField().getValue() ga_storage._trackEvent 'ui', 'Request Gas Button Pressed' analytics?.track 'Request Gas Button Pressed', address_street: deliveryLocName lat: @deliveryLocLat lng: @deliveryLocLng zip: @deliveryAddressZipCode if deliveryLocName is @getRequestAddressField().getInitialConfig().value return # just return, it hasn't loaded the location yet if not (util.ctl('Account').isUserLoggedIn() and util.ctl('Account').isCompleteAccount()) # select the Login view @showLogin() else if ( not localStorage['purpleSubscriptionId']? or localStorage['purpleSubscriptionId'] is '0' ) and ( not localStorage['purpleAdShownTimesSubscription']? or parseInt(localStorage['purpleAdShownTimesSubscription']) < 2 ) and ( Ext.os.is.Android or Ext.os.is.iOS ) and not util.ctl('Account').isManagedAccount() localStorage['purpleAdShownTimesSubscription'] ?= 0 localStorage['purpleAdShownTimesSubscription'] = ( parseInt(localStorage['purpleAdShownTimesSubscription']) + 1 ) util.ctl('Subscriptions').showAd( (=> # pass-thru callback @initRequestGasForm deliveryLocName ) (=> # active callback @getMainContainer().getItems().getAt(0).select 2, no, no util.ctl('Subscriptions').subscriptionsFieldTap() ) ) else @initRequestGasForm deliveryLocName initRequestGasForm: (deliveryLocName) -> # send to request gas form # but first get availbility from disptach system on app service Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}dispatch/availability" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] lat: @deliveryLocLat lng: @deliveryLocLng zip_code: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionLocalStorageData response util.ctl('Subscriptions').subscriptionUsage = response.user.subscription_usage availabilities = response.availabilities totalNumOfTimeOptions = availabilities.reduce (a, b) -> Object.keys(a.times).length + Object.keys(b.times).length if util.isEmpty(availabilities[0].gallon_choices) and util.isEmpty(availabilities[1].gallon_choices) or totalNumOfTimeOptions is 0 util.alert response["unavailable-reason"], "Unavailable", (->) else util.ctl('Menu').pushOntoBackButton => @backToMapFromRequestForm() @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.RequestForm', availabilities: availabilities ) @getRequestForm().setValues lat: @deliveryLocLat lng: @deliveryLocLng address_street: deliveryLocName address_zip: @deliveryAddressZipCode analytics?.page 'Order Form' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false console.log response_obj backToMapFromRequestForm: -> @getRequestGasTabContainer().remove( @getRequestForm(), yes ) backToRequestForm: -> @getRequestGasTabContainer().setActiveItem @getRequestForm() @getRequestGasTabContainer().remove( @getRequestConfirmationForm(), yes ) sendRequest: -> # takes you to the confirmation page @getRequestGasTabContainer().setActiveItem( Ext.create 'Purple.view.RequestConfirmationForm' ) util.ctl('Menu').pushOntoBackButton => @backToRequestForm() vals = @getRequestForm().getValues() availabilities = @getRequestForm().config.availabilities gasType = util.ctl('Vehicles').getVehicleById(vals['vehicle']).gas_type for a in availabilities if a['octane'] is gasType availability = a break vals['gas_type'] = "" + availability.octane # should already be string though vals['gas_type_display'] = "Unleaded #{vals['gas_type']} Octane" gasPrice = availability.price_per_gallon serviceFee = ( availability.times[vals['time']]['service_fee'] + (parseInt(vals['tire_pressure_check_price']) * vals['tire_pressure_check']) ) vals['gas_price'] = "" + util.centsToDollars( gasPrice ) vals['gas_price_display'] = "$#{vals['gas_price']} x #{vals['gallons']}" vals['service_fee'] = "" + util.centsToDollars( serviceFee ) freeGallonsAvailable = parseFloat localStorage['purpleUserReferralGallons'] gallonsToSubtract = 0 if freeGallonsAvailable is 0 @getFreeGasField().hide() else # apply as much free gas as possible gallonsToSubtract = Math.min vals['gallons'], freeGallonsAvailable @getFreeGasField().setValue "- $#{vals['gas_price']} x #{gallonsToSubtract}" # it's called unaltered because it doesn't have a coupon code applied @unalteredTotalPrice = ( parseFloat(gasPrice) * (parseFloat(vals['gallons']) - gallonsToSubtract) + parseFloat(serviceFee) ) vals['total_price'] = "" + util.centsToDollars @unalteredTotalPrice vals['display_time'] = availability.times[vals['time']]['text'] vals['vehicle_id'] = vals['vehicle'] for v in util.ctl('Vehicles').vehicles if v['id'] is vals['vehicle_id'] vals['vehicle'] = "#{v.year} #{v.make} #{v.model}" break @getRequestConfirmationForm().setValues vals if not vals['tire_pressure_check'] Ext.ComponentQuery.query('#tirePressureCheckField')[0].hide() # Ext.ComponentQuery.query('#addressStreetConfirmation')[0].removeCls 'bottom-margin' if vals['special_instructions'] is '' Ext.ComponentQuery.query('#specialInstructionsConfirmationLabel')[0].hide() Ext.ComponentQuery.query('#specialInstructionsConfirmation')[0].hide() Ext.ComponentQuery.query('#addressStreetConfirmation')[0].removeCls 'bottom-margin' else Ext.ComponentQuery.query('#specialInstructionsConfirmation')[0].setHtml(vals['special_instructions']) analytics?.page 'Review Order' promptForCode: -> Ext.Msg.prompt( 'Enter Coupon Code', false, ((buttonId, text) => if buttonId is 'ok' @applyCode text Ext.select('.x-msgbox .x-input-el').setStyle('text-transform', 'none') ) ) applyCode: (code) -> vals = @getRequestConfirmationForm().getValues() vehicleId = vals['vehicle_id'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/code" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] vehicle_id: vehicleId code: code address_zip: @deliveryAddressZipCode headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText analytics?.track 'Tried Coupon Code', valid: response.success coupon_code: code.toUpperCase() if response.success @getDiscountField().setValue( "- $" + util.centsToDollars(Math.abs(response.value)) ) @getCouponCodeField().setValue code totalPrice = Math.max( @unalteredTotalPrice + response.value, 0 ) @getTotalPriceField().setValue "" + util.centsToDollars(totalPrice) else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response confirmOrder: -> if not util.ctl('Account').hasDefaultPaymentMethod() and not util.ctl('Account').isManagedAccount() # select the Account view @getMainContainer().getItems().getAt(0).select 2, no, no pmCtl = util.ctl('PaymentMethods') if not pmCtl.getPaymentMethods()? pmCtl.paymentMethodFieldTap yes pmCtl.showEditPaymentMethodForm 'new', yes util.ctl('Menu').pushOntoBackButton -> pmCtl.backToPreviousPage() util.ctl('Menu').selectOption 0 pmCtl.getEditPaymentMethodForm().config.saveChangesCallback = -> pmCtl.backToPreviousPage() util.ctl('Menu').selectOption 0 else vals = @getRequestConfirmationForm().getValues() # prices are finally given in cents vals['gas_price'] = parseInt( vals['gas_price'].replace('$','').replace('.','') ) vals['service_fee'] = parseInt( vals['service_fee'].replace('$','').replace('.','') ) vals['total_price'] = parseInt( vals['total_price'].replace('$','').replace('.','') ) Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}orders/add" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] order: vals headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['specialInstructions'] = vals['special_instructions'] util.ctl('Vehicles').specialInstructionsAutoFillPrompted = false util.ctl('Menu').selectOption 3 # Orders tab util.ctl('Orders').loadOrdersList yes @getRequestGasTabContainer().setActiveItem @getMapForm() @getRequestGasTabContainer().remove( @getRequestConfirmationForm(), yes ) @getRequestGasTabContainer().remove( @getRequestForm(), yes ) util.ctl('Menu').clearBackButtonStack() util.alert response.message, (response.message_title ? "Success"), (->) # set up push notifications if they arent set up # NOTE: This will matter less and less, now that we set up push # notifications when a user creates their account. But it's nice to # keep this here for existing users that have never ordered and # don't logout and login (which would also cause a setup) @setUpPushNotifications true else util.alert response.message, (response.message_title ? "Error"), (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response sendFeedback: -> params = version: util.VERSION_NUMBER text: @getFeedbackTextField().getValue() if util.ctl('Account').isUserLoggedIn() params['user_id'] = localStorage['purpleUserId'] params['token'] = localStorage['purpleToken'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}feedback/send" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getFeedbackTextField().setValue '' util.flashComponent @getFeedbackThankYouMessage() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response # this is legacy code? sendInvites: -> params = version: util.VERSION_NUMBER email: @getInviteTextField().getValue() if util.ctl('Account').isUserLoggedIn() params['user_id'] = localStorage['purpleUserId'] params['token'] = localStorage['purpleToken'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}invite/send" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getInviteTextField().setValue '' util.flashComponent @getInviteThankYouMessage() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response initCourierPing: -> window.plugin?.backgroundMode.enable() @gpsIntervalRef ?= setInterval (Ext.bind @updateLatlng, this), 5000 @courierPingIntervalRef ?= setInterval (Ext.bind @courierPing, this), 10000 killCourierPing: -> if @gpsIntervalRef? clearInterval @gpsIntervalRef @gpsIntervalRef = null if @courierPingIntervalRef? clearInterval @courierPingIntervalRef @courierPingIntervalRef = null courierPing: (setOnDuty, successCallback, failureCallback) -> @courierPingBusy ?= no if @courierPingBusy and setOnDuty? setTimeout (=> @courierPing setOnDuty, successCallback, failureCallback ), 11000 else @courierPingBusy = yes params = version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['PI:KEY:<KEY>END_PI'] lat: @lat lng: @lng gallons: 87: localStorage['purpleCourierGallons87'] 91: localStorage['purpleCourierGallons91'] position_accuracy: @positionAccuracy if setOnDuty? params.set_on_duty = setOnDuty Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}courier/ping" params: Ext.JSON.encode params headers: 'Content-Type': 'application/json' timeout: 10000 method: 'POST' scope: this success: (response_obj) -> @courierPingBusy = no response = Ext.JSON.decode response_obj.responseText if response.success if @disconnectedMessage? clearTimeout @disconnectedMessage Ext.get(document.getElementsByTagName('body')[0]).removeCls 'disconnected' @disconnectedMessage = setTimeout (-> if localStorage['courierOnDuty'] is 'yes' Ext.get(document.getElementsByTagName('body')[0]).addCls 'disconnected' ), (2 * 60 * 1000) if (response.on_duty and localStorage['courierOnDuty'] is 'no') or (not response.on_duty and localStorage['courierOnDuty'] is 'yes') localStorage['courierOnDuty'] = if response.on_duty then 'yes' else 'no' util.ctl('Menu').updateOnDutyToggle() successCallback?() else failureCallback?() util.alert response.message, (response.message_title ? "Error"), (->) failure: (response_obj) -> @courierPingBusy = no failureCallback?()
[ { "context": "ider,strategy} = {}\n\n beforeEach ->\n token = 't0k3n'\n provider = _.clone providers.oauthtest, true", "end": 460, "score": 0.8468267321586609, "start": 455, "tag": "PASSWORD", "value": "t0k3n" } ]
test/unit/strategies/oauth/resourceOwnerAuthorization.coffee
LorianeE/connect
331
# Test dependencies _ = require 'lodash' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect # Assertions chai.use sinonChai chai.should() # Code under test OAuthStrategy = require '../../../../protocols/OAuth' providers = require '../../../../providers' describe 'OAuthStrategy resourceOwnerAuthorization', -> {token,provider,strategy} = {} beforeEach -> token = 't0k3n' provider = _.clone providers.oauthtest, true client = {} verifier = () -> strategy = new OAuthStrategy provider, client, verifier strategy.redirect = sinon.spy() strategy.resourceOwnerAuthorization(token) it 'should redirect', -> url = provider.endpoints.authorization.url strategy.redirect.should.have.been.calledWith sinon.match(url) it 'should include oauth_token', -> strategy.redirect.should.have.been.calledWith sinon.match( 'oauth_token=' + token )
101656
# Test dependencies _ = require 'lodash' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect # Assertions chai.use sinonChai chai.should() # Code under test OAuthStrategy = require '../../../../protocols/OAuth' providers = require '../../../../providers' describe 'OAuthStrategy resourceOwnerAuthorization', -> {token,provider,strategy} = {} beforeEach -> token = '<PASSWORD>' provider = _.clone providers.oauthtest, true client = {} verifier = () -> strategy = new OAuthStrategy provider, client, verifier strategy.redirect = sinon.spy() strategy.resourceOwnerAuthorization(token) it 'should redirect', -> url = provider.endpoints.authorization.url strategy.redirect.should.have.been.calledWith sinon.match(url) it 'should include oauth_token', -> strategy.redirect.should.have.been.calledWith sinon.match( 'oauth_token=' + token )
true
# Test dependencies _ = require 'lodash' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' expect = chai.expect # Assertions chai.use sinonChai chai.should() # Code under test OAuthStrategy = require '../../../../protocols/OAuth' providers = require '../../../../providers' describe 'OAuthStrategy resourceOwnerAuthorization', -> {token,provider,strategy} = {} beforeEach -> token = 'PI:PASSWORD:<PASSWORD>END_PI' provider = _.clone providers.oauthtest, true client = {} verifier = () -> strategy = new OAuthStrategy provider, client, verifier strategy.redirect = sinon.spy() strategy.resourceOwnerAuthorization(token) it 'should redirect', -> url = provider.endpoints.authorization.url strategy.redirect.should.have.been.calledWith sinon.match(url) it 'should include oauth_token', -> strategy.redirect.should.have.been.calledWith sinon.match( 'oauth_token=' + token )
[ { "context": " qs:\n limit: 100\n apiKey: '77993f4a-e4cd-4403-b030-6f05b40d95cf'\n secretKey: 'ca5a7809-3d94-4951-b2df-", "end": 1663, "score": 0.9997640252113342, "start": 1627, "tag": "KEY", "value": "77993f4a-e4cd-4403-b030-6f05b40d95cf" }, { "context": "d-4403-b030-6f05b40d95cf'\n secretKey: 'ca5a7809-3d94-4951-b2df-024e0bf8bd3e'\n\n request options, (error, response, body) ->", "end": 1725, "score": 0.9997708797454834, "start": 1689, "tag": "KEY", "value": "ca5a7809-3d94-4951-b2df-024e0bf8bd3e" }, { "context": "dbe21467:1/data'\n qs:\n apiKey: '77993f4a-e4cd-4403-b030-6f05b40d95cf'\n secretKey: 'ca5a7809-3d94-4951-b2df-", "end": 2416, "score": 0.999725878238678, "start": 2380, "tag": "KEY", "value": "77993f4a-e4cd-4403-b030-6f05b40d95cf" }, { "context": "d-4403-b030-6f05b40d95cf'\n secretKey: 'ca5a7809-3d94-4951-b2df-024e0bf8bd3e'\n\n request options, (error, response, body) ->", "end": 2478, "score": 0.9997405409812927, "start": 2442, "tag": "KEY", "value": "ca5a7809-3d94-4951-b2df-024e0bf8bd3e" }, { "context": " fields: 'limite'\n apiKey: '77993f4a-e4cd-4403-b030-6f05b40d95cf'\n secretKey: 'ca5a7809-3d94-4951-b", "end": 3938, "score": 0.9997594356536865, "start": 3902, "tag": "KEY", "value": "77993f4a-e4cd-4403-b030-6f05b40d95cf" }, { "context": "03-b030-6f05b40d95cf'\n secretKey: 'ca5a7809-3d94-4951-b2df-024e0bf8bd3e'\n\n request options, (err, response, body) ", "end": 4004, "score": 0.9997580051422119, "start": 3968, "tag": "KEY", "value": "ca5a7809-3d94-4951-b2df-024e0bf8bd3e" } ]
server/app.coffee
EFF/driveSlow
0
async = require 'async' request = require 'request' stylus = require 'stylus' express = require 'express' path = require 'path' http = require 'http' publicDirectory = path.join __dirname, '../build' stylusSource = path.join __dirname, '../client/stylesheets/' stylusDestination = path.join __dirname, '../build/stylesheets/' app = express() app.configure () -> app.use express.static(publicDirectory) app.locals.apiKey = process.env.MAPS_API_KEY app.set 'views', __dirname + '/views' app.set 'view engine', 'jade' app.use express.logger('dev') app.use stylus.middleware({src : stylusSource, dest: stylusDestination}) app.use express.static(publicDirectory) app.use express.bodyParser() app.use express.methodOverride() app.use app.router app.get '/', (req, res) -> res.render 'index' app.get '/api/photo-radar-zones', (req, res) -> northEast = JSON.parse req.query.northEast southWest = JSON.parse req.query.southWest query = match_all: {} filter: geo_shape: sectorBoundaries: shape: type: 'envelope' coordinates: [ [northEast.longitude, northEast.latitude] [southWest.longitude, southWest.latitude] ] relation: 'intersects' options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/3d21936a-db85-41ab-a0b4-b055dbe21467:1/data' qs: limit: 100 apiKey: '77993f4a-e4cd-4403-b030-6f05b40d95cf' secretKey: 'ca5a7809-3d94-4951-b2df-024e0bf8bd3e' request options, (error, response, body) -> res.json body.data app.get '/api/user-in-zone', (req, res) -> query = match_all: {} filter: geo_shape: sectorBoundaries: shape: type: 'point' coordinates: [ req.query.longitude req.query.latitude ] options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/3d21936a-db85-41ab-a0b4-b055dbe21467:1/data' qs: apiKey: '77993f4a-e4cd-4403-b030-6f05b40d95cf' secretKey: 'ca5a7809-3d94-4951-b2df-024e0bf8bd3e' request options, (error, response, body) -> res.json {data: (body.data.length > 0)} app.get '/api/speed-limit', (req, res) -> getAddress = (latitude, longitude, callback) -> json = "{location:{latLng:{lat:#{latitude},lng:#{longitude}}}}" options = json: true url: "http://open.mapquestapi.com/geocoding/v1/reverse?key=#{process.env.MAPQUEST_API_KEY}&json=#{json}" request options, (err, response, body) -> if err callback err else if body.info.statuscode is 200 or body.info.statuscode is 0 callback null, body.results[0].locations[0].street else callback new Error('Something went wrong with MapQuest') getSpeedLimit = (latitude, longitude, street, callback) -> query = sort: [ { _geo_distance: geo: lat: latitude lng: longitude } ] query: match: specifique: street options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/7bbe7e06-d820-4481-ada2-2ad9bd955106:1/data' qs: fields: 'limite' apiKey: '77993f4a-e4cd-4403-b030-6f05b40d95cf' secretKey: 'ca5a7809-3d94-4951-b2df-024e0bf8bd3e' request options, (err, response, body) -> callback null, body.data[0].fields.limite, street sendResponse = (err, limit, street) -> res.charset = 'utf-8' if err res.json 500, {error: err} else result = metadata: note: 'Geocoding Courtesy of MapQuest' fields: [ { name: 'limit' description: 'speed limit in meters per second' } { name: 'street' description: 'Name of the street as return by MapQuest' } ] data: limit: limit street: street res.json result tasks = [ getAddress.bind(@, req.query.latitude, req.query.longitude) getSpeedLimit.bind(@, req.query.latitude, req.query.longitude) ] async.waterfall tasks, sendResponse port = process.env.PORT || 3000 http.createServer(app).listen port, () -> console.log 'server waiting for requests...', port module.exports = app
138283
async = require 'async' request = require 'request' stylus = require 'stylus' express = require 'express' path = require 'path' http = require 'http' publicDirectory = path.join __dirname, '../build' stylusSource = path.join __dirname, '../client/stylesheets/' stylusDestination = path.join __dirname, '../build/stylesheets/' app = express() app.configure () -> app.use express.static(publicDirectory) app.locals.apiKey = process.env.MAPS_API_KEY app.set 'views', __dirname + '/views' app.set 'view engine', 'jade' app.use express.logger('dev') app.use stylus.middleware({src : stylusSource, dest: stylusDestination}) app.use express.static(publicDirectory) app.use express.bodyParser() app.use express.methodOverride() app.use app.router app.get '/', (req, res) -> res.render 'index' app.get '/api/photo-radar-zones', (req, res) -> northEast = JSON.parse req.query.northEast southWest = JSON.parse req.query.southWest query = match_all: {} filter: geo_shape: sectorBoundaries: shape: type: 'envelope' coordinates: [ [northEast.longitude, northEast.latitude] [southWest.longitude, southWest.latitude] ] relation: 'intersects' options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/3d21936a-db85-41ab-a0b4-b055dbe21467:1/data' qs: limit: 100 apiKey: '<KEY>' secretKey: '<KEY>' request options, (error, response, body) -> res.json body.data app.get '/api/user-in-zone', (req, res) -> query = match_all: {} filter: geo_shape: sectorBoundaries: shape: type: 'point' coordinates: [ req.query.longitude req.query.latitude ] options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/3d21936a-db85-41ab-a0b4-b055dbe21467:1/data' qs: apiKey: '<KEY>' secretKey: '<KEY>' request options, (error, response, body) -> res.json {data: (body.data.length > 0)} app.get '/api/speed-limit', (req, res) -> getAddress = (latitude, longitude, callback) -> json = "{location:{latLng:{lat:#{latitude},lng:#{longitude}}}}" options = json: true url: "http://open.mapquestapi.com/geocoding/v1/reverse?key=#{process.env.MAPQUEST_API_KEY}&json=#{json}" request options, (err, response, body) -> if err callback err else if body.info.statuscode is 200 or body.info.statuscode is 0 callback null, body.results[0].locations[0].street else callback new Error('Something went wrong with MapQuest') getSpeedLimit = (latitude, longitude, street, callback) -> query = sort: [ { _geo_distance: geo: lat: latitude lng: longitude } ] query: match: specifique: street options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/7bbe7e06-d820-4481-ada2-2ad9bd955106:1/data' qs: fields: 'limite' apiKey: '<KEY>' secretKey: '<KEY>' request options, (err, response, body) -> callback null, body.data[0].fields.limite, street sendResponse = (err, limit, street) -> res.charset = 'utf-8' if err res.json 500, {error: err} else result = metadata: note: 'Geocoding Courtesy of MapQuest' fields: [ { name: 'limit' description: 'speed limit in meters per second' } { name: 'street' description: 'Name of the street as return by MapQuest' } ] data: limit: limit street: street res.json result tasks = [ getAddress.bind(@, req.query.latitude, req.query.longitude) getSpeedLimit.bind(@, req.query.latitude, req.query.longitude) ] async.waterfall tasks, sendResponse port = process.env.PORT || 3000 http.createServer(app).listen port, () -> console.log 'server waiting for requests...', port module.exports = app
true
async = require 'async' request = require 'request' stylus = require 'stylus' express = require 'express' path = require 'path' http = require 'http' publicDirectory = path.join __dirname, '../build' stylusSource = path.join __dirname, '../client/stylesheets/' stylusDestination = path.join __dirname, '../build/stylesheets/' app = express() app.configure () -> app.use express.static(publicDirectory) app.locals.apiKey = process.env.MAPS_API_KEY app.set 'views', __dirname + '/views' app.set 'view engine', 'jade' app.use express.logger('dev') app.use stylus.middleware({src : stylusSource, dest: stylusDestination}) app.use express.static(publicDirectory) app.use express.bodyParser() app.use express.methodOverride() app.use app.router app.get '/', (req, res) -> res.render 'index' app.get '/api/photo-radar-zones', (req, res) -> northEast = JSON.parse req.query.northEast southWest = JSON.parse req.query.southWest query = match_all: {} filter: geo_shape: sectorBoundaries: shape: type: 'envelope' coordinates: [ [northEast.longitude, northEast.latitude] [southWest.longitude, southWest.latitude] ] relation: 'intersects' options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/3d21936a-db85-41ab-a0b4-b055dbe21467:1/data' qs: limit: 100 apiKey: 'PI:KEY:<KEY>END_PI' secretKey: 'PI:KEY:<KEY>END_PI' request options, (error, response, body) -> res.json body.data app.get '/api/user-in-zone', (req, res) -> query = match_all: {} filter: geo_shape: sectorBoundaries: shape: type: 'point' coordinates: [ req.query.longitude req.query.latitude ] options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/3d21936a-db85-41ab-a0b4-b055dbe21467:1/data' qs: apiKey: 'PI:KEY:<KEY>END_PI' secretKey: 'PI:KEY:<KEY>END_PI' request options, (error, response, body) -> res.json {data: (body.data.length > 0)} app.get '/api/speed-limit', (req, res) -> getAddress = (latitude, longitude, callback) -> json = "{location:{latLng:{lat:#{latitude},lng:#{longitude}}}}" options = json: true url: "http://open.mapquestapi.com/geocoding/v1/reverse?key=#{process.env.MAPQUEST_API_KEY}&json=#{json}" request options, (err, response, body) -> if err callback err else if body.info.statuscode is 200 or body.info.statuscode is 0 callback null, body.results[0].locations[0].street else callback new Error('Something went wrong with MapQuest') getSpeedLimit = (latitude, longitude, street, callback) -> query = sort: [ { _geo_distance: geo: lat: latitude lng: longitude } ] query: match: specifique: street options = method: 'GET' json: query url: 'http://openify-api-staging.herokuapp.com/v0/datasets/7bbe7e06-d820-4481-ada2-2ad9bd955106:1/data' qs: fields: 'limite' apiKey: 'PI:KEY:<KEY>END_PI' secretKey: 'PI:KEY:<KEY>END_PI' request options, (err, response, body) -> callback null, body.data[0].fields.limite, street sendResponse = (err, limit, street) -> res.charset = 'utf-8' if err res.json 500, {error: err} else result = metadata: note: 'Geocoding Courtesy of MapQuest' fields: [ { name: 'limit' description: 'speed limit in meters per second' } { name: 'street' description: 'Name of the street as return by MapQuest' } ] data: limit: limit street: street res.json result tasks = [ getAddress.bind(@, req.query.latitude, req.query.longitude) getSpeedLimit.bind(@, req.query.latitude, req.query.longitude) ] async.waterfall tasks, sendResponse port = process.env.PORT || 3000 http.createServer(app).listen port, () -> console.log 'server waiting for requests...', port module.exports = app
[ { "context": "d lose more XP, at the cost of gold.\n *\n * @name Seeker\n * @prerequisite Gain xp 100000 times\n * @effec", "end": 157, "score": 0.7786118984222412, "start": 151, "tag": "NAME", "value": "Seeker" } ]
src/character/personalities/Seeker.coffee
sadbear-/IdleLands
3
Personality = require "../base/Personality" `/** * This personality makes it so you both gain and lose more XP, at the cost of gold. * * @name Seeker * @prerequisite Gain xp 100000 times * @effect +15% xp * @effect -15% gold * @category Personalities * @package Player */` class Seeker extends Personality constructor: -> goldPercent: -> -15 xpPercent: -> 15 @canUse = (player) -> player.statistics["player xp gain"] >= 100000 @desc = "Gain XP 100000 times" module.exports = exports = Seeker
193430
Personality = require "../base/Personality" `/** * This personality makes it so you both gain and lose more XP, at the cost of gold. * * @name <NAME> * @prerequisite Gain xp 100000 times * @effect +15% xp * @effect -15% gold * @category Personalities * @package Player */` class Seeker extends Personality constructor: -> goldPercent: -> -15 xpPercent: -> 15 @canUse = (player) -> player.statistics["player xp gain"] >= 100000 @desc = "Gain XP 100000 times" module.exports = exports = Seeker
true
Personality = require "../base/Personality" `/** * This personality makes it so you both gain and lose more XP, at the cost of gold. * * @name PI:NAME:<NAME>END_PI * @prerequisite Gain xp 100000 times * @effect +15% xp * @effect -15% gold * @category Personalities * @package Player */` class Seeker extends Personality constructor: -> goldPercent: -> -15 xpPercent: -> 15 @canUse = (player) -> player.statistics["player xp gain"] >= 100000 @desc = "Gain XP 100000 times" module.exports = exports = Seeker
[ { "context": "\n# * bumper | dom | jquery\n# * https://github.com/brewster1134/bumper\n# *\n# * @author Ryan Brewster\n# * Copyrigh", "end": 65, "score": 0.9994032382965088, "start": 53, "tag": "USERNAME", "value": "brewster1134" }, { "context": "s://github.com/brewster1134/bumper\n# *\n# * @author Ryan Brewster\n# * Copyright (c) 2014\n# * Licensed under the MIT", "end": 102, "score": 0.9998905062675476, "start": 89, "tag": "NAME", "value": "Ryan Brewster" } ]
src/bumper-dom-jquery.coffee
brewster1134/bumper
0
### # * bumper | dom | jquery # * https://github.com/brewster1134/bumper # * # * @author Ryan Brewster # * Copyright (c) 2014 # * Licensed under the MIT license. ### ((factory) -> if define?.amd define [ 'jquery' 'bumper-core' ], ($, Core) -> factory $, Core else factory window.jQuery, window.Bumper.Core ) ($, Core) -> class BumperDom extends Core.Module # default options options: parents: false # when set to true, searching for elements will be restricted to the parent chain of a root element # Get data associated with an element given the string interpolation syntax # {selector:method,arg:option=value,foo=bar} # # @param string [String] # A string that may contain the above interpolation syntax # @param rootEl [String/jQuery] (optional) # A jQuery object or a css selector for a root element to search from # # getElementData: (string, rootEl) -> $rootEl = $(rootEl) # regex to match the convention: regex = /\{([^&]+)\}/g # extract matches from string matches = string.match regex # return original string if no interpolation is found return string unless matches # in case there are multiple matches to interpolate, process each one individually for match in matches # extract data from string stringArray = match.replace(/[{}]/g, '').split ':' stringSelector = stringArray[0] stringMethodArgs = stringArray[1] stringOptions = stringArray[2] # extract options into js object stringOptionsObject = {} if stringOptions for option in stringOptions.split(',') keyValue = option.split('=') key = keyValue[0].trim() value = keyValue[1].trim() stringOptionsObject[key] = window.Bumper.Core.castType(value) # merge options into defaults options = $.extend {}, @options, stringOptionsObject # extract method and arguments stringArgs = stringMethodArgs.split ',' # use the first arg as the method name stringMethod = stringArgs.shift() # find match within element's parent chain $element = $rootEl.parent().closest("#{stringSelector}") # find first matching element anywhere in the dom if options.parents == false && !$element.length $element = $("#{stringSelector}").first() # use the nearest visible parent as a last resort with the root element $element = $rootEl.parent().closest(':visible') unless $element.length # use the body tag as a LAST last resort $element = $('body') unless $element.length # convert special value types # typically options passed in the string will want to be boolean (e.g. true vs 'true') for arg, index in stringArgs stringArgs[index] = window.Bumper.Core.castType(arg) # call methods to request data value = $element[stringMethod](stringArgs...) # create data object with details to pass custom functions matchData = element: $element selector: stringSelector method: stringMethod arguments: stringArgs options: options # call custom function on target element (if it exists) value = $element.data('bumper-dom-function')?(value, matchData) || value # call custom function on root element (if it exists) value = $rootEl.data('bumper-dom-function')?(value, matchData) || value # replace inteprolation syntax with value string = string.replace match, value return string window.Bumper ||= {} if window.Bumper.Dom? console.warn 'There is already a dom handler loaded. It will be replaced by the jQuery handler', window.Bumper.Dom window.Bumper.Dom = new BumperDom
99424
### # * bumper | dom | jquery # * https://github.com/brewster1134/bumper # * # * @author <NAME> # * Copyright (c) 2014 # * Licensed under the MIT license. ### ((factory) -> if define?.amd define [ 'jquery' 'bumper-core' ], ($, Core) -> factory $, Core else factory window.jQuery, window.Bumper.Core ) ($, Core) -> class BumperDom extends Core.Module # default options options: parents: false # when set to true, searching for elements will be restricted to the parent chain of a root element # Get data associated with an element given the string interpolation syntax # {selector:method,arg:option=value,foo=bar} # # @param string [String] # A string that may contain the above interpolation syntax # @param rootEl [String/jQuery] (optional) # A jQuery object or a css selector for a root element to search from # # getElementData: (string, rootEl) -> $rootEl = $(rootEl) # regex to match the convention: regex = /\{([^&]+)\}/g # extract matches from string matches = string.match regex # return original string if no interpolation is found return string unless matches # in case there are multiple matches to interpolate, process each one individually for match in matches # extract data from string stringArray = match.replace(/[{}]/g, '').split ':' stringSelector = stringArray[0] stringMethodArgs = stringArray[1] stringOptions = stringArray[2] # extract options into js object stringOptionsObject = {} if stringOptions for option in stringOptions.split(',') keyValue = option.split('=') key = keyValue[0].trim() value = keyValue[1].trim() stringOptionsObject[key] = window.Bumper.Core.castType(value) # merge options into defaults options = $.extend {}, @options, stringOptionsObject # extract method and arguments stringArgs = stringMethodArgs.split ',' # use the first arg as the method name stringMethod = stringArgs.shift() # find match within element's parent chain $element = $rootEl.parent().closest("#{stringSelector}") # find first matching element anywhere in the dom if options.parents == false && !$element.length $element = $("#{stringSelector}").first() # use the nearest visible parent as a last resort with the root element $element = $rootEl.parent().closest(':visible') unless $element.length # use the body tag as a LAST last resort $element = $('body') unless $element.length # convert special value types # typically options passed in the string will want to be boolean (e.g. true vs 'true') for arg, index in stringArgs stringArgs[index] = window.Bumper.Core.castType(arg) # call methods to request data value = $element[stringMethod](stringArgs...) # create data object with details to pass custom functions matchData = element: $element selector: stringSelector method: stringMethod arguments: stringArgs options: options # call custom function on target element (if it exists) value = $element.data('bumper-dom-function')?(value, matchData) || value # call custom function on root element (if it exists) value = $rootEl.data('bumper-dom-function')?(value, matchData) || value # replace inteprolation syntax with value string = string.replace match, value return string window.Bumper ||= {} if window.Bumper.Dom? console.warn 'There is already a dom handler loaded. It will be replaced by the jQuery handler', window.Bumper.Dom window.Bumper.Dom = new BumperDom
true
### # * bumper | dom | jquery # * https://github.com/brewster1134/bumper # * # * @author PI:NAME:<NAME>END_PI # * Copyright (c) 2014 # * Licensed under the MIT license. ### ((factory) -> if define?.amd define [ 'jquery' 'bumper-core' ], ($, Core) -> factory $, Core else factory window.jQuery, window.Bumper.Core ) ($, Core) -> class BumperDom extends Core.Module # default options options: parents: false # when set to true, searching for elements will be restricted to the parent chain of a root element # Get data associated with an element given the string interpolation syntax # {selector:method,arg:option=value,foo=bar} # # @param string [String] # A string that may contain the above interpolation syntax # @param rootEl [String/jQuery] (optional) # A jQuery object or a css selector for a root element to search from # # getElementData: (string, rootEl) -> $rootEl = $(rootEl) # regex to match the convention: regex = /\{([^&]+)\}/g # extract matches from string matches = string.match regex # return original string if no interpolation is found return string unless matches # in case there are multiple matches to interpolate, process each one individually for match in matches # extract data from string stringArray = match.replace(/[{}]/g, '').split ':' stringSelector = stringArray[0] stringMethodArgs = stringArray[1] stringOptions = stringArray[2] # extract options into js object stringOptionsObject = {} if stringOptions for option in stringOptions.split(',') keyValue = option.split('=') key = keyValue[0].trim() value = keyValue[1].trim() stringOptionsObject[key] = window.Bumper.Core.castType(value) # merge options into defaults options = $.extend {}, @options, stringOptionsObject # extract method and arguments stringArgs = stringMethodArgs.split ',' # use the first arg as the method name stringMethod = stringArgs.shift() # find match within element's parent chain $element = $rootEl.parent().closest("#{stringSelector}") # find first matching element anywhere in the dom if options.parents == false && !$element.length $element = $("#{stringSelector}").first() # use the nearest visible parent as a last resort with the root element $element = $rootEl.parent().closest(':visible') unless $element.length # use the body tag as a LAST last resort $element = $('body') unless $element.length # convert special value types # typically options passed in the string will want to be boolean (e.g. true vs 'true') for arg, index in stringArgs stringArgs[index] = window.Bumper.Core.castType(arg) # call methods to request data value = $element[stringMethod](stringArgs...) # create data object with details to pass custom functions matchData = element: $element selector: stringSelector method: stringMethod arguments: stringArgs options: options # call custom function on target element (if it exists) value = $element.data('bumper-dom-function')?(value, matchData) || value # call custom function on root element (if it exists) value = $rootEl.data('bumper-dom-function')?(value, matchData) || value # replace inteprolation syntax with value string = string.replace match, value return string window.Bumper ||= {} if window.Bumper.Dom? console.warn 'There is already a dom handler loaded. It will be replaced by the jQuery handler', window.Bumper.Dom window.Bumper.Dom = new BumperDom
[ { "context": ", isPluginExtension)\n{\n\tthis.id = id;\n\tthis.name = name;\n\tthis.mainPath = mainPath;\n\tthis.basePath = base", "end": 5002, "score": 0.9939008951187134, "start": 4998, "tag": "NAME", "value": "name" } ]
src/CSInterface.coffee
AriaMinaei/photoshopjs-panel
3
` /* ADOBE SYSTEMS INCORPORATED Copyright 2013 Adobe Systems Incorporated. All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. If you have received this file from a source other than Adobe, then your use, modification, or distribution of it requires the prior written permission of Adobe. */ /** * Stores constants for the window types supported by the CSXS infrastructure. */ function CSXSWindowType() { }; /** Constant for the CSXS window type Panel. **/ CSXSWindowType._PANEL = "Panel"; /** Constant for the CSXS window type Modeless. **/ CSXSWindowType._MODELESS = "Modeless"; /** Constant for the CSXS window type ModalDialog. **/ CSXSWindowType._MODAL_DIALOG = "ModalDialog"; /** EvalScript error message**/ EvalScript_ErrMessage = "EvalScript error."; /** * Class Version * Defines a version number with major, minor, micro, and special * components. The major, minor and micro values are numeric; the special * value can be any string. * * @param major The major version component, a positive integer up to nine digits long. * @param minor The minor version component, a positive integer up to nine digits long. * @param micro The micro version component, a positive integer up to nine digits long. * @param special The special version component, an arbitrary string. * * @return A Version object. */ function Version(major, minor, micro, special) { this.major = major; this.minor = minor; this.micro = micro; this.special = special; }; /** * The maximum value allowed for a Numeric version component. * This reflects the maximum value allowed in PlugPlug and the manifest schema. */ Version.MAX_NUM = 999999999; /** * Class VersionBound * Defines a boundary for a version range, which associates a Version object with a flag for whether it is an inclusive * or exclusive boundary. * * @param version The Version object. * @see Version class. * @param inclusive True if this boundary is inclusive, false if it is exclusive. * * @return A VersionBound object. */ function VersionBound(version, inclusive) { this.version = version; this.inclusive = inclusive; }; /** * Class VersionRange. * Defines a range of versions using a lower boundary and optional upper boundary. * * @param lowerBound The VersionBound object. @see VersionBound. * @param upperBound The VersionBound object, or null for a range with no upper boundary. @see VersionBound. * * @return A VersionRange object. */ function VersionRange(lowerBound, upperBound) { this.lowerBound = lowerBound; this.upperBound = upperBound; }; /** * Class Runtime. * Represents a runtime related to the CSXS infrastructure. Extensions can declare dependencies on particular * CSXS runtime versions in the extension manifest. * * @param name The runtime name. * @param version The VersionRange object. @see VersionRange. * * @return A Runtime object. */ function Runtime(name, versionRange) { this.name = name; this.versionRange = versionRange; }; /** * Class Extension. * Contains the classes that define data types for the CEP libraries. * * @param id The unique identifier of this extension. * @param name The localizable display name of this extension. * @param mainPath The path of the "index.html" file. * @param basePath The base path of this extension. * @param windowType The window type of the main window of this extension. Valid values are defined by CSXSWindowType. @see CSXSWindowType. * @param width The default width in pixels of the main window of this extension. * @param height The default height in pixels of the main window of this extension. * @param minWidth The minimum width in pixels of the main window of this extension. * @param minHeight The minimum height in pixels of the main window of this extension. * @param maxWidth The maximum width in pixels of the main window of this extension. * @param maxHeight The maximum height in pixels of the main window of this extension. * @param defaultExtensionDataXml The extension data contained in the default ExtensionDispatchInfo section of the extension manifest. * @param specialExtensionDataXml The extension data contained in the application-specific ExtensionDispatchInfo section of the extension manifest. * @param requiredRuntimeList An array of Runtime objects for runtimes required by this extension. @see VersionRange. * @param isAutoVisible True if this extension is visible on loading. * @param isPluginExtension True if this extension has been deployed in the Plugins folder of the host application. * * @return An Extension object. */ function Extension(id, name, mainPath, basePath, windowType, width, height, minWidth, minHeight, maxWidth, maxHeight, defaultExtensionDataXml, specialExtensionDataXml, requiredRuntimeList, isAutoVisible, isPluginExtension) { this.id = id; this.name = name; this.mainPath = mainPath; this.basePath = basePath; this.windowType = windowType; this.width = width; this.height = height; this.minWidth = minWidth; this.minHeight = minHeight; this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.defaultExtensionDataXml = defaultExtensionDataXml; this.specialExtensionDataXml = specialExtensionDataXml; this.requiredRuntimeList = requiredRuntimeList; this.isAutoVisible = isAutoVisible; this.isPluginExtension = isPluginExtension; }; /** * Class CSEvent. * You can use it to dispatch a standard Javascript event. * * @param type Event type. * @param scope The scope of event, can be "GLOBAL" or "APPLICATION". * @param appId The unique identifier of the application that generated the event. * @param extensionId The unique identifier of the extension that generated the event. * * @return CSEvent object */ function CSEvent(type, scope, appId, extensionId) { this.type = type; this.scope = scope; this.appId = appId; this.extensionId = extensionId; }; /** The event specific data. **/ CSEvent.prototype.data = ""; /** * Class SystemPath * Stores operating-system-specific location constants for use getSystemPath method. */ function SystemPath() { }; /** Identifies the path to user data. */ SystemPath.USER_DATA = "userData"; /** Identifies the path to common files for Adobe applications. */ SystemPath.COMMON_FILES = "commonFiles"; /** Identifies the path to the user's default document folder. */ SystemPath.MY_DOCUMENTS = "myDocuments"; /** Identifies the path to current extension. */ /** DEPRECATED, PLEASE USE EXTENSION INSTEAD. */ SystemPath.APPLICATION = "application"; /** Identifies the path to current extension. */ SystemPath.EXTENSION = "extension"; /** Identifies the path to hosting application's executable. */ SystemPath.HOST_APPLICATION = "hostApplication"; /** * Class ColorType * Stores the color-type constants. */ function ColorType() { }; /** rgb type. */ ColorType.RGB = "rgb"; /** gradient type. */ ColorType.GRADIENT = "gradient"; /** none type. */ ColorType.NONE = "none"; /** * Class RGBColor * Stores an RGB color with red, green, blue, and alpha values. All values are in the range * [0.0 to 255.0]. Invalid numeric values are converted to numbers within this range. * * @param red The red value, in the range [0.0 to 255.0]. * @param green The green value, in the range [0.0 to 255.0]. * @param blue The blue value, in the range [0.0 to 255.0]. * @param alpha The alpha (transparency) value, in the range [0.0 to 255.0]. * The default (255.0) means that the color is fully opaque. * * @return RGBColor object. */ function RGBColor(red, green, blue, alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; }; /** * Class Direction * Stores a point information. * * @param x X axis position. * @param y Y axis position. * * @return Direction object. */ function Direction(x, y) { this.x = x; this.y = y; }; /** * Class GradientStop * Stores gradient stop information. * * @param offset The offset of the gradient stop, in the range [0.0 to 1.0]. * @param rgbColor The RGBColor object. @see RGBColor. * * @return GradientStop object. */ function GradientStop(offset, rgbColor) { this.offset = offset; this.rgbColor = rgbColor; }; /** * Class GradientColor * Stores gradient color information. * * @param type The gradient type, the only valid value is "linear". * @param direction A vector describing the direction of the gradient. * A point value, in which the y component is 0 and the x component * is positive or negative for a right or left direction, * or the x component is 0 and the y component is positive or negative for * an up or down direction. @see Direction. * @param numStops The number of stops. * @param gradientStopList An array of GradientStop objects. @see GradientStop. * * @return GradientColor object. */ function GradientColor(type, direction, numStops, arrGradientStop) { this.type = type; this.direction = direction; this.numStops = numStops; this.arrGradientStop = arrGradientStop; }; /** * Class UIColor * Stores color information, including the type, anti-alias level, and specific color * values in a color object of an appropriate type. * * @param type The color type constant, 1 for "rgb" and 2 for "gradient". * @param antialiasLevel The anti-alias level constant. * @param color A GradientColor object or a RGBColor containing specific color information. * The type of color object depends on type parameter. @see GradientColor and RGBColor. * * @return UIColor object. */ function UIColor(type, antialiasLevel, color) { this.type = type; this.antialiasLevel = antialiasLevel; this.color = color; }; /** * Class AppSkinInfo * Stores window-skin properties, such as color and font. All parameters' type are UIColor. @see UIColor. * * @param baseFontFamily The base font family of the application. * @param baseFontSize The base font size of the application. * @param appBarBackgroundColor The application bar background color. * @param panelBackgroundColor The background color of the extension panel. * @param appBarBackgroundColorSRGB The application bar background color, as sRGB. * @param panelBackgroundColorSRGB The background color of the extension panel, as sRGB. * @param systemHighlightColor The operating-system highlight color, as sRGB. * * @return AppSkinInfo object. */ function AppSkinInfo(baseFontFamily, baseFontSize, appBarBackgroundColor, panelBackgroundColor, appBarBackgroundColorSRGB, panelBackgroundColorSRGB, systemHighlightColor) { this.baseFontFamily = baseFontFamily; this.baseFontSize = baseFontSize; this.appBarBackgroundColor = appBarBackgroundColor; this.panelBackgroundColor = panelBackgroundColor; this.appBarBackgroundColorSRGB = appBarBackgroundColorSRGB; this.panelBackgroundColorSRGB = panelBackgroundColorSRGB; this.systemHighlightColor = systemHighlightColor; }; /** * Class HostEnvironment * Stores information about the environment in which the extension is loaded. * * @param appName The application's name. * @param appVersion The application's version. * @param appLocale The application's current license locale. * @param appId The application's unique identifier. * @param isAppOffline True if the application is currently offline. * @param appSkinInfo A skin-information object containing the application's default color and font styles. @see AppSkinInfo. * @param appUILocale The application's current UI locale. * * @return HostEnvironment object. */ function HostEnvironment(appName, appVersion, appLocale, appUILocale, appId, isAppOffline, appSkinInfo) { this.appName = appName; this.appVersion = appVersion; this.appLocale = appLocale; this.appUILocale = appUILocale; this.appId = appId; this.isAppOffline = isAppOffline; this.appSkinInfo = appSkinInfo; }; /***********************************************************************************/ /** * Class CSInterface. * You can use it to communicate with native application. * * @return CSInterface object */ function CSInterface() { }; /** * User can add this event listener to handle native application theme color changes. * Callback function gives extensions ability to fine-tune their theme color after the * global theme color has been changed. * The callback function should be like below: * * @example * // event is a CSEvent object, but user can ignore it. * function OnAppThemeColorChanged(event) * { * // Should get a latest HostEnvironment object from application. * var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo; * // Gets the style information such as color info from the skinInfo, * // and redraw all UI controls of your extension according to the style info. * } */ CSInterface.THEME_COLOR_CHANGED_EVENT = "com.adobe.csxs.events.ThemeColorChanged"; /** The host environment data object **/ CSInterface.prototype.hostEnvironment = JSON.parse(window.__adobe_cep__.getHostEnvironment()); /** Close the current extension **/ CSInterface.prototype.closeExtension = function() { window.__adobe_cep__.closeExtension(); }; /** * Get system path. * * @param pathType A string containing a path-type constant defined in the SystemPath class, * such as SystemPath.USER_DATA. * @return path string */ CSInterface.prototype.getSystemPath = function(pathType) { var path = decodeURI(window.__adobe_cep__.getSystemPath(pathType)); var OSVersion = this.getOSInformation(); if (OSVersion.indexOf("Windows") >= 0) { path = path.replace("file:///", ""); } else if (OSVersion.indexOf("Mac") >= 0) { path = path.replace("file://", ""); } return path; }; /** * Eval scripts. You can use it to operate the DOM of native application. * * @param script The raw JavaScript. * @param callback The callback function that receives the execution result of the script. This parameter is optional. * If it fails to execute the script, the callback function will receive the error message EvalScript_ErrMessage. */ CSInterface.prototype.evalScript = function(script, callback) { if(callback == null || callback == undefined) { callback = function(result){}; } window.__adobe_cep__.evalScript(script, callback); }; /** * Get the identifier of the host application. * * @return a string identifier of the host application */ CSInterface.prototype.getApplicationID = function() { var appId = this.hostEnvironment.appId; return appId; }; /** * Get host capability information about the host application. * * @return an object that contains host capability information */ CSInterface.prototype.getHostCapabilities = function() { var hostCapabilities = JSON.parse(window.__adobe_cep__.getHostCapabilities() ); return hostCapabilities; }; /** * Triggering a CS Event programmatically. You can use it to dispatch a CSEvent. * * @param event a CS Event */ CSInterface.prototype.dispatchEvent = function(event) { if (typeof event.data == "object") { event.data = JSON.stringify(event.data); } window.__adobe_cep__.dispatchEvent(event); }; /** * Register a CS Event listener. You can use it to listen a CSEvent. * * @param type The Event type * @param listener The JavaScript function that receives a notification when * a CS event of the specified type occurs. * @param obj The object that listener belongs to. Use it when listener is a method * of an object. This parameter is optional and its default value is null. */ CSInterface.prototype.addEventListener = function(type, listener, obj) { window.__adobe_cep__.addEventListener(type, listener, obj); }; /** * Remove the CS Event listener. * * @param type event type * @param listener The JavaScript function that receives a notification when * a CS event of the specified type occurs. * @param obj The object that listener belongs to. Use it when listener is a method * of an object. This parameter is optional and its default value is null. */ CSInterface.prototype.removeEventListener = function(type, listener, obj) { window.__adobe_cep__.removeEventListener(type, listener, obj); }; /** * Loads and launches another extension. If the target extension is already loaded, it is activated. * * @param extensionId The extension's unique identifier. * @param startupParams Startup parameters to be passed to the loaded extension. * Specify key-value pairs as a GET URL parameter list; for example: "key1=value1&amp;key2=value2". * Currently this parameter is not supported by CEP, so it will always be "" for now. * * @example * To launch the extension "help" with ID "HLP" from this extension, call: * requestOpenExtension("HLP", ""); * */ CSInterface.prototype.requestOpenExtension = function(extensionId, params) { window.__adobe_cep__.requestOpenExtension(extensionId, params); }; /** * Retrieves the list of extensions currently loaded in the current host application. * The extension list is initialized once, and remains the same during the lifetime of the CSXS session. * * @param extensionIds An array of unique identifiers for extensions of interest. * If omitted, retrieves data for all extensions. * * @return An Extension object. */ CSInterface.prototype.getExtensions = function(extensionIds) { var extensionIdsStr = JSON.stringify(extensionIds); var extensionsStr = window.__adobe_cep__.getExtensions(extensionIdsStr); var extensions = JSON.parse(extensionsStr); return extensions; }; /** * Retrieves network-related preferences. * * @return A NetworkPreferences object. */ CSInterface.prototype.getNetworkPreferences = function() { var result = window.__adobe_cep__.getNetworkPreferences(); var networkPre = JSON.parse(result); return networkPre; }; /** * Initializes the resource bundle for this extension with property values for the current application and locale. * If user wants to support multi-locale to the extension, they should define a property file. An example of the property file content is: * * key1=value1 * key2=value2 * key3.value=value3 * * The property file should be placed in its corresponding locale folder. For example for en_US, the property file would be placed in YourExtension/locale/en_US/messages.properties. * Users can define a default property file, placed in "YourExtension/locale/" which will be used when the corresponding locale file is not defined. * Users should initialize locale strings during the loading of the extension. The locale loaded should match the current UI locale of the host application. * 'data-locale' is the custom HTML element attribute and you can added it to each HTML element that you want to localize. * * For example: * * <input type="submit" value="" data-locale="key3"/> * <script type="text/javascript"> * var cs = new CSInterface(); * // Get properties according to current locale of host application. * var resourceBundle = cs.initResourceBundle(); * // Refer the locale string. * document.write(resourceBundle.key1); * document.write(resourceBundle.key2); * </script> * * @return An object containing the resource bundle information. */ CSInterface.prototype.initResourceBundle = function() { var resourceBundle = JSON.parse(window.__adobe_cep__.initResourceBundle()); var resElms = document.querySelectorAll('[data-locale]'); for (var n = 0; n < resElms.length; n++) { var resEl = resElms[n]; // Get the resource key from the element. var resKey = resEl.getAttribute('data-locale'); if (resKey) { // Get all the resources that start with the key. for (var key in resourceBundle) { if (key.indexOf(resKey) == 0) { var resValue = resourceBundle[key]; if (key.indexOf('.') == -1) { // No dot notation in resource key, // assign the resource value to the element's // innerHTML. resEl.innerHTML = resValue; } else { // Dot notation in resource key, assign the // resource value to the element's property // whose name corresponds to the substring // after the dot. var attrKey = key.substring(key.indexOf('.') + 1); resEl[attrKey] = resValue; } } } } } return resourceBundle; }; /** * Writes installation information to a file. * * @return The dump info file path. */ CSInterface.prototype.dumpInstallationInfo = function() { return window.__adobe_cep__.dumpInstallationInfo(); }; /** * Get current Operating System information including version and 32-bit/64-bit. * Refer to http://www.useragentstring.com/pages/Chrome/ for all of the navigator.userAgent values retrieved by Chrome. * * @return The OS version in string or "unknown Operation System". */ CSInterface.prototype.getOSInformation = function() { var userAgent = navigator.userAgent; if ((navigator.platform == "Win32") || (navigator.platform == "Windows")) { var winVersion = "Windows platform"; if (userAgent.indexOf("Windows NT 5.0") > -1) { winVersion = "Windows 2000"; } else if (userAgent.indexOf("Windows NT 5.1") > -1) { winVersion = "Windows XP"; } else if (userAgent.indexOf("Windows NT 5.2") > -1) { winVersion = "Windows Server 2003"; } else if (userAgent.indexOf("Windows NT 6.0") > -1) { winVersion = "Windows Vista"; } else if (userAgent.indexOf("Windows NT 6.1") > -1) { winVersion = "Windows 7"; } else if (userAgent.indexOf("Windows NT 6.2") > -1) { winVersion = "Windows 8"; } var winBit = "32-bit"; if (userAgent.indexOf("WOW64") > -1) { winBit = "64-bit"; } return winVersion + " " + winBit; } else if ((navigator.platform == "MacIntel") || (navigator.platform == "Macintosh")) { var agentStr = new String(); agentStr = userAgent; var verLength = agentStr.indexOf(")") - agentStr.indexOf("Mac OS X"); var verStr = agentStr.substr(agentStr.indexOf("Mac OS X"), verLength); var result = verStr.replace("_", "."); result = result.replace("_", "."); return result; } return "Unknown Operation System"; }; ` CSInterface.SystemPath = SystemPath CSInterface.CSEvent = CSEvent module.exports = CSInterface
154460
` /* ADOBE SYSTEMS INCORPORATED Copyright 2013 Adobe Systems Incorporated. All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. If you have received this file from a source other than Adobe, then your use, modification, or distribution of it requires the prior written permission of Adobe. */ /** * Stores constants for the window types supported by the CSXS infrastructure. */ function CSXSWindowType() { }; /** Constant for the CSXS window type Panel. **/ CSXSWindowType._PANEL = "Panel"; /** Constant for the CSXS window type Modeless. **/ CSXSWindowType._MODELESS = "Modeless"; /** Constant for the CSXS window type ModalDialog. **/ CSXSWindowType._MODAL_DIALOG = "ModalDialog"; /** EvalScript error message**/ EvalScript_ErrMessage = "EvalScript error."; /** * Class Version * Defines a version number with major, minor, micro, and special * components. The major, minor and micro values are numeric; the special * value can be any string. * * @param major The major version component, a positive integer up to nine digits long. * @param minor The minor version component, a positive integer up to nine digits long. * @param micro The micro version component, a positive integer up to nine digits long. * @param special The special version component, an arbitrary string. * * @return A Version object. */ function Version(major, minor, micro, special) { this.major = major; this.minor = minor; this.micro = micro; this.special = special; }; /** * The maximum value allowed for a Numeric version component. * This reflects the maximum value allowed in PlugPlug and the manifest schema. */ Version.MAX_NUM = 999999999; /** * Class VersionBound * Defines a boundary for a version range, which associates a Version object with a flag for whether it is an inclusive * or exclusive boundary. * * @param version The Version object. * @see Version class. * @param inclusive True if this boundary is inclusive, false if it is exclusive. * * @return A VersionBound object. */ function VersionBound(version, inclusive) { this.version = version; this.inclusive = inclusive; }; /** * Class VersionRange. * Defines a range of versions using a lower boundary and optional upper boundary. * * @param lowerBound The VersionBound object. @see VersionBound. * @param upperBound The VersionBound object, or null for a range with no upper boundary. @see VersionBound. * * @return A VersionRange object. */ function VersionRange(lowerBound, upperBound) { this.lowerBound = lowerBound; this.upperBound = upperBound; }; /** * Class Runtime. * Represents a runtime related to the CSXS infrastructure. Extensions can declare dependencies on particular * CSXS runtime versions in the extension manifest. * * @param name The runtime name. * @param version The VersionRange object. @see VersionRange. * * @return A Runtime object. */ function Runtime(name, versionRange) { this.name = name; this.versionRange = versionRange; }; /** * Class Extension. * Contains the classes that define data types for the CEP libraries. * * @param id The unique identifier of this extension. * @param name The localizable display name of this extension. * @param mainPath The path of the "index.html" file. * @param basePath The base path of this extension. * @param windowType The window type of the main window of this extension. Valid values are defined by CSXSWindowType. @see CSXSWindowType. * @param width The default width in pixels of the main window of this extension. * @param height The default height in pixels of the main window of this extension. * @param minWidth The minimum width in pixels of the main window of this extension. * @param minHeight The minimum height in pixels of the main window of this extension. * @param maxWidth The maximum width in pixels of the main window of this extension. * @param maxHeight The maximum height in pixels of the main window of this extension. * @param defaultExtensionDataXml The extension data contained in the default ExtensionDispatchInfo section of the extension manifest. * @param specialExtensionDataXml The extension data contained in the application-specific ExtensionDispatchInfo section of the extension manifest. * @param requiredRuntimeList An array of Runtime objects for runtimes required by this extension. @see VersionRange. * @param isAutoVisible True if this extension is visible on loading. * @param isPluginExtension True if this extension has been deployed in the Plugins folder of the host application. * * @return An Extension object. */ function Extension(id, name, mainPath, basePath, windowType, width, height, minWidth, minHeight, maxWidth, maxHeight, defaultExtensionDataXml, specialExtensionDataXml, requiredRuntimeList, isAutoVisible, isPluginExtension) { this.id = id; this.name = <NAME>; this.mainPath = mainPath; this.basePath = basePath; this.windowType = windowType; this.width = width; this.height = height; this.minWidth = minWidth; this.minHeight = minHeight; this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.defaultExtensionDataXml = defaultExtensionDataXml; this.specialExtensionDataXml = specialExtensionDataXml; this.requiredRuntimeList = requiredRuntimeList; this.isAutoVisible = isAutoVisible; this.isPluginExtension = isPluginExtension; }; /** * Class CSEvent. * You can use it to dispatch a standard Javascript event. * * @param type Event type. * @param scope The scope of event, can be "GLOBAL" or "APPLICATION". * @param appId The unique identifier of the application that generated the event. * @param extensionId The unique identifier of the extension that generated the event. * * @return CSEvent object */ function CSEvent(type, scope, appId, extensionId) { this.type = type; this.scope = scope; this.appId = appId; this.extensionId = extensionId; }; /** The event specific data. **/ CSEvent.prototype.data = ""; /** * Class SystemPath * Stores operating-system-specific location constants for use getSystemPath method. */ function SystemPath() { }; /** Identifies the path to user data. */ SystemPath.USER_DATA = "userData"; /** Identifies the path to common files for Adobe applications. */ SystemPath.COMMON_FILES = "commonFiles"; /** Identifies the path to the user's default document folder. */ SystemPath.MY_DOCUMENTS = "myDocuments"; /** Identifies the path to current extension. */ /** DEPRECATED, PLEASE USE EXTENSION INSTEAD. */ SystemPath.APPLICATION = "application"; /** Identifies the path to current extension. */ SystemPath.EXTENSION = "extension"; /** Identifies the path to hosting application's executable. */ SystemPath.HOST_APPLICATION = "hostApplication"; /** * Class ColorType * Stores the color-type constants. */ function ColorType() { }; /** rgb type. */ ColorType.RGB = "rgb"; /** gradient type. */ ColorType.GRADIENT = "gradient"; /** none type. */ ColorType.NONE = "none"; /** * Class RGBColor * Stores an RGB color with red, green, blue, and alpha values. All values are in the range * [0.0 to 255.0]. Invalid numeric values are converted to numbers within this range. * * @param red The red value, in the range [0.0 to 255.0]. * @param green The green value, in the range [0.0 to 255.0]. * @param blue The blue value, in the range [0.0 to 255.0]. * @param alpha The alpha (transparency) value, in the range [0.0 to 255.0]. * The default (255.0) means that the color is fully opaque. * * @return RGBColor object. */ function RGBColor(red, green, blue, alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; }; /** * Class Direction * Stores a point information. * * @param x X axis position. * @param y Y axis position. * * @return Direction object. */ function Direction(x, y) { this.x = x; this.y = y; }; /** * Class GradientStop * Stores gradient stop information. * * @param offset The offset of the gradient stop, in the range [0.0 to 1.0]. * @param rgbColor The RGBColor object. @see RGBColor. * * @return GradientStop object. */ function GradientStop(offset, rgbColor) { this.offset = offset; this.rgbColor = rgbColor; }; /** * Class GradientColor * Stores gradient color information. * * @param type The gradient type, the only valid value is "linear". * @param direction A vector describing the direction of the gradient. * A point value, in which the y component is 0 and the x component * is positive or negative for a right or left direction, * or the x component is 0 and the y component is positive or negative for * an up or down direction. @see Direction. * @param numStops The number of stops. * @param gradientStopList An array of GradientStop objects. @see GradientStop. * * @return GradientColor object. */ function GradientColor(type, direction, numStops, arrGradientStop) { this.type = type; this.direction = direction; this.numStops = numStops; this.arrGradientStop = arrGradientStop; }; /** * Class UIColor * Stores color information, including the type, anti-alias level, and specific color * values in a color object of an appropriate type. * * @param type The color type constant, 1 for "rgb" and 2 for "gradient". * @param antialiasLevel The anti-alias level constant. * @param color A GradientColor object or a RGBColor containing specific color information. * The type of color object depends on type parameter. @see GradientColor and RGBColor. * * @return UIColor object. */ function UIColor(type, antialiasLevel, color) { this.type = type; this.antialiasLevel = antialiasLevel; this.color = color; }; /** * Class AppSkinInfo * Stores window-skin properties, such as color and font. All parameters' type are UIColor. @see UIColor. * * @param baseFontFamily The base font family of the application. * @param baseFontSize The base font size of the application. * @param appBarBackgroundColor The application bar background color. * @param panelBackgroundColor The background color of the extension panel. * @param appBarBackgroundColorSRGB The application bar background color, as sRGB. * @param panelBackgroundColorSRGB The background color of the extension panel, as sRGB. * @param systemHighlightColor The operating-system highlight color, as sRGB. * * @return AppSkinInfo object. */ function AppSkinInfo(baseFontFamily, baseFontSize, appBarBackgroundColor, panelBackgroundColor, appBarBackgroundColorSRGB, panelBackgroundColorSRGB, systemHighlightColor) { this.baseFontFamily = baseFontFamily; this.baseFontSize = baseFontSize; this.appBarBackgroundColor = appBarBackgroundColor; this.panelBackgroundColor = panelBackgroundColor; this.appBarBackgroundColorSRGB = appBarBackgroundColorSRGB; this.panelBackgroundColorSRGB = panelBackgroundColorSRGB; this.systemHighlightColor = systemHighlightColor; }; /** * Class HostEnvironment * Stores information about the environment in which the extension is loaded. * * @param appName The application's name. * @param appVersion The application's version. * @param appLocale The application's current license locale. * @param appId The application's unique identifier. * @param isAppOffline True if the application is currently offline. * @param appSkinInfo A skin-information object containing the application's default color and font styles. @see AppSkinInfo. * @param appUILocale The application's current UI locale. * * @return HostEnvironment object. */ function HostEnvironment(appName, appVersion, appLocale, appUILocale, appId, isAppOffline, appSkinInfo) { this.appName = appName; this.appVersion = appVersion; this.appLocale = appLocale; this.appUILocale = appUILocale; this.appId = appId; this.isAppOffline = isAppOffline; this.appSkinInfo = appSkinInfo; }; /***********************************************************************************/ /** * Class CSInterface. * You can use it to communicate with native application. * * @return CSInterface object */ function CSInterface() { }; /** * User can add this event listener to handle native application theme color changes. * Callback function gives extensions ability to fine-tune their theme color after the * global theme color has been changed. * The callback function should be like below: * * @example * // event is a CSEvent object, but user can ignore it. * function OnAppThemeColorChanged(event) * { * // Should get a latest HostEnvironment object from application. * var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo; * // Gets the style information such as color info from the skinInfo, * // and redraw all UI controls of your extension according to the style info. * } */ CSInterface.THEME_COLOR_CHANGED_EVENT = "com.adobe.csxs.events.ThemeColorChanged"; /** The host environment data object **/ CSInterface.prototype.hostEnvironment = JSON.parse(window.__adobe_cep__.getHostEnvironment()); /** Close the current extension **/ CSInterface.prototype.closeExtension = function() { window.__adobe_cep__.closeExtension(); }; /** * Get system path. * * @param pathType A string containing a path-type constant defined in the SystemPath class, * such as SystemPath.USER_DATA. * @return path string */ CSInterface.prototype.getSystemPath = function(pathType) { var path = decodeURI(window.__adobe_cep__.getSystemPath(pathType)); var OSVersion = this.getOSInformation(); if (OSVersion.indexOf("Windows") >= 0) { path = path.replace("file:///", ""); } else if (OSVersion.indexOf("Mac") >= 0) { path = path.replace("file://", ""); } return path; }; /** * Eval scripts. You can use it to operate the DOM of native application. * * @param script The raw JavaScript. * @param callback The callback function that receives the execution result of the script. This parameter is optional. * If it fails to execute the script, the callback function will receive the error message EvalScript_ErrMessage. */ CSInterface.prototype.evalScript = function(script, callback) { if(callback == null || callback == undefined) { callback = function(result){}; } window.__adobe_cep__.evalScript(script, callback); }; /** * Get the identifier of the host application. * * @return a string identifier of the host application */ CSInterface.prototype.getApplicationID = function() { var appId = this.hostEnvironment.appId; return appId; }; /** * Get host capability information about the host application. * * @return an object that contains host capability information */ CSInterface.prototype.getHostCapabilities = function() { var hostCapabilities = JSON.parse(window.__adobe_cep__.getHostCapabilities() ); return hostCapabilities; }; /** * Triggering a CS Event programmatically. You can use it to dispatch a CSEvent. * * @param event a CS Event */ CSInterface.prototype.dispatchEvent = function(event) { if (typeof event.data == "object") { event.data = JSON.stringify(event.data); } window.__adobe_cep__.dispatchEvent(event); }; /** * Register a CS Event listener. You can use it to listen a CSEvent. * * @param type The Event type * @param listener The JavaScript function that receives a notification when * a CS event of the specified type occurs. * @param obj The object that listener belongs to. Use it when listener is a method * of an object. This parameter is optional and its default value is null. */ CSInterface.prototype.addEventListener = function(type, listener, obj) { window.__adobe_cep__.addEventListener(type, listener, obj); }; /** * Remove the CS Event listener. * * @param type event type * @param listener The JavaScript function that receives a notification when * a CS event of the specified type occurs. * @param obj The object that listener belongs to. Use it when listener is a method * of an object. This parameter is optional and its default value is null. */ CSInterface.prototype.removeEventListener = function(type, listener, obj) { window.__adobe_cep__.removeEventListener(type, listener, obj); }; /** * Loads and launches another extension. If the target extension is already loaded, it is activated. * * @param extensionId The extension's unique identifier. * @param startupParams Startup parameters to be passed to the loaded extension. * Specify key-value pairs as a GET URL parameter list; for example: "key1=value1&amp;key2=value2". * Currently this parameter is not supported by CEP, so it will always be "" for now. * * @example * To launch the extension "help" with ID "HLP" from this extension, call: * requestOpenExtension("HLP", ""); * */ CSInterface.prototype.requestOpenExtension = function(extensionId, params) { window.__adobe_cep__.requestOpenExtension(extensionId, params); }; /** * Retrieves the list of extensions currently loaded in the current host application. * The extension list is initialized once, and remains the same during the lifetime of the CSXS session. * * @param extensionIds An array of unique identifiers for extensions of interest. * If omitted, retrieves data for all extensions. * * @return An Extension object. */ CSInterface.prototype.getExtensions = function(extensionIds) { var extensionIdsStr = JSON.stringify(extensionIds); var extensionsStr = window.__adobe_cep__.getExtensions(extensionIdsStr); var extensions = JSON.parse(extensionsStr); return extensions; }; /** * Retrieves network-related preferences. * * @return A NetworkPreferences object. */ CSInterface.prototype.getNetworkPreferences = function() { var result = window.__adobe_cep__.getNetworkPreferences(); var networkPre = JSON.parse(result); return networkPre; }; /** * Initializes the resource bundle for this extension with property values for the current application and locale. * If user wants to support multi-locale to the extension, they should define a property file. An example of the property file content is: * * key1=value1 * key2=value2 * key3.value=value3 * * The property file should be placed in its corresponding locale folder. For example for en_US, the property file would be placed in YourExtension/locale/en_US/messages.properties. * Users can define a default property file, placed in "YourExtension/locale/" which will be used when the corresponding locale file is not defined. * Users should initialize locale strings during the loading of the extension. The locale loaded should match the current UI locale of the host application. * 'data-locale' is the custom HTML element attribute and you can added it to each HTML element that you want to localize. * * For example: * * <input type="submit" value="" data-locale="key3"/> * <script type="text/javascript"> * var cs = new CSInterface(); * // Get properties according to current locale of host application. * var resourceBundle = cs.initResourceBundle(); * // Refer the locale string. * document.write(resourceBundle.key1); * document.write(resourceBundle.key2); * </script> * * @return An object containing the resource bundle information. */ CSInterface.prototype.initResourceBundle = function() { var resourceBundle = JSON.parse(window.__adobe_cep__.initResourceBundle()); var resElms = document.querySelectorAll('[data-locale]'); for (var n = 0; n < resElms.length; n++) { var resEl = resElms[n]; // Get the resource key from the element. var resKey = resEl.getAttribute('data-locale'); if (resKey) { // Get all the resources that start with the key. for (var key in resourceBundle) { if (key.indexOf(resKey) == 0) { var resValue = resourceBundle[key]; if (key.indexOf('.') == -1) { // No dot notation in resource key, // assign the resource value to the element's // innerHTML. resEl.innerHTML = resValue; } else { // Dot notation in resource key, assign the // resource value to the element's property // whose name corresponds to the substring // after the dot. var attrKey = key.substring(key.indexOf('.') + 1); resEl[attrKey] = resValue; } } } } } return resourceBundle; }; /** * Writes installation information to a file. * * @return The dump info file path. */ CSInterface.prototype.dumpInstallationInfo = function() { return window.__adobe_cep__.dumpInstallationInfo(); }; /** * Get current Operating System information including version and 32-bit/64-bit. * Refer to http://www.useragentstring.com/pages/Chrome/ for all of the navigator.userAgent values retrieved by Chrome. * * @return The OS version in string or "unknown Operation System". */ CSInterface.prototype.getOSInformation = function() { var userAgent = navigator.userAgent; if ((navigator.platform == "Win32") || (navigator.platform == "Windows")) { var winVersion = "Windows platform"; if (userAgent.indexOf("Windows NT 5.0") > -1) { winVersion = "Windows 2000"; } else if (userAgent.indexOf("Windows NT 5.1") > -1) { winVersion = "Windows XP"; } else if (userAgent.indexOf("Windows NT 5.2") > -1) { winVersion = "Windows Server 2003"; } else if (userAgent.indexOf("Windows NT 6.0") > -1) { winVersion = "Windows Vista"; } else if (userAgent.indexOf("Windows NT 6.1") > -1) { winVersion = "Windows 7"; } else if (userAgent.indexOf("Windows NT 6.2") > -1) { winVersion = "Windows 8"; } var winBit = "32-bit"; if (userAgent.indexOf("WOW64") > -1) { winBit = "64-bit"; } return winVersion + " " + winBit; } else if ((navigator.platform == "MacIntel") || (navigator.platform == "Macintosh")) { var agentStr = new String(); agentStr = userAgent; var verLength = agentStr.indexOf(")") - agentStr.indexOf("Mac OS X"); var verStr = agentStr.substr(agentStr.indexOf("Mac OS X"), verLength); var result = verStr.replace("_", "."); result = result.replace("_", "."); return result; } return "Unknown Operation System"; }; ` CSInterface.SystemPath = SystemPath CSInterface.CSEvent = CSEvent module.exports = CSInterface
true
` /* ADOBE SYSTEMS INCORPORATED Copyright 2013 Adobe Systems Incorporated. All Rights Reserved. NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. If you have received this file from a source other than Adobe, then your use, modification, or distribution of it requires the prior written permission of Adobe. */ /** * Stores constants for the window types supported by the CSXS infrastructure. */ function CSXSWindowType() { }; /** Constant for the CSXS window type Panel. **/ CSXSWindowType._PANEL = "Panel"; /** Constant for the CSXS window type Modeless. **/ CSXSWindowType._MODELESS = "Modeless"; /** Constant for the CSXS window type ModalDialog. **/ CSXSWindowType._MODAL_DIALOG = "ModalDialog"; /** EvalScript error message**/ EvalScript_ErrMessage = "EvalScript error."; /** * Class Version * Defines a version number with major, minor, micro, and special * components. The major, minor and micro values are numeric; the special * value can be any string. * * @param major The major version component, a positive integer up to nine digits long. * @param minor The minor version component, a positive integer up to nine digits long. * @param micro The micro version component, a positive integer up to nine digits long. * @param special The special version component, an arbitrary string. * * @return A Version object. */ function Version(major, minor, micro, special) { this.major = major; this.minor = minor; this.micro = micro; this.special = special; }; /** * The maximum value allowed for a Numeric version component. * This reflects the maximum value allowed in PlugPlug and the manifest schema. */ Version.MAX_NUM = 999999999; /** * Class VersionBound * Defines a boundary for a version range, which associates a Version object with a flag for whether it is an inclusive * or exclusive boundary. * * @param version The Version object. * @see Version class. * @param inclusive True if this boundary is inclusive, false if it is exclusive. * * @return A VersionBound object. */ function VersionBound(version, inclusive) { this.version = version; this.inclusive = inclusive; }; /** * Class VersionRange. * Defines a range of versions using a lower boundary and optional upper boundary. * * @param lowerBound The VersionBound object. @see VersionBound. * @param upperBound The VersionBound object, or null for a range with no upper boundary. @see VersionBound. * * @return A VersionRange object. */ function VersionRange(lowerBound, upperBound) { this.lowerBound = lowerBound; this.upperBound = upperBound; }; /** * Class Runtime. * Represents a runtime related to the CSXS infrastructure. Extensions can declare dependencies on particular * CSXS runtime versions in the extension manifest. * * @param name The runtime name. * @param version The VersionRange object. @see VersionRange. * * @return A Runtime object. */ function Runtime(name, versionRange) { this.name = name; this.versionRange = versionRange; }; /** * Class Extension. * Contains the classes that define data types for the CEP libraries. * * @param id The unique identifier of this extension. * @param name The localizable display name of this extension. * @param mainPath The path of the "index.html" file. * @param basePath The base path of this extension. * @param windowType The window type of the main window of this extension. Valid values are defined by CSXSWindowType. @see CSXSWindowType. * @param width The default width in pixels of the main window of this extension. * @param height The default height in pixels of the main window of this extension. * @param minWidth The minimum width in pixels of the main window of this extension. * @param minHeight The minimum height in pixels of the main window of this extension. * @param maxWidth The maximum width in pixels of the main window of this extension. * @param maxHeight The maximum height in pixels of the main window of this extension. * @param defaultExtensionDataXml The extension data contained in the default ExtensionDispatchInfo section of the extension manifest. * @param specialExtensionDataXml The extension data contained in the application-specific ExtensionDispatchInfo section of the extension manifest. * @param requiredRuntimeList An array of Runtime objects for runtimes required by this extension. @see VersionRange. * @param isAutoVisible True if this extension is visible on loading. * @param isPluginExtension True if this extension has been deployed in the Plugins folder of the host application. * * @return An Extension object. */ function Extension(id, name, mainPath, basePath, windowType, width, height, minWidth, minHeight, maxWidth, maxHeight, defaultExtensionDataXml, specialExtensionDataXml, requiredRuntimeList, isAutoVisible, isPluginExtension) { this.id = id; this.name = PI:NAME:<NAME>END_PI; this.mainPath = mainPath; this.basePath = basePath; this.windowType = windowType; this.width = width; this.height = height; this.minWidth = minWidth; this.minHeight = minHeight; this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.defaultExtensionDataXml = defaultExtensionDataXml; this.specialExtensionDataXml = specialExtensionDataXml; this.requiredRuntimeList = requiredRuntimeList; this.isAutoVisible = isAutoVisible; this.isPluginExtension = isPluginExtension; }; /** * Class CSEvent. * You can use it to dispatch a standard Javascript event. * * @param type Event type. * @param scope The scope of event, can be "GLOBAL" or "APPLICATION". * @param appId The unique identifier of the application that generated the event. * @param extensionId The unique identifier of the extension that generated the event. * * @return CSEvent object */ function CSEvent(type, scope, appId, extensionId) { this.type = type; this.scope = scope; this.appId = appId; this.extensionId = extensionId; }; /** The event specific data. **/ CSEvent.prototype.data = ""; /** * Class SystemPath * Stores operating-system-specific location constants for use getSystemPath method. */ function SystemPath() { }; /** Identifies the path to user data. */ SystemPath.USER_DATA = "userData"; /** Identifies the path to common files for Adobe applications. */ SystemPath.COMMON_FILES = "commonFiles"; /** Identifies the path to the user's default document folder. */ SystemPath.MY_DOCUMENTS = "myDocuments"; /** Identifies the path to current extension. */ /** DEPRECATED, PLEASE USE EXTENSION INSTEAD. */ SystemPath.APPLICATION = "application"; /** Identifies the path to current extension. */ SystemPath.EXTENSION = "extension"; /** Identifies the path to hosting application's executable. */ SystemPath.HOST_APPLICATION = "hostApplication"; /** * Class ColorType * Stores the color-type constants. */ function ColorType() { }; /** rgb type. */ ColorType.RGB = "rgb"; /** gradient type. */ ColorType.GRADIENT = "gradient"; /** none type. */ ColorType.NONE = "none"; /** * Class RGBColor * Stores an RGB color with red, green, blue, and alpha values. All values are in the range * [0.0 to 255.0]. Invalid numeric values are converted to numbers within this range. * * @param red The red value, in the range [0.0 to 255.0]. * @param green The green value, in the range [0.0 to 255.0]. * @param blue The blue value, in the range [0.0 to 255.0]. * @param alpha The alpha (transparency) value, in the range [0.0 to 255.0]. * The default (255.0) means that the color is fully opaque. * * @return RGBColor object. */ function RGBColor(red, green, blue, alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; }; /** * Class Direction * Stores a point information. * * @param x X axis position. * @param y Y axis position. * * @return Direction object. */ function Direction(x, y) { this.x = x; this.y = y; }; /** * Class GradientStop * Stores gradient stop information. * * @param offset The offset of the gradient stop, in the range [0.0 to 1.0]. * @param rgbColor The RGBColor object. @see RGBColor. * * @return GradientStop object. */ function GradientStop(offset, rgbColor) { this.offset = offset; this.rgbColor = rgbColor; }; /** * Class GradientColor * Stores gradient color information. * * @param type The gradient type, the only valid value is "linear". * @param direction A vector describing the direction of the gradient. * A point value, in which the y component is 0 and the x component * is positive or negative for a right or left direction, * or the x component is 0 and the y component is positive or negative for * an up or down direction. @see Direction. * @param numStops The number of stops. * @param gradientStopList An array of GradientStop objects. @see GradientStop. * * @return GradientColor object. */ function GradientColor(type, direction, numStops, arrGradientStop) { this.type = type; this.direction = direction; this.numStops = numStops; this.arrGradientStop = arrGradientStop; }; /** * Class UIColor * Stores color information, including the type, anti-alias level, and specific color * values in a color object of an appropriate type. * * @param type The color type constant, 1 for "rgb" and 2 for "gradient". * @param antialiasLevel The anti-alias level constant. * @param color A GradientColor object or a RGBColor containing specific color information. * The type of color object depends on type parameter. @see GradientColor and RGBColor. * * @return UIColor object. */ function UIColor(type, antialiasLevel, color) { this.type = type; this.antialiasLevel = antialiasLevel; this.color = color; }; /** * Class AppSkinInfo * Stores window-skin properties, such as color and font. All parameters' type are UIColor. @see UIColor. * * @param baseFontFamily The base font family of the application. * @param baseFontSize The base font size of the application. * @param appBarBackgroundColor The application bar background color. * @param panelBackgroundColor The background color of the extension panel. * @param appBarBackgroundColorSRGB The application bar background color, as sRGB. * @param panelBackgroundColorSRGB The background color of the extension panel, as sRGB. * @param systemHighlightColor The operating-system highlight color, as sRGB. * * @return AppSkinInfo object. */ function AppSkinInfo(baseFontFamily, baseFontSize, appBarBackgroundColor, panelBackgroundColor, appBarBackgroundColorSRGB, panelBackgroundColorSRGB, systemHighlightColor) { this.baseFontFamily = baseFontFamily; this.baseFontSize = baseFontSize; this.appBarBackgroundColor = appBarBackgroundColor; this.panelBackgroundColor = panelBackgroundColor; this.appBarBackgroundColorSRGB = appBarBackgroundColorSRGB; this.panelBackgroundColorSRGB = panelBackgroundColorSRGB; this.systemHighlightColor = systemHighlightColor; }; /** * Class HostEnvironment * Stores information about the environment in which the extension is loaded. * * @param appName The application's name. * @param appVersion The application's version. * @param appLocale The application's current license locale. * @param appId The application's unique identifier. * @param isAppOffline True if the application is currently offline. * @param appSkinInfo A skin-information object containing the application's default color and font styles. @see AppSkinInfo. * @param appUILocale The application's current UI locale. * * @return HostEnvironment object. */ function HostEnvironment(appName, appVersion, appLocale, appUILocale, appId, isAppOffline, appSkinInfo) { this.appName = appName; this.appVersion = appVersion; this.appLocale = appLocale; this.appUILocale = appUILocale; this.appId = appId; this.isAppOffline = isAppOffline; this.appSkinInfo = appSkinInfo; }; /***********************************************************************************/ /** * Class CSInterface. * You can use it to communicate with native application. * * @return CSInterface object */ function CSInterface() { }; /** * User can add this event listener to handle native application theme color changes. * Callback function gives extensions ability to fine-tune their theme color after the * global theme color has been changed. * The callback function should be like below: * * @example * // event is a CSEvent object, but user can ignore it. * function OnAppThemeColorChanged(event) * { * // Should get a latest HostEnvironment object from application. * var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo; * // Gets the style information such as color info from the skinInfo, * // and redraw all UI controls of your extension according to the style info. * } */ CSInterface.THEME_COLOR_CHANGED_EVENT = "com.adobe.csxs.events.ThemeColorChanged"; /** The host environment data object **/ CSInterface.prototype.hostEnvironment = JSON.parse(window.__adobe_cep__.getHostEnvironment()); /** Close the current extension **/ CSInterface.prototype.closeExtension = function() { window.__adobe_cep__.closeExtension(); }; /** * Get system path. * * @param pathType A string containing a path-type constant defined in the SystemPath class, * such as SystemPath.USER_DATA. * @return path string */ CSInterface.prototype.getSystemPath = function(pathType) { var path = decodeURI(window.__adobe_cep__.getSystemPath(pathType)); var OSVersion = this.getOSInformation(); if (OSVersion.indexOf("Windows") >= 0) { path = path.replace("file:///", ""); } else if (OSVersion.indexOf("Mac") >= 0) { path = path.replace("file://", ""); } return path; }; /** * Eval scripts. You can use it to operate the DOM of native application. * * @param script The raw JavaScript. * @param callback The callback function that receives the execution result of the script. This parameter is optional. * If it fails to execute the script, the callback function will receive the error message EvalScript_ErrMessage. */ CSInterface.prototype.evalScript = function(script, callback) { if(callback == null || callback == undefined) { callback = function(result){}; } window.__adobe_cep__.evalScript(script, callback); }; /** * Get the identifier of the host application. * * @return a string identifier of the host application */ CSInterface.prototype.getApplicationID = function() { var appId = this.hostEnvironment.appId; return appId; }; /** * Get host capability information about the host application. * * @return an object that contains host capability information */ CSInterface.prototype.getHostCapabilities = function() { var hostCapabilities = JSON.parse(window.__adobe_cep__.getHostCapabilities() ); return hostCapabilities; }; /** * Triggering a CS Event programmatically. You can use it to dispatch a CSEvent. * * @param event a CS Event */ CSInterface.prototype.dispatchEvent = function(event) { if (typeof event.data == "object") { event.data = JSON.stringify(event.data); } window.__adobe_cep__.dispatchEvent(event); }; /** * Register a CS Event listener. You can use it to listen a CSEvent. * * @param type The Event type * @param listener The JavaScript function that receives a notification when * a CS event of the specified type occurs. * @param obj The object that listener belongs to. Use it when listener is a method * of an object. This parameter is optional and its default value is null. */ CSInterface.prototype.addEventListener = function(type, listener, obj) { window.__adobe_cep__.addEventListener(type, listener, obj); }; /** * Remove the CS Event listener. * * @param type event type * @param listener The JavaScript function that receives a notification when * a CS event of the specified type occurs. * @param obj The object that listener belongs to. Use it when listener is a method * of an object. This parameter is optional and its default value is null. */ CSInterface.prototype.removeEventListener = function(type, listener, obj) { window.__adobe_cep__.removeEventListener(type, listener, obj); }; /** * Loads and launches another extension. If the target extension is already loaded, it is activated. * * @param extensionId The extension's unique identifier. * @param startupParams Startup parameters to be passed to the loaded extension. * Specify key-value pairs as a GET URL parameter list; for example: "key1=value1&amp;key2=value2". * Currently this parameter is not supported by CEP, so it will always be "" for now. * * @example * To launch the extension "help" with ID "HLP" from this extension, call: * requestOpenExtension("HLP", ""); * */ CSInterface.prototype.requestOpenExtension = function(extensionId, params) { window.__adobe_cep__.requestOpenExtension(extensionId, params); }; /** * Retrieves the list of extensions currently loaded in the current host application. * The extension list is initialized once, and remains the same during the lifetime of the CSXS session. * * @param extensionIds An array of unique identifiers for extensions of interest. * If omitted, retrieves data for all extensions. * * @return An Extension object. */ CSInterface.prototype.getExtensions = function(extensionIds) { var extensionIdsStr = JSON.stringify(extensionIds); var extensionsStr = window.__adobe_cep__.getExtensions(extensionIdsStr); var extensions = JSON.parse(extensionsStr); return extensions; }; /** * Retrieves network-related preferences. * * @return A NetworkPreferences object. */ CSInterface.prototype.getNetworkPreferences = function() { var result = window.__adobe_cep__.getNetworkPreferences(); var networkPre = JSON.parse(result); return networkPre; }; /** * Initializes the resource bundle for this extension with property values for the current application and locale. * If user wants to support multi-locale to the extension, they should define a property file. An example of the property file content is: * * key1=value1 * key2=value2 * key3.value=value3 * * The property file should be placed in its corresponding locale folder. For example for en_US, the property file would be placed in YourExtension/locale/en_US/messages.properties. * Users can define a default property file, placed in "YourExtension/locale/" which will be used when the corresponding locale file is not defined. * Users should initialize locale strings during the loading of the extension. The locale loaded should match the current UI locale of the host application. * 'data-locale' is the custom HTML element attribute and you can added it to each HTML element that you want to localize. * * For example: * * <input type="submit" value="" data-locale="key3"/> * <script type="text/javascript"> * var cs = new CSInterface(); * // Get properties according to current locale of host application. * var resourceBundle = cs.initResourceBundle(); * // Refer the locale string. * document.write(resourceBundle.key1); * document.write(resourceBundle.key2); * </script> * * @return An object containing the resource bundle information. */ CSInterface.prototype.initResourceBundle = function() { var resourceBundle = JSON.parse(window.__adobe_cep__.initResourceBundle()); var resElms = document.querySelectorAll('[data-locale]'); for (var n = 0; n < resElms.length; n++) { var resEl = resElms[n]; // Get the resource key from the element. var resKey = resEl.getAttribute('data-locale'); if (resKey) { // Get all the resources that start with the key. for (var key in resourceBundle) { if (key.indexOf(resKey) == 0) { var resValue = resourceBundle[key]; if (key.indexOf('.') == -1) { // No dot notation in resource key, // assign the resource value to the element's // innerHTML. resEl.innerHTML = resValue; } else { // Dot notation in resource key, assign the // resource value to the element's property // whose name corresponds to the substring // after the dot. var attrKey = key.substring(key.indexOf('.') + 1); resEl[attrKey] = resValue; } } } } } return resourceBundle; }; /** * Writes installation information to a file. * * @return The dump info file path. */ CSInterface.prototype.dumpInstallationInfo = function() { return window.__adobe_cep__.dumpInstallationInfo(); }; /** * Get current Operating System information including version and 32-bit/64-bit. * Refer to http://www.useragentstring.com/pages/Chrome/ for all of the navigator.userAgent values retrieved by Chrome. * * @return The OS version in string or "unknown Operation System". */ CSInterface.prototype.getOSInformation = function() { var userAgent = navigator.userAgent; if ((navigator.platform == "Win32") || (navigator.platform == "Windows")) { var winVersion = "Windows platform"; if (userAgent.indexOf("Windows NT 5.0") > -1) { winVersion = "Windows 2000"; } else if (userAgent.indexOf("Windows NT 5.1") > -1) { winVersion = "Windows XP"; } else if (userAgent.indexOf("Windows NT 5.2") > -1) { winVersion = "Windows Server 2003"; } else if (userAgent.indexOf("Windows NT 6.0") > -1) { winVersion = "Windows Vista"; } else if (userAgent.indexOf("Windows NT 6.1") > -1) { winVersion = "Windows 7"; } else if (userAgent.indexOf("Windows NT 6.2") > -1) { winVersion = "Windows 8"; } var winBit = "32-bit"; if (userAgent.indexOf("WOW64") > -1) { winBit = "64-bit"; } return winVersion + " " + winBit; } else if ((navigator.platform == "MacIntel") || (navigator.platform == "Macintosh")) { var agentStr = new String(); agentStr = userAgent; var verLength = agentStr.indexOf(")") - agentStr.indexOf("Mac OS X"); var verStr = agentStr.substr(agentStr.indexOf("Mac OS X"), verLength); var result = verStr.replace("_", "."); result = result.replace("_", "."); return result; } return "Unknown Operation System"; }; ` CSInterface.SystemPath = SystemPath CSInterface.CSEvent = CSEvent module.exports = CSInterface
[ { "context": "ashana', 'ErebYomTob', 'HataratNedarim'], '1': ['RoshHashana', 'YomTob', '1stDayOfYomTob'], '2': ['RoshHashana", "end": 6276, "score": 0.9794101715087891, "start": 6266, "tag": "NAME", "value": "oshHashana" }, { "context": "oshHashana', 'YomTob', '1stDayOfYomTob'], '2': ['RoshHashana', 'YomTob', '2ndDayOfYomTob'], '3': ['FastOfGedal", "end": 6326, "score": 0.9229238629341125, "start": 6316, "tag": "NAME", "value": "oshHashana" }, { "context": "'BeginTalUmatar', new Date(1899,11,4), before: ['RoshHodesh', 'Chanukkah'], during: ['Chanukkah'])\n edgeTest", "end": 8578, "score": 0.6843663454055786, "start": 8569, "tag": "NAME", "value": "oshHodesh" }, { "context": " new Date(1899,11,4), before: ['RoshHodesh', 'Chanukkah'], during: ['Chanukkah'])\n edgeTestOneDayChag('B", "end": 8591, "score": 0.5758122205734253, "start": 8586, "tag": "NAME", "value": "ukkah" }, { "context": "'BeginTalUmatar', new Date(1999,11,5), all: ['Chanukkah'], before: ['Shabbat', 'ShabbatMevarechim'])\n ed", "end": 8694, "score": 0.6943069100379944, "start": 8689, "tag": "NAME", "value": "ukkah" }, { "context": "'BeginTalUmatar', new Date(2010,11,4), all: ['Chanukkah'], before: ['ErebShabbat'], during: ['Shabbat', '", "end": 8816, "score": 0.6012330055236816, "start": 8811, "tag": "NAME", "value": "ukkah" }, { "context": "'BeginTalUmatar', new Date(2013,11,4), all: ['Chanukkah'], before: ['RoshHodesh'], during: ['RoshHodesh']", "end": 9083, "score": 0.7545645833015442, "start": 9078, "tag": "NAME", "value": "ukkah" }, { "context": "w Date(2013,11,4), all: ['Chanukkah'], before: ['RoshHodesh'], during: ['RoshHodesh'])\n edgeTestOneDayChag('", "end": 9107, "score": 0.7584924697875977, "start": 9098, "tag": "NAME", "value": "oshHodesh" }, { "context": "BeginTalUmatar', new Date(2100,11,5), before: ['Shabbat'])\n edgeTestOneDayChag('BeginTalUmatar', new Dat", "end": 9339, "score": 0.7411704063415527, "start": 9334, "tag": "NAME", "value": "abbat" }, { "context": "eginTalUmatar', new Date(2102,11,5), after: ['Chanukkah'])\n edgeTestOneDayChag('BeginTalUmatar', new Dat", "end": 9481, "score": 0.6515474319458008, "start": 9476, "tag": "NAME", "value": "ukkah" } ]
qunit/hebrewDateTest.coffee
betesh/hebrewDate.js
0
assetHebrewDate = (date, hebrewYear, hebrewMonth, dayOfMonth, dayOfYear) -> QUnit.test "#{date} is '#{hebrewMonth.name}' #{dayOfMonth}, #{hebrewYear}", (assert) -> actual = new HebrewDate(date) assert.deepEqual actual.getYearFromCreation(), hebrewYear assert.deepEqual actual.getHebrewMonth().getName(), hebrewMonth.name assert.deepEqual actual.getDayOfMonth(), dayOfMonth assert.deepEqual actual.getDayOfYear(), dayOfYear assertChag = (name, date, otherOccasions = [], _is) -> QUnit.test "#{date} is #{if _is then '' else 'not'} #{name}", (assert) -> target = new HebrewDate(date) result = target["is#{name}"]() assert.ok(if _is then result else !result) otherOccasions.push(name) if _is assert.deepEqual target.occasions(), otherOccasions.sort() assertIsChag = (name, date, otherOccasions) -> assertChag(name, date, otherOccasions, true) assertNotChag = (name, date, otherOccasions) -> assertChag(name, date, otherOccasions, false) edgeTestOneDayChag = (name, date, otherOccasions = {}) -> otherOccasions.all ?= [] before = new Date(date) before.setDate(before.getDate() - 1) after = new Date(date) after.setDate(after.getDate() + 1) assertNotChag(name, before, (otherOccasions.before ? []).concat(otherOccasions.all)) assertIsChag(name, date, (otherOccasions.during ? []).concat(otherOccasions.all)) assertNotChag(name, after, (otherOccasions.after ? []).concat(otherOccasions.all)) edgeTestMultiDayChag = (name, date, length, otherOccasions = {}) -> otherOccasions.all ?= [] otherOccasions.during ?= [] otherOccasions.around ?= [] before = new Date(date) before.setDate(before.getDate() - 1) assertNotChag(name, before, (otherOccasions.before ? []).concat(otherOccasions.all, otherOccasions.around)) for i in [1..length] assertIsChag(name, new Date(date), (otherOccasions["#{i}"] ? []).concat(otherOccasions.all, otherOccasions.during)) date.setDate(date.getDate() + 1) assertNotChag(name, date, (otherOccasions.after ? []).concat(otherOccasions.all, otherOccasions.around)) roshHodeshTest = -> edgeTestOneDayChag('RoshHodesh', new Date(2015,6,17), after: ['Shabbat'], during: ['ErebShabbat']) edgeTestMultiDayChag('RoshHodesh', new Date(2015,9,13), 2) shabbatTest = -> edgeTestOneDayChag('Shabbat', new Date(2014,6,19), before: ['ErebShabbat']) edgeTestOneDayChag('Shabbat', new Date(2014,6,26), before: ['ErebShabbat'], during: ['ShabbatMevarechim']) purimTest = -> edgeTestOneDayChag('Purim', new Date(2013,1,24), before: ['Shabbat', 'ShabbatZachor'], after: ['ShushanPurim']) edgeTestOneDayChag('Purim', new Date(2014,2,16), before: ['Shabbat', 'ShabbatZachor'], after: ['ShushanPurim']) assertNotChag('Purim', new Date(2014,1,14), ['PurimKatan', 'ErebShabbat']) edgeTestOneDayChag('ShushanPurim', new Date(2013,1,25), before: ['Purim']) edgeTestOneDayChag('ShushanPurim', new Date(2014,2,17), before: ['Purim']) edgeTestOneDayChag('PurimKatan', new Date(2014,1,14), during: ['ErebShabbat'], after: ['ShushanPurimKatan', 'Shabbat']) edgeTestOneDayChag('ShushanPurimKatan', new Date(2014,1,15), during: ['Shabbat'], before: ['PurimKatan', 'ErebShabbat']) moedTest = -> edgeTestMultiDayChag('Moed', new Date(2014,3,17), 4, all: ['Pesach', 'Regel'], before: ['2ndDayOfPesach', '2ndDayOfYomTob'], around: ['YomTob'], '2': ['ErebShabbat'], '3': ['Shabbat'], '4': ['ErebYomTob', '6thDayOfPesach'], after: ['1stDayOfYomTob', '7thDayOfPesach']) edgeTestMultiDayChag('Moed', new Date(2014,9,11), 5, all: ['Sukkot', 'Regel'], around: ['YomTob'], before: ['ErebShabbat', '2ndDayOfYomTob'], '1': ['Shabbat'], '4': ['ErebHoshanaRaba'], '5': ['ErebYomTob', 'ErubTabshilin', 'HoshanaRaba'], after: ['SheminiAseret', '1stDayOfYomTob']) pesachTest = -> edgeTestMultiDayChag('Pesach', new Date(2013,2,26), 8, before: ['ErebYomTob','ErebPesach'], '1': ['YomTob', '1stDayOfYomTob', '1stDayOfPesach'], '2': ['YomTob', '2ndDayOfYomTob', '2ndDayOfPesach'], '3': ['Moed'], '4': ['Moed', 'ErebShabbat'], '5': ['Moed','Shabbat'], '6': ['Moed', 'ErebYomTob', '6thDayOfPesach'], '7': ['YomTob', '1stDayOfYomTob', '7thDayOfPesach'], '8': ['YomTob', '2ndDayOfYomTob', '8thDayOfPesach'], during: ['Regel']) edgeTestMultiDayChag('Pesach', new Date(2015,3,4), 8, before: ['ErebShabbat', 'ErebYomTob', 'ErebPesach'], '1': ['Shabbat', 'YomTob', '1stDayOfYomTob', '1stDayOfPesach'], '2': ['YomTob', '2ndDayOfYomTob', '2ndDayOfPesach'], '3': ['Moed'], '4': ['Moed'], '5': ['Moed'], '6': ['Moed', 'ErebYomTob', 'ErubTabshilin', '6thDayOfPesach'], '7': ['YomTob', 'ErebShabbat', '1stDayOfYomTob', '7thDayOfPesach'], '8': ['Shabbat', 'YomTob', '2ndDayOfYomTob', '8thDayOfPesach'], during: ['Regel']) shabuotTest = -> edgeTestMultiDayChag('Shabuot', new Date(2013,4,15), 2, before: ['ErebYomTob','ErebShabuot'], '1':['1stDayOfYomTob', '1stDayOfShabuot'], '2': ['2ndDayOfYomTob'], during: ['Regel', 'YomTob'], after: ['ErebShabbat']) edgeTestMultiDayChag('Shabuot', new Date(2015,4,24), 2, before: ['Shabbat', 'ErebYomTob','ErebShabuot'], '1':['1stDayOfYomTob', '1stDayOfShabuot'], '2': ['2ndDayOfYomTob'], during: ['Regel', 'YomTob']) roshHashanaTest = -> edgeTestMultiDayChag('RoshHashana', new Date(2011,8,29), 2, before: ['ErebYomTob', 'HataratNedarim', 'ErubTabshilin','ErebRoshHashana'], during: ['10DaysOfTeshuba', 'YomTob'], '1': ['1stDayOfYomTob'], '2': ['ErebShabbat', '2ndDayOfYomTob'], after: ['Shabbat', '10DaysOfTeshuba']) edgeTestMultiDayChag('RoshHashana', new Date(2015,8,14), 2, before: ['ErebYomTob', 'HataratNedarim','ErebRoshHashana'], during: ['10DaysOfTeshuba', 'YomTob'], '1': ['1stDayOfYomTob'], '2': ['2ndDayOfYomTob'], after: ['10DaysOfTeshuba', 'FastOfGedaliah', 'Taanit']) tenDaysOfTeshubaTest = -> edgeTestMultiDayChag('10DaysOfTeshuba', new Date(2011,8,29), 10, before: ['ErebRoshHashana', 'ErebYomTob', 'HataratNedarim', 'ErubTabshilin'], '1': ['RoshHashana', 'YomTob', '1stDayOfYomTob'], '2': ['RoshHashana', 'YomTob', 'ErebShabbat', '2ndDayOfYomTob'], '3': ['Shabbat'], '4': ['FastOfGedaliah', 'Taanit'], '9': ['ErebShabbat', 'ErebYomKippur', 'HataratNedarim'], '10': ['Shabbat', 'YomKippur']) edgeTestMultiDayChag('10DaysOfTeshuba', new Date(2015,8,14), 10, before: ['ErebRoshHashana', 'ErebYomTob', 'HataratNedarim'], '1': ['RoshHashana', 'YomTob', '1stDayOfYomTob'], '2': ['RoshHashana', 'YomTob', '2ndDayOfYomTob'], '3': ['FastOfGedaliah', 'Taanit'], '5': ['ErebShabbat'], '6': ['Shabbat'], '9': ['HataratNedarim', 'ErebYomKippur'], '10': ['YomKippur']) yomKippurTest = -> edgeTestMultiDayChag('YomKippur', new Date(2011,9,8), 1, before: ['10DaysOfTeshuba', 'ErebShabbat', 'HataratNedarim', 'ErebYomKippur'], '1': ['Shabbat', '10DaysOfTeshuba']) edgeTestMultiDayChag('YomKippur', new Date(2015,8,23), 1, before: ['10DaysOfTeshuba', 'HataratNedarim', 'ErebYomKippur'], '1': ['10DaysOfTeshuba']) sukkotTest = -> edgeTestMultiDayChag('Sukkot', new Date(2011,9,13), 9, before: ['ErebYomTob', 'ErubTabshilin', 'ErebSukkot'], '1': ['YomTob', '1stDayOfYomTob'], '2': ['YomTob', 'ErebShabbat', '2ndDayOfYomTob'], '3': ['Moed', 'Shabbat'], '4': ['Moed'], '5': ['Moed'], '6': ['Moed', 'ErebHoshanaRaba'], '7': ['Moed', 'ErebYomTob', 'ErubTabshilin', 'HoshanaRaba'], '8': ['YomTob', '1stDayOfYomTob', 'SheminiAseret'], '9': ['YomTob', 'ErebShabbat', '2ndDayOfYomTob', 'SheminiAseret'], after: ['Shabbat', 'ShabbatMevarechim'], during: ['Regel']) edgeTestMultiDayChag('Sukkot', new Date(2015,8,28), 9, before: ['ErebYomTob', 'ErebSukkot'], '1': ['YomTob', '1stDayOfYomTob'], '2': ['YomTob', '2ndDayOfYomTob'], '3': ['Moed'], '4': ['Moed'], '5': ['Moed', 'ErebShabbat'], '6': ['Moed','Shabbat', 'ErebHoshanaRaba'], '7': ['Moed', 'ErebYomTob', 'HoshanaRaba'], '8': ['YomTob', '1stDayOfYomTob', 'SheminiAseret'], '9': ['YomTob', '2ndDayOfYomTob', 'SheminiAseret'], during: ['Regel']) chanukkahTest = -> edgeTestMultiDayChag('Chanukkah', new Date(2011,11,21), 8, '3': ['ErebShabbat'], '4': ['Shabbat', 'ShabbatMevarechim'], '6': ['RoshHodesh'], '7': ['RoshHodesh']) edgeTestMultiDayChag('Chanukkah', new Date(2012,11,9), 8, '6': ['RoshHodesh', 'ErebShabbat'], '7': ['Shabbat'], before: ['Shabbat', 'ShabbatMevarechim']) edgeTestMultiDayChag('Chanukkah', new Date(2013,10,28), 8, '2': ['ErebShabbat'], '3': ['Shabbat', 'ShabbatMevarechim'], '6': ['RoshHodesh'], '7': ['RoshHodesh', 'BeginTalUmatar'], after: ['ErebShabbat']) beginTalUmatarTest = -> edgeTestOneDayChag('BeginTalUmatar', new Date(1898,11,3), before: ['ErebShabbat'], during: ['Shabbat']) edgeTestOneDayChag('BeginTalUmatar', new Date(1899,11,4), before: ['RoshHodesh', 'Chanukkah'], during: ['Chanukkah']) edgeTestOneDayChag('BeginTalUmatar', new Date(1999,11,5), all: ['Chanukkah'], before: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2010,11,4), all: ['Chanukkah'], before: ['ErebShabbat'], during: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2011,11,5)) edgeTestOneDayChag('BeginTalUmatar', new Date(2012,11,4)) edgeTestOneDayChag('BeginTalUmatar', new Date(2013,11,4), all: ['Chanukkah'], before: ['RoshHodesh'], during: ['RoshHodesh']) edgeTestOneDayChag('BeginTalUmatar', new Date(2099,11,5), before: ['ErebShabbat'], during: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2100,11,5), before: ['Shabbat']) edgeTestOneDayChag('BeginTalUmatar', new Date(2101,11,5)) edgeTestOneDayChag('BeginTalUmatar', new Date(2102,11,5), after: ['Chanukkah']) edgeTestOneDayChag('BeginTalUmatar', new Date(2103,11,6), after: ['ErebShabbat']) omerTest = (date, omerDay) -> QUnit.test "#{date} is day #{omerDay} of the omer", (assert) -> actual = new HebrewDate(date) assert.deepEqual actual.omer(), { today: omerDay, tonight: omerDay + 1 } omerEdgeTest = (date, omerDay, prop) -> QUnit.test "On #{date}, day #{omerDay} of the omer is #{prop}", (assert) -> actual = new HebrewDate(date) assert.equal actual.omer()[prop], omerDay size = 0 size++ for k,v of actual.omer() assert.equal size, 1 notOmerTest = (date) -> QUnit.test "#{date} is not during the omer", (assert) -> actual = new HebrewDate(date) assert.ok not actual.omer() assetHebrewDate(new Date(2014,6,20), 5774, HebrewMonth.TAMUZ, 22, 319) assetHebrewDate(new Date(2014,4,12), 5774, HebrewMonth.IYAR, 12, 250) roshHodeshTest() shabbatTest() purimTest() moedTest() pesachTest() shabuotTest() roshHashanaTest() tenDaysOfTeshubaTest() yomKippurTest() sukkotTest() chanukkahTest() beginTalUmatarTest() notOmerTest(new Date(2015,3,3)) omerEdgeTest(new Date(2015,3,4), 1, 'tonight') omerTest(new Date(2015,3,5), 1) omerTest(new Date(2015,3,6), 2) omerTest(new Date(2015,3,18), 14) omerTest(new Date(2015,3,19), 15) omerTest(new Date(2015,3,20), 16) omerTest(new Date(2015,4,17), 43) omerTest(new Date(2015,4,18), 44) omerTest(new Date(2015,4,19), 45) omerTest(new Date(2015,4,22), 48) omerEdgeTest(new Date(2015,4,23), 49, 'today') notOmerTest(new Date(2015,4,24)) notOmerTest(new Date(2015,9,1))
69433
assetHebrewDate = (date, hebrewYear, hebrewMonth, dayOfMonth, dayOfYear) -> QUnit.test "#{date} is '#{hebrewMonth.name}' #{dayOfMonth}, #{hebrewYear}", (assert) -> actual = new HebrewDate(date) assert.deepEqual actual.getYearFromCreation(), hebrewYear assert.deepEqual actual.getHebrewMonth().getName(), hebrewMonth.name assert.deepEqual actual.getDayOfMonth(), dayOfMonth assert.deepEqual actual.getDayOfYear(), dayOfYear assertChag = (name, date, otherOccasions = [], _is) -> QUnit.test "#{date} is #{if _is then '' else 'not'} #{name}", (assert) -> target = new HebrewDate(date) result = target["is#{name}"]() assert.ok(if _is then result else !result) otherOccasions.push(name) if _is assert.deepEqual target.occasions(), otherOccasions.sort() assertIsChag = (name, date, otherOccasions) -> assertChag(name, date, otherOccasions, true) assertNotChag = (name, date, otherOccasions) -> assertChag(name, date, otherOccasions, false) edgeTestOneDayChag = (name, date, otherOccasions = {}) -> otherOccasions.all ?= [] before = new Date(date) before.setDate(before.getDate() - 1) after = new Date(date) after.setDate(after.getDate() + 1) assertNotChag(name, before, (otherOccasions.before ? []).concat(otherOccasions.all)) assertIsChag(name, date, (otherOccasions.during ? []).concat(otherOccasions.all)) assertNotChag(name, after, (otherOccasions.after ? []).concat(otherOccasions.all)) edgeTestMultiDayChag = (name, date, length, otherOccasions = {}) -> otherOccasions.all ?= [] otherOccasions.during ?= [] otherOccasions.around ?= [] before = new Date(date) before.setDate(before.getDate() - 1) assertNotChag(name, before, (otherOccasions.before ? []).concat(otherOccasions.all, otherOccasions.around)) for i in [1..length] assertIsChag(name, new Date(date), (otherOccasions["#{i}"] ? []).concat(otherOccasions.all, otherOccasions.during)) date.setDate(date.getDate() + 1) assertNotChag(name, date, (otherOccasions.after ? []).concat(otherOccasions.all, otherOccasions.around)) roshHodeshTest = -> edgeTestOneDayChag('RoshHodesh', new Date(2015,6,17), after: ['Shabbat'], during: ['ErebShabbat']) edgeTestMultiDayChag('RoshHodesh', new Date(2015,9,13), 2) shabbatTest = -> edgeTestOneDayChag('Shabbat', new Date(2014,6,19), before: ['ErebShabbat']) edgeTestOneDayChag('Shabbat', new Date(2014,6,26), before: ['ErebShabbat'], during: ['ShabbatMevarechim']) purimTest = -> edgeTestOneDayChag('Purim', new Date(2013,1,24), before: ['Shabbat', 'ShabbatZachor'], after: ['ShushanPurim']) edgeTestOneDayChag('Purim', new Date(2014,2,16), before: ['Shabbat', 'ShabbatZachor'], after: ['ShushanPurim']) assertNotChag('Purim', new Date(2014,1,14), ['PurimKatan', 'ErebShabbat']) edgeTestOneDayChag('ShushanPurim', new Date(2013,1,25), before: ['Purim']) edgeTestOneDayChag('ShushanPurim', new Date(2014,2,17), before: ['Purim']) edgeTestOneDayChag('PurimKatan', new Date(2014,1,14), during: ['ErebShabbat'], after: ['ShushanPurimKatan', 'Shabbat']) edgeTestOneDayChag('ShushanPurimKatan', new Date(2014,1,15), during: ['Shabbat'], before: ['PurimKatan', 'ErebShabbat']) moedTest = -> edgeTestMultiDayChag('Moed', new Date(2014,3,17), 4, all: ['Pesach', 'Regel'], before: ['2ndDayOfPesach', '2ndDayOfYomTob'], around: ['YomTob'], '2': ['ErebShabbat'], '3': ['Shabbat'], '4': ['ErebYomTob', '6thDayOfPesach'], after: ['1stDayOfYomTob', '7thDayOfPesach']) edgeTestMultiDayChag('Moed', new Date(2014,9,11), 5, all: ['Sukkot', 'Regel'], around: ['YomTob'], before: ['ErebShabbat', '2ndDayOfYomTob'], '1': ['Shabbat'], '4': ['ErebHoshanaRaba'], '5': ['ErebYomTob', 'ErubTabshilin', 'HoshanaRaba'], after: ['SheminiAseret', '1stDayOfYomTob']) pesachTest = -> edgeTestMultiDayChag('Pesach', new Date(2013,2,26), 8, before: ['ErebYomTob','ErebPesach'], '1': ['YomTob', '1stDayOfYomTob', '1stDayOfPesach'], '2': ['YomTob', '2ndDayOfYomTob', '2ndDayOfPesach'], '3': ['Moed'], '4': ['Moed', 'ErebShabbat'], '5': ['Moed','Shabbat'], '6': ['Moed', 'ErebYomTob', '6thDayOfPesach'], '7': ['YomTob', '1stDayOfYomTob', '7thDayOfPesach'], '8': ['YomTob', '2ndDayOfYomTob', '8thDayOfPesach'], during: ['Regel']) edgeTestMultiDayChag('Pesach', new Date(2015,3,4), 8, before: ['ErebShabbat', 'ErebYomTob', 'ErebPesach'], '1': ['Shabbat', 'YomTob', '1stDayOfYomTob', '1stDayOfPesach'], '2': ['YomTob', '2ndDayOfYomTob', '2ndDayOfPesach'], '3': ['Moed'], '4': ['Moed'], '5': ['Moed'], '6': ['Moed', 'ErebYomTob', 'ErubTabshilin', '6thDayOfPesach'], '7': ['YomTob', 'ErebShabbat', '1stDayOfYomTob', '7thDayOfPesach'], '8': ['Shabbat', 'YomTob', '2ndDayOfYomTob', '8thDayOfPesach'], during: ['Regel']) shabuotTest = -> edgeTestMultiDayChag('Shabuot', new Date(2013,4,15), 2, before: ['ErebYomTob','ErebShabuot'], '1':['1stDayOfYomTob', '1stDayOfShabuot'], '2': ['2ndDayOfYomTob'], during: ['Regel', 'YomTob'], after: ['ErebShabbat']) edgeTestMultiDayChag('Shabuot', new Date(2015,4,24), 2, before: ['Shabbat', 'ErebYomTob','ErebShabuot'], '1':['1stDayOfYomTob', '1stDayOfShabuot'], '2': ['2ndDayOfYomTob'], during: ['Regel', 'YomTob']) roshHashanaTest = -> edgeTestMultiDayChag('RoshHashana', new Date(2011,8,29), 2, before: ['ErebYomTob', 'HataratNedarim', 'ErubTabshilin','ErebRoshHashana'], during: ['10DaysOfTeshuba', 'YomTob'], '1': ['1stDayOfYomTob'], '2': ['ErebShabbat', '2ndDayOfYomTob'], after: ['Shabbat', '10DaysOfTeshuba']) edgeTestMultiDayChag('RoshHashana', new Date(2015,8,14), 2, before: ['ErebYomTob', 'HataratNedarim','ErebRoshHashana'], during: ['10DaysOfTeshuba', 'YomTob'], '1': ['1stDayOfYomTob'], '2': ['2ndDayOfYomTob'], after: ['10DaysOfTeshuba', 'FastOfGedaliah', 'Taanit']) tenDaysOfTeshubaTest = -> edgeTestMultiDayChag('10DaysOfTeshuba', new Date(2011,8,29), 10, before: ['ErebRoshHashana', 'ErebYomTob', 'HataratNedarim', 'ErubTabshilin'], '1': ['RoshHashana', 'YomTob', '1stDayOfYomTob'], '2': ['RoshHashana', 'YomTob', 'ErebShabbat', '2ndDayOfYomTob'], '3': ['Shabbat'], '4': ['FastOfGedaliah', 'Taanit'], '9': ['ErebShabbat', 'ErebYomKippur', 'HataratNedarim'], '10': ['Shabbat', 'YomKippur']) edgeTestMultiDayChag('10DaysOfTeshuba', new Date(2015,8,14), 10, before: ['ErebRoshHashana', 'ErebYomTob', 'HataratNedarim'], '1': ['R<NAME>', 'YomTob', '1stDayOfYomTob'], '2': ['R<NAME>', 'YomTob', '2ndDayOfYomTob'], '3': ['FastOfGedaliah', 'Taanit'], '5': ['ErebShabbat'], '6': ['Shabbat'], '9': ['HataratNedarim', 'ErebYomKippur'], '10': ['YomKippur']) yomKippurTest = -> edgeTestMultiDayChag('YomKippur', new Date(2011,9,8), 1, before: ['10DaysOfTeshuba', 'ErebShabbat', 'HataratNedarim', 'ErebYomKippur'], '1': ['Shabbat', '10DaysOfTeshuba']) edgeTestMultiDayChag('YomKippur', new Date(2015,8,23), 1, before: ['10DaysOfTeshuba', 'HataratNedarim', 'ErebYomKippur'], '1': ['10DaysOfTeshuba']) sukkotTest = -> edgeTestMultiDayChag('Sukkot', new Date(2011,9,13), 9, before: ['ErebYomTob', 'ErubTabshilin', 'ErebSukkot'], '1': ['YomTob', '1stDayOfYomTob'], '2': ['YomTob', 'ErebShabbat', '2ndDayOfYomTob'], '3': ['Moed', 'Shabbat'], '4': ['Moed'], '5': ['Moed'], '6': ['Moed', 'ErebHoshanaRaba'], '7': ['Moed', 'ErebYomTob', 'ErubTabshilin', 'HoshanaRaba'], '8': ['YomTob', '1stDayOfYomTob', 'SheminiAseret'], '9': ['YomTob', 'ErebShabbat', '2ndDayOfYomTob', 'SheminiAseret'], after: ['Shabbat', 'ShabbatMevarechim'], during: ['Regel']) edgeTestMultiDayChag('Sukkot', new Date(2015,8,28), 9, before: ['ErebYomTob', 'ErebSukkot'], '1': ['YomTob', '1stDayOfYomTob'], '2': ['YomTob', '2ndDayOfYomTob'], '3': ['Moed'], '4': ['Moed'], '5': ['Moed', 'ErebShabbat'], '6': ['Moed','Shabbat', 'ErebHoshanaRaba'], '7': ['Moed', 'ErebYomTob', 'HoshanaRaba'], '8': ['YomTob', '1stDayOfYomTob', 'SheminiAseret'], '9': ['YomTob', '2ndDayOfYomTob', 'SheminiAseret'], during: ['Regel']) chanukkahTest = -> edgeTestMultiDayChag('Chanukkah', new Date(2011,11,21), 8, '3': ['ErebShabbat'], '4': ['Shabbat', 'ShabbatMevarechim'], '6': ['RoshHodesh'], '7': ['RoshHodesh']) edgeTestMultiDayChag('Chanukkah', new Date(2012,11,9), 8, '6': ['RoshHodesh', 'ErebShabbat'], '7': ['Shabbat'], before: ['Shabbat', 'ShabbatMevarechim']) edgeTestMultiDayChag('Chanukkah', new Date(2013,10,28), 8, '2': ['ErebShabbat'], '3': ['Shabbat', 'ShabbatMevarechim'], '6': ['RoshHodesh'], '7': ['RoshHodesh', 'BeginTalUmatar'], after: ['ErebShabbat']) beginTalUmatarTest = -> edgeTestOneDayChag('BeginTalUmatar', new Date(1898,11,3), before: ['ErebShabbat'], during: ['Shabbat']) edgeTestOneDayChag('BeginTalUmatar', new Date(1899,11,4), before: ['R<NAME>', 'Chan<NAME>'], during: ['Chanukkah']) edgeTestOneDayChag('BeginTalUmatar', new Date(1999,11,5), all: ['Chan<NAME>'], before: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2010,11,4), all: ['Chan<NAME>'], before: ['ErebShabbat'], during: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2011,11,5)) edgeTestOneDayChag('BeginTalUmatar', new Date(2012,11,4)) edgeTestOneDayChag('BeginTalUmatar', new Date(2013,11,4), all: ['Chan<NAME>'], before: ['R<NAME>'], during: ['RoshHodesh']) edgeTestOneDayChag('BeginTalUmatar', new Date(2099,11,5), before: ['ErebShabbat'], during: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2100,11,5), before: ['Sh<NAME>']) edgeTestOneDayChag('BeginTalUmatar', new Date(2101,11,5)) edgeTestOneDayChag('BeginTalUmatar', new Date(2102,11,5), after: ['Chan<NAME>']) edgeTestOneDayChag('BeginTalUmatar', new Date(2103,11,6), after: ['ErebShabbat']) omerTest = (date, omerDay) -> QUnit.test "#{date} is day #{omerDay} of the omer", (assert) -> actual = new HebrewDate(date) assert.deepEqual actual.omer(), { today: omerDay, tonight: omerDay + 1 } omerEdgeTest = (date, omerDay, prop) -> QUnit.test "On #{date}, day #{omerDay} of the omer is #{prop}", (assert) -> actual = new HebrewDate(date) assert.equal actual.omer()[prop], omerDay size = 0 size++ for k,v of actual.omer() assert.equal size, 1 notOmerTest = (date) -> QUnit.test "#{date} is not during the omer", (assert) -> actual = new HebrewDate(date) assert.ok not actual.omer() assetHebrewDate(new Date(2014,6,20), 5774, HebrewMonth.TAMUZ, 22, 319) assetHebrewDate(new Date(2014,4,12), 5774, HebrewMonth.IYAR, 12, 250) roshHodeshTest() shabbatTest() purimTest() moedTest() pesachTest() shabuotTest() roshHashanaTest() tenDaysOfTeshubaTest() yomKippurTest() sukkotTest() chanukkahTest() beginTalUmatarTest() notOmerTest(new Date(2015,3,3)) omerEdgeTest(new Date(2015,3,4), 1, 'tonight') omerTest(new Date(2015,3,5), 1) omerTest(new Date(2015,3,6), 2) omerTest(new Date(2015,3,18), 14) omerTest(new Date(2015,3,19), 15) omerTest(new Date(2015,3,20), 16) omerTest(new Date(2015,4,17), 43) omerTest(new Date(2015,4,18), 44) omerTest(new Date(2015,4,19), 45) omerTest(new Date(2015,4,22), 48) omerEdgeTest(new Date(2015,4,23), 49, 'today') notOmerTest(new Date(2015,4,24)) notOmerTest(new Date(2015,9,1))
true
assetHebrewDate = (date, hebrewYear, hebrewMonth, dayOfMonth, dayOfYear) -> QUnit.test "#{date} is '#{hebrewMonth.name}' #{dayOfMonth}, #{hebrewYear}", (assert) -> actual = new HebrewDate(date) assert.deepEqual actual.getYearFromCreation(), hebrewYear assert.deepEqual actual.getHebrewMonth().getName(), hebrewMonth.name assert.deepEqual actual.getDayOfMonth(), dayOfMonth assert.deepEqual actual.getDayOfYear(), dayOfYear assertChag = (name, date, otherOccasions = [], _is) -> QUnit.test "#{date} is #{if _is then '' else 'not'} #{name}", (assert) -> target = new HebrewDate(date) result = target["is#{name}"]() assert.ok(if _is then result else !result) otherOccasions.push(name) if _is assert.deepEqual target.occasions(), otherOccasions.sort() assertIsChag = (name, date, otherOccasions) -> assertChag(name, date, otherOccasions, true) assertNotChag = (name, date, otherOccasions) -> assertChag(name, date, otherOccasions, false) edgeTestOneDayChag = (name, date, otherOccasions = {}) -> otherOccasions.all ?= [] before = new Date(date) before.setDate(before.getDate() - 1) after = new Date(date) after.setDate(after.getDate() + 1) assertNotChag(name, before, (otherOccasions.before ? []).concat(otherOccasions.all)) assertIsChag(name, date, (otherOccasions.during ? []).concat(otherOccasions.all)) assertNotChag(name, after, (otherOccasions.after ? []).concat(otherOccasions.all)) edgeTestMultiDayChag = (name, date, length, otherOccasions = {}) -> otherOccasions.all ?= [] otherOccasions.during ?= [] otherOccasions.around ?= [] before = new Date(date) before.setDate(before.getDate() - 1) assertNotChag(name, before, (otherOccasions.before ? []).concat(otherOccasions.all, otherOccasions.around)) for i in [1..length] assertIsChag(name, new Date(date), (otherOccasions["#{i}"] ? []).concat(otherOccasions.all, otherOccasions.during)) date.setDate(date.getDate() + 1) assertNotChag(name, date, (otherOccasions.after ? []).concat(otherOccasions.all, otherOccasions.around)) roshHodeshTest = -> edgeTestOneDayChag('RoshHodesh', new Date(2015,6,17), after: ['Shabbat'], during: ['ErebShabbat']) edgeTestMultiDayChag('RoshHodesh', new Date(2015,9,13), 2) shabbatTest = -> edgeTestOneDayChag('Shabbat', new Date(2014,6,19), before: ['ErebShabbat']) edgeTestOneDayChag('Shabbat', new Date(2014,6,26), before: ['ErebShabbat'], during: ['ShabbatMevarechim']) purimTest = -> edgeTestOneDayChag('Purim', new Date(2013,1,24), before: ['Shabbat', 'ShabbatZachor'], after: ['ShushanPurim']) edgeTestOneDayChag('Purim', new Date(2014,2,16), before: ['Shabbat', 'ShabbatZachor'], after: ['ShushanPurim']) assertNotChag('Purim', new Date(2014,1,14), ['PurimKatan', 'ErebShabbat']) edgeTestOneDayChag('ShushanPurim', new Date(2013,1,25), before: ['Purim']) edgeTestOneDayChag('ShushanPurim', new Date(2014,2,17), before: ['Purim']) edgeTestOneDayChag('PurimKatan', new Date(2014,1,14), during: ['ErebShabbat'], after: ['ShushanPurimKatan', 'Shabbat']) edgeTestOneDayChag('ShushanPurimKatan', new Date(2014,1,15), during: ['Shabbat'], before: ['PurimKatan', 'ErebShabbat']) moedTest = -> edgeTestMultiDayChag('Moed', new Date(2014,3,17), 4, all: ['Pesach', 'Regel'], before: ['2ndDayOfPesach', '2ndDayOfYomTob'], around: ['YomTob'], '2': ['ErebShabbat'], '3': ['Shabbat'], '4': ['ErebYomTob', '6thDayOfPesach'], after: ['1stDayOfYomTob', '7thDayOfPesach']) edgeTestMultiDayChag('Moed', new Date(2014,9,11), 5, all: ['Sukkot', 'Regel'], around: ['YomTob'], before: ['ErebShabbat', '2ndDayOfYomTob'], '1': ['Shabbat'], '4': ['ErebHoshanaRaba'], '5': ['ErebYomTob', 'ErubTabshilin', 'HoshanaRaba'], after: ['SheminiAseret', '1stDayOfYomTob']) pesachTest = -> edgeTestMultiDayChag('Pesach', new Date(2013,2,26), 8, before: ['ErebYomTob','ErebPesach'], '1': ['YomTob', '1stDayOfYomTob', '1stDayOfPesach'], '2': ['YomTob', '2ndDayOfYomTob', '2ndDayOfPesach'], '3': ['Moed'], '4': ['Moed', 'ErebShabbat'], '5': ['Moed','Shabbat'], '6': ['Moed', 'ErebYomTob', '6thDayOfPesach'], '7': ['YomTob', '1stDayOfYomTob', '7thDayOfPesach'], '8': ['YomTob', '2ndDayOfYomTob', '8thDayOfPesach'], during: ['Regel']) edgeTestMultiDayChag('Pesach', new Date(2015,3,4), 8, before: ['ErebShabbat', 'ErebYomTob', 'ErebPesach'], '1': ['Shabbat', 'YomTob', '1stDayOfYomTob', '1stDayOfPesach'], '2': ['YomTob', '2ndDayOfYomTob', '2ndDayOfPesach'], '3': ['Moed'], '4': ['Moed'], '5': ['Moed'], '6': ['Moed', 'ErebYomTob', 'ErubTabshilin', '6thDayOfPesach'], '7': ['YomTob', 'ErebShabbat', '1stDayOfYomTob', '7thDayOfPesach'], '8': ['Shabbat', 'YomTob', '2ndDayOfYomTob', '8thDayOfPesach'], during: ['Regel']) shabuotTest = -> edgeTestMultiDayChag('Shabuot', new Date(2013,4,15), 2, before: ['ErebYomTob','ErebShabuot'], '1':['1stDayOfYomTob', '1stDayOfShabuot'], '2': ['2ndDayOfYomTob'], during: ['Regel', 'YomTob'], after: ['ErebShabbat']) edgeTestMultiDayChag('Shabuot', new Date(2015,4,24), 2, before: ['Shabbat', 'ErebYomTob','ErebShabuot'], '1':['1stDayOfYomTob', '1stDayOfShabuot'], '2': ['2ndDayOfYomTob'], during: ['Regel', 'YomTob']) roshHashanaTest = -> edgeTestMultiDayChag('RoshHashana', new Date(2011,8,29), 2, before: ['ErebYomTob', 'HataratNedarim', 'ErubTabshilin','ErebRoshHashana'], during: ['10DaysOfTeshuba', 'YomTob'], '1': ['1stDayOfYomTob'], '2': ['ErebShabbat', '2ndDayOfYomTob'], after: ['Shabbat', '10DaysOfTeshuba']) edgeTestMultiDayChag('RoshHashana', new Date(2015,8,14), 2, before: ['ErebYomTob', 'HataratNedarim','ErebRoshHashana'], during: ['10DaysOfTeshuba', 'YomTob'], '1': ['1stDayOfYomTob'], '2': ['2ndDayOfYomTob'], after: ['10DaysOfTeshuba', 'FastOfGedaliah', 'Taanit']) tenDaysOfTeshubaTest = -> edgeTestMultiDayChag('10DaysOfTeshuba', new Date(2011,8,29), 10, before: ['ErebRoshHashana', 'ErebYomTob', 'HataratNedarim', 'ErubTabshilin'], '1': ['RoshHashana', 'YomTob', '1stDayOfYomTob'], '2': ['RoshHashana', 'YomTob', 'ErebShabbat', '2ndDayOfYomTob'], '3': ['Shabbat'], '4': ['FastOfGedaliah', 'Taanit'], '9': ['ErebShabbat', 'ErebYomKippur', 'HataratNedarim'], '10': ['Shabbat', 'YomKippur']) edgeTestMultiDayChag('10DaysOfTeshuba', new Date(2015,8,14), 10, before: ['ErebRoshHashana', 'ErebYomTob', 'HataratNedarim'], '1': ['RPI:NAME:<NAME>END_PI', 'YomTob', '1stDayOfYomTob'], '2': ['RPI:NAME:<NAME>END_PI', 'YomTob', '2ndDayOfYomTob'], '3': ['FastOfGedaliah', 'Taanit'], '5': ['ErebShabbat'], '6': ['Shabbat'], '9': ['HataratNedarim', 'ErebYomKippur'], '10': ['YomKippur']) yomKippurTest = -> edgeTestMultiDayChag('YomKippur', new Date(2011,9,8), 1, before: ['10DaysOfTeshuba', 'ErebShabbat', 'HataratNedarim', 'ErebYomKippur'], '1': ['Shabbat', '10DaysOfTeshuba']) edgeTestMultiDayChag('YomKippur', new Date(2015,8,23), 1, before: ['10DaysOfTeshuba', 'HataratNedarim', 'ErebYomKippur'], '1': ['10DaysOfTeshuba']) sukkotTest = -> edgeTestMultiDayChag('Sukkot', new Date(2011,9,13), 9, before: ['ErebYomTob', 'ErubTabshilin', 'ErebSukkot'], '1': ['YomTob', '1stDayOfYomTob'], '2': ['YomTob', 'ErebShabbat', '2ndDayOfYomTob'], '3': ['Moed', 'Shabbat'], '4': ['Moed'], '5': ['Moed'], '6': ['Moed', 'ErebHoshanaRaba'], '7': ['Moed', 'ErebYomTob', 'ErubTabshilin', 'HoshanaRaba'], '8': ['YomTob', '1stDayOfYomTob', 'SheminiAseret'], '9': ['YomTob', 'ErebShabbat', '2ndDayOfYomTob', 'SheminiAseret'], after: ['Shabbat', 'ShabbatMevarechim'], during: ['Regel']) edgeTestMultiDayChag('Sukkot', new Date(2015,8,28), 9, before: ['ErebYomTob', 'ErebSukkot'], '1': ['YomTob', '1stDayOfYomTob'], '2': ['YomTob', '2ndDayOfYomTob'], '3': ['Moed'], '4': ['Moed'], '5': ['Moed', 'ErebShabbat'], '6': ['Moed','Shabbat', 'ErebHoshanaRaba'], '7': ['Moed', 'ErebYomTob', 'HoshanaRaba'], '8': ['YomTob', '1stDayOfYomTob', 'SheminiAseret'], '9': ['YomTob', '2ndDayOfYomTob', 'SheminiAseret'], during: ['Regel']) chanukkahTest = -> edgeTestMultiDayChag('Chanukkah', new Date(2011,11,21), 8, '3': ['ErebShabbat'], '4': ['Shabbat', 'ShabbatMevarechim'], '6': ['RoshHodesh'], '7': ['RoshHodesh']) edgeTestMultiDayChag('Chanukkah', new Date(2012,11,9), 8, '6': ['RoshHodesh', 'ErebShabbat'], '7': ['Shabbat'], before: ['Shabbat', 'ShabbatMevarechim']) edgeTestMultiDayChag('Chanukkah', new Date(2013,10,28), 8, '2': ['ErebShabbat'], '3': ['Shabbat', 'ShabbatMevarechim'], '6': ['RoshHodesh'], '7': ['RoshHodesh', 'BeginTalUmatar'], after: ['ErebShabbat']) beginTalUmatarTest = -> edgeTestOneDayChag('BeginTalUmatar', new Date(1898,11,3), before: ['ErebShabbat'], during: ['Shabbat']) edgeTestOneDayChag('BeginTalUmatar', new Date(1899,11,4), before: ['RPI:NAME:<NAME>END_PI', 'ChanPI:NAME:<NAME>END_PI'], during: ['Chanukkah']) edgeTestOneDayChag('BeginTalUmatar', new Date(1999,11,5), all: ['ChanPI:NAME:<NAME>END_PI'], before: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2010,11,4), all: ['ChanPI:NAME:<NAME>END_PI'], before: ['ErebShabbat'], during: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2011,11,5)) edgeTestOneDayChag('BeginTalUmatar', new Date(2012,11,4)) edgeTestOneDayChag('BeginTalUmatar', new Date(2013,11,4), all: ['ChanPI:NAME:<NAME>END_PI'], before: ['RPI:NAME:<NAME>END_PI'], during: ['RoshHodesh']) edgeTestOneDayChag('BeginTalUmatar', new Date(2099,11,5), before: ['ErebShabbat'], during: ['Shabbat', 'ShabbatMevarechim']) edgeTestOneDayChag('BeginTalUmatar', new Date(2100,11,5), before: ['ShPI:NAME:<NAME>END_PI']) edgeTestOneDayChag('BeginTalUmatar', new Date(2101,11,5)) edgeTestOneDayChag('BeginTalUmatar', new Date(2102,11,5), after: ['ChanPI:NAME:<NAME>END_PI']) edgeTestOneDayChag('BeginTalUmatar', new Date(2103,11,6), after: ['ErebShabbat']) omerTest = (date, omerDay) -> QUnit.test "#{date} is day #{omerDay} of the omer", (assert) -> actual = new HebrewDate(date) assert.deepEqual actual.omer(), { today: omerDay, tonight: omerDay + 1 } omerEdgeTest = (date, omerDay, prop) -> QUnit.test "On #{date}, day #{omerDay} of the omer is #{prop}", (assert) -> actual = new HebrewDate(date) assert.equal actual.omer()[prop], omerDay size = 0 size++ for k,v of actual.omer() assert.equal size, 1 notOmerTest = (date) -> QUnit.test "#{date} is not during the omer", (assert) -> actual = new HebrewDate(date) assert.ok not actual.omer() assetHebrewDate(new Date(2014,6,20), 5774, HebrewMonth.TAMUZ, 22, 319) assetHebrewDate(new Date(2014,4,12), 5774, HebrewMonth.IYAR, 12, 250) roshHodeshTest() shabbatTest() purimTest() moedTest() pesachTest() shabuotTest() roshHashanaTest() tenDaysOfTeshubaTest() yomKippurTest() sukkotTest() chanukkahTest() beginTalUmatarTest() notOmerTest(new Date(2015,3,3)) omerEdgeTest(new Date(2015,3,4), 1, 'tonight') omerTest(new Date(2015,3,5), 1) omerTest(new Date(2015,3,6), 2) omerTest(new Date(2015,3,18), 14) omerTest(new Date(2015,3,19), 15) omerTest(new Date(2015,3,20), 16) omerTest(new Date(2015,4,17), 43) omerTest(new Date(2015,4,18), 44) omerTest(new Date(2015,4,19), 45) omerTest(new Date(2015,4,22), 48) omerEdgeTest(new Date(2015,4,23), 49, 'today') notOmerTest(new Date(2015,4,24)) notOmerTest(new Date(2015,9,1))
[ { "context": "'bidder')\n @req = user: new CurrentUser(id: 'foobar'), params: id: 'foobar'\n routes.index @req, ", "end": 2550, "score": 0.9979222416877747, "start": 2544, "tag": "USERNAME", "value": "foobar" }, { "context": " @req.params.id = 'bar'\n @req.body.email = 'foobar@baz.com'\n routes.inviteForm @req, @res, @next\n ", "end": 3314, "score": 0.9999192953109741, "start": 3300, "tag": "EMAIL", "value": "foobar@baz.com" } ]
desktop/apps/auction/test/routes.coffee
dblock/force
1
_ = require 'underscore' Q = require 'bluebird-q' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' { fabricate } = require 'antigravity' CurrentUser = require '../../../models/current_user' Auction = require '../../../models/auction' routes = rewire '../routes' moment = require 'moment' describe '/auction routes', -> beforeEach -> sinon.stub Backbone, 'sync' sinon.stub Q, 'promise' routes.__set__ 'sailthru', @sailthru = apiGet: sinon.stub() apiPost: sinon.stub() @req = body: {}, params: id: 'foobar' @res = render: sinon.stub() redirect: sinon.stub() send: sinon.stub() locals: sd: {} @next = sinon.stub() afterEach -> Backbone.sync.restore() Q.promise.restore() it 'fetches the auction data and renders the index template', (done) -> routes.index @req, @res, @next Backbone.sync.callCount.should.equal 2 Backbone.sync.args[0][1].url().should.containEql '/api/v1/sale/foobar' Backbone.sync.args[1][1].url().should.containEql '/api/v1/sale/foobar/sale_artworks' Backbone.sync.args[1][2].data.should.equal 'total_count=1&size=10' Backbone.sync.args[0][2].success fabricate 'sale', is_auction: true Backbone.sync.args[1][2].success {} _.defer => _.defer => Q.promise.args[0][0]() _.last(Backbone.sync.args)[1].url.should.containEql '/api/articles' @next.called.should.be.false() @res.render.args[0][0].should.equal 'index' _.keys(@res.render.args[0][1]).should.eql [ 'auction' 'artworks' 'saleArtworks' 'articles' 'user' 'state' 'displayBlurbs' 'maxBlurbHeight' 'footerItems' 'myActiveBids' ] done() it 'fetches the auction data and nexts to the sale if it is a sale', (done) -> routes.index @req, @res, @next Backbone.sync.args[0][2].success fabricate 'sale', is_auction: false Backbone.sync.args[1][2].success {} _.defer => _.defer => @next.called.should.be.true() @res.render.called.should.be.false() done() it 'passes down the error', (done) -> routes.index @req, @res, @next @next.called.should.be.false() Backbone.sync.args[0][2].error() Backbone.sync.args[1][2].error() _.defer => _.defer => @next.called.should.be.true() done() describe 'with logged in user', -> beforeEach (done) -> Backbone.sync.returns Promise.resolve(fabricate 'bidder') @req = user: new CurrentUser(id: 'foobar'), params: id: 'foobar' routes.index @req, @res, @next _.defer => _.defer => @userReqs = _.last Backbone.sync.args, 1 done() it 'fetches the bidder positions', -> @userReqs[0][2].url.should.containEql '/api/v1/me/bidders' @userReqs[0][2].data.sale_id.should.equal 'foobar' it 'sets the `registered_to_bid` attr', -> @userReqs[0][2].success ['existy'] @req.user.get('registered_to_bid').should.be.true() describe '#inviteForm', -> it 'submits to sailthru including previously subscribed auctions', -> @sailthru.apiGet.callsArgWith(2, null, vars: auction_slugs: ['foo']) @sailthru.apiPost.callsArgWith(2, null, {}) @req.params.id = 'bar' @req.body.email = 'foobar@baz.com' routes.inviteForm @req, @res, @next @sailthru.apiPost.args[0][1].vars.auction_slugs.join(',') .should.equal 'foo,bar' it 'sets source if it doesnt exist', -> @sailthru.apiGet.callsArgWith(2, null, vars: source: 'foo') routes.inviteForm @req, @res, @next @sailthru.apiPost.args[0][1].vars.source.should.equal 'foo' @sailthru.apiGet.callsArgWith(2, null, vars: source: null) routes.inviteForm @req, @res, @next @sailthru.apiPost.args[1][1].vars.source.should.equal 'auction' it 'continues fine for ST error 99 (user not found)', -> @req.params.id = 'baz' @sailthru.apiGet.callsArgWith(2, { error: 99 }) routes.inviteForm @req, @res, @next @sailthru.apiGet.callsArgWith(2, null, vars: source: null) routes.inviteForm @req, @res, @next @sailthru.apiPost.args[1][1].vars.source.should.equal 'auction' @sailthru.apiPost.args[0][1].vars.auction_slugs.join(',') .should.equal 'baz' describe '#redirectLive', -> beforeEach -> sinon.stub Backbone, 'sync' @req = body: {}, params: id: 'foobar' user: new CurrentUser(fabricate 'user') @res = redirect: sinon.stub() @next = sinon.stub() afterEach -> Backbone.sync.restore() it 'redirects on confirm if the auction is live and bidder is qualified', (done) -> auction = fabricate 'sale', id: 'foo' is_auction: true auction_state: 'open' start_at: moment().startOf('day') live_start_at: moment().startOf('day') end_at: moment().endOf('day') bidder = { id: 'me', qualified_for_bidding: true, sale: auction } @res = redirect: (url) -> url.should.equal 'https://live.artsy.net/foo/login' done() routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction Backbone.sync.args[1][2].success [bidder] Backbone.sync.args[2][2].success bidder it 'does not redirect if bidder is not qualified', () -> auction = fabricate 'sale', id: 'foo' is_auction: true start_at: moment().startOf('day') auction_state: 'open' live_start_at: moment().startOf('day') end_at: moment().endOf('day') bidder = { id: 'me', qualified_for_bidding: false, sale: auction } routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction Backbone.sync.args[1][2].success [bidder] Backbone.sync.args[2][2].success bidder @res.redirect.called.should.not.be.ok() @next.called.should.be.ok() it 'does not redirect on confirm if the auction is not live', () -> auction = fabricate 'sale', id: 'foo' is_auction: true auction_state: 'open' live_start_at: null end_at: moment().endOf('day') routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction @res.redirect.called.should.not.be.ok() @next.called.should.be.ok()
94229
_ = require 'underscore' Q = require 'bluebird-q' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' { fabricate } = require 'antigravity' CurrentUser = require '../../../models/current_user' Auction = require '../../../models/auction' routes = rewire '../routes' moment = require 'moment' describe '/auction routes', -> beforeEach -> sinon.stub Backbone, 'sync' sinon.stub Q, 'promise' routes.__set__ 'sailthru', @sailthru = apiGet: sinon.stub() apiPost: sinon.stub() @req = body: {}, params: id: 'foobar' @res = render: sinon.stub() redirect: sinon.stub() send: sinon.stub() locals: sd: {} @next = sinon.stub() afterEach -> Backbone.sync.restore() Q.promise.restore() it 'fetches the auction data and renders the index template', (done) -> routes.index @req, @res, @next Backbone.sync.callCount.should.equal 2 Backbone.sync.args[0][1].url().should.containEql '/api/v1/sale/foobar' Backbone.sync.args[1][1].url().should.containEql '/api/v1/sale/foobar/sale_artworks' Backbone.sync.args[1][2].data.should.equal 'total_count=1&size=10' Backbone.sync.args[0][2].success fabricate 'sale', is_auction: true Backbone.sync.args[1][2].success {} _.defer => _.defer => Q.promise.args[0][0]() _.last(Backbone.sync.args)[1].url.should.containEql '/api/articles' @next.called.should.be.false() @res.render.args[0][0].should.equal 'index' _.keys(@res.render.args[0][1]).should.eql [ 'auction' 'artworks' 'saleArtworks' 'articles' 'user' 'state' 'displayBlurbs' 'maxBlurbHeight' 'footerItems' 'myActiveBids' ] done() it 'fetches the auction data and nexts to the sale if it is a sale', (done) -> routes.index @req, @res, @next Backbone.sync.args[0][2].success fabricate 'sale', is_auction: false Backbone.sync.args[1][2].success {} _.defer => _.defer => @next.called.should.be.true() @res.render.called.should.be.false() done() it 'passes down the error', (done) -> routes.index @req, @res, @next @next.called.should.be.false() Backbone.sync.args[0][2].error() Backbone.sync.args[1][2].error() _.defer => _.defer => @next.called.should.be.true() done() describe 'with logged in user', -> beforeEach (done) -> Backbone.sync.returns Promise.resolve(fabricate 'bidder') @req = user: new CurrentUser(id: 'foobar'), params: id: 'foobar' routes.index @req, @res, @next _.defer => _.defer => @userReqs = _.last Backbone.sync.args, 1 done() it 'fetches the bidder positions', -> @userReqs[0][2].url.should.containEql '/api/v1/me/bidders' @userReqs[0][2].data.sale_id.should.equal 'foobar' it 'sets the `registered_to_bid` attr', -> @userReqs[0][2].success ['existy'] @req.user.get('registered_to_bid').should.be.true() describe '#inviteForm', -> it 'submits to sailthru including previously subscribed auctions', -> @sailthru.apiGet.callsArgWith(2, null, vars: auction_slugs: ['foo']) @sailthru.apiPost.callsArgWith(2, null, {}) @req.params.id = 'bar' @req.body.email = '<EMAIL>' routes.inviteForm @req, @res, @next @sailthru.apiPost.args[0][1].vars.auction_slugs.join(',') .should.equal 'foo,bar' it 'sets source if it doesnt exist', -> @sailthru.apiGet.callsArgWith(2, null, vars: source: 'foo') routes.inviteForm @req, @res, @next @sailthru.apiPost.args[0][1].vars.source.should.equal 'foo' @sailthru.apiGet.callsArgWith(2, null, vars: source: null) routes.inviteForm @req, @res, @next @sailthru.apiPost.args[1][1].vars.source.should.equal 'auction' it 'continues fine for ST error 99 (user not found)', -> @req.params.id = 'baz' @sailthru.apiGet.callsArgWith(2, { error: 99 }) routes.inviteForm @req, @res, @next @sailthru.apiGet.callsArgWith(2, null, vars: source: null) routes.inviteForm @req, @res, @next @sailthru.apiPost.args[1][1].vars.source.should.equal 'auction' @sailthru.apiPost.args[0][1].vars.auction_slugs.join(',') .should.equal 'baz' describe '#redirectLive', -> beforeEach -> sinon.stub Backbone, 'sync' @req = body: {}, params: id: 'foobar' user: new CurrentUser(fabricate 'user') @res = redirect: sinon.stub() @next = sinon.stub() afterEach -> Backbone.sync.restore() it 'redirects on confirm if the auction is live and bidder is qualified', (done) -> auction = fabricate 'sale', id: 'foo' is_auction: true auction_state: 'open' start_at: moment().startOf('day') live_start_at: moment().startOf('day') end_at: moment().endOf('day') bidder = { id: 'me', qualified_for_bidding: true, sale: auction } @res = redirect: (url) -> url.should.equal 'https://live.artsy.net/foo/login' done() routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction Backbone.sync.args[1][2].success [bidder] Backbone.sync.args[2][2].success bidder it 'does not redirect if bidder is not qualified', () -> auction = fabricate 'sale', id: 'foo' is_auction: true start_at: moment().startOf('day') auction_state: 'open' live_start_at: moment().startOf('day') end_at: moment().endOf('day') bidder = { id: 'me', qualified_for_bidding: false, sale: auction } routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction Backbone.sync.args[1][2].success [bidder] Backbone.sync.args[2][2].success bidder @res.redirect.called.should.not.be.ok() @next.called.should.be.ok() it 'does not redirect on confirm if the auction is not live', () -> auction = fabricate 'sale', id: 'foo' is_auction: true auction_state: 'open' live_start_at: null end_at: moment().endOf('day') routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction @res.redirect.called.should.not.be.ok() @next.called.should.be.ok()
true
_ = require 'underscore' Q = require 'bluebird-q' sinon = require 'sinon' rewire = require 'rewire' Backbone = require 'backbone' { fabricate } = require 'antigravity' CurrentUser = require '../../../models/current_user' Auction = require '../../../models/auction' routes = rewire '../routes' moment = require 'moment' describe '/auction routes', -> beforeEach -> sinon.stub Backbone, 'sync' sinon.stub Q, 'promise' routes.__set__ 'sailthru', @sailthru = apiGet: sinon.stub() apiPost: sinon.stub() @req = body: {}, params: id: 'foobar' @res = render: sinon.stub() redirect: sinon.stub() send: sinon.stub() locals: sd: {} @next = sinon.stub() afterEach -> Backbone.sync.restore() Q.promise.restore() it 'fetches the auction data and renders the index template', (done) -> routes.index @req, @res, @next Backbone.sync.callCount.should.equal 2 Backbone.sync.args[0][1].url().should.containEql '/api/v1/sale/foobar' Backbone.sync.args[1][1].url().should.containEql '/api/v1/sale/foobar/sale_artworks' Backbone.sync.args[1][2].data.should.equal 'total_count=1&size=10' Backbone.sync.args[0][2].success fabricate 'sale', is_auction: true Backbone.sync.args[1][2].success {} _.defer => _.defer => Q.promise.args[0][0]() _.last(Backbone.sync.args)[1].url.should.containEql '/api/articles' @next.called.should.be.false() @res.render.args[0][0].should.equal 'index' _.keys(@res.render.args[0][1]).should.eql [ 'auction' 'artworks' 'saleArtworks' 'articles' 'user' 'state' 'displayBlurbs' 'maxBlurbHeight' 'footerItems' 'myActiveBids' ] done() it 'fetches the auction data and nexts to the sale if it is a sale', (done) -> routes.index @req, @res, @next Backbone.sync.args[0][2].success fabricate 'sale', is_auction: false Backbone.sync.args[1][2].success {} _.defer => _.defer => @next.called.should.be.true() @res.render.called.should.be.false() done() it 'passes down the error', (done) -> routes.index @req, @res, @next @next.called.should.be.false() Backbone.sync.args[0][2].error() Backbone.sync.args[1][2].error() _.defer => _.defer => @next.called.should.be.true() done() describe 'with logged in user', -> beforeEach (done) -> Backbone.sync.returns Promise.resolve(fabricate 'bidder') @req = user: new CurrentUser(id: 'foobar'), params: id: 'foobar' routes.index @req, @res, @next _.defer => _.defer => @userReqs = _.last Backbone.sync.args, 1 done() it 'fetches the bidder positions', -> @userReqs[0][2].url.should.containEql '/api/v1/me/bidders' @userReqs[0][2].data.sale_id.should.equal 'foobar' it 'sets the `registered_to_bid` attr', -> @userReqs[0][2].success ['existy'] @req.user.get('registered_to_bid').should.be.true() describe '#inviteForm', -> it 'submits to sailthru including previously subscribed auctions', -> @sailthru.apiGet.callsArgWith(2, null, vars: auction_slugs: ['foo']) @sailthru.apiPost.callsArgWith(2, null, {}) @req.params.id = 'bar' @req.body.email = 'PI:EMAIL:<EMAIL>END_PI' routes.inviteForm @req, @res, @next @sailthru.apiPost.args[0][1].vars.auction_slugs.join(',') .should.equal 'foo,bar' it 'sets source if it doesnt exist', -> @sailthru.apiGet.callsArgWith(2, null, vars: source: 'foo') routes.inviteForm @req, @res, @next @sailthru.apiPost.args[0][1].vars.source.should.equal 'foo' @sailthru.apiGet.callsArgWith(2, null, vars: source: null) routes.inviteForm @req, @res, @next @sailthru.apiPost.args[1][1].vars.source.should.equal 'auction' it 'continues fine for ST error 99 (user not found)', -> @req.params.id = 'baz' @sailthru.apiGet.callsArgWith(2, { error: 99 }) routes.inviteForm @req, @res, @next @sailthru.apiGet.callsArgWith(2, null, vars: source: null) routes.inviteForm @req, @res, @next @sailthru.apiPost.args[1][1].vars.source.should.equal 'auction' @sailthru.apiPost.args[0][1].vars.auction_slugs.join(',') .should.equal 'baz' describe '#redirectLive', -> beforeEach -> sinon.stub Backbone, 'sync' @req = body: {}, params: id: 'foobar' user: new CurrentUser(fabricate 'user') @res = redirect: sinon.stub() @next = sinon.stub() afterEach -> Backbone.sync.restore() it 'redirects on confirm if the auction is live and bidder is qualified', (done) -> auction = fabricate 'sale', id: 'foo' is_auction: true auction_state: 'open' start_at: moment().startOf('day') live_start_at: moment().startOf('day') end_at: moment().endOf('day') bidder = { id: 'me', qualified_for_bidding: true, sale: auction } @res = redirect: (url) -> url.should.equal 'https://live.artsy.net/foo/login' done() routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction Backbone.sync.args[1][2].success [bidder] Backbone.sync.args[2][2].success bidder it 'does not redirect if bidder is not qualified', () -> auction = fabricate 'sale', id: 'foo' is_auction: true start_at: moment().startOf('day') auction_state: 'open' live_start_at: moment().startOf('day') end_at: moment().endOf('day') bidder = { id: 'me', qualified_for_bidding: false, sale: auction } routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction Backbone.sync.args[1][2].success [bidder] Backbone.sync.args[2][2].success bidder @res.redirect.called.should.not.be.ok() @next.called.should.be.ok() it 'does not redirect on confirm if the auction is not live', () -> auction = fabricate 'sale', id: 'foo' is_auction: true auction_state: 'open' live_start_at: null end_at: moment().endOf('day') routes.redirectLive @req, @res, @next Backbone.sync.args[0][2].success auction @res.redirect.called.should.not.be.ok() @next.called.should.be.ok()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission ", "end": 18, "score": 0.8936300873756409, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-module-loading-error.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") common.debug "load test-module-loading-error.js" error_desc = win32: "%1 is not a valid Win32 application" linux: "file too short" sunos: "unknown file type" dlerror_msg = error_desc[process.platform] unless dlerror_msg console.error "Skipping test, platform not supported." process.exit() try require "../fixtures/module-loading-error.node" catch e assert.notEqual e.toString().indexOf(dlerror_msg), -1 try require() catch e assert.notEqual e.toString().indexOf("missing path"), -1 try require {} catch e assert.notEqual e.toString().indexOf("path must be a string"), -1
201902
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") common.debug "load test-module-loading-error.js" error_desc = win32: "%1 is not a valid Win32 application" linux: "file too short" sunos: "unknown file type" dlerror_msg = error_desc[process.platform] unless dlerror_msg console.error "Skipping test, platform not supported." process.exit() try require "../fixtures/module-loading-error.node" catch e assert.notEqual e.toString().indexOf(dlerror_msg), -1 try require() catch e assert.notEqual e.toString().indexOf("missing path"), -1 try require {} catch e assert.notEqual e.toString().indexOf("path must be a string"), -1
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") common.debug "load test-module-loading-error.js" error_desc = win32: "%1 is not a valid Win32 application" linux: "file too short" sunos: "unknown file type" dlerror_msg = error_desc[process.platform] unless dlerror_msg console.error "Skipping test, platform not supported." process.exit() try require "../fixtures/module-loading-error.node" catch e assert.notEqual e.toString().indexOf(dlerror_msg), -1 try require() catch e assert.notEqual e.toString().indexOf("missing path"), -1 try require {} catch e assert.notEqual e.toString().indexOf("path must be a string"), -1
[ { "context": "cGPG2 v2\nComment: GPGTools - https://gpgtools.org\n\nmQENBFRtEYQBCADSAtDn9FmeoXy1eSl5BKsZvBcQWNVx3so/CGqsXZrQu3lVftFY\nv90eqxlg/GHtZL26Aii08a9XLTazu3BeIKdokpdCtf2EO3q5dH1k1FAXLoSKvDXL\nnhAtiEUzwQOLZgU5LuFafgCeVwzMeT76++ILpdo0Mil09df28JyLX3NqL6xW4I09\nt2aFxgDxbfPYaYvFLw3IfYfaS1l3f2jvUmo4udXkNBNHHcvnJXEYOa+eHDJLt10I\nq+Dx/w30VmXoqXrEFIkZg2H54Gjg1tiwxTK0UiU6aO+msEAKIrIBu4WFDzwbYy6U\nxVmKjap3TWSlmhWWroqWADiNMcWnVJlat2pbABEBAAG0FldCIFllYXRzIDx3YkB5\nZWF0cy5tZT6JATgEEwEKACIFAlRtEYQCGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4B\nAheAAAoJEPzlvJborD4UxmQIAJfN+C+5EvvRsx2PuyHuqtHHuOnGSF70yvBI1poZ\nG/Oy7xDHPSzezD7FhTi0LLLQ2yt6//sljOudcWr3udk1EShgrxXuNTfdBKZgKi/H\nV03IxvIbcBGL7JQhYmayMie9LNo6U415gFyxysldHOzFWNARo4CiR/cQ2Y0X6jCd\nnfqR1d5XvHPVfI0LepCPxX9U90t84exkrrYo/fykLdNQukjO9zlywtjB1Z7b39oI\nItz6Cd/EQeOgxIiOBA0vS3sq/U5KyYEOufZm1NELQp7Nd+xTaOE/2ZB1mIrr6PQi\nR/h6L4WlA3j/TsPKWB3J9Y7wFYe5NRampiKt5BD020KkV/G5AQ0EVG0RhAEIANij\nMTFZ+1Hev55LQK/gB3t/LfbGmtHFKgtUCEbSwOAdVkFLr9BJNyhM3j3RS1U2QEdF\nqAtcQMhiANFjPGM1rJ3WmwQMdrVLdEmMNv9NskBJKYAV3cVw2MzkrwHoqUBmq9SX\nUnGj9wkezsQWsThGqcRws2ngOtMNNVi6wNY0eIrrs5KOQjhPcIthn2ffdw5dpj8l\ndx1uZpwWSFTrDosX7Q8eLYwt1SKX5h5uIMXSrX0BP+sOlbZn1gxLnH6e4log84fg\nJww0a2JMdTTOmvCgTtxmIoCF6dqK1GB4CAD8b9NgdbG3BM+KenpN1/YM1Nb46wDM\n0hyh6VjKvAFzl2sENLMAEQEAAYkBHwQoAQoACQUCVG0RyAIdAQAKCRD85byW6Kw+\nFIbSCACjOtd46OszAK9d/YRJ/eFT+OR8cx24xtUSMro4EQ3vJz1Hc7jznjTooL/s\nC25Kokpj0a+y8YaVGfmmvUzfT+g8N+Z0BraJShO5GpkLbG/+BrZw30lOE39iJZDh\nHfe4j80RDLnYaw0hMR8fjrONztQItbYvoALNl4NuzK4AA/r1i/3fxlGfRR+mtLrQ\n76AbX+52WfrXZK7vGALUkJgV2tFtgcSJbgbZSKYWzykWttOe5sxpczkaaB+DS9UJ\n7+LlUMJbFaqllE6WVqAqODP1n4R96rHh+Xc2uVtxe/NcWYRe8TmtBec8icujhPnE\ni+4E4W6HgmhlWjy002/TfNzM5VgMiQEfBBgBCgAJBQJUbRGEAhsMAAoJEPzlvJbo\nrD4Uum8H/inVByzp4X2Ja3Ng2LDHbF8suwMoF4AS2Nx0uKnQMHKb6L7g9uHpMPpF\noW6HeU3CGjmjj3eZufF+40UcsWOXhmQIu2RLo/F7oQhbWpCSGlmfzuBP2stRbnON\nLt7+AmHnT/Cm2+Ts4iVxeGdSF3M2hbOfPkxI0Rf+ud0pi7hgVJWkDoCe4Nc/HDkd\n+i58l/qGsWATh3lsi45IaGU4GzUUnbTEWbqrkwR66uVtc1u7XhaA5KOf52Efwc5S\nS7GjjxYDuC/+tP8+NZKVk8z4+4RG8Xru+/QlzMhJOkelsxS96+gLOFOHoXw4VxBq\nPZePpV7Wp8/9uN223QFzDZA629Khr3u5AQ0EVG0R1AEIANVqKo6aXtyaR/sEd0Ex\nr0OigaSAOE/sj/LN+xWuwQ45CP2oQDlWneBb3Nvkqmxyx03INPHeza8SvYkl7CBx\nZs2qh9Kr7yeP0QQkDrCE4BT1jP+L5xDaveGo91hddW3Q7qVHoASULJzKQOQvGTtu\nlPjl16St7OBzjy3E0dwrOJahV5IetG9BrvTJdM96vTDK0VZAm6UqNUmJVcDhlZFp\nUL7B+mtLp8WT51gahnZTX+m8l9OhhU66YRWEmdgKyn+dUJ3OZP/50I5vJpwJkNe2\nHvHrkvnIbdJuuYlvlj/X2LG9oAWFJvkOaYzv7gUgP+kgWKcI8XXCcKQySHFnlvOC\nn/UAEQEAAYkBHwQYAQoACQUCVG0R1AIbDAAKCRD85byW6Kw+FIkbB/wOXAtYHLuh\nPiR+y8HN3RKFj+U3/OoqZnzRmuYgBF7bPO8O3QcskstqYFlSYr4RqN4SphZ/opaC\npUFQ8uWNecUdb4cS2CxJ3HnrNOIgtcIe8TXIQckEeKL1Bu2KfGq4kjcm+94QEg3j\ncXEPpzarbPQPBVuv1y2LPfbmMSVc3xPfaK90otI5K9kAiHMt1s0P6BCySHOjH0CV\ncIjvlClr8HJ3IxUv79nggzC5t0YF5rHJtiHnmIWCg/NyAAwuKQVwNKTwtnR6vrol\nKETKgMhGyqALWVuOhy4Y33RjSjggHP9q2bAW6aWHHxJLQF5GBD0pQrAJJoItLe/w\nuJWPkuBbJCRf\n=32Wp\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n\npriv = \"\"", "end": 4852, "score": 0.9995787143707275, "start": 2104, "tag": "KEY", "value": "mQENBFRtEYQBCADSAtDn9FmeoXy1eSl5BKsZvBcQWNVx3so/CGqsXZrQu3lVftFY\nv90eqxlg/GHtZL26Aii08a9XLTazu3BeIKdokpdCtf2EO3q5dH1k1FAXLoSKvDXL\nnhAtiEUzwQOLZgU5LuFafgCeVwzMeT76++ILpdo0Mil09df28JyLX3NqL6xW4I09\nt2aFxgDxbfPYaYvFLw3IfYfaS1l3f2jvUmo4udXkNBNHHcvnJXEYOa+eHDJLt10I\nq+Dx/w30VmXoqXrEFIkZg2H54Gjg1tiwxTK0UiU6aO+msEAKIrIBu4WFDzwbYy6U\nxVmKjap3TWSlmhWWroqWADiNMcWnVJlat2pbABEBAAG0FldCIFllYXRzIDx3YkB5\nZWF0cy5tZT6JATgEEwEKACIFAlRtEYQCGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4B\nAheAAAoJEPzlvJborD4UxmQIAJfN+C+5EvvRsx2PuyHuqtHHuOnGSF70yvBI1poZ\nG/Oy7xDHPSzezD7FhTi0LLLQ2yt6//sljOudcWr3udk1EShgrxXuNTfdBKZgKi/H\nV03IxvIbcBGL7JQhYmayMie9LNo6U415gFyxysldHOzFWNARo4CiR/cQ2Y0X6jCd\nnfqR1d5XvHPVfI0LepCPxX9U90t84exkrrYo/fykLdNQukjO9zlywtjB1Z7b39oI\nItz6Cd/EQeOgxIiOBA0vS3sq/U5KyYEOufZm1NELQp7Nd+xTaOE/2ZB1mIrr6PQi\nR/h6L4WlA3j/TsPKWB3J9Y7wFYe5NRampiKt5BD020KkV/G5AQ0EVG0RhAEIANij\nMTFZ+1Hev55LQK/gB3t/LfbGmtHFKgtUCEbSwOAdVkFLr9BJNyhM3j3RS1U2QEdF\nqAtcQMhiANFjPGM1rJ3WmwQMdrVLdEmMNv9NskBJKYAV3cVw2MzkrwHoqUBmq9SX\nUnGj9wkezsQWsThGqcRws2ngOtMNNVi6wNY0eIrrs5KOQjhPcIthn2ffdw5dpj8l\ndx1uZpwWSFTrDosX7Q8eLYwt1SKX5h5uIMXSrX0BP+sOlbZn1gxLnH6e4log84fg\nJww0a2JMdTTOmvCgTtxmIoCF6dqK1GB4CAD8b9NgdbG3BM+KenpN1/YM1Nb46wDM\n0hyh6VjKvAFzl2sENLMAEQEAAYkBHwQoAQoACQUCVG0RyAIdAQAKCRD85byW6Kw+\nFIbSCACjOtd46OszAK9d/YRJ/eFT+OR8cx24xtUSMro4EQ3vJz1Hc7jznjTooL/s\nC25Kokpj0a+y8YaVGfmmvUzfT+g8N+Z0BraJShO5GpkLbG/+BrZw30lOE39iJZDh\nHfe4j80RDLnYaw0hMR8fjrONztQItbYvoALNl4NuzK4AA/r1i/3fxlGfRR+mtLrQ\n76AbX+52WfrXZK7vGALUkJgV2tFtgcSJbgbZSKYWzykWttOe5sxpczkaaB+DS9UJ\n7+LlUMJbFaqllE6WVqAqODP1n4R96rHh+Xc2uVtxe/NcWYRe8TmtBec8icujhPnE\ni+4E4W6HgmhlWjy002/TfNzM5VgMiQEfBBgBCgAJBQJUbRGEAhsMAAoJEPzlvJbo\nrD4Uum8H/inVByzp4X2Ja3Ng2LDHbF8suwMoF4AS2Nx0uKnQMHKb6L7g9uHpMPpF\noW6HeU3CGjmjj3eZufF+40UcsWOXhmQIu2RLo/F7oQhbWpCSGlmfzuBP2stRbnON\nLt7+AmHnT/Cm2+Ts4iVxeGdSF3M2hbOfPkxI0Rf+ud0pi7hgVJWkDoCe4Nc/HDkd\n+i58l/qGsWATh3lsi45IaGU4GzUUnbTEWbqrkwR66uVtc1u7XhaA5KOf52Efwc5S\nS7GjjxYDuC/+tP8+NZKVk8z4+4RG8Xru+/QlzMhJOkelsxS96+gLOFOHoXw4VxBq\nPZePpV7Wp8/9uN223QFzDZA629Khr3u5AQ0EVG0R1AEIANVqKo6aXtyaR/sEd0Ex\nr0OigaSAOE/sj/LN+xWuwQ45CP2oQDlWneBb3Nvkqmxyx03INPHeza8SvYkl7CBx\nZs2qh9Kr7yeP0QQkDrCE4BT1jP+L5xDaveGo91hddW3Q7qVHoASULJzKQOQvGTtu\nlPjl16St7OBzjy3E0dwrOJahV5IetG9BrvTJdM96vTDK0VZAm6UqNUmJVcDhlZFp\nUL7B+mtLp8WT51gahnZTX+m8l9OhhU66YRWEmdgKyn+dUJ3OZP/50I5vJpwJkNe2\nHvHrkvnIbdJuuYlvlj/X2LG9oAWFJvkOaYzv7gUgP+kgWKcI8XXCcKQySHFnlvOC\nn/UAEQEAAYkBHwQYAQoACQUCVG0R1AIbDAAKCRD85byW6Kw+FIkbB/wOXAtYHLuh\nPiR+y8HN3RKFj+U3/OoqZnzRmuYgBF7bPO8O3QcskstqYFlSYr4RqN4SphZ/opaC\npUFQ8uWNecUdb4cS2CxJ3HnrNOIgtcIe8TXIQckEeKL1Bu2KfGq4kjcm+94QEg3j\ncXEPpzarbPQPBVuv1y2LPfbmMSVc3xPfaK90otI5K9kAiHMt1s0P6BCySHOjH0CV\ncIjvlClr8HJ3IxUv79nggzC5t0YF5rHJtiHnmIWCg/NyAAwuKQVwNKTwtnR6vrol\nKETKgMhGyqALWVuOhy4Y33RjSjggHP9q2bAW6aWHHxJLQF5GBD0pQrAJJoItLe/w\nuJWPkuBbJCRf\n=32Wp" }, { "context": "cGPG2 v2\nComment: GPGTools - https://gpgtools.org\n\nlQO+BFRtEYQBCADSAtDn9FmeoXy1eSl5BKsZvBcQWNVx3so/CGqsXZrQu3lVftFY\nv90eqxlg/GHtZL26Aii08a9XLTazu3BeIKdokpdCtf2EO3q5dH1k1FAXLoSKvDXL\nnhAtiEUzwQOLZgU5LuFafgCeVwzMeT76++ILpdo0Mil09df28JyLX3NqL6xW4I09\nt2aFxgDxbfPYaYvFLw3IfYfaS1l3f2jvUmo4udXkNBNHHcvnJXEYOa+eHDJLt10I\nq+Dx/w30VmXoqXrEFIkZg2H54Gjg1tiwxTK0UiU6aO+msEAKIrIBu4WFDzwbYy6U\nxVmKjap3TWSlmhWWroqWADiNMcWnVJlat2pbABEBAAH+AwMCWHkEYBrCObXj8HDk\nLsmlG8uGNNinP00kpcR8QYUAtnE5Z45ODvuabOC0fghOnwQeVeqzE27nZdGzfnsq\nCvpucvCdvcOrgggp9UgKMceEmhOpACQPZTim59BeJ0M8EHMwcGKzT/Y1RNIlsh3X\n/HFVg+NRDvjSOoBFBvskCLwFDYsBACBZYzWhCxsY88WJ7S6jJnbsXzyCN4B76cXM\noLN1NRrQQYCGw2nfYvT057FHc6Ztr6aniw7nz1hqoLIdxlBSrcLUg+KpBAftcL+r\nGOScLqymWLCvZvTNoGbNXI9L8a7r1cEjVfg1z8Mu8O4BjwCZHqNps/YR5HEfnZPE\nixhQAstSzNF2Mtuzzo0bY5UDOmxUrqr5UOJ6CdwvglFiixzUf3/EgJpj4bHl8cv6\nZb0XOO05r6KQ6eWrIKtUfla8H1JRwpHWLHYBYHozPiGLgzgaTLSCjQFE1RlXFdDa\nU8e8cR66c/2bkjeoo5thKarXZ9iJkHUgpu8RA4mk+DF11anxvBJkryVukDMskgtJ\n2/3aFVj+8E2fjGjBq8LgdZwtZzH8+ZVf+6Y/5ok7twnDRVh4yROvsGS7AjO82FLi\n0qMPqVLmmJgwocbzOahZUa/iL7iHJXyL+Lfp9kVgZv1t8HPcHMOUJjkterip1Pli\nn4nZvewQngLaTbOxHyEcCtkYop2/RqkHgMZ6r5H+xXXEWljZhKcEDg6mOYRbDATN\nYSwlMpycDJrtXwcHuKJmDPu7txRbxT/6sGT9M8JIIonppaT35VO21pjEFwVhGlg3\nMFOlGZLdjhN3vM0J+i4sycNpalZmAn+PWiu3YsJg5EO2rPb5a/42TyZmB/dHGxKy\nt1bDzeSrvaWtgM/VzGMWeJ8oXWk/+aXLgqDrpx4lx0OqFEfy8CyUbHk+BGdq/rLT\nGLQWV0IgWWVhdHMgPHdiQHllYXRzLm1lPokBOAQTAQoAIgUCVG0RhAIbAwYLCQgH\nAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ/OW8luisPhTGZAgAl834L7kS+9GzHY+7\nIe6q0ce46cZIXvTK8EjWmhkb87LvEMc9LN7MPsWFOLQsstDbK3r/+yWM651xave5\n2TURKGCvFe41N90EpmAqL8dXTcjG8htwEYvslCFiZrIyJ70s2jpTjXmAXLHKyV0c\n7MVY0BGjgKJH9xDZjRfqMJ2d+pHV3le8c9V8jQt6kI/Ff1T3S3zh7GSutij9/KQt\n01C6SM73OXLC2MHVntvf2ggi3PoJ38RB46DEiI4EDS9Leyr9TkrJgQ659mbU0QtC\nns137FNo4T/ZkHWYiuvo9CJH+HovhaUDeP9Ow8pYHcn1jvAVh7k1FqamIq3kEPTb\nQqRX8Z0DvgRUbRGEAQgA2KMxMVn7Ud6/nktAr+AHe38t9saa0cUqC1QIRtLA4B1W\nQUuv0Ek3KEzePdFLVTZAR0WoC1xAyGIA0WM8YzWsndabBAx2tUt0SYw2/02yQEkp\ngBXdxXDYzOSvAeipQGar1JdScaP3CR7OxBaxOEapxHCzaeA60w01WLrA1jR4iuuz\nko5COE9wi2GfZ993Dl2mPyV3HW5mnBZIVOsOixftDx4tjC3VIpfmHm4gxdKtfQE/\n6w6VtmfWDEucfp7iWiDzh+AnDDRrYkx1NM6a8KBO3GYigIXp2orUYHgIAPxv02B1\nsbcEz4p6ek3X9gzU1vjrAMzSHKHpWMq8AXOXawQ0swARAQAB/gMDAlh5BGAawjm1\n4yCBgm0dF7pKOZbWyfPFrGbqZT28w+RgzJFz3kKzM+MQigSfaDIuhm84S/QqdVEa\npvYYg8VhqTd0NhBUSGlbyD+401g/qCGuki2hM4hL0TLOCMoaKUwcj8E5Ke3JdOmt\naIIV50LnG77G1py0IEknn7fGoT+r6+zIQBsJn5za/d+YoqlkcMV/PLAOtRbBDHur\nAF86b326QcqXSQeylKRW8j+wBoJKMk/MJJpkajQ39nkaBOA+/3T9sBiRYj7Rf/N7\n5cBr26Uam8Dgb/grndtQv3A9hm0NP/zg70Baq35vZo/1Inssdjp/HSwTs595CKWG\nxPcqpqthJbwN3aXqMd05JnZhlaLH+J/FXCsBXw8Fok2Xd0PTeMDL2LnGieYHlYYn\nBhI7J8xIvYjvwVkYEN1KGIdpvrZQ7eIy51sVywjUqOoajY2fSujt97z51gO0oE2e\naNqce/MFxKk50RRUT15RTMKQnRy+3xHKp4C7sX8+0TZR/MtaU6rXukrInDr52qcF\nAhn6EEv+xGuDSbyeIoLyRo0u88uug5t633wJB0pcilUguNGMo5YMGDVPOFnCOvxa\nWeNkGQlDvgxherp/XjjTbYrwztwuGaNAWKfkvyzpUEG3+sb5fXVO1lxECmSjbQUN\nndG6LKm1w9RwGqIKdkomxXGdC74BUCaU9w9OEoLJQw6mqm7YNt2ADP2qAhOYsgUA\n8dOQ37ryRbbL1F37M5SedeHM3sirrTtX6O41ASDYldOADUWNeaYc0X+G8drVQ2rg\nIn4L1yh4pOA/sqIqNg9jgfW4kh7jaN1zrI7E7eiAGYBeVFVbMCCmyl4Rifc0vVi/\nL/nL/BYLRG1h7xIqQ5lz3DvtYbqpAUlCQWaXApnKEIMuKPvAycQ0Yzckzdccro88\n1m3dO/OJAR8EGAEKAAkFAlRtEYQCGwwACgkQ/OW8luisPhS6bwf+KdUHLOnhfYlr\nc2DYsMdsXyy7AygXgBLY3HS4qdAwcpvovuD24ekw+kWhbod5TcIaOaOPd5m58X7j\nRRyxY5eGZAi7ZEuj8XuhCFtakJIaWZ/O4E/ay1Fuc40u3v4CYedP8Kbb5OziJXF4\nZ1IXczaFs58+TEjRF/653SmLuGBUlaQOgJ7g1z8cOR36LnyX+oaxYBOHeWyLjkho\nZTgbNRSdtMRZuquTBHrq5W1zW7teFoDko5/nYR/BzlJLsaOPFgO4L/60/z41kpWT\nzPj7hEbxeu779CXMyEk6R6WzFL3r6As4U4ehfDhXEGo9l4+lXtanz/243bbdAXMN\nkDrb0qGve50DvgRUbRHUAQgA1Woqjppe3JpH+wR3QTGvQ6KBpIA4T+yP8s37Fa7B\nDjkI/ahAOVad4Fvc2+SqbHLHTcg08d7NrxK9iSXsIHFmzaqH0qvvJ4/RBCQOsITg\nFPWM/4vnENq94aj3WF11bdDupUegBJQsnMpA5C8ZO26U+OXXpK3s4HOPLcTR3Cs4\nlqFXkh60b0Gu9Ml0z3q9MMrRVkCbpSo1SYlVwOGVkWlQvsH6a0unxZPnWBqGdlNf\n6byX06GFTrphFYSZ2ArKf51Qnc5k//nQjm8mnAmQ17Ye8euS+cht0m65iW+WP9fY\nsb2gBYUm+Q5pjO/uBSA/6SBYpwjxdcJwpDJIcWeW84Kf9QARAQAB/gMDAtdDRfms\nXnAL4xbpconkskRGMpfNwdbf+rSUW800D2xF1e48FOE4V+bZJr6ONEdhu94Gl7oV\n2Cq6lvP3/H/W+wwbWP0SYGyKVFSmM/D5UTFNz6BSml6pCOaPLeaB3FkX2RFtBppO\nvIDCQo/MoEjWor29QVF13M+Cp8Xv8B3WPIhHQ7O32j0w7micgEDiSnL5Cgeb1Ekz\nN4c4LcTIL0jl0G/J2YLlRNR7g8PPypdDDceRa/nfDiP2X4MSrH2ed9V+NY3emToD\n4yuHu4h4uuStdWnE1c7KyUjZK4vhPHHkX4Atmg3M2xEqG9UdA0D7pJofce7Op+kX\ni5hqNtlsgE1wdgAX4BhJlZTZwTK0nbcu8flssl4Qu4Tl/JEi/dTvEW5m2gz0Vpjz\nJ+bSdAe3UyaeIdIAieO7TOcO+2IGy7p0f3eLKCLQd4w0ob8o0RCMat9G0kSJaC/N\nxhr/TEPPJMRRuqT8UGHpcuuNQf82VPFol/C7Z3jBG21FdLSdALXHPt+0AwEbiD2R\npEH39GQjgbKBWgrlW/QSm3aRfLseaYd2tbEsW1MP84I1hnncNRWWV8c5PnXpZhrS\nKQHptKuERZu9s6nC8AOGKYugywuBKHmg5c+svDmdD9kL5vLV1snljJjYYXpiMoJA\nSkVtj0Kq9k9i7L5IfoieU0pwjd9ngkJ7x6FKxmRTAg27jm5exsHnqxCEx7tw1akw\nSxe0kfz5eWgwQgV1r9qo9xY7eb2hv4mAQWbySu/7+NBeRz6SZHS0gpkA+2qAkPie\nMrzQ1wUyMfNc8Ij93x+hLKpgFZSKJB9X53Ot8IS2OJMdgZXHrr7JzHwDiyGxkBLi\nfoXP/SjwFjbaARKGQeJhlocGYv7BqAIMnYEzQfTQHCcUetVOleQQSgK8mvZ76o/c\nx4JTP0VPAxiJAR8EGAEKAAkFAlRtEdQCGwwACgkQ/OW8luisPhSJGwf8DlwLWBy7\noT4kfsvBzd0ShY/lN/zqKmZ80ZrmIARe2zzvDt0HLJLLamBZUmK+EajeEqYWf6KW\ngqVBUPLljXnFHW+HEtgsSdx56zTiILXCHvE1yEHJBHii9QbtinxquJI3JvveEBIN\n43FxD6c2q2z0DwVbr9ctiz325jElXN8T32ivdKLSOSvZAIhzLdbND+gQskhzox9A\nlXCI75Qpa/BydyMVL+/Z4IMwubdGBeaxybYh55iFgoPzcgAMLikFcDSk8LZ0er66\nJShEyoDIRsqgC1lbjocuGN90Y0o4IBz/atmwFumlhx8SS0BeRgQ9KUKwCSaCLS3v\n8LiVj5LgWyQkXw==\n=VQP1\n-----END PGP PRIVA", "end": 10136, "score": 0.9994102716445923, "start": 5010, "tag": "KEY", "value": "lQO+BFRtEYQBCADSAtDn9FmeoXy1eSl5BKsZvBcQWNVx3so/CGqsXZrQu3lVftFY\nv90eqxlg/GHtZL26Aii08a9XLTazu3BeIKdokpdCtf2EO3q5dH1k1FAXLoSKvDXL\nnhAtiEUzwQOLZgU5LuFafgCeVwzMeT76++ILpdo0Mil09df28JyLX3NqL6xW4I09\nt2aFxgDxbfPYaYvFLw3IfYfaS1l3f2jvUmo4udXkNBNHHcvnJXEYOa+eHDJLt10I\nq+Dx/w30VmXoqXrEFIkZg2H54Gjg1tiwxTK0UiU6aO+msEAKIrIBu4WFDzwbYy6U\nxVmKjap3TWSlmhWWroqWADiNMcWnVJlat2pbABEBAAH+AwMCWHkEYBrCObXj8HDk\nLsmlG8uGNNinP00kpcR8QYUAtnE5Z45ODvuabOC0fghOnwQeVeqzE27nZdGzfnsq\nCvpucvCdvcOrgggp9UgKMceEmhOpACQPZTim59BeJ0M8EHMwcGKzT/Y1RNIlsh3X\n/HFVg+NRDvjSOoBFBvskCLwFDYsBACBZYzWhCxsY88WJ7S6jJnbsXzyCN4B76cXM\noLN1NRrQQYCGw2nfYvT057FHc6Ztr6aniw7nz1hqoLIdxlBSrcLUg+KpBAftcL+r\nGOScLqymWLCvZvTNoGbNXI9L8a7r1cEjVfg1z8Mu8O4BjwCZHqNps/YR5HEfnZPE\nixhQAstSzNF2Mtuzzo0bY5UDOmxUrqr5UOJ6CdwvglFiixzUf3/EgJpj4bHl8cv6\nZb0XOO05r6KQ6eWrIKtUfla8H1JRwpHWLHYBYHozPiGLgzgaTLSCjQFE1RlXFdDa\nU8e8cR66c/2bkjeoo5thKarXZ9iJkHUgpu8RA4mk+DF11anxvBJkryVukDMskgtJ\n2/3aFVj+8E2fjGjBq8LgdZwtZzH8+ZVf+6Y/5ok7twnDRVh4yROvsGS7AjO82FLi\n0qMPqVLmmJgwocbzOahZUa/iL7iHJXyL+Lfp9kVgZv1t8HPcHMOUJjkterip1Pli\nn4nZvewQngLaTbOxHyEcCtkYop2/RqkHgMZ6r5H+xXXEWljZhKcEDg6mOYRbDATN\nYSwlMpycDJrtXwcHuKJmDPu7txRbxT/6sGT9M8JIIonppaT35VO21pjEFwVhGlg3\nMFOlGZLdjhN3vM0J+i4sycNpalZmAn+PWiu3YsJg5EO2rPb5a/42TyZmB/dHGxKy\nt1bDzeSrvaWtgM/VzGMWeJ8oXWk/+aXLgqDrpx4lx0OqFEfy8CyUbHk+BGdq/rLT\nGLQWV0IgWWVhdHMgPHdiQHllYXRzLm1lPokBOAQTAQoAIgUCVG0RhAIbAwYLCQgH\nAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ/OW8luisPhTGZAgAl834L7kS+9GzHY+7\nIe6q0ce46cZIXvTK8EjWmhkb87LvEMc9LN7MPsWFOLQsstDbK3r/+yWM651xave5\n2TURKGCvFe41N90EpmAqL8dXTcjG8htwEYvslCFiZrIyJ70s2jpTjXmAXLHKyV0c\n7MVY0BGjgKJH9xDZjRfqMJ2d+pHV3le8c9V8jQt6kI/Ff1T3S3zh7GSutij9/KQt\n01C6SM73OXLC2MHVntvf2ggi3PoJ38RB46DEiI4EDS9Leyr9TkrJgQ659mbU0QtC\nns137FNo4T/ZkHWYiuvo9CJH+HovhaUDeP9Ow8pYHcn1jvAVh7k1FqamIq3kEPTb\nQqRX8Z0DvgRUbRGEAQgA2KMxMVn7Ud6/nktAr+AHe38t9saa0cUqC1QIRtLA4B1W\nQUuv0Ek3KEzePdFLVTZAR0WoC1xAyGIA0WM8YzWsndabBAx2tUt0SYw2/02yQEkp\ngBXdxXDYzOSvAeipQGar1JdScaP3CR7OxBaxOEapxHCzaeA60w01WLrA1jR4iuuz\nko5COE9wi2GfZ993Dl2mPyV3HW5mnBZIVOsOixftDx4tjC3VIpfmHm4gxdKtfQE/\n6w6VtmfWDEucfp7iWiDzh+AnDDRrYkx1NM6a8KBO3GYigIXp2orUYHgIAPxv02B1\nsbcEz4p6ek3X9gzU1vjrAMzSHKHpWMq8AXOXawQ0swARAQAB/gMDAlh5BGAawjm1\n4yCBgm0dF7pKOZbWyfPFrGbqZT28w+RgzJFz3kKzM+MQigSfaDIuhm84S/QqdVEa\npvYYg8VhqTd0NhBUSGlbyD+401g/qCGuki2hM4hL0TLOCMoaKUwcj8E5Ke3JdOmt\naIIV50LnG77G1py0IEknn7fGoT+r6+zIQBsJn5za/d+YoqlkcMV/PLAOtRbBDHur\nAF86b326QcqXSQeylKRW8j+wBoJKMk/MJJpkajQ39nkaBOA+/3T9sBiRYj7Rf/N7\n5cBr26Uam8Dgb/grndtQv3A9hm0NP/zg70Baq35vZo/1Inssdjp/HSwTs595CKWG\nxPcqpqthJbwN3aXqMd05JnZhlaLH+J/FXCsBXw8Fok2Xd0PTeMDL2LnGieYHlYYn\nBhI7J8xIvYjvwVkYEN1KGIdpvrZQ7eIy51sVywjUqOoajY2fSujt97z51gO0oE2e\naNqce/MFxKk50RRUT15RTMKQnRy+3xHKp4C7sX8+0TZR/MtaU6rXukrInDr52qcF\nAhn6EEv+xGuDSbyeIoLyRo0u88uug5t633wJB0pcilUguNGMo5YMGDVPOFnCOvxa\nWeNkGQlDvgxherp/XjjTbYrwztwuGaNAWKfkvyzpUEG3+sb5fXVO1lxECmSjbQUN\nndG6LKm1w9RwGqIKdkomxXGdC74BUCaU9w9OEoLJQw6mqm7YNt2ADP2qAhOYsgUA\n8dOQ37ryRbbL1F37M5SedeHM3sirrTtX6O41ASDYldOADUWNeaYc0X+G8drVQ2rg\nIn4L1yh4pOA/sqIqNg9jgfW4kh7jaN1zrI7E7eiAGYBeVFVbMCCmyl4Rifc0vVi/\nL/nL/BYLRG1h7xIqQ5lz3DvtYbqpAUlCQWaXApnKEIMuKPvAycQ0Yzckzdccro88\n1m3dO/OJAR8EGAEKAAkFAlRtEYQCGwwACgkQ/OW8luisPhS6bwf+KdUHLOnhfYlr\nc2DYsMdsXyy7AygXgBLY3HS4qdAwcpvovuD24ekw+kWhbod5TcIaOaOPd5m58X7j\nRRyxY5eGZAi7ZEuj8XuhCFtakJIaWZ/O4E/ay1Fuc40u3v4CYedP8Kbb5OziJXF4\nZ1IXczaFs58+TEjRF/653SmLuGBUlaQOgJ7g1z8cOR36LnyX+oaxYBOHeWyLjkho\nZTgbNRSdtMRZuquTBHrq5W1zW7teFoDko5/nYR/BzlJLsaOPFgO4L/60/z41kpWT\nzPj7hEbxeu779CXMyEk6R6WzFL3r6As4U4ehfDhXEGo9l4+lXtanz/243bbdAXMN\nkDrb0qGve50DvgRUbRHUAQgA1Woqjppe3JpH+wR3QTGvQ6KBpIA4T+yP8s37Fa7B\nDjkI/ahAOVad4Fvc2+SqbHLHTcg08d7NrxK9iSXsIHFmzaqH0qvvJ4/RBCQOsITg\nFPWM/4vnENq94aj3WF11bdDupUegBJQsnMpA5C8ZO26U+OXXpK3s4HOPLcTR3Cs4\nlqFXkh60b0Gu9Ml0z3q9MMrRVkCbpSo1SYlVwOGVkWlQvsH6a0unxZPnWBqGdlNf\n6byX06GFTrphFYSZ2ArKf51Qnc5k//nQjm8mnAmQ17Ye8euS+cht0m65iW+WP9fY\nsb2gBYUm+Q5pjO/uBSA/6SBYpwjxdcJwpDJIcWeW84Kf9QARAQAB/gMDAtdDRfms\nXnAL4xbpconkskRGMpfNwdbf+rSUW800D2xF1e48FOE4V+bZJr6ONEdhu94Gl7oV\n2Cq6lvP3/H/W+wwbWP0SYGyKVFSmM/D5UTFNz6BSml6pCOaPLeaB3FkX2RFtBppO\nvIDCQo/MoEjWor29QVF13M+Cp8Xv8B3WPIhHQ7O32j0w7micgEDiSnL5Cgeb1Ekz\nN4c4LcTIL0jl0G/J2YLlRNR7g8PPypdDDceRa/nfDiP2X4MSrH2ed9V+NY3emToD\n4yuHu4h4uuStdWnE1c7KyUjZK4vhPHHkX4Atmg3M2xEqG9UdA0D7pJofce7Op+kX\ni5hqNtlsgE1wdgAX4BhJlZTZwTK0nbcu8flssl4Qu4Tl/JEi/dTvEW5m2gz0Vpjz\nJ+bSdAe3UyaeIdIAieO7TOcO+2IGy7p0f3eLKCLQd4w0ob8o0RCMat9G0kSJaC/N\nxhr/TEPPJMRRuqT8UGHpcuuNQf82VPFol/C7Z3jBG21FdLSdALXHPt+0AwEbiD2R\npEH39GQjgbKBWgrlW/QSm3aRfLseaYd2tbEsW1MP84I1hnncNRWWV8c5PnXpZhrS\nKQHptKuERZu9s6nC8AOGKYugywuBKHmg5c+svDmdD9kL5vLV1snljJjYYXpiMoJA\nSkVtj0Kq9k9i7L5IfoieU0pwjd9ngkJ7x6FKxmRTAg27jm5exsHnqxCEx7tw1akw\nSxe0kfz5eWgwQgV1r9qo9xY7eb2hv4mAQWbySu/7+NBeRz6SZHS0gpkA+2qAkPie\nMrzQ1wUyMfNc8Ij93x+hLKpgFZSKJB9X53Ot8IS2OJMdgZXHrr7JzHwDiyGxkBLi\nfoXP/SjwFjbaARKGQeJhlocGYv7BqAIMnYEzQfTQHCcUetVOleQQSgK8mvZ76o/c\nx4JTP0VPAxiJAR8EGAEKAAkFAlRtEdQCGwwACgkQ/OW8luisPhSJGwf8DlwLWBy7\noT4kfsvBzd0ShY/lN/zqKmZ80ZrmIARe2zzvDt0HLJLLamBZUmK+EajeEqYWf6KW\ngqVBUPLljXnFHW+HEtgsSdx56zTiILXCHvE1yEHJBHii9QbtinxquJI3JvveEBIN\n43FxD6c2q2z0DwVbr9ctiz325jElXN8T32ivdKLSOSvZAIhzLdbND+gQskhzox9A\nlXCI75Qpa/BydyMVL+/Z4IMwubdGBeaxybYh55iFgoPzcgAMLikFcDSk8LZ0er66\nJShEyoDIRsqgC1lbjocuGN90Y0o4IBz/atmwFumlhx8SS0BeRgQ9KUKw" }, { "context": "END PGP PRIVATE KEY BLOCK-----\n\"\"\"\n\npassphrase = \"asdf\"\ngood_subkey = \"94A0 6B09 0623 2D4F 4D4C 45F1 72", "end": 10227, "score": 0.9990335702896118, "start": 10223, "tag": "PASSWORD", "value": "asdf" }, { "context": "LOCK-----\n\"\"\"\n\npassphrase = \"asdf\"\ngood_subkey = \"94A0 6B09 0623 2D4F 4D4C 45F1 729A CF60 BEC2 95CC\".split(/\\s+/).join('').toLowerCase()\n\n#==========", "end": 10294, "score": 0.9985137581825256, "start": 10244, "tag": "KEY", "value": "94A0 6B09 0623 2D4F 4D4C 45F1 729A CF60 BEC2 95CC" } ]
test/files/revoked_subkey.iced
johnnyRose/kbpgp
1
{KeyManager,box,unbox} = require '../..' #================================================================= pubkm = null seckm = null ctext = null ptext = null exports.import_public = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pub }, T.esc(defer(tmp, warnings), cb, "import_public") T.assert (warnings.warnings().length is 0), "didn't get any warnings" pubkm = tmp cb() #================================================================================= exports.import_private = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : priv }, T.esc(defer(tmp, warnings), cb, "import_private") T.assert (warnings.warnings().length is 0), "didn't get any warnings" seckm = tmp T.waypoint "about to s2k with very big parameters..." T.assert seckm.has_pgp_private(), "has a private key" await seckm.unlock_pgp { passphrase }, T.esc(defer()) cb() #================================================================================= exports.encrypt = (T, cb) -> ptext = """" That is no country for old men. The young In one another’s arms, birds in the trees —Those dying generations—at their song, The salmon-falls, the mackerel-crowded seas, Fish, flesh, or fowl, commend all summer long Whatever is begotten, born, and dies. Caught in that sensual music all neglect Monuments of unageing intellect. """ await box { msg : ptext, encrypt_for : pubkm }, T.esc(defer(aout, raw), cb, "encrypt") ctext = aout cb() #================================================================================= exports.decrypt = (T, cb) -> await unbox { keyfetch : seckm, armored : ctext }, T.esc(defer(literals, warnings, esk), cb, "decrypt") T.equal ptext, literals[0].toString(), "ciphertext came back OK" T.equal warnings.warnings().length, 0, "no warnings" T.equal esk.get_fingerprint().toString("hex"), good_subkey, "encrypted with the right subkey" cb() #================================================================================= pub = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2 Comment: GPGTools - https://gpgtools.org mQENBFRtEYQBCADSAtDn9FmeoXy1eSl5BKsZvBcQWNVx3so/CGqsXZrQu3lVftFY v90eqxlg/GHtZL26Aii08a9XLTazu3BeIKdokpdCtf2EO3q5dH1k1FAXLoSKvDXL nhAtiEUzwQOLZgU5LuFafgCeVwzMeT76++ILpdo0Mil09df28JyLX3NqL6xW4I09 t2aFxgDxbfPYaYvFLw3IfYfaS1l3f2jvUmo4udXkNBNHHcvnJXEYOa+eHDJLt10I q+Dx/w30VmXoqXrEFIkZg2H54Gjg1tiwxTK0UiU6aO+msEAKIrIBu4WFDzwbYy6U xVmKjap3TWSlmhWWroqWADiNMcWnVJlat2pbABEBAAG0FldCIFllYXRzIDx3YkB5 ZWF0cy5tZT6JATgEEwEKACIFAlRtEYQCGwMGCwkIBwMCBhUIAgkKCwQWAgMBAh4B AheAAAoJEPzlvJborD4UxmQIAJfN+C+5EvvRsx2PuyHuqtHHuOnGSF70yvBI1poZ G/Oy7xDHPSzezD7FhTi0LLLQ2yt6//sljOudcWr3udk1EShgrxXuNTfdBKZgKi/H V03IxvIbcBGL7JQhYmayMie9LNo6U415gFyxysldHOzFWNARo4CiR/cQ2Y0X6jCd nfqR1d5XvHPVfI0LepCPxX9U90t84exkrrYo/fykLdNQukjO9zlywtjB1Z7b39oI Itz6Cd/EQeOgxIiOBA0vS3sq/U5KyYEOufZm1NELQp7Nd+xTaOE/2ZB1mIrr6PQi R/h6L4WlA3j/TsPKWB3J9Y7wFYe5NRampiKt5BD020KkV/G5AQ0EVG0RhAEIANij MTFZ+1Hev55LQK/gB3t/LfbGmtHFKgtUCEbSwOAdVkFLr9BJNyhM3j3RS1U2QEdF qAtcQMhiANFjPGM1rJ3WmwQMdrVLdEmMNv9NskBJKYAV3cVw2MzkrwHoqUBmq9SX UnGj9wkezsQWsThGqcRws2ngOtMNNVi6wNY0eIrrs5KOQjhPcIthn2ffdw5dpj8l dx1uZpwWSFTrDosX7Q8eLYwt1SKX5h5uIMXSrX0BP+sOlbZn1gxLnH6e4log84fg Jww0a2JMdTTOmvCgTtxmIoCF6dqK1GB4CAD8b9NgdbG3BM+KenpN1/YM1Nb46wDM 0hyh6VjKvAFzl2sENLMAEQEAAYkBHwQoAQoACQUCVG0RyAIdAQAKCRD85byW6Kw+ FIbSCACjOtd46OszAK9d/YRJ/eFT+OR8cx24xtUSMro4EQ3vJz1Hc7jznjTooL/s C25Kokpj0a+y8YaVGfmmvUzfT+g8N+Z0BraJShO5GpkLbG/+BrZw30lOE39iJZDh Hfe4j80RDLnYaw0hMR8fjrONztQItbYvoALNl4NuzK4AA/r1i/3fxlGfRR+mtLrQ 76AbX+52WfrXZK7vGALUkJgV2tFtgcSJbgbZSKYWzykWttOe5sxpczkaaB+DS9UJ 7+LlUMJbFaqllE6WVqAqODP1n4R96rHh+Xc2uVtxe/NcWYRe8TmtBec8icujhPnE i+4E4W6HgmhlWjy002/TfNzM5VgMiQEfBBgBCgAJBQJUbRGEAhsMAAoJEPzlvJbo rD4Uum8H/inVByzp4X2Ja3Ng2LDHbF8suwMoF4AS2Nx0uKnQMHKb6L7g9uHpMPpF oW6HeU3CGjmjj3eZufF+40UcsWOXhmQIu2RLo/F7oQhbWpCSGlmfzuBP2stRbnON Lt7+AmHnT/Cm2+Ts4iVxeGdSF3M2hbOfPkxI0Rf+ud0pi7hgVJWkDoCe4Nc/HDkd +i58l/qGsWATh3lsi45IaGU4GzUUnbTEWbqrkwR66uVtc1u7XhaA5KOf52Efwc5S S7GjjxYDuC/+tP8+NZKVk8z4+4RG8Xru+/QlzMhJOkelsxS96+gLOFOHoXw4VxBq PZePpV7Wp8/9uN223QFzDZA629Khr3u5AQ0EVG0R1AEIANVqKo6aXtyaR/sEd0Ex r0OigaSAOE/sj/LN+xWuwQ45CP2oQDlWneBb3Nvkqmxyx03INPHeza8SvYkl7CBx Zs2qh9Kr7yeP0QQkDrCE4BT1jP+L5xDaveGo91hddW3Q7qVHoASULJzKQOQvGTtu lPjl16St7OBzjy3E0dwrOJahV5IetG9BrvTJdM96vTDK0VZAm6UqNUmJVcDhlZFp UL7B+mtLp8WT51gahnZTX+m8l9OhhU66YRWEmdgKyn+dUJ3OZP/50I5vJpwJkNe2 HvHrkvnIbdJuuYlvlj/X2LG9oAWFJvkOaYzv7gUgP+kgWKcI8XXCcKQySHFnlvOC n/UAEQEAAYkBHwQYAQoACQUCVG0R1AIbDAAKCRD85byW6Kw+FIkbB/wOXAtYHLuh PiR+y8HN3RKFj+U3/OoqZnzRmuYgBF7bPO8O3QcskstqYFlSYr4RqN4SphZ/opaC pUFQ8uWNecUdb4cS2CxJ3HnrNOIgtcIe8TXIQckEeKL1Bu2KfGq4kjcm+94QEg3j cXEPpzarbPQPBVuv1y2LPfbmMSVc3xPfaK90otI5K9kAiHMt1s0P6BCySHOjH0CV cIjvlClr8HJ3IxUv79nggzC5t0YF5rHJtiHnmIWCg/NyAAwuKQVwNKTwtnR6vrol KETKgMhGyqALWVuOhy4Y33RjSjggHP9q2bAW6aWHHxJLQF5GBD0pQrAJJoItLe/w uJWPkuBbJCRf =32Wp -----END PGP PUBLIC KEY BLOCK----- """ priv = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2 Comment: GPGTools - https://gpgtools.org lQO+BFRtEYQBCADSAtDn9FmeoXy1eSl5BKsZvBcQWNVx3so/CGqsXZrQu3lVftFY v90eqxlg/GHtZL26Aii08a9XLTazu3BeIKdokpdCtf2EO3q5dH1k1FAXLoSKvDXL nhAtiEUzwQOLZgU5LuFafgCeVwzMeT76++ILpdo0Mil09df28JyLX3NqL6xW4I09 t2aFxgDxbfPYaYvFLw3IfYfaS1l3f2jvUmo4udXkNBNHHcvnJXEYOa+eHDJLt10I q+Dx/w30VmXoqXrEFIkZg2H54Gjg1tiwxTK0UiU6aO+msEAKIrIBu4WFDzwbYy6U xVmKjap3TWSlmhWWroqWADiNMcWnVJlat2pbABEBAAH+AwMCWHkEYBrCObXj8HDk LsmlG8uGNNinP00kpcR8QYUAtnE5Z45ODvuabOC0fghOnwQeVeqzE27nZdGzfnsq CvpucvCdvcOrgggp9UgKMceEmhOpACQPZTim59BeJ0M8EHMwcGKzT/Y1RNIlsh3X /HFVg+NRDvjSOoBFBvskCLwFDYsBACBZYzWhCxsY88WJ7S6jJnbsXzyCN4B76cXM oLN1NRrQQYCGw2nfYvT057FHc6Ztr6aniw7nz1hqoLIdxlBSrcLUg+KpBAftcL+r GOScLqymWLCvZvTNoGbNXI9L8a7r1cEjVfg1z8Mu8O4BjwCZHqNps/YR5HEfnZPE ixhQAstSzNF2Mtuzzo0bY5UDOmxUrqr5UOJ6CdwvglFiixzUf3/EgJpj4bHl8cv6 Zb0XOO05r6KQ6eWrIKtUfla8H1JRwpHWLHYBYHozPiGLgzgaTLSCjQFE1RlXFdDa U8e8cR66c/2bkjeoo5thKarXZ9iJkHUgpu8RA4mk+DF11anxvBJkryVukDMskgtJ 2/3aFVj+8E2fjGjBq8LgdZwtZzH8+ZVf+6Y/5ok7twnDRVh4yROvsGS7AjO82FLi 0qMPqVLmmJgwocbzOahZUa/iL7iHJXyL+Lfp9kVgZv1t8HPcHMOUJjkterip1Pli n4nZvewQngLaTbOxHyEcCtkYop2/RqkHgMZ6r5H+xXXEWljZhKcEDg6mOYRbDATN YSwlMpycDJrtXwcHuKJmDPu7txRbxT/6sGT9M8JIIonppaT35VO21pjEFwVhGlg3 MFOlGZLdjhN3vM0J+i4sycNpalZmAn+PWiu3YsJg5EO2rPb5a/42TyZmB/dHGxKy t1bDzeSrvaWtgM/VzGMWeJ8oXWk/+aXLgqDrpx4lx0OqFEfy8CyUbHk+BGdq/rLT GLQWV0IgWWVhdHMgPHdiQHllYXRzLm1lPokBOAQTAQoAIgUCVG0RhAIbAwYLCQgH AwIGFQgCCQoLBBYCAwECHgECF4AACgkQ/OW8luisPhTGZAgAl834L7kS+9GzHY+7 Ie6q0ce46cZIXvTK8EjWmhkb87LvEMc9LN7MPsWFOLQsstDbK3r/+yWM651xave5 2TURKGCvFe41N90EpmAqL8dXTcjG8htwEYvslCFiZrIyJ70s2jpTjXmAXLHKyV0c 7MVY0BGjgKJH9xDZjRfqMJ2d+pHV3le8c9V8jQt6kI/Ff1T3S3zh7GSutij9/KQt 01C6SM73OXLC2MHVntvf2ggi3PoJ38RB46DEiI4EDS9Leyr9TkrJgQ659mbU0QtC ns137FNo4T/ZkHWYiuvo9CJH+HovhaUDeP9Ow8pYHcn1jvAVh7k1FqamIq3kEPTb QqRX8Z0DvgRUbRGEAQgA2KMxMVn7Ud6/nktAr+AHe38t9saa0cUqC1QIRtLA4B1W QUuv0Ek3KEzePdFLVTZAR0WoC1xAyGIA0WM8YzWsndabBAx2tUt0SYw2/02yQEkp gBXdxXDYzOSvAeipQGar1JdScaP3CR7OxBaxOEapxHCzaeA60w01WLrA1jR4iuuz ko5COE9wi2GfZ993Dl2mPyV3HW5mnBZIVOsOixftDx4tjC3VIpfmHm4gxdKtfQE/ 6w6VtmfWDEucfp7iWiDzh+AnDDRrYkx1NM6a8KBO3GYigIXp2orUYHgIAPxv02B1 sbcEz4p6ek3X9gzU1vjrAMzSHKHpWMq8AXOXawQ0swARAQAB/gMDAlh5BGAawjm1 4yCBgm0dF7pKOZbWyfPFrGbqZT28w+RgzJFz3kKzM+MQigSfaDIuhm84S/QqdVEa pvYYg8VhqTd0NhBUSGlbyD+401g/qCGuki2hM4hL0TLOCMoaKUwcj8E5Ke3JdOmt aIIV50LnG77G1py0IEknn7fGoT+r6+zIQBsJn5za/d+YoqlkcMV/PLAOtRbBDHur AF86b326QcqXSQeylKRW8j+wBoJKMk/MJJpkajQ39nkaBOA+/3T9sBiRYj7Rf/N7 5cBr26Uam8Dgb/grndtQv3A9hm0NP/zg70Baq35vZo/1Inssdjp/HSwTs595CKWG xPcqpqthJbwN3aXqMd05JnZhlaLH+J/FXCsBXw8Fok2Xd0PTeMDL2LnGieYHlYYn BhI7J8xIvYjvwVkYEN1KGIdpvrZQ7eIy51sVywjUqOoajY2fSujt97z51gO0oE2e aNqce/MFxKk50RRUT15RTMKQnRy+3xHKp4C7sX8+0TZR/MtaU6rXukrInDr52qcF Ahn6EEv+xGuDSbyeIoLyRo0u88uug5t633wJB0pcilUguNGMo5YMGDVPOFnCOvxa WeNkGQlDvgxherp/XjjTbYrwztwuGaNAWKfkvyzpUEG3+sb5fXVO1lxECmSjbQUN ndG6LKm1w9RwGqIKdkomxXGdC74BUCaU9w9OEoLJQw6mqm7YNt2ADP2qAhOYsgUA 8dOQ37ryRbbL1F37M5SedeHM3sirrTtX6O41ASDYldOADUWNeaYc0X+G8drVQ2rg In4L1yh4pOA/sqIqNg9jgfW4kh7jaN1zrI7E7eiAGYBeVFVbMCCmyl4Rifc0vVi/ L/nL/BYLRG1h7xIqQ5lz3DvtYbqpAUlCQWaXApnKEIMuKPvAycQ0Yzckzdccro88 1m3dO/OJAR8EGAEKAAkFAlRtEYQCGwwACgkQ/OW8luisPhS6bwf+KdUHLOnhfYlr c2DYsMdsXyy7AygXgBLY3HS4qdAwcpvovuD24ekw+kWhbod5TcIaOaOPd5m58X7j RRyxY5eGZAi7ZEuj8XuhCFtakJIaWZ/O4E/ay1Fuc40u3v4CYedP8Kbb5OziJXF4 Z1IXczaFs58+TEjRF/653SmLuGBUlaQOgJ7g1z8cOR36LnyX+oaxYBOHeWyLjkho ZTgbNRSdtMRZuquTBHrq5W1zW7teFoDko5/nYR/BzlJLsaOPFgO4L/60/z41kpWT zPj7hEbxeu779CXMyEk6R6WzFL3r6As4U4ehfDhXEGo9l4+lXtanz/243bbdAXMN kDrb0qGve50DvgRUbRHUAQgA1Woqjppe3JpH+wR3QTGvQ6KBpIA4T+yP8s37Fa7B DjkI/ahAOVad4Fvc2+SqbHLHTcg08d7NrxK9iSXsIHFmzaqH0qvvJ4/RBCQOsITg FPWM/4vnENq94aj3WF11bdDupUegBJQsnMpA5C8ZO26U+OXXpK3s4HOPLcTR3Cs4 lqFXkh60b0Gu9Ml0z3q9MMrRVkCbpSo1SYlVwOGVkWlQvsH6a0unxZPnWBqGdlNf 6byX06GFTrphFYSZ2ArKf51Qnc5k//nQjm8mnAmQ17Ye8euS+cht0m65iW+WP9fY sb2gBYUm+Q5pjO/uBSA/6SBYpwjxdcJwpDJIcWeW84Kf9QARAQAB/gMDAtdDRfms XnAL4xbpconkskRGMpfNwdbf+rSUW800D2xF1e48FOE4V+bZJr6ONEdhu94Gl7oV 2Cq6lvP3/H/W+wwbWP0SYGyKVFSmM/D5UTFNz6BSml6pCOaPLeaB3FkX2RFtBppO vIDCQo/MoEjWor29QVF13M+Cp8Xv8B3WPIhHQ7O32j0w7micgEDiSnL5Cgeb1Ekz N4c4LcTIL0jl0G/J2YLlRNR7g8PPypdDDceRa/nfDiP2X4MSrH2ed9V+NY3emToD 4yuHu4h4uuStdWnE1c7KyUjZK4vhPHHkX4Atmg3M2xEqG9UdA0D7pJofce7Op+kX i5hqNtlsgE1wdgAX4BhJlZTZwTK0nbcu8flssl4Qu4Tl/JEi/dTvEW5m2gz0Vpjz J+bSdAe3UyaeIdIAieO7TOcO+2IGy7p0f3eLKCLQd4w0ob8o0RCMat9G0kSJaC/N xhr/TEPPJMRRuqT8UGHpcuuNQf82VPFol/C7Z3jBG21FdLSdALXHPt+0AwEbiD2R pEH39GQjgbKBWgrlW/QSm3aRfLseaYd2tbEsW1MP84I1hnncNRWWV8c5PnXpZhrS KQHptKuERZu9s6nC8AOGKYugywuBKHmg5c+svDmdD9kL5vLV1snljJjYYXpiMoJA SkVtj0Kq9k9i7L5IfoieU0pwjd9ngkJ7x6FKxmRTAg27jm5exsHnqxCEx7tw1akw Sxe0kfz5eWgwQgV1r9qo9xY7eb2hv4mAQWbySu/7+NBeRz6SZHS0gpkA+2qAkPie MrzQ1wUyMfNc8Ij93x+hLKpgFZSKJB9X53Ot8IS2OJMdgZXHrr7JzHwDiyGxkBLi foXP/SjwFjbaARKGQeJhlocGYv7BqAIMnYEzQfTQHCcUetVOleQQSgK8mvZ76o/c x4JTP0VPAxiJAR8EGAEKAAkFAlRtEdQCGwwACgkQ/OW8luisPhSJGwf8DlwLWBy7 oT4kfsvBzd0ShY/lN/zqKmZ80ZrmIARe2zzvDt0HLJLLamBZUmK+EajeEqYWf6KW gqVBUPLljXnFHW+HEtgsSdx56zTiILXCHvE1yEHJBHii9QbtinxquJI3JvveEBIN 43FxD6c2q2z0DwVbr9ctiz325jElXN8T32ivdKLSOSvZAIhzLdbND+gQskhzox9A lXCI75Qpa/BydyMVL+/Z4IMwubdGBeaxybYh55iFgoPzcgAMLikFcDSk8LZ0er66 JShEyoDIRsqgC1lbjocuGN90Y0o4IBz/atmwFumlhx8SS0BeRgQ9KUKwCSaCLS3v 8LiVj5LgWyQkXw== =VQP1 -----END PGP PRIVATE KEY BLOCK----- """ passphrase = "asdf" good_subkey = "94A0 6B09 0623 2D4F 4D4C 45F1 729A CF60 BEC2 95CC".split(/\s+/).join('').toLowerCase() #=================================================================================
161149
{KeyManager,box,unbox} = require '../..' #================================================================= pubkm = null seckm = null ctext = null ptext = null exports.import_public = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pub }, T.esc(defer(tmp, warnings), cb, "import_public") T.assert (warnings.warnings().length is 0), "didn't get any warnings" pubkm = tmp cb() #================================================================================= exports.import_private = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : priv }, T.esc(defer(tmp, warnings), cb, "import_private") T.assert (warnings.warnings().length is 0), "didn't get any warnings" seckm = tmp T.waypoint "about to s2k with very big parameters..." T.assert seckm.has_pgp_private(), "has a private key" await seckm.unlock_pgp { passphrase }, T.esc(defer()) cb() #================================================================================= exports.encrypt = (T, cb) -> ptext = """" That is no country for old men. The young In one another’s arms, birds in the trees —Those dying generations—at their song, The salmon-falls, the mackerel-crowded seas, Fish, flesh, or fowl, commend all summer long Whatever is begotten, born, and dies. Caught in that sensual music all neglect Monuments of unageing intellect. """ await box { msg : ptext, encrypt_for : pubkm }, T.esc(defer(aout, raw), cb, "encrypt") ctext = aout cb() #================================================================================= exports.decrypt = (T, cb) -> await unbox { keyfetch : seckm, armored : ctext }, T.esc(defer(literals, warnings, esk), cb, "decrypt") T.equal ptext, literals[0].toString(), "ciphertext came back OK" T.equal warnings.warnings().length, 0, "no warnings" T.equal esk.get_fingerprint().toString("hex"), good_subkey, "encrypted with the right subkey" cb() #================================================================================= pub = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2 Comment: GPGTools - https://gpgtools.org <KEY> -----END PGP PUBLIC KEY BLOCK----- """ priv = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2 Comment: GPGTools - https://gpgtools.org <KEY>CSaCLS3v 8LiVj5LgWyQkXw== =VQP1 -----END PGP PRIVATE KEY BLOCK----- """ passphrase = "<PASSWORD>" good_subkey = "<KEY>".split(/\s+/).join('').toLowerCase() #=================================================================================
true
{KeyManager,box,unbox} = require '../..' #================================================================= pubkm = null seckm = null ctext = null ptext = null exports.import_public = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : pub }, T.esc(defer(tmp, warnings), cb, "import_public") T.assert (warnings.warnings().length is 0), "didn't get any warnings" pubkm = tmp cb() #================================================================================= exports.import_private = (T,cb) -> await KeyManager.import_from_armored_pgp { raw : priv }, T.esc(defer(tmp, warnings), cb, "import_private") T.assert (warnings.warnings().length is 0), "didn't get any warnings" seckm = tmp T.waypoint "about to s2k with very big parameters..." T.assert seckm.has_pgp_private(), "has a private key" await seckm.unlock_pgp { passphrase }, T.esc(defer()) cb() #================================================================================= exports.encrypt = (T, cb) -> ptext = """" That is no country for old men. The young In one another’s arms, birds in the trees —Those dying generations—at their song, The salmon-falls, the mackerel-crowded seas, Fish, flesh, or fowl, commend all summer long Whatever is begotten, born, and dies. Caught in that sensual music all neglect Monuments of unageing intellect. """ await box { msg : ptext, encrypt_for : pubkm }, T.esc(defer(aout, raw), cb, "encrypt") ctext = aout cb() #================================================================================= exports.decrypt = (T, cb) -> await unbox { keyfetch : seckm, armored : ctext }, T.esc(defer(literals, warnings, esk), cb, "decrypt") T.equal ptext, literals[0].toString(), "ciphertext came back OK" T.equal warnings.warnings().length, 0, "no warnings" T.equal esk.get_fingerprint().toString("hex"), good_subkey, "encrypted with the right subkey" cb() #================================================================================= pub = """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG/MacGPG2 v2 Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK----- """ priv = """ -----BEGIN PGP PRIVATE KEY BLOCK----- Version: GnuPG/MacGPG2 v2 Comment: GPGTools - https://gpgtools.org PI:KEY:<KEY>END_PICSaCLS3v 8LiVj5LgWyQkXw== =VQP1 -----END PGP PRIVATE KEY BLOCK----- """ passphrase = "PI:PASSWORD:<PASSWORD>END_PI" good_subkey = "PI:KEY:<KEY>END_PI".split(/\s+/).join('').toLowerCase() #=================================================================================
[ { "context": "ateContextObject()], \"it is STUNNED\",{\n\t\t\t\tname: \"Winterblade\"\n\t\t\t\tdescription: \"Enemy minions damaged by your ", "end": 13425, "score": 0.8677189350128174, "start": 13414, "tag": "NAME", "value": "Winterblade" }, { "context": "AbsorbDamage.createContextObject(1, {\n\t\t\t\t\tname: \"Frost Armor\"\n\t\t\t\t\tdescription: \"The first time your", "end": 64830, "score": 0.5913923978805542, "start": 64829, "tag": "NAME", "value": "F" }, { "context": "mageAttacker.createContextObject(1, {\n\t\t\t\t\tname: \"Frost Armor\"\n\t\t\t\t\tdescription: \"Whenever your Gener", "end": 65019, "score": 0.6428711414337158, "start": 65018, "tag": "NAME", "value": "F" }, { "context": "= Cards.BossSpell.LaceratingFrost\n\t\t\tcard.name = \"Lacerating Frost\"\n\t\t\tcard.setDescription(\"Deal 2 damage to the ene", "end": 139223, "score": 0.8912884593009949, "start": 139207, "tag": "NAME", "value": "Lacerating Frost" }, { "context": "ds.BossSpell.LivingFlame\n\t\t\tcard.name = \"Living Flame\"\n\t\t\tcard.setDescription(\"Deal 2 damage to an enem", "end": 140719, "score": 0.5989724397659302, "start": 140716, "tag": "NAME", "value": "ame" }, { "context": " Cards.BossSpell.AncientKnowledge\n\t\t\tcard.name = \"Ancient Knowledge\"\n\t\t\tcard.setDescription(\"Draw 2 ca", "end": 143832, "score": 0.8063216805458069, "start": 143830, "tag": "NAME", "value": "An" } ]
app/sdk/cards/factory/misc/bosses.coffee
willroberts/duelyst
5
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' Artifact = require 'app/sdk/artifacts/artifact' Spell = require 'app/sdk/spells/spell' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellSpawnEntity = require 'app/sdk/spells/spellSpawnEntity' SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers' SpellEquipBossArtifacts = require 'app/sdk/spells/spellEquipBossArtifacts' SpellLaceratingFrost = require 'app/sdk/spells/spellLaceratingFrost' SpellEntanglingShadows = require 'app/sdk/spells/spellEntanglingShadows' SpellMoldingEarth = require 'app/sdk/spells/spellMoldingEarth' SpellDamageAndSpawnEntitiesNearbyGeneral = require 'app/sdk/spells/spellDamageAndSpawnEntitiesNearbyGeneral' SpellSilenceAndSpawnEntityNearby = require 'app/sdk/spells/spellSilenceAndSpawnEntityNearby' SpellRestoringLight = require 'app/sdk/spells/spellRestoringLight' Modifier = require 'app/sdk/modifiers/modifier' PlayerModifierManaModifier = require 'app/sdk/playerModifiers/playerModifierManaModifier' ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke' ModifierEndTurnWatchDamageNearbyEnemy = require 'app/sdk/modifiers/modifierEndTurnWatchDamageNearbyEnemy' ModifierFrenzy = require 'app/sdk/modifiers/modifierFrenzy' ModifierFlying = require 'app/sdk/modifiers/modifierFlying' ModifierTranscendance = require 'app/sdk/modifiers/modifierTranscendance' ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierRebirth = require 'app/sdk/modifiers/modifierRebirth' ModifierBlastAttack = require 'app/sdk/modifiers/modifierBlastAttack' ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield' ModifierStartTurnWatchEquipArtifact = require 'app/sdk/modifiers/modifierStartTurnWatchEquipArtifact' ModifierTakeDamageWatchSpawnRandomToken = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnRandomToken' ModifierDealDamageWatchKillTarget = require 'app/sdk/modifiers/modifierDealDamageWatchKillTarget' ModifierStartTurnWatchPlaySpell = require 'app/sdk/modifiers/modifierStartTurnWatchPlaySpell' ModifierDealDamageWatchModifyTarget = require 'app/sdk/modifiers/modifierDealDamageWatchModifyTarget' ModifierStunned = require 'app/sdk/modifiers/modifierStunned' ModifierStunnedVanar = require 'app/sdk/modifiers/modifierStunnedVanar' ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers' ModifierBattlePet = require 'app/sdk/modifiers/modifierBattlePet' ModifierImmuneToDamage = require 'app/sdk/modifiers/modifierImmuneToDamage' ModifierStartTurnWatchDispelAllEnemyMinionsDrawCard = require 'app/sdk/modifiers/modifierStartTurnWatchDispelAllEnemyMinionsDrawCard' ModifierImmuneToSpellsByEnemy = require 'app/sdk/modifiers/modifierImmuneToSpellsByEnemy' ModifierAbsorbDamageGolems = require 'app/sdk/modifiers/modifierAbsorbDamageGolems' ModifierExpireApplyModifiers = require 'app/sdk/modifiers/modifierExpireApplyModifiers' ModifierSecondWind = require 'app/sdk/modifiers/modifierSecondWind' ModifierKillWatchRespawnEntity = require 'app/sdk/modifiers/modifierKillWatchRespawnEntity' ModifierOpponentSummonWatchSpawn1HealthClone = require 'app/sdk/modifiers/modifierOpponentSummonWatchSpawn1HealthClone' ModifierDealOrTakeDamageWatchRandomTeleportOther = require 'app/sdk/modifiers/modifierDealOrTakeDamageWatchRandomTeleportOther' ModifierMyAttackOrAttackedWatchSpawnMinionNearby = require 'app/sdk/modifiers/modifierMyAttackOrAttackedWatchSpawnMinionNearby' ModifierEndTurnWatchTeleportCorner = require 'app/sdk/modifiers/modifierEndTurnWatchTeleportCorner' ModifierBackstab = require 'app/sdk/modifiers/modifierBackstab' ModifierDieSpawnNewGeneral = require 'app/sdk/modifiers/modifierDieSpawnNewGeneral' ModifierKillWatchRefreshExhaustion = require 'app/sdk/modifiers/modifierKillWatchRefreshExhaustion' ModifierEndTurnWatchDealDamageToSelfAndNearbyEnemies = require 'app/sdk/modifiers/modifierEndTurnWatchDealDamageToSelfAndNearbyEnemies' ModifierDispelAreaAttack = require 'app/sdk/modifiers/modifierDispelAreaAttack' ModifierSelfDamageAreaAttack = require 'app/sdk/modifiers/modifierSelfDamageAreaAttack' ModifierMyMinionOrGeneralDamagedWatchBuffSelf = require 'app/sdk/modifiers/modifierMyMinionOrGeneralDamagedWatchBuffSelf' ModifierSummonWatchNearbyAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchNearbyAnyPlayerApplyModifiers' ModifierOpponentSummonWatchOpponentDrawCard = require 'app/sdk/modifiers/modifierOpponentSummonWatchOpponentDrawCard' ModifierOpponentDrawCardWatchOverdrawSummonEntity = require 'app/sdk/modifiers/modifierOpponentDrawCardWatchOverdrawSummonEntity' ModifierEndTurnWatchDamagePlayerBasedOnRemainingMana = require 'app/sdk/modifiers/modifierEndTurnWatchDamagePlayerBasedOnRemainingMana' ModifierHPThresholdGainModifiers = require 'app/sdk/modifiers/modifierHPThresholdGainModifiers' ModifierHealSelfWhenDealingDamage = require 'app/sdk/modifiers/modifierHealSelfWhenDealingDamage' ModifierExtraDamageOnCounterattack = require 'app/sdk/modifiers/modifierExtraDamageOnCounterattack' ModifierOnOpponentDeathWatchSpawnEntityOnSpace = require 'app/sdk/modifiers/modifierOnOpponentDeathWatchSpawnEntityOnSpace' ModifierDyingWishSpawnEgg = require 'app/sdk/modifiers/modifierDyingWishSpawnEgg' ModifierSummonWatchFromActionBarApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchFromActionBarApplyModifiers' ModifierGrowPermanent = require 'app/sdk/modifiers/modifierGrowPermanent' ModifierTakeDamageWatchSpawnWraithlings = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnWraithlings' ModifierTakeDamageWatchDamageAttacker = require 'app/sdk/modifiers/modifierTakeDamageWatchDamageAttacker' ModifierAbsorbDamage = require 'app/sdk/modifiers/modifierAbsorbDamage' ModifierDyingWishDamageNearbyEnemies = require 'app/sdk/modifiers/modifierDyingWishDamageNearbyEnemies' ModifierStartTurnWatchTeleportRandomSpace = require 'app/sdk/modifiers/modifierStartTurnWatchTeleportRandomSpace' ModifierSummonWatchFromActionBarAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchFromActionBarAnyPlayerApplyModifiers' ModifierStartTurnWatchDamageGeneralEqualToMinionsOwned = require 'app/sdk/modifiers/modifierStartTurnWatchDamageGeneralEqualToMinionsOwned' ModifierDeathWatchDamageEnemyGeneralHealMyGeneral = require 'app/sdk/modifiers/modifierDeathWatchDamageEnemyGeneralHealMyGeneral' ModifierRangedProvoke = require 'app/sdk/modifiers/modifierRangedProvoke' ModifierHPChangeSummonEntity = require 'app/sdk/modifiers/modifierHPChangeSummonEntity' ModifierStartTurnWatchDamageAndBuffSelf = require 'app/sdk/modifiers/modifierStartTurnWatchDamageAndBuffSelf' ModifierEnemyTeamMoveWatchSummonEntityBehind = require 'app/sdk/modifiers/modifierEnemyTeamMoveWatchSummonEntityBehind' ModifierMyTeamMoveWatchBuffTarget = require 'app/sdk/modifiers/modifierMyTeamMoveWatchAnyReasonBuffTarget' ModifierDyingWishLoseGame = require 'app/sdk/modifiers/modifierDyingWishLoseGame' ModifierAttacksDamageAllEnemyMinions = require 'app/sdk/modifiers/modifierAttacksDamageAllEnemyMinions' ModifierSummonWatchAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchAnyPlayerApplyModifiers' ModifierDoubleDamageToGenerals = require 'app/sdk/modifiers/modifierDoubleDamageToGenerals' ModifierATKThresholdDie = require 'app/sdk/modifiers/modifierATKThresholdDie' ModifierDeathWatchDamageRandomMinionHealMyGeneral = require 'app/sdk/modifiers/modifierDeathWatchDamageRandomMinionHealMyGeneral' ModifierStartTurnWatchSpawnTile = require 'app/sdk/modifiers/modifierStartTurnWatchSpawnTile' ModifierStartTurnWatchSpawnEntity = require 'app/sdk/modifiers/modifierStartTurnWatchSpawnEntity' ModifierEndTurnWatchGainTempBuff = require 'app/sdk/modifiers/modifierEndTurnWatchGainTempBuff' ModifierSentinel = require 'app/sdk/modifiers/modifierSentinel' ModifierSentinelSetup = require 'app/sdk/modifiers/modifierSentinelSetup' ModifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard' ModifierSentinelOpponentSummonBuffItDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentSummonBuffItDrawCard' ModifierSentinelOpponentSpellCastRefundManaDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentSpellCastRefundManaDrawCard' ModifierTakeDamageWatchSpawnRandomHaunt = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnRandomHaunt' ModifierDyingWishDrawCard = require "app/sdk/modifiers/modifierDyingWishDrawCard" ModifierCannotAttackGeneral = require 'app/sdk/modifiers/modifierCannotAttackGeneral' ModifierCannotCastBBS = require 'app/sdk/modifiers/modifierCannotCastBBS' ModifierStartTurnWatchPutCardInOpponentsHand = require 'app/sdk/modifiers/modifierStartTurnWatchPutCardInOpponentsHand' ModifierEndTurnWatchHealSelf = require 'app/sdk/modifiers/modifierEndTurnWatchHealSelf' ModifierBackupGeneral = require 'app/sdk/modifiers/modifierBackupGeneral' ModifierStartTurnWatchRespawnClones = require 'app/sdk/modifiers/modifierStartTurnWatchRespawnClones' ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers' ModifierSwitchAllegiancesGainAttack = require 'app/sdk/modifiers/modifierSwitchAllegiancesGainAttack' ModifierOpponentSummonWatchRandomTransform = require 'app/sdk/modifiers/modifierOpponentSummonWatchRandomTransform' ModifierOnSpawnKillMyGeneral = require 'app/sdk/modifiers/modifierOnSpawnKillMyGeneral' ModifierDeathWatchGainAttackEqualToEnemyAttack = require 'app/sdk/modifiers/modifierDeathWatchGainAttackEqualToEnemyAttack' ModifierDyingWishBuffEnemyGeneral = require 'app/sdk/modifiers/modifierDyingWishBuffEnemyGeneral' ModifierStartTurnWatchDamageRandom = require 'app/sdk/modifiers/modifierStartTurnWatchDamageRandom' ModifierOpponentSummonWatchSwapGeneral = require 'app/sdk/modifiers/modifierOpponentSummonWatchSwapGeneral' ModifierDyingWishPutCardInOpponentHand = require 'app/sdk/modifiers/modifierDyingWishPutCardInOpponentHand' ModifierEnemySpellWatchGainRandomKeyword = require 'app/sdk/modifiers/modifierEnemySpellWatchGainRandomKeyword' ModifierAnySummonWatchGainGeneralKeywords = require 'app/sdk/modifiers/modifierAnySummonWatchGainGeneralKeywords' PlayerModifierSummonWatchApplyModifiers = require 'app/sdk/playerModifiers/playerModifierSummonWatchApplyModifiers' PlayerModifierOpponentSummonWatchSwapGeneral = require 'app/sdk/playerModifiers/playerModifierOpponentSummonWatchSwapGeneral' class CardFactory_Bosses ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Boss.Boss1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_1_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_1_bio")) card.setDescription(i18next.t("boss_battles.boss_1_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_boreal_juggernaut) card.setPortraitResource(RSX.speech_portrait_boreal_juggernaut) card.setPortraitHexResource(RSX.boss_boreal_juggernaut_hex_portrait) card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setBoundingBoxWidth(120) card.setBoundingBoxHeight(95) card.setFXResource(["FX.Cards.Faction5.Dreadnaught"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_rook_attack_impact.audio receiveDamage : RSX.sfx_neutral_makantorwarbeast_hit.audio attackDamage : RSX.sfx_neutral_silitharveteran_attack_impact.audio death : RSX.sfx_neutral_makantorwarbeast_death.audio ) card.setBaseAnimResource( breathing : RSX.bossBorealJuggernautBreathing.name idle : RSX.bossBorealJuggernautIdle.name walk : RSX.bossBorealJuggernautRun.name attack : RSX.bossBorealJuggernautAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossBorealJuggernautHit.name death : RSX.bossBorealJuggernautDeath.name ) card.atk = 5 card.speed = 1 card.maxHP = 40 frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.addKeywordClassToInclude(ModifierStunned) stunContextObject = ModifierDealDamageWatchModifyTarget.createContextObject([ModifierStunnedVanar.createContextObject()], "it is STUNNED",{ name: "Winterblade" description: "Enemy minions damaged by your General are Stunned" }) stunContextObject.isRemovable = false #startTurnCastFrostburnObject = ModifierStartTurnWatchPlaySpell.createContextObject({id: Cards.Spell.Frostburn, manaCost: 0}, "Frostburn") #startTurnCastFrostburnObject.isRemovable = false card.setInherentModifiersContextObjects([frenzyContextObject, stunContextObject]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_2_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_2_bio")) card.setDescription(i18next.t("boss_battles.boss_2_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_umbra) card.setPortraitResource(RSX.speech_portrait_umbra) card.setPortraitHexResource(RSX.boss_umbra_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setBoundingBoxWidth(75) card.setBoundingBoxHeight(75) card.setFXResource(["FX.Cards.Neutral.MirkbloodDevourer"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_mirkblooddevourer_attack_swing.audio receiveDamage : RSX.sfx_neutral_mirkblooddevourer_hit.audio attackDamage : RSX.sfx_neutral_mirkblooddevourer_attack_impact.audio death : RSX.sfx_neutral_mirkblooddevourer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossUmbraBreathing.name idle : RSX.bossUmbraIdle.name walk : RSX.bossUmbraRun.name attack : RSX.bossUmbraAttack.name attackReleaseDelay: 0.0 attackDelay: 1.25 damage : RSX.bossUmbraHit.name death : RSX.bossUmbraDeath.name ) card.atk = 2 card.maxHP = 30 modifierSpawnClone = ModifierOpponentSummonWatchSpawn1HealthClone.createContextObject("a 1 health clone") modifierSpawnClone.isRemovable = false card.setInherentModifiersContextObjects([modifierSpawnClone]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_3_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_3_bio")) card.setDescription(i18next.t("boss_battles.boss_3_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 30 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false excludedArtifacts = [ Cards.Artifact.Spinecleaver, Cards.Artifact.IndomitableWill ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, excludedArtifacts) equipArtifactObject.isRemovable = false card.setInherentModifiersContextObjects([ forceFieldObject, equipArtifactObject ]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.QABoss3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = "QA-IBERO" card.manaCost = 0 card.setBossBattleDescription("A Dev Boss for quickly testing flow.") card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 1 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false excludedArtifacts = [ Cards.Artifact.Spinecleaver, Cards.Artifact.IndomitableWill ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, excludedArtifacts) equipArtifactObject.isRemovable = false card.setInherentModifiersContextObjects([ equipArtifactObject ]) if (identifier == Cards.Boss.Boss4) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_4_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_4_bio")) card.setDescription(i18next.t("boss_battles.boss_4_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_chaos_knight) card.setPortraitResource(RSX.speech_portrait_chaos_knight) card.setPortraitHexResource(RSX.boss_chaos_knight_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Ironclad"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossChaosKnightBreathing.name idle : RSX.bossChaosKnightIdle.name walk : RSX.bossChaosKnightRun.name attack : RSX.bossChaosKnightAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.bossChaosKnightHit.name death : RSX.bossChaosKnightDeath.name ) card.atk = 3 card.maxHP = 35 frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false dealOrTakeDamageRandomTeleportObject = ModifierDealOrTakeDamageWatchRandomTeleportOther.createContextObject() dealOrTakeDamageRandomTeleportObject.isRemovable = false card.setInherentModifiersContextObjects([frenzyContextObject, dealOrTakeDamageRandomTeleportObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss5) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_5_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_5_bio")) card.setDescription(i18next.t("boss_battles.boss_5_desc")) card.setBossBattleBattleMapIndex(4) card.setSpeechResource(RSX.speech_portrait_shinkage_zendo) card.setPortraitResource(RSX.speech_portrait_shinkage_zendo) card.setPortraitHexResource(RSX.boss_shinkage_zendo_hex_portrait) card.setConceptResource(RSX.boss_shinkage_zendo_versus_portrait) card.setFXResource(["FX.Cards.Faction2.GrandmasterZendo"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_run_magical_3.audio attack : RSX.sfx_spell_darkseed.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_daggerkiri_attack_swing.audio death : RSX.sfx_neutral_prophetofthewhite_death.audio ) card.setBaseAnimResource( breathing : RSX.bossShinkageZendoBreathing.name idle : RSX.bossShinkageZendoIdle.name walk : RSX.bossShinkageZendoRun.name attack : RSX.bossShinkageZendoAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.bossShinkageZendoHit.name death : RSX.bossShinkageZendoDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 6 card.maxHP = 20 card.speed = 0 immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], i18next.t("modifiers.boss_5_applied_desc")) immunityContextObject.appliedName = i18next.t("modifiers.boss_5_applied_name") applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, null, null, "Cannot be damaged while friendly minions live") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = true zendoBattlePetContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([ModifierBattlePet.createContextObject()], "The enemy General moves and attacks as if they are a Battle Pet") #zendoBattlePetContextObject = Modifier.createContextObjectWithOnBoardAuraForAllEnemies([ModifierBattlePet.createContextObject()], "All enemies move and attack as if they are Battle Pets") zendoBattlePetContextObject.isRemovable = false card.setInherentModifiersContextObjects([applyGeneralImmunityContextObject, zendoBattlePetContextObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss6) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_6_bio")) card.setDescription(i18next.t("boss_battles.boss_6_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_decepticle) card.setPortraitResource(RSX.speech_portrait_decepticle) card.setPortraitHexResource(RSX.boss_decepticle_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Mechaz0rHelm"]) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_wingsmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_wingsmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_wingsmechaz0r_impact.audio death : RSX.sfx_neutral_wingsmechaz0r_hit.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleBreathing.name idle : RSX.bossDecepticleIdle.name walk : RSX.bossDecepticleRun.name attack : RSX.bossDecepticleAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossDecepticleHit.name death : RSX.bossDecepticleDeath.name ) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(50) card.atk = 2 card.maxHP = 1 immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], "Decepticle cannot be damaged while this minion lives.") immunityContextObject.appliedName = i18next.t("modifiers.boss_6_applied_name") mechs = [ Cards.Boss.Boss6Wings, Cards.Boss.Boss6Chassis, Cards.Boss.Boss6Sword, Cards.Boss.Boss6Helm ] applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, mechs, null, "Cannot be damaged while other D3cepticle parts live") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = false provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false spawnPrimeBoss = ModifierDieSpawnNewGeneral.createContextObject({id: Cards.Boss.Boss6Prime}) spawnPrimeBoss.isRemovable = false spawnPrimeBoss.isHiddenToUI = true card.setInherentModifiersContextObjects([applyGeneralImmunityContextObject, provokeObject, spawnPrimeBoss]) #card.setInherentModifiersContextObjects([provokeObject, spawnPrimeBoss]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss6Wings) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part1_name") card.setDescription(i18next.t("boss_battles.boss_6_part1_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rWings"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_wingsmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_wingsmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_wingsmechaz0r_impact.audio death : RSX.sfx_neutral_wingsmechaz0r_hit.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleWingsBreathing.name idle : RSX.bossDecepticleWingsIdle.name walk : RSX.bossDecepticleWingsRun.name attack : RSX.bossDecepticleWingsAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossDecepticleWingsHit.name death : RSX.bossDecepticleWingsDeath.name ) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(50) card.atk = 2 card.maxHP = 3 flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false card.setInherentModifiersContextObjects([flyingObject]) if (identifier == Cards.Boss.Boss6Chassis) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part2_name") card.setDescription(i18next.t("boss_battles.boss_6_part2_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rChassis"]) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio death : RSX.sfx_neutral_hailstonehowler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleChassisBreathing.name idle : RSX.bossDecepticleChassisIdle.name walk : RSX.bossDecepticleChassisRun.name attack : RSX.bossDecepticleChassisAttack.name attackReleaseDelay: 0.0 attackDelay: 0.5 damage : RSX.bossDecepticleChassisHit.name death : RSX.bossDecepticleChassisDeath.name ) card.atk = 5 card.maxHP = 4 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false card.setInherentModifiersContextObjects([forceFieldObject]) if (identifier == Cards.Boss.Boss6Sword) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part3_name") card.setDescription(i18next.t("boss_battles.boss_6_part3_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rSword"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_swordmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_swordmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_swordmechaz0r_attack_impact.audio death : RSX.sfx_neutral_swordmechaz0r_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleSwordBreathing.name idle : RSX.bossDecepticleSwordIdle.name walk : RSX.bossDecepticleSwordRun.name attack : RSX.bossDecepticleSwordAttack.name attackReleaseDelay: 0.0 attackDelay: 0.25 damage : RSX.bossDecepticleSwordHit.name death : RSX.bossDecepticleSwordDeath.name ) card.atk = 4 card.maxHP = 2 backstabObject = ModifierBackstab.createContextObject(2) backstabObject.isRemovable = false card.setInherentModifiersContextObjects([backstabObject]) if (identifier == Cards.Boss.Boss6Helm) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part4_name") card.setDescription(i18next.t("boss_battles.boss_6_part4_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rHelm"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleHelmBreathing.name idle : RSX.bossDecepticleHelmIdle.name walk : RSX.bossDecepticleHelmRun.name attack : RSX.bossDecepticleHelmAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossDecepticleHelmHit.name death : RSX.bossDecepticleHelmDeath.name ) card.atk = 3 card.maxHP = 3 celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false card.setInherentModifiersContextObjects([celerityObject]) if (identifier == Cards.Boss.Boss6Prime) card = new Unit(gameSession) card.setIsHiddenInCollection(true) #card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_prime_name") card.setDescription(i18next.t("boss_battles.boss_6_prime_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.AlterRexx"]) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_ladylocke_attack_impact.audio attack : RSX.sfx_neutral_wingsofparadise_attack_swing.audio receiveDamage : RSX.sfx_f1_oserix_hit.audio attackDamage : RSX.sfx_f1_oserix_attack_impact.audio death : RSX.sfx_neutral_sunelemental_attack_swing.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticlePrimeBreathing.name idle : RSX.bossDecepticlePrimeIdle.name walk : RSX.bossDecepticlePrimeRun.name attack : RSX.bossDecepticlePrimeAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossDecepticlePrimeHit.name death : RSX.bossDecepticlePrimeDeath.name ) card.atk = 4 card.maxHP = 16 celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false backstabObject = ModifierBackstab.createContextObject(2) backstabObject.isRemovable = false forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false card.setInherentModifiersContextObjects([celerityObject, backstabObject, forceFieldObject, flyingObject, provokeObject]) if (identifier == Cards.Boss.Boss7) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_7_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_7_bio")) card.setDescription(i18next.t("boss_battles.boss_7_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 20 includedArtifacts = [ {id: Cards.Artifact.SunstoneBracers}, {id: Cards.Artifact.ArclyteRegalia}, {id: Cards.Artifact.StaffOfYKir} ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, includedArtifacts) equipArtifactObject.isRemovable = false equipArtifactFirstTurn = ModifierExpireApplyModifiers.createContextObject([equipArtifactObject], 0, 1, true, true, false, 0, true, "At the start of your second turn and every turn thereafter, equip a random artifact") equipArtifactFirstTurn.isRemovable = false card.setInherentModifiersContextObjects([ equipArtifactFirstTurn ]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.BossArtifact.CycloneGenerator) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.DanceOfSteel card.name = i18next.t("boss_battles.boss_7_artifact_name") card.setDescription(i18next.t("boss_battles.boss_7_artifact_desc")) card.addKeywordClassToInclude(ModifierTranscendance) card.manaCost = 0 card.setBossBattleDescription("__Boss Battle Description") card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierTranscendance.createContextObject({ type: "ModifierTranscendance" name: "Cyclone Generator" }) ]) card.setFXResource(["FX.Cards.Artifact.IndomitableWill"]) card.setBaseAnimResource( idle: RSX.iconSkywindGlaivesIdle.name active: RSX.iconSkywindGlaivesActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Boss.Boss8) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_8_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_8_bio")) card.setDescription(i18next.t("boss_battles.boss_8_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_portal_guardian) card.setPortraitResource(RSX.speech_portrait_portal_guardian) card.setPortraitHexResource(RSX.boss_portal_guardian_hex_portrait) card.setConceptResource(RSX.boss_portal_guardian_versus_portrait) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralMysteryBreathing.name idle : RSX.neutralMysteryIdle.name walk : RSX.neutralMysteryRun.name attack : RSX.neutralMysteryAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralMysteryHit.name death : RSX.neutralMysteryDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 15 respawnKilledEnemy = ModifierKillWatchRespawnEntity.createContextObject() respawnKilledEnemy.isRemovable = false secondWind = ModifierSecondWind.createContextObject(2, 5, false, "Awakened", "Failure prevented. Strength renewed. Systems adapted.") secondWind.isRemovable = false secondWind.isHiddenToUI = true card.setInherentModifiersContextObjects([respawnKilledEnemy, secondWind]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss9) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_9_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_9_bio")) card.setDescription(i18next.t("boss_battles.boss_9_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_wujin) card.setPortraitResource(RSX.speech_portrait_wujin) card.setPortraitHexResource(RSX.boss_wujin_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_f1_oserix_death.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_silitharveteran_hit.audio attackDamage : RSX.sfx_neutral_prophetofthewhite_death.audio death : RSX.sfx_neutral_daggerkiri_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWujinBreathing.name idle : RSX.bossWujinIdle.name walk : RSX.bossWujinRun.name attack : RSX.bossWujinAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWujinHit.name death : RSX.bossWujinDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 3 card.maxHP = 30 spawnCloneObject = ModifierMyAttackOrAttackedWatchSpawnMinionNearby.createContextObject({id: Cards.Boss.Boss9Clone}, "a decoy") spawnCloneObject.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false teleportCornerObject = ModifierEndTurnWatchTeleportCorner.createContextObject() teleportCornerObject.isRemovable = false card.setInherentModifiersContextObjects([flyingObject, spawnCloneObject, teleportCornerObject]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss9Clone) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_9_clone_name") card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_f1_oserix_death.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_silitharveteran_hit.audio attackDamage : RSX.sfx_neutral_prophetofthewhite_death.audio death : RSX.sfx_neutral_daggerkiri_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWujinBreathing.name idle : RSX.bossWujinIdle.name walk : RSX.bossWujinRun.name attack : RSX.bossWujinAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWujinHit.name death : RSX.bossWujinDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 1 card.maxHP = 5 provokeObject = ModifierProvoke.createContextObject() #provokeObject.isRemovable = false card.setInherentModifiersContextObjects([provokeObject]) if (identifier == Cards.Boss.Boss10) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_10_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_10_bio")) card.setDescription(i18next.t("boss_battles.boss_10_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_solfist) card.setPortraitResource(RSX.speech_portrait_solfist) card.setPortraitHexResource(RSX.boss_solfist_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setFXResource(["FX.Cards.Neutral.WarTalon"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSolfistBreathing.name idle : RSX.bossSolfistIdle.name walk : RSX.bossSolfistRun.name attack : RSX.bossSolfistAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossSolfistHit.name death : RSX.bossSolfistDeath.name ) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(95) card.atk = 3 card.maxHP = 35 killWatchRefreshObject = ModifierKillWatchRefreshExhaustion.createContextObject(true, false) killWatchRefreshObject.isRemovable = false #killWatchRefreshObject.description = "Whenever Solfist destroys a minion, reactivate it." modifierDamageSelfAndNearby = ModifierEndTurnWatchDealDamageToSelfAndNearbyEnemies.createContextObject() modifierDamageSelfAndNearby.isRemovable = false #modifierDamageSelfAndNearby.description = "At the end of Solfist's turn, deal 1 damage to self and all nearby enemies." card.setInherentModifiersContextObjects([killWatchRefreshObject, modifierDamageSelfAndNearby]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss11) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.raceId = Races.Golem card.name = i18next.t("boss_battles.boss_11_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_11_bio")) card.setDescription(i18next.t("boss_battles.boss_11_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_nullifier) card.setPortraitResource(RSX.speech_portrait_nullifier) card.setPortraitHexResource(RSX.boss_nullifier_hex_portrait) card.setFXResource(["FX.Cards.Neutral.EMP"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossEMPBreathing.name idle : RSX.bossEMPIdle.name walk : RSX.bossEMPRun.name attack : RSX.bossEMPAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.bossEMPHit.name death : RSX.bossEMPDeath.name ) card.atk = 3 card.maxHP = 60 modifierSelfDamageAreaAttack = ModifierSelfDamageAreaAttack.createContextObject() modifierSelfDamageAreaAttack.isRemovable = false rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, modifierSelfDamageAreaAttack]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss12) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_12_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_12_bio")) card.setDescription(i18next.t("boss_battles.boss_12_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_orias) card.setPortraitResource(RSX.speech_portrait_orias) card.setPortraitHexResource(RSX.boss_orias_hex_portrait) card.setFXResource(["FX.Cards.Neutral.ArchonSpellbinder"]) card.setBoundingBoxWidth(55) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_archonspellbinder_attack_swing.audio receiveDamage : RSX.sfx_neutral_archonspellbinder_hit.audio attackDamage : RSX.sfx_neutral_archonspellbinder_attack_impact.audio death : RSX.sfx_neutral_archonspellbinder_death.audio ) card.setBaseAnimResource( breathing : RSX.bossOriasBreathing.name idle : RSX.bossOriasIdle.name walk : RSX.bossOriasRun.name attack : RSX.bossOriasAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossOriasHit.name death : RSX.bossOriasDeath.name ) card.atk = 0 card.maxHP = 35 modifierDamageWatchBuffSelf = ModifierMyMinionOrGeneralDamagedWatchBuffSelf.createContextObject(1, 0) modifierDamageWatchBuffSelf.isRemovable = false card.setInherentModifiersContextObjects([modifierDamageWatchBuffSelf]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss12Idol) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_12_idol_name") card.setDescription(i18next.t("boss_battles.boss_12_idol_desc")) card.manaCost = 0 card.raceId = Races.Structure card.setFXResource(["FX.Cards.Neutral.Bastion"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(125) card.setBaseSoundResource( apply : RSX.sfx_spell_divinebond.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_golembloodshard_death.audio ) card.setBaseAnimResource( breathing : RSX.bossOriasIdolBreathing.name idle : RSX.bossOriasIdolIdle.name walk : RSX.bossOriasIdolIdle.name attack : RSX.bossOriasIdolAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossOriasIdolHit.name death : RSX.bossOriasIdolDeath.name ) card.atk = 0 card.maxHP = 6 card.speed = 0 rushContextObject = ModifierFirstBlood.createContextObject() modifierSummonNearbyRush = ModifierSummonWatchNearbyAnyPlayerApplyModifiers.createContextObject([rushContextObject], "gains Rush") card.setInherentModifiersContextObjects([modifierSummonNearbyRush]) if (identifier == Cards.Boss.Boss13) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_13_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_13_bio")) card.setDescription(i18next.t("boss_battles.boss_13_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_malyk) card.setPortraitResource(RSX.speech_portrait_malyk) card.setPortraitHexResource(RSX.boss_malyk_hex_portrait) card.setFXResource(["FX.Cards.Neutral.TheHighHand"]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(105) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_grimrock_attack_swing.audio receiveDamage : RSX.sfx_neutral_grimrock_hit.audio attackDamage : RSX.sfx_neutral_grimrock_attack_impact.audio death : RSX.sfx_neutral_grimrock_death.audio ) card.setBaseAnimResource( breathing : RSX.bossMalykBreathing.name idle : RSX.bossMalykIdle.name walk : RSX.bossMalykRun.name attack : RSX.bossMalykAttack.name attackReleaseDelay: 0.0 attackDelay: 0.95 damage : RSX.bossMalykHit.name death : RSX.bossMalykDeath.name ) card.atk = 2 card.maxHP = 30 rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false opponentDrawCardOnSummon = ModifierOpponentSummonWatchOpponentDrawCard.createContextObject() opponentDrawCardOnSummon.isRemovable = false summonEntityOnOverdraw = ModifierOpponentDrawCardWatchOverdrawSummonEntity.createContextObject({id: Cards.Faction4.Ooz}, "a 3/3 Ooz") summonEntityOnOverdraw.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, opponentDrawCardOnSummon, summonEntityOnOverdraw]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss14) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_14_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_14_bio")) card.setDescription(i18next.t("boss_battles.boss_14_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_archonis) card.setPortraitResource(RSX.speech_portrait_archonis) card.setPortraitHexResource(RSX.boss_archonis_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction4.BlackSolus"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_blacksolus_attack_swing.audio receiveDamage : RSX.sfx_f4_blacksolus_hit.audio attackDamage : RSX.sfx_f4_blacksolus_attack_impact.audio death : RSX.sfx_f4_blacksolus_death.audio ) card.setBaseAnimResource( breathing : RSX.bossManaManBreathing.name idle : RSX.bossManaManIdle.name walk : RSX.bossManaManRun.name attack : RSX.bossManaManAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossManaManDamage.name death : RSX.bossManaManDeath.name ) card.atk = 6 card.maxHP = 60 damageBasedOnRemainingMana = ModifierEndTurnWatchDamagePlayerBasedOnRemainingMana.createContextObject() damageBasedOnRemainingMana.isRemovable = false card.setInherentModifiersContextObjects([damageBasedOnRemainingMana]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss15) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_15_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_15_bio")) card.setDescription(i18next.t("boss_battles.boss_15_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_paragon) card.setPortraitResource(RSX.speech_portrait_paragon) card.setPortraitHexResource(RSX.boss_paragon_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio death : RSX.sfx_neutral_hailstonehowler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossParagonBreathing.name idle : RSX.bossParagonIdle.name walk : RSX.bossParagonRun.name attack : RSX.bossParagonAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossParagonHit.name death : RSX.bossParagonDeath.name ) card.atk = 3 card.maxHP = 30 card.setDamage(10) gainModifiersOnHPChange = ModifierHPThresholdGainModifiers.createContextObject() gainModifiersOnHPChange.isRemovable = false card.setInherentModifiersContextObjects([gainModifiersOnHPChange]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss16) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_16_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_16_desc")) card.setBossBattleDescription(i18next.t("boss_battles.boss_16_bio")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_vampire) card.setPortraitResource(RSX.speech_portrait_vampire) card.setPortraitHexResource(RSX.boss_vampire_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.Chakkram"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_prophetofthewhite_hit.audio walk : RSX.sfx_neutral_firestarter_impact.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firestarter_hit.audio attackDamage : RSX.sfx_neutral_firestarter_impact.audio death : RSX.sfx_neutral_alcuinloremaster_death.audio ) card.setBaseAnimResource( breathing : RSX.bossVampireBreathing.name idle : RSX.bossVampireIdle.name walk : RSX.bossVampireRun.name attack : RSX.bossVampireAttack.name attackReleaseDelay: 0.0 attackDelay: 1.5 damage : RSX.bossVampireHit.name death : RSX.bossVampireDeath.name ) card.atk = 2 card.maxHP = 30 lifestealModifier = ModifierHealSelfWhenDealingDamage.createContextObject() lifestealModifier.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false extraDamageCounterAttack = ModifierExtraDamageOnCounterattack.createContextObject(2) extraDamageCounterAttack.isRemovable = false card.setInherentModifiersContextObjects([lifestealModifier, extraDamageCounterAttack, flyingObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss17) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_17_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_17_bio")) card.setDescription(i18next.t("boss_battles.boss_17_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_kron) card.setPortraitResource(RSX.speech_portrait_kron) card.setPortraitHexResource(RSX.boss_kron_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.WhiteWidow"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_windstopper_attack_impact.audio attack : RSX.sfx_neutral_crossbones_attack_swing.audio receiveDamage : RSX.sfx_neutral_mirkblooddevourer_hit.audio attackDamage : RSX.sfx_neutral_mirkblooddevourer_attack_impact.audio death : RSX.sfx_neutral_mirkblooddevourer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossKronBreathing.name idle : RSX.bossKronIdle.name walk : RSX.bossKronRun.name attack : RSX.bossKronAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossKronHit.name death : RSX.bossKronDeath.name ) card.atk = 2 card.maxHP = 30 spawnPrisoners = ModifierOnOpponentDeathWatchSpawnEntityOnSpace.createContextObject() spawnPrisoners.isRemovable = false contextObject = PlayerModifierManaModifier.createCostChangeContextObject(-2, CardType.Spell) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true contextObject.isRemovable = false card.setInherentModifiersContextObjects([spawnPrisoners, contextObject]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss18) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_18_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_18_bio")) card.setDescription(i18next.t("boss_battles.boss_18_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_serpenti) card.setPortraitResource(RSX.speech_portrait_serpenti) card.setPortraitHexResource(RSX.boss_serpenti_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Serpenti"]) card.setBoundingBoxWidth(105) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_serpenti_attack_swing.audio receiveDamage : RSX.sfx_neutral_serpenti_hit.audio attackDamage : RSX.sfx_neutral_serpenti_attack_impact.audio death : RSX.sfx_neutral_serpenti_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSerpentiBreathing.name idle : RSX.bossSerpentiIdle.name walk : RSX.bossSerpentiRun.name attack : RSX.bossSerpentiAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossSerpentiHit.name death : RSX.bossSerpentiDeath.name ) card.atk = 4 card.maxHP = 40 spawnSerpentiEgg = ModifierDyingWishSpawnEgg.createContextObject({id: Cards.Neutral.Serpenti}, "7/4 Serpenti") spawnSerpentiEgg.isRemovable = false applyModifierToSummonedMinions = ModifierSummonWatchFromActionBarApplyModifiers.createContextObject([spawnSerpentiEgg], "Rebirth: Serpenti") applyModifierToSummonedMinions.isRemovable = false card.setInherentModifiersContextObjects([applyModifierToSummonedMinions]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss19) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_19_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_19_bio")) card.setDescription(i18next.t("boss_battles.boss_19_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_wraith) card.setPortraitResource(RSX.speech_portrait_wraith) card.setPortraitHexResource(RSX.boss_wraith_hex_portrait) card.setFXResource(["FX.Cards.Faction4.ArcaneDevourer"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_spell_icepillar_melt.audio attack : RSX.sfx_f6_waterelemental_death.audio receiveDamage : RSX.sfx_f1windbladecommander_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f1elyxstormblade_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWraithBreathing.name idle : RSX.bossWraithIdle.name walk : RSX.bossWraithRun.name attack : RSX.bossWraithAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWraithHit.name death : RSX.bossWraithDeath.name ) card.atk = 1 card.maxHP = 40 growAura = Modifier.createContextObjectWithAuraForAllAllies([ModifierGrowPermanent.createContextObject(1)], null, null, null, "Your minions have \"Grow: +1/+1.\"") growAura.isRemovable = false takeDamageSpawnWraithlings = ModifierTakeDamageWatchSpawnWraithlings.createContextObject() takeDamageSpawnWraithlings.isRemovable = false card.setInherentModifiersContextObjects([growAura, takeDamageSpawnWraithlings]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss20) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_20_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_20_bio")) card.setDescription(i18next.t("boss_battles.boss_20_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_skyfall_tyrant) card.setPortraitResource(RSX.speech_portrait_skyfall_tyrant) card.setPortraitHexResource(RSX.boss_skyfall_tyrant_hex_portrait) card.setFXResource(["FX.Cards.Neutral.FlameWing"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_2.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_spell_blindscorch.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2lanternfox_attack_impact.audio death : RSX.sfx_f6_draugarlord_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSkyfallTyrantBreathing.name idle : RSX.bossSkyfallTyrantIdle.name walk : RSX.bossSkyfallTyrantRun.name attack : RSX.bossSkyfallTyrantAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossSkyfallTyrantHit.name death : RSX.bossSkyfallTyrantDeath.name ) card.atk = 2 card.maxHP = 35 card.speed = 0 includedArtifacts = [ {id: Cards.BossArtifact.FrostArmor} ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, includedArtifacts) equipArtifactObject.isRemovable = false rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false card.setInherentModifiersContextObjects([equipArtifactObject, rangedModifier]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.BossArtifact.FrostArmor) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.FrostArmor card.name = i18next.t("boss_battles.boss_20_artifact_name") card.setDescription(i18next.t("boss_battles.boss_20_artifact_desc")) #card.addKeywordClassToInclude(ModifierTranscendance) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierAbsorbDamage.createContextObject(1, { name: "Frost Armor" description: "The first time your General takes damage each turn, prevent 1 of it." }), ModifierTakeDamageWatchDamageAttacker.createContextObject(1, { name: "Frost Armor" description: "Whenever your General takes damage, deal 1 damage to the attacker." }), ]) card.setFXResource(["FX.Cards.Artifact.ArclyteRegalia"]) card.setBaseAnimResource( idle: RSX.iconFrostArmorIdle.name active: RSX.iconFrostArmorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Boss.Boss21) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_21_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_21_bio")) card.setDescription(i18next.t("boss_battles.boss_21_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_cindera) card.setPortraitResource(RSX.speech_portrait_cindera) card.setPortraitHexResource(RSX.boss_cindera_hex_portrait) card.setFXResource(["FX.Cards.Faction4.AbyssalCrawler"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f3_aymarahealer_attack_swing.audio receiveDamage : RSX.sfx_f3_aymarahealer_hit.audio attackDamage : RSX.sfx_f3_aymarahealer_impact.audio death : RSX.sfx_f3_aymarahealer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCinderaBreathing.name idle : RSX.bossCinderaIdle.name walk : RSX.bossCinderaRun.name attack : RSX.bossCinderaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCinderaHit.name death : RSX.bossCinderaDeath.name ) card.atk = 2 card.maxHP = 35 explodeAura = Modifier.createContextObjectWithAuraForAllAllies([ModifierDyingWishDamageNearbyEnemies.createContextObject(2)], null, null, null, "Your minions have \"Dying Wish: Deal 2 damage to all nearby enemies\"") explodeAura.isRemovable = false startTurnTeleport = ModifierStartTurnWatchTeleportRandomSpace.createContextObject() startTurnTeleport.isRemovable = false frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.setInherentModifiersContextObjects([explodeAura, startTurnTeleport, frenzyContextObject]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss22) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_22_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_22_bio")) card.setDescription(i18next.t("boss_battles.boss_22_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_crystal) card.setPortraitResource(RSX.speech_portrait_crystal) card.setPortraitHexResource(RSX.boss_crystal_hex_portrait) card.setFXResource(["FX.Cards.Faction1.ArclyteSentinel"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f2stormkage_attack_swing.audio receiveDamage : RSX.sfx_f2stormkage_hit.audio attackDamage : RSX.sfx_f2stormkage_attack_impact.audio death : RSX.sfx_f2stormkage_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCrystalBreathing.name idle : RSX.bossCrystalIdle.name walk : RSX.bossCrystalRun.name attack : RSX.bossCrystalAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossCrystalDamage.name death : RSX.bossCrystalDeath.name ) card.atk = 3 card.maxHP = 30 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false attackBuff = 2 maxHPNerf = -2 followupModifierContextObject = Modifier.createContextObjectWithAttributeBuffs(attackBuff,maxHPNerf) followupModifierContextObject.appliedName = i18next.t("modifiers.boss_22_applied_name") statModifierAura = ModifierSummonWatchFromActionBarAnyPlayerApplyModifiers.createContextObject([followupModifierContextObject], "gain +2 Attack, but -2 Health") statModifierAura.isRemovable = false card.setInherentModifiersContextObjects([forceFieldObject, statModifierAura]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss23) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_23_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_23_bio")) card.setDescription(i18next.t("boss_battles.boss_23_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_antiswarm) card.setPortraitResource(RSX.speech_portrait_antiswarm) card.setPortraitHexResource(RSX.boss_antiswarm_hex_portrait) card.setFXResource(["FX.Cards.Faction5.PrimordialGazer"]) card.setBoundingBoxWidth(90) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_screenshake.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_primordialgazer_attack_swing.audio receiveDamage : RSX.sfx_neutral_primordialgazer_hit.audio attackDamage : RSX.sfx_neutral_primordialgazer_attack_impact.audio death : RSX.sfx_neutral_primordialgazer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossAntiswarmBreathing.name idle : RSX.bossAntiswarmIdle.name walk : RSX.bossAntiswarmRun.name attack : RSX.bossAntiswarmAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossAntiswarmHit.name death : RSX.bossAntiswarmDeath.name ) card.atk = 1 card.maxHP = 30 card.speed = 0 damageGeneralEqualToMinions = ModifierStartTurnWatchDamageGeneralEqualToMinionsOwned.createContextObject() damageGeneralEqualToMinions.isRemovable = false shadowDancerAbility = ModifierDeathWatchDamageEnemyGeneralHealMyGeneral.createContextObject(1,1) shadowDancerAbility.isRemovable = false card.setInherentModifiersContextObjects([damageGeneralEqualToMinions, shadowDancerAbility]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss24) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_24_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_24_bio")) card.setDescription(i18next.t("boss_battles.boss_24_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_skurge) card.setPortraitResource(RSX.speech_portrait_skurge) card.setPortraitHexResource(RSX.boss_skurge_hex_portrait) card.setFXResource(["FX.Cards.Neutral.SwornAvenger"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_swornavenger_attack_swing.audio receiveDamage : RSX.sfx_neutral_swornavenger_hit.audio attackDamage : RSX.sfx_neutral_swornavenger_attack_impact.audio death : RSX.sfx_neutral_swornavenger_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSkurgeBreathing.name idle : RSX.bossSkurgeIdle.name walk : RSX.bossSkurgeRun.name attack : RSX.bossSkurgeAttack.name attackReleaseDelay: 0.2 attackDelay: 0.4 damage : RSX.bossSkurgeHit.name death : RSX.bossSkurgeDeath.name ) card.atk = 1 card.maxHP = 25 rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false attackBuffContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) attackBuffContextObject.appliedName = i18next.t("modifiers.boss_24_applied_name_1") #rangedAura = Modifier.createContextObjectWithAuraForAllAllies([attackBuffContextObject], null, null, [ModifierRanged.type], "Your minions with Ranged gain +1/+1") #rangedAura.isRemovable = false immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], "Skurge cannot be damaged while Valiant lives") immunityContextObject.appliedName = i18next.t("modifiers.boss_24_applied_name_2") valiantProtector = [ Cards.Boss.Boss24Valiant ] applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, valiantProtector, null, "Cannot be damaged while Valiant lives") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = true summonValiant = ModifierHPChangeSummonEntity.createContextObject({id: Cards.Boss.Boss24Valiant},15,"Valiant") summonValiant.isRemovable = false summonValiant.isHiddenToUI = true damageAndBuffSelf = ModifierStartTurnWatchDamageAndBuffSelf.createContextObject(1,0,3) damageAndBuffSelf.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, applyGeneralImmunityContextObject, damageAndBuffSelf, summonValiant]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss24Valiant) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_24_valiant_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_24_valiant_desc")) card.setFXResource(["FX.Cards.Neutral.SwornDefender"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossValiantBreathing.name idle : RSX.bossValiantIdle.name walk : RSX.bossValiantRun.name attack : RSX.bossValiantAttack.name attackReleaseDelay: 0.0 attackDelay: 0.25 damage : RSX.bossValiantHit.name death : RSX.bossValiantDeath.name ) card.atk = 4 card.maxHP = 15 card.speed = 4 provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false rangedProvoke = ModifierRangedProvoke.createContextObject() rangedProvoke.isRemovable = false card.setInherentModifiersContextObjects([provokeObject, rangedProvoke]) if (identifier == Cards.Boss.Boss25) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_25_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_25_bio")) card.setDescription(i18next.t("boss_battles.boss_25_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_shadow_lord) card.setPortraitResource(RSX.speech_portrait_shadow_lord) card.setPortraitHexResource(RSX.boss_shadow_lord_hex_portrait) card.setFXResource(["FX.Cards.Neutral.QuartermasterGauj"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_run_magical_4.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_neutral_monsterdreamoracle_hit.audio attackDamage : RSX.sfx_neutral_monsterdreamoracle_attack_impact.audio death : RSX.sfx_neutral_monsterdreamoracle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossShadowLordBreathing.name idle : RSX.bossShadowLordIdle.name walk : RSX.bossShadowLordRun.name attack : RSX.bossShadowLordAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossShadowLordHit.name death : RSX.bossShadowLordDeath.name ) card.atk = 3 card.maxHP = 30 summonAssassinOnMove = ModifierEnemyTeamMoveWatchSummonEntityBehind.createContextObject({id: Cards.Faction2.KaidoAssassin},"Kaido Assassin") summonAssassinOnMove.isRemovable = false modContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) modContextObject.appliedName = i18next.t("modifiers.boss_25_applied_name") allyMinionMoveBuff = ModifierMyTeamMoveWatchBuffTarget.createContextObject([modContextObject], "give it +1/+1") allyMinionMoveBuff.isRemovable = false card.setInherentModifiersContextObjects([summonAssassinOnMove, allyMinionMoveBuff]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss26) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_26_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_26_bio")) card.setDescription(i18next.t("boss_battles.boss_26_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_gol) card.setPortraitResource(RSX.speech_portrait_gol) card.setPortraitHexResource(RSX.boss_gol_hex_portrait) card.setFXResource(["FX.Cards.Neutral.BloodTaura"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_rook_hit.audio attack : RSX.sfx_neutral_khymera_attack_swing.audio receiveDamage : RSX.sfx_neutral_khymera_hit.audio attackDamage : RSX.sfx_neutral_khymera_impact.audio death : RSX.sfx_neutral_khymera_death.audio ) card.setBaseAnimResource( breathing : RSX.bossGolBreathing.name idle : RSX.bossGolIdle.name walk : RSX.bossGolRun.name attack : RSX.bossGolAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossGolHit.name death : RSX.bossGolDeath.name ) card.atk = 2 card.maxHP = 40 card.speed = 0 attacksDamageAllMinions = ModifierAttacksDamageAllEnemyMinions.createContextObject() attacksDamageAllMinions.isRemovable = false card.setInherentModifiersContextObjects([attacksDamageAllMinions]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss26Companion) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_26_zane_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_26_zane_desc")) card.setFXResource(["FX.Cards.Faction1.RadiantDragoon"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_neutral_arcanelimiter_attack_impact.audio attack : RSX.sfx_neutral_rook_attack_swing.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_rook_attack_impact.audio death : RSX.sfx_neutral_windstopper_death.audio ) card.setBaseAnimResource( breathing : RSX.bossKaneBreathing.name idle : RSX.bossKaneIdle.name walk : RSX.bossKaneRun.name attack : RSX.bossKaneAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossKaneHit.name death : RSX.bossKaneDeath.name ) card.atk = 3 card.maxHP = 20 card.speed = 3 dyingWishKillGeneral = ModifierDyingWishLoseGame.createContextObject() dyingWishKillGeneral.isRemovable = false atkLimiter = ModifierATKThresholdDie.createContextObject(6) atkLimiter.isRemovable = false doubleDamageGenerals = ModifierDoubleDamageToGenerals.createContextObject() doubleDamageGenerals.isRemovable = false card.setInherentModifiersContextObjects([ModifierBattlePet.createContextObject(), doubleDamageGenerals, atkLimiter, dyingWishKillGeneral]) if (identifier == Cards.Boss.Boss27) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_27_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_27_bio")) card.setDescription(i18next.t("boss_battles.boss_27_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_taskmaster) card.setPortraitResource(RSX.speech_portrait_taskmaster) card.setPortraitHexResource(RSX.boss_taskmaster_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Tethermancer"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_neutral_ubo_attack_swing.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_spiritscribe_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTaskmasterBreathing.name idle : RSX.bossTaskmasterIdle.name walk : RSX.bossTaskmasterRun.name attack : RSX.bossTaskmasterAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossTaskmasterHit.name death : RSX.bossTaskmasterDeath.name ) card.atk = 3 card.maxHP = 35 card.speed = 0 battlePetModifier = ModifierBattlePet.createContextObject() battlePetModifier.isRemovable = false summonWatchApplyBattlepet = ModifierSummonWatchAnyPlayerApplyModifiers.createContextObject([battlePetModifier], "act like Battle Pets") summonWatchApplyBattlepet.isRemovable = false speedBuffContextObject = Modifier.createContextObjectOnBoard() speedBuffContextObject.attributeBuffs = {"speed": 0} speedBuffContextObject.attributeBuffsAbsolute = ["speed"] speedBuffContextObject.attributeBuffsFixed = ["speed"] speedBuffContextObject.appliedName = i18next.t("modifiers.faction_3_spell_sand_trap_1") speedBuffContextObject.isRemovable = false speed0Modifier = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([speedBuffContextObject], "The enemy General cannot move") speed0Modifier.isRemovable = false immuneToSpellTargeting = ModifierImmuneToSpellsByEnemy.createContextObject() immuneToSpellTargeting.isRemovable = false card.setInherentModifiersContextObjects([summonWatchApplyBattlepet, speed0Modifier, immuneToSpellTargeting]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss28) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_28_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_28_bio")) card.setDescription(i18next.t("boss_battles.boss_28_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_grym) card.setPortraitResource(RSX.speech_portrait_grym) card.setPortraitHexResource(RSX.boss_grym_hex_portrait) card.setFXResource(["FX.Cards.Faction5.EarthWalker"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_screenshake.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_earthwalker_attack_swing.audio receiveDamage : RSX.sfx_neutral_earthwalker_hit.audio attackDamage : RSX.sfx_neutral_earthwalker_attack_impact.audio death : RSX.sfx_neutral_earthwalker_death.audio ) card.setBaseAnimResource( breathing : RSX.bossGrymBreathing.name idle : RSX.bossGrymIdle.name walk : RSX.bossGrymRun.name attack : RSX.bossGrymAttack.name attackReleaseDelay: 0.0 attackDelay: 0.9 damage : RSX.bossGrymHit.name death : RSX.bossGrymDeath.name ) card.atk = 3 card.maxHP = 30 deathWatchDamageRandomMinionHealGeneral = ModifierDeathWatchDamageRandomMinionHealMyGeneral.createContextObject() deathWatchDamageRandomMinionHealGeneral.isRemovable = false card.setInherentModifiersContextObjects([deathWatchDamageRandomMinionHealGeneral]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss29) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_29_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_29_bio")) card.setDescription(i18next.t("boss_battles.boss_29_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_sandpanther) card.setPortraitResource(RSX.speech_portrait_sandpanther) card.setPortraitHexResource(RSX.boss_sandpanther_hex_portrait) card.setFXResource(["FX.Cards.Faction3.Pantheran"]) card.setBaseSoundResource( apply : RSX.sfx_spell_ghostlightning.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_makantorwarbeast_attack_swing.audio receiveDamage : RSX.sfx_f6_boreanbear_hit.audio attackDamage : RSX.sfx_f6_boreanbear_attack_impact.audio death : RSX.sfx_f6_boreanbear_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSandPantherBreathing.name idle : RSX.bossSandPantherIdle.name walk : RSX.bossSandPantherRun.name attack : RSX.bossSandPantherAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossSandPantherDamage.name death : RSX.bossSandPantherDeath.name ) card.atk = 2 card.maxHP = 40 spawnSandTile = ModifierStartTurnWatchSpawnTile.createContextObject({id: Cards.Tile.SandPortal}, "Exhuming Sands", 1, CONFIG.PATTERN_WHOLE_BOARD) spawnSandTile.isRemovable = false card.setInherentModifiersContextObjects([spawnSandTile]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss30) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_30_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_30_bio")) card.setDescription(i18next.t("boss_battles.boss_30_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_wolfpunch) card.setPortraitResource(RSX.speech_portrait_wolfpunch) card.setPortraitHexResource(RSX.boss_wolfpunch_hex_portrait) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(75) card.setFXResource(["FX.Cards.Faction1.LysianBrawler"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f1lysianbrawler_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_f1lysianbrawler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWolfpunchBreathing.name idle : RSX.bossWolfpunchIdle.name walk : RSX.bossWolfpunchRun.name attack : RSX.bossWolfpunchAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossWolfpunchDamage.name death : RSX.bossWolfpunchDeath.name ) card.atk = 2 card.maxHP = 40 gainATKOpponentTurn = ModifierEndTurnWatchGainTempBuff.createContextObject(4,0,i18next.t("modifiers.boss_30_applied_name")) gainATKOpponentTurn.isRemovable = false celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false startTurnSpawnWolf = ModifierStartTurnWatchSpawnEntity.createContextObject({id: Cards.Faction6.WolfAspect}) startTurnSpawnWolf.isRemovable = false card.setInherentModifiersContextObjects([gainATKOpponentTurn, celerityObject, startTurnSpawnWolf]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss31) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_31_bio")) card.setDescription(i18next.t("boss_battles.boss_31_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_unhallowed) card.setPortraitResource(RSX.speech_portrait_unhallowed) card.setPortraitHexResource(RSX.boss_unhallowed_hex_portrait) card.setFXResource(["FX.Cards.Faction4.DeathKnell"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_spell_icepillar_melt.audio attack : RSX.sfx_f6_waterelemental_death.audio receiveDamage : RSX.sfx_f1windbladecommander_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f1elyxstormblade_death.audio ) card.setBaseAnimResource( breathing : RSX.bossUnhallowedBreathing.name idle : RSX.bossUnhallowedIdle.name walk : RSX.bossUnhallowedRun.name attack : RSX.bossUnhallowedAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossUnhallowedHit.name death : RSX.bossUnhallowedDeath.name ) card.atk = 2 card.maxHP = 50 takeDamageSpawnHaunt = ModifierTakeDamageWatchSpawnRandomHaunt.createContextObject() takeDamageSpawnHaunt.isRemovable = false card.setInherentModifiersContextObjects([takeDamageSpawnHaunt]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss31Treat1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_1_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction2.SonghaiSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat1})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Treat2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_2_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction4.AbyssSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentSummonBuffItDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat2})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Treat3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_3_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction6.VanarSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentSpellCastRefundManaDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat3})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Haunt1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_1_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_1_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatDemonBreathing.name idle : RSX.bossTreatDemonIdle.name walk : RSX.bossTreatDemonRun.name attack : RSX.bossTreatDemonAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatDemonHit.name death : RSX.bossTreatDemonDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Unit) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's minions cost 1 more to play") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss31Haunt2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_2_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_2_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatOniBreathing.name idle : RSX.bossTreatOniIdle.name walk : RSX.bossTreatOniRun.name attack : RSX.bossTreatOniAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatOniHit.name death : RSX.bossTreatOniDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Spell) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's non-Bloodbound spells cost 1 more to cast") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss31Haunt3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_3_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_3_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatDrakeBreathing.name idle : RSX.bossTreatDrakeIdle.name walk : RSX.bossTreatDrakeRun.name attack : RSX.bossTreatDrakeAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatDrakeHit.name death : RSX.bossTreatDrakeDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Artifact) contextObject.activeInHand = contextObject.activeInDeck = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's artifacts cost 1 more to cast") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss32) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_32_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_32_bio")) card.setDescription(i18next.t("boss_battles.boss_32_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_christmas) card.setPortraitResource(RSX.speech_portrait_christmas) card.setPortraitHexResource(RSX.boss_christmas_hex_portrait) card.setBoundingBoxWidth(120) card.setBoundingBoxHeight(95) card.setFXResource(["FX.Cards.Faction6.PrismaticGiant"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_f6_draugarlord_attack_impact.audio death : RSX.sfx_f6_draugarlord_death.audio ) card.setBaseAnimResource( breathing : RSX.bossChristmasBreathing.name idle : RSX.bossChristmasIdle.name walk : RSX.bossChristmasRun.name attack : RSX.bossChristmasAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossChristmasDamage.name death : RSX.bossChristmasDeath.name ) card.atk = 4 card.maxHP = 50 #giftPlayer = ModifierStartTurnWatchPutCardInOpponentsHand.createContextObject({id: Cards.BossSpell.HolidayGift}) #giftPlayer.isRemovable = false startTurnSpawnElf = ModifierStartTurnWatchSpawnEntity.createContextObject({id: Cards.Boss.Boss32_2}) startTurnSpawnElf.isRemovable = false card.setInherentModifiersContextObjects([startTurnSpawnElf]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss32_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_32_elf_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_32_elf_desc")) card.setFXResource(["FX.Cards.Neutral.Zyx"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_emeraldrejuvenator_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_neutral_emeraldrejuvenator_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralZyxFestiveBreathing.name idle : RSX.neutralZyxFestiveIdle.name walk : RSX.neutralZyxFestiveRun.name attack : RSX.neutralZyxFestiveAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralZyxFestiveHit.name death : RSX.neutralZyxFestiveDeath.name ) card.atk = 2 card.maxHP = 3 celerityObject = ModifierTranscendance.createContextObject() rushContextObject = ModifierFirstBlood.createContextObject() dyingWishPresent = ModifierDyingWishPutCardInOpponentHand.createContextObject({id: Cards.BossSpell.HolidayGift}) card.setInherentModifiersContextObjects([celerityObject, dyingWishPresent]) if (identifier == Cards.BossArtifact.FlyingBells) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.FlyingBells card.name = i18next.t("boss_battles.boss_32_gift_1_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_1_desc")) card.addKeywordClassToInclude(ModifierFlying) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierFlying.createContextObject({ type: "ModifierFlying" name: i18next.t("boss_battles.boss_32_gift_1_name") }) ]) card.setFXResource(["FX.Cards.Artifact.MaskOfShadows"]) card.setBaseAnimResource( idle: RSX.bossChristmasJinglebellsIdle.name active: RSX.bossChristmasJinglebellsActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.BossArtifact.Coal) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.Coal card.name = i18next.t("boss_battles.boss_32_gift_2_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_2_desc")) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierCannotCastBBS.createContextObject({ type: "ModifierCannotCastBBS" name: i18next.t("boss_battles.boss_32_gift_2_name") }) ]) card.setFXResource(["FX.Cards.Artifact.PristineScale"]) card.setBaseAnimResource( idle: RSX.bossChristmasCoalIdle.name active: RSX.bossChristmasCoalActive.name ) card.setBaseSoundResource( apply : RSX.sfx_artifact_equip.audio ) if (identifier == Cards.BossArtifact.CostReducer) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.CostReducer card.name = i18next.t("boss_battles.boss_32_gift_3_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_3_desc")) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 artifactContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Artifact) artifactContextObject.activeInHand = artifactContextObject.activeInDeck = false artifactContextObject.activeOnBoard = true spellContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Spell) spellContextObject.activeInHand = spellContextObject.activeInDeck = spellContextObject.activeInSignatureCards = false spellContextObject.activeOnBoard = true minionContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Unit) minionContextObject.activeInHand = minionContextObject.activeInDeck = false minionContextObject.activeOnBoard = true card.setTargetModifiersContextObjects([ ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([artifactContextObject,spellContextObject,minionContextObject], "Cards in your hand cost 1 less to play.") ]) card.setFXResource(["FX.Cards.Artifact.SoulGrimwar"]) card.setBaseAnimResource( idle: RSX.bossChristmasMistletoeIdle.name active: RSX.bossChristmasMistletoeActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.BossSpell.HolidayGift) card = new SpellEquipBossArtifacts(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.id = Cards.Spell.HolidayGift card.name = i18next.t("boss_battles.boss_32_gift_spell_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_spell_desc")) card.manaCost = 1 card.rarityId = Rarity.Legendary card.setFXResource(["FX.Cards.Spell.AutarchsGifts"]) card.setBaseSoundResource( apply : RSX.sfx_spell_entropicdecay.audio ) card.setBaseAnimResource( idle : RSX.bossChristmasPresentIdle.name active : RSX.bossChristmasPresentActive.name ) if (identifier == Cards.BossArtifact.Snowball) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.Snowball card.name = i18next.t("boss_battles.boss_32_gift_4_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_4_desc")) card.addKeywordClassToInclude(ModifierRanged) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierRanged.createContextObject({ type: "ModifierRanged" name: i18next.t("boss_battles.boss_32_gift_4_name") }), Modifier.createContextObjectWithAttributeBuffs(-1,undefined, { name: "Snowball" description: "-1 Attack." }) ]) card.setFXResource(["FX.Cards.Artifact.EternalHeart"]) card.setBaseAnimResource( idle: RSX.bossChristmasSnowballIdle.name active: RSX.bossChristmasSnowballActive.name ) card.setBaseSoundResource( apply : RSX.sfx_artifact_equip.audio ) if (identifier == Cards.Boss.Boss33) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_33_bio")) card.setDescription(i18next.t("boss_battles.boss_33_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_legion) card.setPortraitResource(RSX.speech_portrait_legion) card.setPortraitHexResource(RSX.boss_legion_hex_portrait) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 healObject = ModifierEndTurnWatchHealSelf.createContextObject(3) healObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] healAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([healObject], null, legion, null, "Heals for 3 at end of turn") healAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([healAura, backupGeneral, respawnClones]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss33_1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 healObject = ModifierEndTurnWatchHealSelf.createContextObject(3) healObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] healAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([healObject], null, legion, null, "Heals for 3 at end of turn") healAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([healAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_2_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 attackObject = Modifier.createContextObjectWithAttributeBuffs(2,undefined, { name: "Legion's Strength" description: "+2 Attack." }) attackObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] attackAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([attackObject], null, legion, null, "Gains +2 Attack") attackAura.isRemovable = false attackAura.appliedName = i18next.t("modifiers.boss_33_applied_name_2") backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([attackAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_3_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 speedBuffContextObject = Modifier.createContextObjectOnBoard() speedBuffContextObject.attributeBuffs = {"speed": 3} speedBuffContextObject.attributeBuffsAbsolute = ["speed"] speedBuffContextObject.attributeBuffsFixed = ["speed"] speedBuffContextObject.appliedName = i18next.t("modifiers.boss_33_applied_name") speedBuffContextObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] speedAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([speedBuffContextObject], null, legion, null, "Can move 2 extra spaces") speedAura.isRemovable = false speedAura.appliedName = i18next.t("modifiers.boss_33_applied_name") backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([speedAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_4) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_4_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 immuneToSpellTargeting = ModifierImmuneToSpellsByEnemy.createContextObject() immuneToSpellTargeting.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] spellImmuneAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([immuneToSpellTargeting], null, legion, null, "Cannot be targeted by enemy spells") spellImmuneAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([spellImmuneAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss34) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_34_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_34_bio")) card.setDescription(i18next.t("boss_battles.boss_34_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_harmony) card.setPortraitResource(RSX.speech_portrait_harmony) card.setPortraitHexResource(RSX.boss_harmony_hex_portrait) card.setFXResource(["FX.Cards.Faction2.JadeOgre"]) card.setBoundingBoxWidth(65) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2_jadeogre_attack_impact.audio death : RSX.sfx_f2_jadeogre_death.audio ) card.setBaseAnimResource( breathing : RSX.bossHarmonyBreathing.name idle : RSX.bossHarmonyIdle.name walk : RSX.bossHarmonyRun.name attack : RSX.bossHarmonyAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossHarmonyHit.name death : RSX.bossHarmonyRun.name ) card.atk = 3 card.maxHP = 25 contextObject = PlayerModifierManaModifier.createCostChangeContextObject(-25, CardType.Unit) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true reducedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetBothPlayers([contextObject], "Minions cost 0 mana") reducedManaCost.isRemovable = false spawnDissonance = ModifierDieSpawnNewGeneral.createContextObject({id: Cards.Boss.Boss34_2}) spawnDissonance.isRemovable = false spawnDissonance.isHiddenToUI = true #customContextObject = PlayerModifierManaModifier.createCostChangeContextObject(0, CardType.Unit) #customContextObject.modifiersContextObjects[0].attributeBuffsAbsolute = ["manaCost"] #customContextObject.modifiersContextObjects[0].attributeBuffsFixed = ["manaCost"] #manaReduction = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetBothPlayers([customContextObject], "All minions cost 0 mana.") #manaReduction.isRemovable = false card.setInherentModifiersContextObjects([reducedManaCost, spawnDissonance]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss34_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_34_2_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_34_2_desc")) card.setFXResource(["FX.Cards.Faction2.JadeOgre"]) card.setBoundingBoxWidth(65) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2_jadeogre_attack_impact.audio death : RSX.sfx_f2_jadeogre_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDissonanceBreathing.name idle : RSX.bossDissonanceIdle.name walk : RSX.bossDissonanceRun.name attack : RSX.bossDissonanceAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossDissonanceHit.name death : RSX.bossDissonanceRun.name ) card.atk = 3 card.maxHP = 25 swapAllegiancesGainAttack = ModifierSwitchAllegiancesGainAttack.createContextObject() swapAllegiancesGainAttack.isRemovable = false frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.setInherentModifiersContextObjects([swapAllegiancesGainAttack, frenzyContextObject]) if (identifier == Cards.Boss.Boss35) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_35_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_35_bio")) card.setDescription(i18next.t("boss_battles.boss_35_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_andromeda) card.setPortraitResource(RSX.speech_portrait_andromeda) card.setPortraitHexResource(RSX.boss_andromeda_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Pandora"]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_pandora_attack_swing.audio receiveDamage : RSX.sfx_neutral_pandora_hit.audio attackDamage : RSX.sfx_neutral_pandora_attack_impact.audio death : RSX.sfx_neutral_pandora_death.audio ) card.setBaseAnimResource( breathing : RSX.bossAndromedaBreathing.name idle : RSX.bossAndromedaIdle.name walk : RSX.bossAndromedaRun.name attack : RSX.bossAndromedaAttack.name attackReleaseDelay: 0.0 attackDelay: 1.0 damage : RSX.bossAndromedaHit.name death : RSX.bossAndromedaDeath.name ) card.atk = 3 card.maxHP = 42 randomTransformMinions = ModifierOpponentSummonWatchRandomTransform.createContextObject() randomTransformMinions.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false card.setInherentModifiersContextObjects([randomTransformMinions, flyingObject]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss36) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_36_bio")) card.setDescription(i18next.t("boss_battles.boss_36_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_kaiju) card.setPortraitResource(RSX.speech_portrait_kaiju) card.setPortraitHexResource(RSX.boss_kaiju_hex_portrait) card.setFXResource(["FX.Cards.Faction3.GrandmasterNoshRak"]) card.setBaseSoundResource( apply : RSX.sfx_spell_ghostlightning.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_makantorwarbeast_attack_swing.audio receiveDamage : RSX.sfx_f6_boreanbear_hit.audio attackDamage : RSX.sfx_f6_boreanbear_attack_impact.audio death : RSX.sfx_f6_boreanbear_death.audio ) card.setBaseAnimResource( breathing : RSX.bossInvaderBreathing.name idle : RSX.bossInvaderIdle.name walk : RSX.bossInvaderRun.name attack : RSX.bossInvaderAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossInvaderHit.name death : RSX.bossInvaderDeath.name ) card.atk = 3 card.maxHP = 80 damageRandom = ModifierStartTurnWatchDamageRandom.createContextObject(6) damageRandom.isRemovable = false card.setInherentModifiersContextObjects([damageRandom]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss36_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_2_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_36_2_desc")) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction1.IroncliffeGuardian"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossProtectorBreathing.name idle : RSX.bossProtectorIdle.name walk : RSX.bossProtectorRun.name attack : RSX.bossProtectorAttack.name attackReleaseDelay: 0.0 attackDelay: 0.7 damage : RSX.bossProtectorDamage.name death : RSX.bossProtectorDeath.name ) card.atk = 1 card.maxHP = 50 replaceGeneral = ModifierOnSpawnKillMyGeneral.createContextObject() replaceGeneral.isRemovable = false gainAttackOnKill = ModifierDeathWatchGainAttackEqualToEnemyAttack.createContextObject() gainAttackOnKill.isRemovable = false card.setInherentModifiersContextObjects([replaceGeneral, gainAttackOnKill]) if (identifier == Cards.Boss.Boss36_3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_3_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_36_3_desc")) card.raceId = Races.Structure card.setFXResource(["FX.Cards.Faction3.BrazierDuskWind"]) card.setBaseSoundResource( apply : RSX.sfx_spell_divinebond.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_monsterdreamoracle_attack_swing.audio receiveDamage : RSX.sfx_neutral_monsterdreamoracle_hit.audio attackDamage : RSX.sfx_f1_general_attack_impact.audio death : RSX.sfx_neutral_golembloodshard_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCityBreathing.name idle : RSX.bossCityIdle.name walk : RSX.bossCityIdle.name attack : RSX.bossCityAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossCityDamage.name death : RSX.bossCityDeath.name ) card.atk = 0 card.maxHP = 3 buffEnemyGeneralOnDeath = ModifierDyingWishBuffEnemyGeneral.createContextObject(2,6) buffEnemyGeneralOnDeath.isRemovable = false card.setInherentModifiersContextObjects([buffEnemyGeneralOnDeath]) if (identifier == Cards.Boss.Boss37) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_37_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_37_bio")) card.setDescription(i18next.t("boss_battles.boss_37_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_soulstealer) card.setPortraitResource(RSX.speech_portrait_soulstealer) card.setPortraitHexResource(RSX.boss_soulstealer_hex_portrait) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSoulstealerBreathing.name idle : RSX.bossSoulstealerIdle.name walk : RSX.bossSoulstealerRun.name attack : RSX.bossSoulstealerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossSoulstealerDamage.name death : RSX.bossSoulstealerDeath.name ) card.atk = 3 card.maxHP = 30 enemyMinionGeneralSwap = PlayerModifierOpponentSummonWatchSwapGeneral.createContextObject() enemyMinionGeneralSwap.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false backupGeneral.appliedName = i18next.t("modifiers.boss_37_applied_name") backupGeneral.appliedDescription = i18next.t("modifiers.boss_37_applied_desc") applyModifierToSummonedMinions = PlayerModifierSummonWatchApplyModifiers.createContextObject([backupGeneral], i18next.t("modifiers.boss_37_applied_name")) applyModifierToSummonedMinions.isRemovable = false #applyBackUpGeneralApplyingModifierToSummonedMinions = ModifierSummonWatchFromActionBarApplyModifiers.createContextObject([applyModifierToSummonedMinions], "Soul Vessel") #applyBackUpGeneralApplyingModifierToSummonedMinions.isRemovable = false card.setInherentModifiersContextObjects([enemyMinionGeneralSwap, applyModifierToSummonedMinions]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss38) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_38_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_38_bio")) card.setDescription(i18next.t("boss_battles.boss_38_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_spelleater) card.setPortraitResource(RSX.speech_portrait_spelleater) card.setPortraitHexResource(RSX.boss_spelleater_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Grailmaster"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(105) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_neutral_sai_attack_impact.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_spiritscribe_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSpelleaterBreathing.name idle : RSX.bossSpelleaterIdle.name walk : RSX.bossSpelleaterRun.name attack : RSX.bossSpelleaterAttack.name attackReleaseDelay: 0.0 attackDelay: 0.9 damage : RSX.bossSpelleaterHit.name death : RSX.bossSpelleaterDeath.name ) card.atk = 3 card.maxHP = 35 spellWatchGainKeyword = ModifierEnemySpellWatchGainRandomKeyword.createContextObject() spellWatchGainKeyword.isRemovable = false summonsGainKeywords = ModifierAnySummonWatchGainGeneralKeywords.createContextObject() summonsGainKeywords.isRemovable = false card.setInherentModifiersContextObjects([spellWatchGainKeyword, summonsGainKeywords]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.FrostfireImp) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_imp_name") card.manaCost = 0 card.setDescription(i18next.t("cards.faction_1_unit_lysian_brawler_desc")) card.setFXResource(["FX.Cards.Neutral.Zyx"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_emeraldrejuvenator_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_neutral_emeraldrejuvenator_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralZyxFestiveBreathing.name idle : RSX.neutralZyxFestiveIdle.name walk : RSX.neutralZyxFestiveRun.name attack : RSX.neutralZyxFestiveAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralZyxFestiveHit.name death : RSX.neutralZyxFestiveDeath.name ) card.atk = 2 card.maxHP = 3 card.setInherentModifiersContextObjects([ModifierTranscendance.createContextObject()]) if (identifier == Cards.Boss.FrostfireTiger) card = new Unit(gameSession) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_tiger_name") card.setDescription(i18next.t("cards.neutral_saberspine_tiger_desc")) card.setFXResource(["FX.Cards.Neutral.SaberspineTiger"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f6_boreanbear_attack_swing.audio receiveDamage : RSX.sfx_neutral_beastsaberspinetiger_hit.audio attackDamage : RSX.sfx_neutral_beastsaberspinetiger_attack_impact.audio death : RSX.sfx_neutral_beastsaberspinetiger_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralFrostfireTigerBreathing.name idle : RSX.neutralFrostfireTigerIdle.name walk : RSX.neutralFrostfireTigerRun.name attack : RSX.neutralFrostfireTigerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.neutralFrostfireTigerHit.name death : RSX.neutralFrostfireTigerDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 4 card.setInherentModifiersContextObjects([ModifierFirstBlood.createContextObject()]) if (identifier == Cards.Boss.FrostfireSnowchaser) card = new Unit(gameSession) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_snowchser_name") card.setDescription(i18next.t("cards.neutral_vale_hunter_desc")) card.raceId = Races.Vespyr card.setFXResource(["FX.Cards.Faction6.SnowElemental"]) card.setBaseSoundResource( apply : RSX.sfx_spell_amplification.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_artifacthunter_attack_swing.audio receiveDamage : RSX.sfx_neutral_artifacthunter_hit.audio attackDamage : RSX.sfx_neutral_artifacthunter_attack_impact.audio death : RSX.sfx_neutral_artifacthunter_death.audio ) card.setBaseAnimResource( breathing : RSX.f6FestiveSnowchaserBreathing.name idle : RSX.f6FestiveSnowchaserIdle.name walk : RSX.f6FestiveSnowchaserRun.name attack : RSX.f6FestiveSnowchaserAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.f6FestiveSnowchaserDamage.name death : RSX.f6FestiveSnowchaserDeath.name ) card.atk = 2 card.maxHP = 1 card.manaCost = 1 card.setInherentModifiersContextObjects([ModifierRanged.createContextObject()]) if (identifier == Cards.BossSpell.LaceratingFrost) card = new SpellLaceratingFrost(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.LaceratingFrost card.name = "Lacerating Frost" card.setDescription("Deal 2 damage to the enemy General and stun all nearby enemy minions.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.damageAmount = 2 card.setFXResource(["FX.Cards.Spell.LaceratingFrost"]) card.setBaseSoundResource( apply : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( idle : RSX.iconLaceratingFrostIdle.name active : RSX.iconLaceratingFrostActive.name ) if (identifier == Cards.BossSpell.EntanglingShadow) card = new SpellEntanglingShadows(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.EntanglingShadow card.name = "Entangling Shadow" card.setDescription("Summon Wraithlings and Shadow Creep in a 2x2 area.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.setAffectPattern(CONFIG.PATTERN_2X2) card.cardDataOrIndexToSpawn = {id: Cards.Faction4.Wraithling} card.setFXResource(["FX.Cards.Spell.EntanglingShadow"]) card.setBaseSoundResource( apply : RSX.sfx_spell_shadowreflection.audio ) card.setBaseAnimResource( idle : RSX.iconCultivatingDarkIdle.name active : RSX.iconCultivatingDarkActive.name ) if (identifier == Cards.BossSpell.LivingFlame) card = new SpellDamageAndSpawnEntitiesNearbyGeneral(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.LivingFlame card.name = "Living Flame" card.setDescription("Deal 2 damage to an enemy and summon two Spellsparks nearby your General.") card.spellFilterType = SpellFilterType.EnemyDirect card.manaCost = 1 card.damageAmount = 2 card.canTargetGeneral = true card.cardDataOrIndexToSpawn = {id: Cards.Neutral.Spellspark} card.setFXResource(["FX.Cards.Spell.LivingFlame"]) card.setBaseSoundResource( apply : RSX.sfx_spell_phoenixfire.audio ) card.setBaseAnimResource( idle : RSX.iconLivingFlameIdle.name active : RSX.iconLivingFlameActive.name ) if (identifier == Cards.BossSpell.MoldingEarth) card = new SpellMoldingEarth(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.MoldingEarth card.name = "Molding Earth" card.setDescription("Summon 3 Magmas with random keywords nearby your General.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.cardDataOrIndexToSpawn = {id: Cards.Faction5.MiniMagmar} card.setFXResource(["FX.Cards.Spell.MoldingEarth"]) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) card.setBaseAnimResource( idle : RSX.iconModlingEarthIdle.name active : RSX.iconModlingEarthActive.name ) if (identifier == Cards.BossSpell.EtherealWind) card = new SpellSilenceAndSpawnEntityNearby(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.EtherealWind card.name = "Ethereal Wind" card.setDescription("Dispel an enemy and summon a Wind Dervish nearby.") card.spellFilterType = SpellFilterType.EnemyDirect card.manaCost = 1 card.canTargetGeneral = true card.cardDataOrIndexToSpawn = {id: Cards.Faction3.Dervish} card.setFXResource(["FX.Cards.Spell.EtherealWind"]) card.setBaseSoundResource( apply : RSX.sfx_spell_entropicdecay.audio ) card.setBaseAnimResource( idle : RSX.iconEtherealWindIdle.name active : RSX.iconEtherealWindActive.name ) if (identifier == Cards.BossSpell.RestoringLight) card = new SpellRestoringLight(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.RestoringLight card.name = "Restoring Light" card.setDescription("Restore 3 Health to your General. Give your friendly minions +1 Health.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 buffContextObject = Modifier.createContextObjectWithAttributeBuffs(0,1) buffContextObject.appliedName = "Restored Light" card.setTargetModifiersContextObjects([ buffContextObject ]) card.setFXResource(["FX.Cards.Spell.RestoringLight"]) card.setBaseSoundResource( apply : RSX.sfx_spell_sunbloom.audio ) card.setBaseAnimResource( idle : RSX.iconRestoringLightIdle.name active : RSX.iconRestoringLightActive.name ) if (identifier == Cards.BossSpell.AncientKnowledge) card = new Spell(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.AncientKnowledge card.name = "Ancient Knowledge" card.setDescription("Draw 2 cards.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.drawCardsPostPlay = 2 card.setFXResource(["FX.Cards.Spell.AncientKnowledge"]) card.setBaseSoundResource( apply : RSX.sfx_spell_scionsfirstwish.audio ) card.setBaseAnimResource( idle : RSX.iconAncientKnowledgeIdle.name active : RSX.iconAncientKnowledgeActive.name ) return card module.exports = CardFactory_Bosses
161073
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' Artifact = require 'app/sdk/artifacts/artifact' Spell = require 'app/sdk/spells/spell' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellSpawnEntity = require 'app/sdk/spells/spellSpawnEntity' SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers' SpellEquipBossArtifacts = require 'app/sdk/spells/spellEquipBossArtifacts' SpellLaceratingFrost = require 'app/sdk/spells/spellLaceratingFrost' SpellEntanglingShadows = require 'app/sdk/spells/spellEntanglingShadows' SpellMoldingEarth = require 'app/sdk/spells/spellMoldingEarth' SpellDamageAndSpawnEntitiesNearbyGeneral = require 'app/sdk/spells/spellDamageAndSpawnEntitiesNearbyGeneral' SpellSilenceAndSpawnEntityNearby = require 'app/sdk/spells/spellSilenceAndSpawnEntityNearby' SpellRestoringLight = require 'app/sdk/spells/spellRestoringLight' Modifier = require 'app/sdk/modifiers/modifier' PlayerModifierManaModifier = require 'app/sdk/playerModifiers/playerModifierManaModifier' ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke' ModifierEndTurnWatchDamageNearbyEnemy = require 'app/sdk/modifiers/modifierEndTurnWatchDamageNearbyEnemy' ModifierFrenzy = require 'app/sdk/modifiers/modifierFrenzy' ModifierFlying = require 'app/sdk/modifiers/modifierFlying' ModifierTranscendance = require 'app/sdk/modifiers/modifierTranscendance' ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierRebirth = require 'app/sdk/modifiers/modifierRebirth' ModifierBlastAttack = require 'app/sdk/modifiers/modifierBlastAttack' ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield' ModifierStartTurnWatchEquipArtifact = require 'app/sdk/modifiers/modifierStartTurnWatchEquipArtifact' ModifierTakeDamageWatchSpawnRandomToken = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnRandomToken' ModifierDealDamageWatchKillTarget = require 'app/sdk/modifiers/modifierDealDamageWatchKillTarget' ModifierStartTurnWatchPlaySpell = require 'app/sdk/modifiers/modifierStartTurnWatchPlaySpell' ModifierDealDamageWatchModifyTarget = require 'app/sdk/modifiers/modifierDealDamageWatchModifyTarget' ModifierStunned = require 'app/sdk/modifiers/modifierStunned' ModifierStunnedVanar = require 'app/sdk/modifiers/modifierStunnedVanar' ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers' ModifierBattlePet = require 'app/sdk/modifiers/modifierBattlePet' ModifierImmuneToDamage = require 'app/sdk/modifiers/modifierImmuneToDamage' ModifierStartTurnWatchDispelAllEnemyMinionsDrawCard = require 'app/sdk/modifiers/modifierStartTurnWatchDispelAllEnemyMinionsDrawCard' ModifierImmuneToSpellsByEnemy = require 'app/sdk/modifiers/modifierImmuneToSpellsByEnemy' ModifierAbsorbDamageGolems = require 'app/sdk/modifiers/modifierAbsorbDamageGolems' ModifierExpireApplyModifiers = require 'app/sdk/modifiers/modifierExpireApplyModifiers' ModifierSecondWind = require 'app/sdk/modifiers/modifierSecondWind' ModifierKillWatchRespawnEntity = require 'app/sdk/modifiers/modifierKillWatchRespawnEntity' ModifierOpponentSummonWatchSpawn1HealthClone = require 'app/sdk/modifiers/modifierOpponentSummonWatchSpawn1HealthClone' ModifierDealOrTakeDamageWatchRandomTeleportOther = require 'app/sdk/modifiers/modifierDealOrTakeDamageWatchRandomTeleportOther' ModifierMyAttackOrAttackedWatchSpawnMinionNearby = require 'app/sdk/modifiers/modifierMyAttackOrAttackedWatchSpawnMinionNearby' ModifierEndTurnWatchTeleportCorner = require 'app/sdk/modifiers/modifierEndTurnWatchTeleportCorner' ModifierBackstab = require 'app/sdk/modifiers/modifierBackstab' ModifierDieSpawnNewGeneral = require 'app/sdk/modifiers/modifierDieSpawnNewGeneral' ModifierKillWatchRefreshExhaustion = require 'app/sdk/modifiers/modifierKillWatchRefreshExhaustion' ModifierEndTurnWatchDealDamageToSelfAndNearbyEnemies = require 'app/sdk/modifiers/modifierEndTurnWatchDealDamageToSelfAndNearbyEnemies' ModifierDispelAreaAttack = require 'app/sdk/modifiers/modifierDispelAreaAttack' ModifierSelfDamageAreaAttack = require 'app/sdk/modifiers/modifierSelfDamageAreaAttack' ModifierMyMinionOrGeneralDamagedWatchBuffSelf = require 'app/sdk/modifiers/modifierMyMinionOrGeneralDamagedWatchBuffSelf' ModifierSummonWatchNearbyAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchNearbyAnyPlayerApplyModifiers' ModifierOpponentSummonWatchOpponentDrawCard = require 'app/sdk/modifiers/modifierOpponentSummonWatchOpponentDrawCard' ModifierOpponentDrawCardWatchOverdrawSummonEntity = require 'app/sdk/modifiers/modifierOpponentDrawCardWatchOverdrawSummonEntity' ModifierEndTurnWatchDamagePlayerBasedOnRemainingMana = require 'app/sdk/modifiers/modifierEndTurnWatchDamagePlayerBasedOnRemainingMana' ModifierHPThresholdGainModifiers = require 'app/sdk/modifiers/modifierHPThresholdGainModifiers' ModifierHealSelfWhenDealingDamage = require 'app/sdk/modifiers/modifierHealSelfWhenDealingDamage' ModifierExtraDamageOnCounterattack = require 'app/sdk/modifiers/modifierExtraDamageOnCounterattack' ModifierOnOpponentDeathWatchSpawnEntityOnSpace = require 'app/sdk/modifiers/modifierOnOpponentDeathWatchSpawnEntityOnSpace' ModifierDyingWishSpawnEgg = require 'app/sdk/modifiers/modifierDyingWishSpawnEgg' ModifierSummonWatchFromActionBarApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchFromActionBarApplyModifiers' ModifierGrowPermanent = require 'app/sdk/modifiers/modifierGrowPermanent' ModifierTakeDamageWatchSpawnWraithlings = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnWraithlings' ModifierTakeDamageWatchDamageAttacker = require 'app/sdk/modifiers/modifierTakeDamageWatchDamageAttacker' ModifierAbsorbDamage = require 'app/sdk/modifiers/modifierAbsorbDamage' ModifierDyingWishDamageNearbyEnemies = require 'app/sdk/modifiers/modifierDyingWishDamageNearbyEnemies' ModifierStartTurnWatchTeleportRandomSpace = require 'app/sdk/modifiers/modifierStartTurnWatchTeleportRandomSpace' ModifierSummonWatchFromActionBarAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchFromActionBarAnyPlayerApplyModifiers' ModifierStartTurnWatchDamageGeneralEqualToMinionsOwned = require 'app/sdk/modifiers/modifierStartTurnWatchDamageGeneralEqualToMinionsOwned' ModifierDeathWatchDamageEnemyGeneralHealMyGeneral = require 'app/sdk/modifiers/modifierDeathWatchDamageEnemyGeneralHealMyGeneral' ModifierRangedProvoke = require 'app/sdk/modifiers/modifierRangedProvoke' ModifierHPChangeSummonEntity = require 'app/sdk/modifiers/modifierHPChangeSummonEntity' ModifierStartTurnWatchDamageAndBuffSelf = require 'app/sdk/modifiers/modifierStartTurnWatchDamageAndBuffSelf' ModifierEnemyTeamMoveWatchSummonEntityBehind = require 'app/sdk/modifiers/modifierEnemyTeamMoveWatchSummonEntityBehind' ModifierMyTeamMoveWatchBuffTarget = require 'app/sdk/modifiers/modifierMyTeamMoveWatchAnyReasonBuffTarget' ModifierDyingWishLoseGame = require 'app/sdk/modifiers/modifierDyingWishLoseGame' ModifierAttacksDamageAllEnemyMinions = require 'app/sdk/modifiers/modifierAttacksDamageAllEnemyMinions' ModifierSummonWatchAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchAnyPlayerApplyModifiers' ModifierDoubleDamageToGenerals = require 'app/sdk/modifiers/modifierDoubleDamageToGenerals' ModifierATKThresholdDie = require 'app/sdk/modifiers/modifierATKThresholdDie' ModifierDeathWatchDamageRandomMinionHealMyGeneral = require 'app/sdk/modifiers/modifierDeathWatchDamageRandomMinionHealMyGeneral' ModifierStartTurnWatchSpawnTile = require 'app/sdk/modifiers/modifierStartTurnWatchSpawnTile' ModifierStartTurnWatchSpawnEntity = require 'app/sdk/modifiers/modifierStartTurnWatchSpawnEntity' ModifierEndTurnWatchGainTempBuff = require 'app/sdk/modifiers/modifierEndTurnWatchGainTempBuff' ModifierSentinel = require 'app/sdk/modifiers/modifierSentinel' ModifierSentinelSetup = require 'app/sdk/modifiers/modifierSentinelSetup' ModifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard' ModifierSentinelOpponentSummonBuffItDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentSummonBuffItDrawCard' ModifierSentinelOpponentSpellCastRefundManaDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentSpellCastRefundManaDrawCard' ModifierTakeDamageWatchSpawnRandomHaunt = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnRandomHaunt' ModifierDyingWishDrawCard = require "app/sdk/modifiers/modifierDyingWishDrawCard" ModifierCannotAttackGeneral = require 'app/sdk/modifiers/modifierCannotAttackGeneral' ModifierCannotCastBBS = require 'app/sdk/modifiers/modifierCannotCastBBS' ModifierStartTurnWatchPutCardInOpponentsHand = require 'app/sdk/modifiers/modifierStartTurnWatchPutCardInOpponentsHand' ModifierEndTurnWatchHealSelf = require 'app/sdk/modifiers/modifierEndTurnWatchHealSelf' ModifierBackupGeneral = require 'app/sdk/modifiers/modifierBackupGeneral' ModifierStartTurnWatchRespawnClones = require 'app/sdk/modifiers/modifierStartTurnWatchRespawnClones' ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers' ModifierSwitchAllegiancesGainAttack = require 'app/sdk/modifiers/modifierSwitchAllegiancesGainAttack' ModifierOpponentSummonWatchRandomTransform = require 'app/sdk/modifiers/modifierOpponentSummonWatchRandomTransform' ModifierOnSpawnKillMyGeneral = require 'app/sdk/modifiers/modifierOnSpawnKillMyGeneral' ModifierDeathWatchGainAttackEqualToEnemyAttack = require 'app/sdk/modifiers/modifierDeathWatchGainAttackEqualToEnemyAttack' ModifierDyingWishBuffEnemyGeneral = require 'app/sdk/modifiers/modifierDyingWishBuffEnemyGeneral' ModifierStartTurnWatchDamageRandom = require 'app/sdk/modifiers/modifierStartTurnWatchDamageRandom' ModifierOpponentSummonWatchSwapGeneral = require 'app/sdk/modifiers/modifierOpponentSummonWatchSwapGeneral' ModifierDyingWishPutCardInOpponentHand = require 'app/sdk/modifiers/modifierDyingWishPutCardInOpponentHand' ModifierEnemySpellWatchGainRandomKeyword = require 'app/sdk/modifiers/modifierEnemySpellWatchGainRandomKeyword' ModifierAnySummonWatchGainGeneralKeywords = require 'app/sdk/modifiers/modifierAnySummonWatchGainGeneralKeywords' PlayerModifierSummonWatchApplyModifiers = require 'app/sdk/playerModifiers/playerModifierSummonWatchApplyModifiers' PlayerModifierOpponentSummonWatchSwapGeneral = require 'app/sdk/playerModifiers/playerModifierOpponentSummonWatchSwapGeneral' class CardFactory_Bosses ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Boss.Boss1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_1_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_1_bio")) card.setDescription(i18next.t("boss_battles.boss_1_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_boreal_juggernaut) card.setPortraitResource(RSX.speech_portrait_boreal_juggernaut) card.setPortraitHexResource(RSX.boss_boreal_juggernaut_hex_portrait) card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setBoundingBoxWidth(120) card.setBoundingBoxHeight(95) card.setFXResource(["FX.Cards.Faction5.Dreadnaught"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_rook_attack_impact.audio receiveDamage : RSX.sfx_neutral_makantorwarbeast_hit.audio attackDamage : RSX.sfx_neutral_silitharveteran_attack_impact.audio death : RSX.sfx_neutral_makantorwarbeast_death.audio ) card.setBaseAnimResource( breathing : RSX.bossBorealJuggernautBreathing.name idle : RSX.bossBorealJuggernautIdle.name walk : RSX.bossBorealJuggernautRun.name attack : RSX.bossBorealJuggernautAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossBorealJuggernautHit.name death : RSX.bossBorealJuggernautDeath.name ) card.atk = 5 card.speed = 1 card.maxHP = 40 frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.addKeywordClassToInclude(ModifierStunned) stunContextObject = ModifierDealDamageWatchModifyTarget.createContextObject([ModifierStunnedVanar.createContextObject()], "it is STUNNED",{ name: "<NAME>" description: "Enemy minions damaged by your General are Stunned" }) stunContextObject.isRemovable = false #startTurnCastFrostburnObject = ModifierStartTurnWatchPlaySpell.createContextObject({id: Cards.Spell.Frostburn, manaCost: 0}, "Frostburn") #startTurnCastFrostburnObject.isRemovable = false card.setInherentModifiersContextObjects([frenzyContextObject, stunContextObject]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_2_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_2_bio")) card.setDescription(i18next.t("boss_battles.boss_2_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_umbra) card.setPortraitResource(RSX.speech_portrait_umbra) card.setPortraitHexResource(RSX.boss_umbra_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setBoundingBoxWidth(75) card.setBoundingBoxHeight(75) card.setFXResource(["FX.Cards.Neutral.MirkbloodDevourer"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_mirkblooddevourer_attack_swing.audio receiveDamage : RSX.sfx_neutral_mirkblooddevourer_hit.audio attackDamage : RSX.sfx_neutral_mirkblooddevourer_attack_impact.audio death : RSX.sfx_neutral_mirkblooddevourer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossUmbraBreathing.name idle : RSX.bossUmbraIdle.name walk : RSX.bossUmbraRun.name attack : RSX.bossUmbraAttack.name attackReleaseDelay: 0.0 attackDelay: 1.25 damage : RSX.bossUmbraHit.name death : RSX.bossUmbraDeath.name ) card.atk = 2 card.maxHP = 30 modifierSpawnClone = ModifierOpponentSummonWatchSpawn1HealthClone.createContextObject("a 1 health clone") modifierSpawnClone.isRemovable = false card.setInherentModifiersContextObjects([modifierSpawnClone]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_3_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_3_bio")) card.setDescription(i18next.t("boss_battles.boss_3_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 30 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false excludedArtifacts = [ Cards.Artifact.Spinecleaver, Cards.Artifact.IndomitableWill ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, excludedArtifacts) equipArtifactObject.isRemovable = false card.setInherentModifiersContextObjects([ forceFieldObject, equipArtifactObject ]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.QABoss3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = "QA-IBERO" card.manaCost = 0 card.setBossBattleDescription("A Dev Boss for quickly testing flow.") card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 1 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false excludedArtifacts = [ Cards.Artifact.Spinecleaver, Cards.Artifact.IndomitableWill ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, excludedArtifacts) equipArtifactObject.isRemovable = false card.setInherentModifiersContextObjects([ equipArtifactObject ]) if (identifier == Cards.Boss.Boss4) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_4_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_4_bio")) card.setDescription(i18next.t("boss_battles.boss_4_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_chaos_knight) card.setPortraitResource(RSX.speech_portrait_chaos_knight) card.setPortraitHexResource(RSX.boss_chaos_knight_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Ironclad"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossChaosKnightBreathing.name idle : RSX.bossChaosKnightIdle.name walk : RSX.bossChaosKnightRun.name attack : RSX.bossChaosKnightAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.bossChaosKnightHit.name death : RSX.bossChaosKnightDeath.name ) card.atk = 3 card.maxHP = 35 frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false dealOrTakeDamageRandomTeleportObject = ModifierDealOrTakeDamageWatchRandomTeleportOther.createContextObject() dealOrTakeDamageRandomTeleportObject.isRemovable = false card.setInherentModifiersContextObjects([frenzyContextObject, dealOrTakeDamageRandomTeleportObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss5) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_5_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_5_bio")) card.setDescription(i18next.t("boss_battles.boss_5_desc")) card.setBossBattleBattleMapIndex(4) card.setSpeechResource(RSX.speech_portrait_shinkage_zendo) card.setPortraitResource(RSX.speech_portrait_shinkage_zendo) card.setPortraitHexResource(RSX.boss_shinkage_zendo_hex_portrait) card.setConceptResource(RSX.boss_shinkage_zendo_versus_portrait) card.setFXResource(["FX.Cards.Faction2.GrandmasterZendo"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_run_magical_3.audio attack : RSX.sfx_spell_darkseed.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_daggerkiri_attack_swing.audio death : RSX.sfx_neutral_prophetofthewhite_death.audio ) card.setBaseAnimResource( breathing : RSX.bossShinkageZendoBreathing.name idle : RSX.bossShinkageZendoIdle.name walk : RSX.bossShinkageZendoRun.name attack : RSX.bossShinkageZendoAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.bossShinkageZendoHit.name death : RSX.bossShinkageZendoDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 6 card.maxHP = 20 card.speed = 0 immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], i18next.t("modifiers.boss_5_applied_desc")) immunityContextObject.appliedName = i18next.t("modifiers.boss_5_applied_name") applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, null, null, "Cannot be damaged while friendly minions live") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = true zendoBattlePetContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([ModifierBattlePet.createContextObject()], "The enemy General moves and attacks as if they are a Battle Pet") #zendoBattlePetContextObject = Modifier.createContextObjectWithOnBoardAuraForAllEnemies([ModifierBattlePet.createContextObject()], "All enemies move and attack as if they are Battle Pets") zendoBattlePetContextObject.isRemovable = false card.setInherentModifiersContextObjects([applyGeneralImmunityContextObject, zendoBattlePetContextObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss6) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_6_bio")) card.setDescription(i18next.t("boss_battles.boss_6_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_decepticle) card.setPortraitResource(RSX.speech_portrait_decepticle) card.setPortraitHexResource(RSX.boss_decepticle_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Mechaz0rHelm"]) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_wingsmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_wingsmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_wingsmechaz0r_impact.audio death : RSX.sfx_neutral_wingsmechaz0r_hit.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleBreathing.name idle : RSX.bossDecepticleIdle.name walk : RSX.bossDecepticleRun.name attack : RSX.bossDecepticleAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossDecepticleHit.name death : RSX.bossDecepticleDeath.name ) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(50) card.atk = 2 card.maxHP = 1 immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], "Decepticle cannot be damaged while this minion lives.") immunityContextObject.appliedName = i18next.t("modifiers.boss_6_applied_name") mechs = [ Cards.Boss.Boss6Wings, Cards.Boss.Boss6Chassis, Cards.Boss.Boss6Sword, Cards.Boss.Boss6Helm ] applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, mechs, null, "Cannot be damaged while other D3cepticle parts live") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = false provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false spawnPrimeBoss = ModifierDieSpawnNewGeneral.createContextObject({id: Cards.Boss.Boss6Prime}) spawnPrimeBoss.isRemovable = false spawnPrimeBoss.isHiddenToUI = true card.setInherentModifiersContextObjects([applyGeneralImmunityContextObject, provokeObject, spawnPrimeBoss]) #card.setInherentModifiersContextObjects([provokeObject, spawnPrimeBoss]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss6Wings) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part1_name") card.setDescription(i18next.t("boss_battles.boss_6_part1_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rWings"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_wingsmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_wingsmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_wingsmechaz0r_impact.audio death : RSX.sfx_neutral_wingsmechaz0r_hit.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleWingsBreathing.name idle : RSX.bossDecepticleWingsIdle.name walk : RSX.bossDecepticleWingsRun.name attack : RSX.bossDecepticleWingsAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossDecepticleWingsHit.name death : RSX.bossDecepticleWingsDeath.name ) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(50) card.atk = 2 card.maxHP = 3 flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false card.setInherentModifiersContextObjects([flyingObject]) if (identifier == Cards.Boss.Boss6Chassis) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part2_name") card.setDescription(i18next.t("boss_battles.boss_6_part2_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rChassis"]) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio death : RSX.sfx_neutral_hailstonehowler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleChassisBreathing.name idle : RSX.bossDecepticleChassisIdle.name walk : RSX.bossDecepticleChassisRun.name attack : RSX.bossDecepticleChassisAttack.name attackReleaseDelay: 0.0 attackDelay: 0.5 damage : RSX.bossDecepticleChassisHit.name death : RSX.bossDecepticleChassisDeath.name ) card.atk = 5 card.maxHP = 4 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false card.setInherentModifiersContextObjects([forceFieldObject]) if (identifier == Cards.Boss.Boss6Sword) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part3_name") card.setDescription(i18next.t("boss_battles.boss_6_part3_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rSword"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_swordmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_swordmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_swordmechaz0r_attack_impact.audio death : RSX.sfx_neutral_swordmechaz0r_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleSwordBreathing.name idle : RSX.bossDecepticleSwordIdle.name walk : RSX.bossDecepticleSwordRun.name attack : RSX.bossDecepticleSwordAttack.name attackReleaseDelay: 0.0 attackDelay: 0.25 damage : RSX.bossDecepticleSwordHit.name death : RSX.bossDecepticleSwordDeath.name ) card.atk = 4 card.maxHP = 2 backstabObject = ModifierBackstab.createContextObject(2) backstabObject.isRemovable = false card.setInherentModifiersContextObjects([backstabObject]) if (identifier == Cards.Boss.Boss6Helm) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part4_name") card.setDescription(i18next.t("boss_battles.boss_6_part4_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rHelm"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleHelmBreathing.name idle : RSX.bossDecepticleHelmIdle.name walk : RSX.bossDecepticleHelmRun.name attack : RSX.bossDecepticleHelmAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossDecepticleHelmHit.name death : RSX.bossDecepticleHelmDeath.name ) card.atk = 3 card.maxHP = 3 celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false card.setInherentModifiersContextObjects([celerityObject]) if (identifier == Cards.Boss.Boss6Prime) card = new Unit(gameSession) card.setIsHiddenInCollection(true) #card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_prime_name") card.setDescription(i18next.t("boss_battles.boss_6_prime_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.AlterRexx"]) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_ladylocke_attack_impact.audio attack : RSX.sfx_neutral_wingsofparadise_attack_swing.audio receiveDamage : RSX.sfx_f1_oserix_hit.audio attackDamage : RSX.sfx_f1_oserix_attack_impact.audio death : RSX.sfx_neutral_sunelemental_attack_swing.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticlePrimeBreathing.name idle : RSX.bossDecepticlePrimeIdle.name walk : RSX.bossDecepticlePrimeRun.name attack : RSX.bossDecepticlePrimeAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossDecepticlePrimeHit.name death : RSX.bossDecepticlePrimeDeath.name ) card.atk = 4 card.maxHP = 16 celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false backstabObject = ModifierBackstab.createContextObject(2) backstabObject.isRemovable = false forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false card.setInherentModifiersContextObjects([celerityObject, backstabObject, forceFieldObject, flyingObject, provokeObject]) if (identifier == Cards.Boss.Boss7) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_7_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_7_bio")) card.setDescription(i18next.t("boss_battles.boss_7_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 20 includedArtifacts = [ {id: Cards.Artifact.SunstoneBracers}, {id: Cards.Artifact.ArclyteRegalia}, {id: Cards.Artifact.StaffOfYKir} ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, includedArtifacts) equipArtifactObject.isRemovable = false equipArtifactFirstTurn = ModifierExpireApplyModifiers.createContextObject([equipArtifactObject], 0, 1, true, true, false, 0, true, "At the start of your second turn and every turn thereafter, equip a random artifact") equipArtifactFirstTurn.isRemovable = false card.setInherentModifiersContextObjects([ equipArtifactFirstTurn ]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.BossArtifact.CycloneGenerator) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.DanceOfSteel card.name = i18next.t("boss_battles.boss_7_artifact_name") card.setDescription(i18next.t("boss_battles.boss_7_artifact_desc")) card.addKeywordClassToInclude(ModifierTranscendance) card.manaCost = 0 card.setBossBattleDescription("__Boss Battle Description") card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierTranscendance.createContextObject({ type: "ModifierTranscendance" name: "Cyclone Generator" }) ]) card.setFXResource(["FX.Cards.Artifact.IndomitableWill"]) card.setBaseAnimResource( idle: RSX.iconSkywindGlaivesIdle.name active: RSX.iconSkywindGlaivesActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Boss.Boss8) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_8_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_8_bio")) card.setDescription(i18next.t("boss_battles.boss_8_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_portal_guardian) card.setPortraitResource(RSX.speech_portrait_portal_guardian) card.setPortraitHexResource(RSX.boss_portal_guardian_hex_portrait) card.setConceptResource(RSX.boss_portal_guardian_versus_portrait) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralMysteryBreathing.name idle : RSX.neutralMysteryIdle.name walk : RSX.neutralMysteryRun.name attack : RSX.neutralMysteryAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralMysteryHit.name death : RSX.neutralMysteryDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 15 respawnKilledEnemy = ModifierKillWatchRespawnEntity.createContextObject() respawnKilledEnemy.isRemovable = false secondWind = ModifierSecondWind.createContextObject(2, 5, false, "Awakened", "Failure prevented. Strength renewed. Systems adapted.") secondWind.isRemovable = false secondWind.isHiddenToUI = true card.setInherentModifiersContextObjects([respawnKilledEnemy, secondWind]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss9) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_9_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_9_bio")) card.setDescription(i18next.t("boss_battles.boss_9_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_wujin) card.setPortraitResource(RSX.speech_portrait_wujin) card.setPortraitHexResource(RSX.boss_wujin_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_f1_oserix_death.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_silitharveteran_hit.audio attackDamage : RSX.sfx_neutral_prophetofthewhite_death.audio death : RSX.sfx_neutral_daggerkiri_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWujinBreathing.name idle : RSX.bossWujinIdle.name walk : RSX.bossWujinRun.name attack : RSX.bossWujinAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWujinHit.name death : RSX.bossWujinDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 3 card.maxHP = 30 spawnCloneObject = ModifierMyAttackOrAttackedWatchSpawnMinionNearby.createContextObject({id: Cards.Boss.Boss9Clone}, "a decoy") spawnCloneObject.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false teleportCornerObject = ModifierEndTurnWatchTeleportCorner.createContextObject() teleportCornerObject.isRemovable = false card.setInherentModifiersContextObjects([flyingObject, spawnCloneObject, teleportCornerObject]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss9Clone) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_9_clone_name") card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_f1_oserix_death.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_silitharveteran_hit.audio attackDamage : RSX.sfx_neutral_prophetofthewhite_death.audio death : RSX.sfx_neutral_daggerkiri_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWujinBreathing.name idle : RSX.bossWujinIdle.name walk : RSX.bossWujinRun.name attack : RSX.bossWujinAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWujinHit.name death : RSX.bossWujinDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 1 card.maxHP = 5 provokeObject = ModifierProvoke.createContextObject() #provokeObject.isRemovable = false card.setInherentModifiersContextObjects([provokeObject]) if (identifier == Cards.Boss.Boss10) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_10_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_10_bio")) card.setDescription(i18next.t("boss_battles.boss_10_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_solfist) card.setPortraitResource(RSX.speech_portrait_solfist) card.setPortraitHexResource(RSX.boss_solfist_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setFXResource(["FX.Cards.Neutral.WarTalon"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSolfistBreathing.name idle : RSX.bossSolfistIdle.name walk : RSX.bossSolfistRun.name attack : RSX.bossSolfistAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossSolfistHit.name death : RSX.bossSolfistDeath.name ) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(95) card.atk = 3 card.maxHP = 35 killWatchRefreshObject = ModifierKillWatchRefreshExhaustion.createContextObject(true, false) killWatchRefreshObject.isRemovable = false #killWatchRefreshObject.description = "Whenever Solfist destroys a minion, reactivate it." modifierDamageSelfAndNearby = ModifierEndTurnWatchDealDamageToSelfAndNearbyEnemies.createContextObject() modifierDamageSelfAndNearby.isRemovable = false #modifierDamageSelfAndNearby.description = "At the end of Solfist's turn, deal 1 damage to self and all nearby enemies." card.setInherentModifiersContextObjects([killWatchRefreshObject, modifierDamageSelfAndNearby]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss11) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.raceId = Races.Golem card.name = i18next.t("boss_battles.boss_11_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_11_bio")) card.setDescription(i18next.t("boss_battles.boss_11_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_nullifier) card.setPortraitResource(RSX.speech_portrait_nullifier) card.setPortraitHexResource(RSX.boss_nullifier_hex_portrait) card.setFXResource(["FX.Cards.Neutral.EMP"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossEMPBreathing.name idle : RSX.bossEMPIdle.name walk : RSX.bossEMPRun.name attack : RSX.bossEMPAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.bossEMPHit.name death : RSX.bossEMPDeath.name ) card.atk = 3 card.maxHP = 60 modifierSelfDamageAreaAttack = ModifierSelfDamageAreaAttack.createContextObject() modifierSelfDamageAreaAttack.isRemovable = false rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, modifierSelfDamageAreaAttack]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss12) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_12_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_12_bio")) card.setDescription(i18next.t("boss_battles.boss_12_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_orias) card.setPortraitResource(RSX.speech_portrait_orias) card.setPortraitHexResource(RSX.boss_orias_hex_portrait) card.setFXResource(["FX.Cards.Neutral.ArchonSpellbinder"]) card.setBoundingBoxWidth(55) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_archonspellbinder_attack_swing.audio receiveDamage : RSX.sfx_neutral_archonspellbinder_hit.audio attackDamage : RSX.sfx_neutral_archonspellbinder_attack_impact.audio death : RSX.sfx_neutral_archonspellbinder_death.audio ) card.setBaseAnimResource( breathing : RSX.bossOriasBreathing.name idle : RSX.bossOriasIdle.name walk : RSX.bossOriasRun.name attack : RSX.bossOriasAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossOriasHit.name death : RSX.bossOriasDeath.name ) card.atk = 0 card.maxHP = 35 modifierDamageWatchBuffSelf = ModifierMyMinionOrGeneralDamagedWatchBuffSelf.createContextObject(1, 0) modifierDamageWatchBuffSelf.isRemovable = false card.setInherentModifiersContextObjects([modifierDamageWatchBuffSelf]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss12Idol) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_12_idol_name") card.setDescription(i18next.t("boss_battles.boss_12_idol_desc")) card.manaCost = 0 card.raceId = Races.Structure card.setFXResource(["FX.Cards.Neutral.Bastion"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(125) card.setBaseSoundResource( apply : RSX.sfx_spell_divinebond.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_golembloodshard_death.audio ) card.setBaseAnimResource( breathing : RSX.bossOriasIdolBreathing.name idle : RSX.bossOriasIdolIdle.name walk : RSX.bossOriasIdolIdle.name attack : RSX.bossOriasIdolAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossOriasIdolHit.name death : RSX.bossOriasIdolDeath.name ) card.atk = 0 card.maxHP = 6 card.speed = 0 rushContextObject = ModifierFirstBlood.createContextObject() modifierSummonNearbyRush = ModifierSummonWatchNearbyAnyPlayerApplyModifiers.createContextObject([rushContextObject], "gains Rush") card.setInherentModifiersContextObjects([modifierSummonNearbyRush]) if (identifier == Cards.Boss.Boss13) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_13_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_13_bio")) card.setDescription(i18next.t("boss_battles.boss_13_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_malyk) card.setPortraitResource(RSX.speech_portrait_malyk) card.setPortraitHexResource(RSX.boss_malyk_hex_portrait) card.setFXResource(["FX.Cards.Neutral.TheHighHand"]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(105) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_grimrock_attack_swing.audio receiveDamage : RSX.sfx_neutral_grimrock_hit.audio attackDamage : RSX.sfx_neutral_grimrock_attack_impact.audio death : RSX.sfx_neutral_grimrock_death.audio ) card.setBaseAnimResource( breathing : RSX.bossMalykBreathing.name idle : RSX.bossMalykIdle.name walk : RSX.bossMalykRun.name attack : RSX.bossMalykAttack.name attackReleaseDelay: 0.0 attackDelay: 0.95 damage : RSX.bossMalykHit.name death : RSX.bossMalykDeath.name ) card.atk = 2 card.maxHP = 30 rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false opponentDrawCardOnSummon = ModifierOpponentSummonWatchOpponentDrawCard.createContextObject() opponentDrawCardOnSummon.isRemovable = false summonEntityOnOverdraw = ModifierOpponentDrawCardWatchOverdrawSummonEntity.createContextObject({id: Cards.Faction4.Ooz}, "a 3/3 Ooz") summonEntityOnOverdraw.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, opponentDrawCardOnSummon, summonEntityOnOverdraw]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss14) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_14_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_14_bio")) card.setDescription(i18next.t("boss_battles.boss_14_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_archonis) card.setPortraitResource(RSX.speech_portrait_archonis) card.setPortraitHexResource(RSX.boss_archonis_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction4.BlackSolus"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_blacksolus_attack_swing.audio receiveDamage : RSX.sfx_f4_blacksolus_hit.audio attackDamage : RSX.sfx_f4_blacksolus_attack_impact.audio death : RSX.sfx_f4_blacksolus_death.audio ) card.setBaseAnimResource( breathing : RSX.bossManaManBreathing.name idle : RSX.bossManaManIdle.name walk : RSX.bossManaManRun.name attack : RSX.bossManaManAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossManaManDamage.name death : RSX.bossManaManDeath.name ) card.atk = 6 card.maxHP = 60 damageBasedOnRemainingMana = ModifierEndTurnWatchDamagePlayerBasedOnRemainingMana.createContextObject() damageBasedOnRemainingMana.isRemovable = false card.setInherentModifiersContextObjects([damageBasedOnRemainingMana]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss15) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_15_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_15_bio")) card.setDescription(i18next.t("boss_battles.boss_15_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_paragon) card.setPortraitResource(RSX.speech_portrait_paragon) card.setPortraitHexResource(RSX.boss_paragon_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio death : RSX.sfx_neutral_hailstonehowler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossParagonBreathing.name idle : RSX.bossParagonIdle.name walk : RSX.bossParagonRun.name attack : RSX.bossParagonAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossParagonHit.name death : RSX.bossParagonDeath.name ) card.atk = 3 card.maxHP = 30 card.setDamage(10) gainModifiersOnHPChange = ModifierHPThresholdGainModifiers.createContextObject() gainModifiersOnHPChange.isRemovable = false card.setInherentModifiersContextObjects([gainModifiersOnHPChange]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss16) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_16_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_16_desc")) card.setBossBattleDescription(i18next.t("boss_battles.boss_16_bio")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_vampire) card.setPortraitResource(RSX.speech_portrait_vampire) card.setPortraitHexResource(RSX.boss_vampire_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.Chakkram"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_prophetofthewhite_hit.audio walk : RSX.sfx_neutral_firestarter_impact.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firestarter_hit.audio attackDamage : RSX.sfx_neutral_firestarter_impact.audio death : RSX.sfx_neutral_alcuinloremaster_death.audio ) card.setBaseAnimResource( breathing : RSX.bossVampireBreathing.name idle : RSX.bossVampireIdle.name walk : RSX.bossVampireRun.name attack : RSX.bossVampireAttack.name attackReleaseDelay: 0.0 attackDelay: 1.5 damage : RSX.bossVampireHit.name death : RSX.bossVampireDeath.name ) card.atk = 2 card.maxHP = 30 lifestealModifier = ModifierHealSelfWhenDealingDamage.createContextObject() lifestealModifier.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false extraDamageCounterAttack = ModifierExtraDamageOnCounterattack.createContextObject(2) extraDamageCounterAttack.isRemovable = false card.setInherentModifiersContextObjects([lifestealModifier, extraDamageCounterAttack, flyingObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss17) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_17_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_17_bio")) card.setDescription(i18next.t("boss_battles.boss_17_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_kron) card.setPortraitResource(RSX.speech_portrait_kron) card.setPortraitHexResource(RSX.boss_kron_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.WhiteWidow"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_windstopper_attack_impact.audio attack : RSX.sfx_neutral_crossbones_attack_swing.audio receiveDamage : RSX.sfx_neutral_mirkblooddevourer_hit.audio attackDamage : RSX.sfx_neutral_mirkblooddevourer_attack_impact.audio death : RSX.sfx_neutral_mirkblooddevourer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossKronBreathing.name idle : RSX.bossKronIdle.name walk : RSX.bossKronRun.name attack : RSX.bossKronAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossKronHit.name death : RSX.bossKronDeath.name ) card.atk = 2 card.maxHP = 30 spawnPrisoners = ModifierOnOpponentDeathWatchSpawnEntityOnSpace.createContextObject() spawnPrisoners.isRemovable = false contextObject = PlayerModifierManaModifier.createCostChangeContextObject(-2, CardType.Spell) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true contextObject.isRemovable = false card.setInherentModifiersContextObjects([spawnPrisoners, contextObject]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss18) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_18_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_18_bio")) card.setDescription(i18next.t("boss_battles.boss_18_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_serpenti) card.setPortraitResource(RSX.speech_portrait_serpenti) card.setPortraitHexResource(RSX.boss_serpenti_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Serpenti"]) card.setBoundingBoxWidth(105) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_serpenti_attack_swing.audio receiveDamage : RSX.sfx_neutral_serpenti_hit.audio attackDamage : RSX.sfx_neutral_serpenti_attack_impact.audio death : RSX.sfx_neutral_serpenti_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSerpentiBreathing.name idle : RSX.bossSerpentiIdle.name walk : RSX.bossSerpentiRun.name attack : RSX.bossSerpentiAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossSerpentiHit.name death : RSX.bossSerpentiDeath.name ) card.atk = 4 card.maxHP = 40 spawnSerpentiEgg = ModifierDyingWishSpawnEgg.createContextObject({id: Cards.Neutral.Serpenti}, "7/4 Serpenti") spawnSerpentiEgg.isRemovable = false applyModifierToSummonedMinions = ModifierSummonWatchFromActionBarApplyModifiers.createContextObject([spawnSerpentiEgg], "Rebirth: Serpenti") applyModifierToSummonedMinions.isRemovable = false card.setInherentModifiersContextObjects([applyModifierToSummonedMinions]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss19) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_19_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_19_bio")) card.setDescription(i18next.t("boss_battles.boss_19_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_wraith) card.setPortraitResource(RSX.speech_portrait_wraith) card.setPortraitHexResource(RSX.boss_wraith_hex_portrait) card.setFXResource(["FX.Cards.Faction4.ArcaneDevourer"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_spell_icepillar_melt.audio attack : RSX.sfx_f6_waterelemental_death.audio receiveDamage : RSX.sfx_f1windbladecommander_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f1elyxstormblade_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWraithBreathing.name idle : RSX.bossWraithIdle.name walk : RSX.bossWraithRun.name attack : RSX.bossWraithAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWraithHit.name death : RSX.bossWraithDeath.name ) card.atk = 1 card.maxHP = 40 growAura = Modifier.createContextObjectWithAuraForAllAllies([ModifierGrowPermanent.createContextObject(1)], null, null, null, "Your minions have \"Grow: +1/+1.\"") growAura.isRemovable = false takeDamageSpawnWraithlings = ModifierTakeDamageWatchSpawnWraithlings.createContextObject() takeDamageSpawnWraithlings.isRemovable = false card.setInherentModifiersContextObjects([growAura, takeDamageSpawnWraithlings]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss20) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_20_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_20_bio")) card.setDescription(i18next.t("boss_battles.boss_20_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_skyfall_tyrant) card.setPortraitResource(RSX.speech_portrait_skyfall_tyrant) card.setPortraitHexResource(RSX.boss_skyfall_tyrant_hex_portrait) card.setFXResource(["FX.Cards.Neutral.FlameWing"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_2.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_spell_blindscorch.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2lanternfox_attack_impact.audio death : RSX.sfx_f6_draugarlord_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSkyfallTyrantBreathing.name idle : RSX.bossSkyfallTyrantIdle.name walk : RSX.bossSkyfallTyrantRun.name attack : RSX.bossSkyfallTyrantAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossSkyfallTyrantHit.name death : RSX.bossSkyfallTyrantDeath.name ) card.atk = 2 card.maxHP = 35 card.speed = 0 includedArtifacts = [ {id: Cards.BossArtifact.FrostArmor} ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, includedArtifacts) equipArtifactObject.isRemovable = false rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false card.setInherentModifiersContextObjects([equipArtifactObject, rangedModifier]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.BossArtifact.FrostArmor) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.FrostArmor card.name = i18next.t("boss_battles.boss_20_artifact_name") card.setDescription(i18next.t("boss_battles.boss_20_artifact_desc")) #card.addKeywordClassToInclude(ModifierTranscendance) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierAbsorbDamage.createContextObject(1, { name: "<NAME>rost Armor" description: "The first time your General takes damage each turn, prevent 1 of it." }), ModifierTakeDamageWatchDamageAttacker.createContextObject(1, { name: "<NAME>rost Armor" description: "Whenever your General takes damage, deal 1 damage to the attacker." }), ]) card.setFXResource(["FX.Cards.Artifact.ArclyteRegalia"]) card.setBaseAnimResource( idle: RSX.iconFrostArmorIdle.name active: RSX.iconFrostArmorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Boss.Boss21) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_21_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_21_bio")) card.setDescription(i18next.t("boss_battles.boss_21_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_cindera) card.setPortraitResource(RSX.speech_portrait_cindera) card.setPortraitHexResource(RSX.boss_cindera_hex_portrait) card.setFXResource(["FX.Cards.Faction4.AbyssalCrawler"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f3_aymarahealer_attack_swing.audio receiveDamage : RSX.sfx_f3_aymarahealer_hit.audio attackDamage : RSX.sfx_f3_aymarahealer_impact.audio death : RSX.sfx_f3_aymarahealer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCinderaBreathing.name idle : RSX.bossCinderaIdle.name walk : RSX.bossCinderaRun.name attack : RSX.bossCinderaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCinderaHit.name death : RSX.bossCinderaDeath.name ) card.atk = 2 card.maxHP = 35 explodeAura = Modifier.createContextObjectWithAuraForAllAllies([ModifierDyingWishDamageNearbyEnemies.createContextObject(2)], null, null, null, "Your minions have \"Dying Wish: Deal 2 damage to all nearby enemies\"") explodeAura.isRemovable = false startTurnTeleport = ModifierStartTurnWatchTeleportRandomSpace.createContextObject() startTurnTeleport.isRemovable = false frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.setInherentModifiersContextObjects([explodeAura, startTurnTeleport, frenzyContextObject]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss22) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_22_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_22_bio")) card.setDescription(i18next.t("boss_battles.boss_22_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_crystal) card.setPortraitResource(RSX.speech_portrait_crystal) card.setPortraitHexResource(RSX.boss_crystal_hex_portrait) card.setFXResource(["FX.Cards.Faction1.ArclyteSentinel"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f2stormkage_attack_swing.audio receiveDamage : RSX.sfx_f2stormkage_hit.audio attackDamage : RSX.sfx_f2stormkage_attack_impact.audio death : RSX.sfx_f2stormkage_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCrystalBreathing.name idle : RSX.bossCrystalIdle.name walk : RSX.bossCrystalRun.name attack : RSX.bossCrystalAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossCrystalDamage.name death : RSX.bossCrystalDeath.name ) card.atk = 3 card.maxHP = 30 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false attackBuff = 2 maxHPNerf = -2 followupModifierContextObject = Modifier.createContextObjectWithAttributeBuffs(attackBuff,maxHPNerf) followupModifierContextObject.appliedName = i18next.t("modifiers.boss_22_applied_name") statModifierAura = ModifierSummonWatchFromActionBarAnyPlayerApplyModifiers.createContextObject([followupModifierContextObject], "gain +2 Attack, but -2 Health") statModifierAura.isRemovable = false card.setInherentModifiersContextObjects([forceFieldObject, statModifierAura]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss23) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_23_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_23_bio")) card.setDescription(i18next.t("boss_battles.boss_23_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_antiswarm) card.setPortraitResource(RSX.speech_portrait_antiswarm) card.setPortraitHexResource(RSX.boss_antiswarm_hex_portrait) card.setFXResource(["FX.Cards.Faction5.PrimordialGazer"]) card.setBoundingBoxWidth(90) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_screenshake.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_primordialgazer_attack_swing.audio receiveDamage : RSX.sfx_neutral_primordialgazer_hit.audio attackDamage : RSX.sfx_neutral_primordialgazer_attack_impact.audio death : RSX.sfx_neutral_primordialgazer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossAntiswarmBreathing.name idle : RSX.bossAntiswarmIdle.name walk : RSX.bossAntiswarmRun.name attack : RSX.bossAntiswarmAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossAntiswarmHit.name death : RSX.bossAntiswarmDeath.name ) card.atk = 1 card.maxHP = 30 card.speed = 0 damageGeneralEqualToMinions = ModifierStartTurnWatchDamageGeneralEqualToMinionsOwned.createContextObject() damageGeneralEqualToMinions.isRemovable = false shadowDancerAbility = ModifierDeathWatchDamageEnemyGeneralHealMyGeneral.createContextObject(1,1) shadowDancerAbility.isRemovable = false card.setInherentModifiersContextObjects([damageGeneralEqualToMinions, shadowDancerAbility]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss24) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_24_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_24_bio")) card.setDescription(i18next.t("boss_battles.boss_24_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_skurge) card.setPortraitResource(RSX.speech_portrait_skurge) card.setPortraitHexResource(RSX.boss_skurge_hex_portrait) card.setFXResource(["FX.Cards.Neutral.SwornAvenger"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_swornavenger_attack_swing.audio receiveDamage : RSX.sfx_neutral_swornavenger_hit.audio attackDamage : RSX.sfx_neutral_swornavenger_attack_impact.audio death : RSX.sfx_neutral_swornavenger_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSkurgeBreathing.name idle : RSX.bossSkurgeIdle.name walk : RSX.bossSkurgeRun.name attack : RSX.bossSkurgeAttack.name attackReleaseDelay: 0.2 attackDelay: 0.4 damage : RSX.bossSkurgeHit.name death : RSX.bossSkurgeDeath.name ) card.atk = 1 card.maxHP = 25 rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false attackBuffContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) attackBuffContextObject.appliedName = i18next.t("modifiers.boss_24_applied_name_1") #rangedAura = Modifier.createContextObjectWithAuraForAllAllies([attackBuffContextObject], null, null, [ModifierRanged.type], "Your minions with Ranged gain +1/+1") #rangedAura.isRemovable = false immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], "Skurge cannot be damaged while Valiant lives") immunityContextObject.appliedName = i18next.t("modifiers.boss_24_applied_name_2") valiantProtector = [ Cards.Boss.Boss24Valiant ] applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, valiantProtector, null, "Cannot be damaged while Valiant lives") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = true summonValiant = ModifierHPChangeSummonEntity.createContextObject({id: Cards.Boss.Boss24Valiant},15,"Valiant") summonValiant.isRemovable = false summonValiant.isHiddenToUI = true damageAndBuffSelf = ModifierStartTurnWatchDamageAndBuffSelf.createContextObject(1,0,3) damageAndBuffSelf.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, applyGeneralImmunityContextObject, damageAndBuffSelf, summonValiant]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss24Valiant) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_24_valiant_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_24_valiant_desc")) card.setFXResource(["FX.Cards.Neutral.SwornDefender"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossValiantBreathing.name idle : RSX.bossValiantIdle.name walk : RSX.bossValiantRun.name attack : RSX.bossValiantAttack.name attackReleaseDelay: 0.0 attackDelay: 0.25 damage : RSX.bossValiantHit.name death : RSX.bossValiantDeath.name ) card.atk = 4 card.maxHP = 15 card.speed = 4 provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false rangedProvoke = ModifierRangedProvoke.createContextObject() rangedProvoke.isRemovable = false card.setInherentModifiersContextObjects([provokeObject, rangedProvoke]) if (identifier == Cards.Boss.Boss25) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_25_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_25_bio")) card.setDescription(i18next.t("boss_battles.boss_25_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_shadow_lord) card.setPortraitResource(RSX.speech_portrait_shadow_lord) card.setPortraitHexResource(RSX.boss_shadow_lord_hex_portrait) card.setFXResource(["FX.Cards.Neutral.QuartermasterGauj"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_run_magical_4.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_neutral_monsterdreamoracle_hit.audio attackDamage : RSX.sfx_neutral_monsterdreamoracle_attack_impact.audio death : RSX.sfx_neutral_monsterdreamoracle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossShadowLordBreathing.name idle : RSX.bossShadowLordIdle.name walk : RSX.bossShadowLordRun.name attack : RSX.bossShadowLordAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossShadowLordHit.name death : RSX.bossShadowLordDeath.name ) card.atk = 3 card.maxHP = 30 summonAssassinOnMove = ModifierEnemyTeamMoveWatchSummonEntityBehind.createContextObject({id: Cards.Faction2.KaidoAssassin},"Kaido Assassin") summonAssassinOnMove.isRemovable = false modContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) modContextObject.appliedName = i18next.t("modifiers.boss_25_applied_name") allyMinionMoveBuff = ModifierMyTeamMoveWatchBuffTarget.createContextObject([modContextObject], "give it +1/+1") allyMinionMoveBuff.isRemovable = false card.setInherentModifiersContextObjects([summonAssassinOnMove, allyMinionMoveBuff]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss26) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_26_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_26_bio")) card.setDescription(i18next.t("boss_battles.boss_26_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_gol) card.setPortraitResource(RSX.speech_portrait_gol) card.setPortraitHexResource(RSX.boss_gol_hex_portrait) card.setFXResource(["FX.Cards.Neutral.BloodTaura"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_rook_hit.audio attack : RSX.sfx_neutral_khymera_attack_swing.audio receiveDamage : RSX.sfx_neutral_khymera_hit.audio attackDamage : RSX.sfx_neutral_khymera_impact.audio death : RSX.sfx_neutral_khymera_death.audio ) card.setBaseAnimResource( breathing : RSX.bossGolBreathing.name idle : RSX.bossGolIdle.name walk : RSX.bossGolRun.name attack : RSX.bossGolAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossGolHit.name death : RSX.bossGolDeath.name ) card.atk = 2 card.maxHP = 40 card.speed = 0 attacksDamageAllMinions = ModifierAttacksDamageAllEnemyMinions.createContextObject() attacksDamageAllMinions.isRemovable = false card.setInherentModifiersContextObjects([attacksDamageAllMinions]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss26Companion) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_26_zane_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_26_zane_desc")) card.setFXResource(["FX.Cards.Faction1.RadiantDragoon"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_neutral_arcanelimiter_attack_impact.audio attack : RSX.sfx_neutral_rook_attack_swing.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_rook_attack_impact.audio death : RSX.sfx_neutral_windstopper_death.audio ) card.setBaseAnimResource( breathing : RSX.bossKaneBreathing.name idle : RSX.bossKaneIdle.name walk : RSX.bossKaneRun.name attack : RSX.bossKaneAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossKaneHit.name death : RSX.bossKaneDeath.name ) card.atk = 3 card.maxHP = 20 card.speed = 3 dyingWishKillGeneral = ModifierDyingWishLoseGame.createContextObject() dyingWishKillGeneral.isRemovable = false atkLimiter = ModifierATKThresholdDie.createContextObject(6) atkLimiter.isRemovable = false doubleDamageGenerals = ModifierDoubleDamageToGenerals.createContextObject() doubleDamageGenerals.isRemovable = false card.setInherentModifiersContextObjects([ModifierBattlePet.createContextObject(), doubleDamageGenerals, atkLimiter, dyingWishKillGeneral]) if (identifier == Cards.Boss.Boss27) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_27_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_27_bio")) card.setDescription(i18next.t("boss_battles.boss_27_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_taskmaster) card.setPortraitResource(RSX.speech_portrait_taskmaster) card.setPortraitHexResource(RSX.boss_taskmaster_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Tethermancer"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_neutral_ubo_attack_swing.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_spiritscribe_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTaskmasterBreathing.name idle : RSX.bossTaskmasterIdle.name walk : RSX.bossTaskmasterRun.name attack : RSX.bossTaskmasterAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossTaskmasterHit.name death : RSX.bossTaskmasterDeath.name ) card.atk = 3 card.maxHP = 35 card.speed = 0 battlePetModifier = ModifierBattlePet.createContextObject() battlePetModifier.isRemovable = false summonWatchApplyBattlepet = ModifierSummonWatchAnyPlayerApplyModifiers.createContextObject([battlePetModifier], "act like Battle Pets") summonWatchApplyBattlepet.isRemovable = false speedBuffContextObject = Modifier.createContextObjectOnBoard() speedBuffContextObject.attributeBuffs = {"speed": 0} speedBuffContextObject.attributeBuffsAbsolute = ["speed"] speedBuffContextObject.attributeBuffsFixed = ["speed"] speedBuffContextObject.appliedName = i18next.t("modifiers.faction_3_spell_sand_trap_1") speedBuffContextObject.isRemovable = false speed0Modifier = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([speedBuffContextObject], "The enemy General cannot move") speed0Modifier.isRemovable = false immuneToSpellTargeting = ModifierImmuneToSpellsByEnemy.createContextObject() immuneToSpellTargeting.isRemovable = false card.setInherentModifiersContextObjects([summonWatchApplyBattlepet, speed0Modifier, immuneToSpellTargeting]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss28) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_28_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_28_bio")) card.setDescription(i18next.t("boss_battles.boss_28_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_grym) card.setPortraitResource(RSX.speech_portrait_grym) card.setPortraitHexResource(RSX.boss_grym_hex_portrait) card.setFXResource(["FX.Cards.Faction5.EarthWalker"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_screenshake.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_earthwalker_attack_swing.audio receiveDamage : RSX.sfx_neutral_earthwalker_hit.audio attackDamage : RSX.sfx_neutral_earthwalker_attack_impact.audio death : RSX.sfx_neutral_earthwalker_death.audio ) card.setBaseAnimResource( breathing : RSX.bossGrymBreathing.name idle : RSX.bossGrymIdle.name walk : RSX.bossGrymRun.name attack : RSX.bossGrymAttack.name attackReleaseDelay: 0.0 attackDelay: 0.9 damage : RSX.bossGrymHit.name death : RSX.bossGrymDeath.name ) card.atk = 3 card.maxHP = 30 deathWatchDamageRandomMinionHealGeneral = ModifierDeathWatchDamageRandomMinionHealMyGeneral.createContextObject() deathWatchDamageRandomMinionHealGeneral.isRemovable = false card.setInherentModifiersContextObjects([deathWatchDamageRandomMinionHealGeneral]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss29) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_29_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_29_bio")) card.setDescription(i18next.t("boss_battles.boss_29_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_sandpanther) card.setPortraitResource(RSX.speech_portrait_sandpanther) card.setPortraitHexResource(RSX.boss_sandpanther_hex_portrait) card.setFXResource(["FX.Cards.Faction3.Pantheran"]) card.setBaseSoundResource( apply : RSX.sfx_spell_ghostlightning.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_makantorwarbeast_attack_swing.audio receiveDamage : RSX.sfx_f6_boreanbear_hit.audio attackDamage : RSX.sfx_f6_boreanbear_attack_impact.audio death : RSX.sfx_f6_boreanbear_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSandPantherBreathing.name idle : RSX.bossSandPantherIdle.name walk : RSX.bossSandPantherRun.name attack : RSX.bossSandPantherAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossSandPantherDamage.name death : RSX.bossSandPantherDeath.name ) card.atk = 2 card.maxHP = 40 spawnSandTile = ModifierStartTurnWatchSpawnTile.createContextObject({id: Cards.Tile.SandPortal}, "Exhuming Sands", 1, CONFIG.PATTERN_WHOLE_BOARD) spawnSandTile.isRemovable = false card.setInherentModifiersContextObjects([spawnSandTile]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss30) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_30_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_30_bio")) card.setDescription(i18next.t("boss_battles.boss_30_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_wolfpunch) card.setPortraitResource(RSX.speech_portrait_wolfpunch) card.setPortraitHexResource(RSX.boss_wolfpunch_hex_portrait) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(75) card.setFXResource(["FX.Cards.Faction1.LysianBrawler"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f1lysianbrawler_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_f1lysianbrawler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWolfpunchBreathing.name idle : RSX.bossWolfpunchIdle.name walk : RSX.bossWolfpunchRun.name attack : RSX.bossWolfpunchAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossWolfpunchDamage.name death : RSX.bossWolfpunchDeath.name ) card.atk = 2 card.maxHP = 40 gainATKOpponentTurn = ModifierEndTurnWatchGainTempBuff.createContextObject(4,0,i18next.t("modifiers.boss_30_applied_name")) gainATKOpponentTurn.isRemovable = false celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false startTurnSpawnWolf = ModifierStartTurnWatchSpawnEntity.createContextObject({id: Cards.Faction6.WolfAspect}) startTurnSpawnWolf.isRemovable = false card.setInherentModifiersContextObjects([gainATKOpponentTurn, celerityObject, startTurnSpawnWolf]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss31) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_31_bio")) card.setDescription(i18next.t("boss_battles.boss_31_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_unhallowed) card.setPortraitResource(RSX.speech_portrait_unhallowed) card.setPortraitHexResource(RSX.boss_unhallowed_hex_portrait) card.setFXResource(["FX.Cards.Faction4.DeathKnell"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_spell_icepillar_melt.audio attack : RSX.sfx_f6_waterelemental_death.audio receiveDamage : RSX.sfx_f1windbladecommander_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f1elyxstormblade_death.audio ) card.setBaseAnimResource( breathing : RSX.bossUnhallowedBreathing.name idle : RSX.bossUnhallowedIdle.name walk : RSX.bossUnhallowedRun.name attack : RSX.bossUnhallowedAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossUnhallowedHit.name death : RSX.bossUnhallowedDeath.name ) card.atk = 2 card.maxHP = 50 takeDamageSpawnHaunt = ModifierTakeDamageWatchSpawnRandomHaunt.createContextObject() takeDamageSpawnHaunt.isRemovable = false card.setInherentModifiersContextObjects([takeDamageSpawnHaunt]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss31Treat1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_1_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction2.SonghaiSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat1})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Treat2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_2_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction4.AbyssSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentSummonBuffItDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat2})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Treat3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_3_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction6.VanarSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentSpellCastRefundManaDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat3})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Haunt1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_1_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_1_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatDemonBreathing.name idle : RSX.bossTreatDemonIdle.name walk : RSX.bossTreatDemonRun.name attack : RSX.bossTreatDemonAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatDemonHit.name death : RSX.bossTreatDemonDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Unit) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's minions cost 1 more to play") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss31Haunt2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_2_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_2_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatOniBreathing.name idle : RSX.bossTreatOniIdle.name walk : RSX.bossTreatOniRun.name attack : RSX.bossTreatOniAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatOniHit.name death : RSX.bossTreatOniDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Spell) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's non-Bloodbound spells cost 1 more to cast") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss31Haunt3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_3_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_3_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatDrakeBreathing.name idle : RSX.bossTreatDrakeIdle.name walk : RSX.bossTreatDrakeRun.name attack : RSX.bossTreatDrakeAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatDrakeHit.name death : RSX.bossTreatDrakeDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Artifact) contextObject.activeInHand = contextObject.activeInDeck = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's artifacts cost 1 more to cast") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss32) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_32_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_32_bio")) card.setDescription(i18next.t("boss_battles.boss_32_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_christmas) card.setPortraitResource(RSX.speech_portrait_christmas) card.setPortraitHexResource(RSX.boss_christmas_hex_portrait) card.setBoundingBoxWidth(120) card.setBoundingBoxHeight(95) card.setFXResource(["FX.Cards.Faction6.PrismaticGiant"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_f6_draugarlord_attack_impact.audio death : RSX.sfx_f6_draugarlord_death.audio ) card.setBaseAnimResource( breathing : RSX.bossChristmasBreathing.name idle : RSX.bossChristmasIdle.name walk : RSX.bossChristmasRun.name attack : RSX.bossChristmasAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossChristmasDamage.name death : RSX.bossChristmasDeath.name ) card.atk = 4 card.maxHP = 50 #giftPlayer = ModifierStartTurnWatchPutCardInOpponentsHand.createContextObject({id: Cards.BossSpell.HolidayGift}) #giftPlayer.isRemovable = false startTurnSpawnElf = ModifierStartTurnWatchSpawnEntity.createContextObject({id: Cards.Boss.Boss32_2}) startTurnSpawnElf.isRemovable = false card.setInherentModifiersContextObjects([startTurnSpawnElf]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss32_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_32_elf_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_32_elf_desc")) card.setFXResource(["FX.Cards.Neutral.Zyx"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_emeraldrejuvenator_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_neutral_emeraldrejuvenator_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralZyxFestiveBreathing.name idle : RSX.neutralZyxFestiveIdle.name walk : RSX.neutralZyxFestiveRun.name attack : RSX.neutralZyxFestiveAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralZyxFestiveHit.name death : RSX.neutralZyxFestiveDeath.name ) card.atk = 2 card.maxHP = 3 celerityObject = ModifierTranscendance.createContextObject() rushContextObject = ModifierFirstBlood.createContextObject() dyingWishPresent = ModifierDyingWishPutCardInOpponentHand.createContextObject({id: Cards.BossSpell.HolidayGift}) card.setInherentModifiersContextObjects([celerityObject, dyingWishPresent]) if (identifier == Cards.BossArtifact.FlyingBells) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.FlyingBells card.name = i18next.t("boss_battles.boss_32_gift_1_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_1_desc")) card.addKeywordClassToInclude(ModifierFlying) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierFlying.createContextObject({ type: "ModifierFlying" name: i18next.t("boss_battles.boss_32_gift_1_name") }) ]) card.setFXResource(["FX.Cards.Artifact.MaskOfShadows"]) card.setBaseAnimResource( idle: RSX.bossChristmasJinglebellsIdle.name active: RSX.bossChristmasJinglebellsActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.BossArtifact.Coal) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.Coal card.name = i18next.t("boss_battles.boss_32_gift_2_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_2_desc")) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierCannotCastBBS.createContextObject({ type: "ModifierCannotCastBBS" name: i18next.t("boss_battles.boss_32_gift_2_name") }) ]) card.setFXResource(["FX.Cards.Artifact.PristineScale"]) card.setBaseAnimResource( idle: RSX.bossChristmasCoalIdle.name active: RSX.bossChristmasCoalActive.name ) card.setBaseSoundResource( apply : RSX.sfx_artifact_equip.audio ) if (identifier == Cards.BossArtifact.CostReducer) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.CostReducer card.name = i18next.t("boss_battles.boss_32_gift_3_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_3_desc")) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 artifactContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Artifact) artifactContextObject.activeInHand = artifactContextObject.activeInDeck = false artifactContextObject.activeOnBoard = true spellContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Spell) spellContextObject.activeInHand = spellContextObject.activeInDeck = spellContextObject.activeInSignatureCards = false spellContextObject.activeOnBoard = true minionContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Unit) minionContextObject.activeInHand = minionContextObject.activeInDeck = false minionContextObject.activeOnBoard = true card.setTargetModifiersContextObjects([ ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([artifactContextObject,spellContextObject,minionContextObject], "Cards in your hand cost 1 less to play.") ]) card.setFXResource(["FX.Cards.Artifact.SoulGrimwar"]) card.setBaseAnimResource( idle: RSX.bossChristmasMistletoeIdle.name active: RSX.bossChristmasMistletoeActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.BossSpell.HolidayGift) card = new SpellEquipBossArtifacts(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.id = Cards.Spell.HolidayGift card.name = i18next.t("boss_battles.boss_32_gift_spell_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_spell_desc")) card.manaCost = 1 card.rarityId = Rarity.Legendary card.setFXResource(["FX.Cards.Spell.AutarchsGifts"]) card.setBaseSoundResource( apply : RSX.sfx_spell_entropicdecay.audio ) card.setBaseAnimResource( idle : RSX.bossChristmasPresentIdle.name active : RSX.bossChristmasPresentActive.name ) if (identifier == Cards.BossArtifact.Snowball) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.Snowball card.name = i18next.t("boss_battles.boss_32_gift_4_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_4_desc")) card.addKeywordClassToInclude(ModifierRanged) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierRanged.createContextObject({ type: "ModifierRanged" name: i18next.t("boss_battles.boss_32_gift_4_name") }), Modifier.createContextObjectWithAttributeBuffs(-1,undefined, { name: "Snowball" description: "-1 Attack." }) ]) card.setFXResource(["FX.Cards.Artifact.EternalHeart"]) card.setBaseAnimResource( idle: RSX.bossChristmasSnowballIdle.name active: RSX.bossChristmasSnowballActive.name ) card.setBaseSoundResource( apply : RSX.sfx_artifact_equip.audio ) if (identifier == Cards.Boss.Boss33) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_33_bio")) card.setDescription(i18next.t("boss_battles.boss_33_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_legion) card.setPortraitResource(RSX.speech_portrait_legion) card.setPortraitHexResource(RSX.boss_legion_hex_portrait) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 healObject = ModifierEndTurnWatchHealSelf.createContextObject(3) healObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] healAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([healObject], null, legion, null, "Heals for 3 at end of turn") healAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([healAura, backupGeneral, respawnClones]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss33_1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 healObject = ModifierEndTurnWatchHealSelf.createContextObject(3) healObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] healAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([healObject], null, legion, null, "Heals for 3 at end of turn") healAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([healAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_2_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 attackObject = Modifier.createContextObjectWithAttributeBuffs(2,undefined, { name: "Legion's Strength" description: "+2 Attack." }) attackObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] attackAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([attackObject], null, legion, null, "Gains +2 Attack") attackAura.isRemovable = false attackAura.appliedName = i18next.t("modifiers.boss_33_applied_name_2") backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([attackAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_3_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 speedBuffContextObject = Modifier.createContextObjectOnBoard() speedBuffContextObject.attributeBuffs = {"speed": 3} speedBuffContextObject.attributeBuffsAbsolute = ["speed"] speedBuffContextObject.attributeBuffsFixed = ["speed"] speedBuffContextObject.appliedName = i18next.t("modifiers.boss_33_applied_name") speedBuffContextObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] speedAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([speedBuffContextObject], null, legion, null, "Can move 2 extra spaces") speedAura.isRemovable = false speedAura.appliedName = i18next.t("modifiers.boss_33_applied_name") backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([speedAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_4) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_4_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 immuneToSpellTargeting = ModifierImmuneToSpellsByEnemy.createContextObject() immuneToSpellTargeting.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] spellImmuneAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([immuneToSpellTargeting], null, legion, null, "Cannot be targeted by enemy spells") spellImmuneAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([spellImmuneAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss34) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_34_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_34_bio")) card.setDescription(i18next.t("boss_battles.boss_34_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_harmony) card.setPortraitResource(RSX.speech_portrait_harmony) card.setPortraitHexResource(RSX.boss_harmony_hex_portrait) card.setFXResource(["FX.Cards.Faction2.JadeOgre"]) card.setBoundingBoxWidth(65) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2_jadeogre_attack_impact.audio death : RSX.sfx_f2_jadeogre_death.audio ) card.setBaseAnimResource( breathing : RSX.bossHarmonyBreathing.name idle : RSX.bossHarmonyIdle.name walk : RSX.bossHarmonyRun.name attack : RSX.bossHarmonyAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossHarmonyHit.name death : RSX.bossHarmonyRun.name ) card.atk = 3 card.maxHP = 25 contextObject = PlayerModifierManaModifier.createCostChangeContextObject(-25, CardType.Unit) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true reducedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetBothPlayers([contextObject], "Minions cost 0 mana") reducedManaCost.isRemovable = false spawnDissonance = ModifierDieSpawnNewGeneral.createContextObject({id: Cards.Boss.Boss34_2}) spawnDissonance.isRemovable = false spawnDissonance.isHiddenToUI = true #customContextObject = PlayerModifierManaModifier.createCostChangeContextObject(0, CardType.Unit) #customContextObject.modifiersContextObjects[0].attributeBuffsAbsolute = ["manaCost"] #customContextObject.modifiersContextObjects[0].attributeBuffsFixed = ["manaCost"] #manaReduction = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetBothPlayers([customContextObject], "All minions cost 0 mana.") #manaReduction.isRemovable = false card.setInherentModifiersContextObjects([reducedManaCost, spawnDissonance]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss34_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_34_2_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_34_2_desc")) card.setFXResource(["FX.Cards.Faction2.JadeOgre"]) card.setBoundingBoxWidth(65) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2_jadeogre_attack_impact.audio death : RSX.sfx_f2_jadeogre_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDissonanceBreathing.name idle : RSX.bossDissonanceIdle.name walk : RSX.bossDissonanceRun.name attack : RSX.bossDissonanceAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossDissonanceHit.name death : RSX.bossDissonanceRun.name ) card.atk = 3 card.maxHP = 25 swapAllegiancesGainAttack = ModifierSwitchAllegiancesGainAttack.createContextObject() swapAllegiancesGainAttack.isRemovable = false frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.setInherentModifiersContextObjects([swapAllegiancesGainAttack, frenzyContextObject]) if (identifier == Cards.Boss.Boss35) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_35_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_35_bio")) card.setDescription(i18next.t("boss_battles.boss_35_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_andromeda) card.setPortraitResource(RSX.speech_portrait_andromeda) card.setPortraitHexResource(RSX.boss_andromeda_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Pandora"]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_pandora_attack_swing.audio receiveDamage : RSX.sfx_neutral_pandora_hit.audio attackDamage : RSX.sfx_neutral_pandora_attack_impact.audio death : RSX.sfx_neutral_pandora_death.audio ) card.setBaseAnimResource( breathing : RSX.bossAndromedaBreathing.name idle : RSX.bossAndromedaIdle.name walk : RSX.bossAndromedaRun.name attack : RSX.bossAndromedaAttack.name attackReleaseDelay: 0.0 attackDelay: 1.0 damage : RSX.bossAndromedaHit.name death : RSX.bossAndromedaDeath.name ) card.atk = 3 card.maxHP = 42 randomTransformMinions = ModifierOpponentSummonWatchRandomTransform.createContextObject() randomTransformMinions.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false card.setInherentModifiersContextObjects([randomTransformMinions, flyingObject]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss36) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_36_bio")) card.setDescription(i18next.t("boss_battles.boss_36_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_kaiju) card.setPortraitResource(RSX.speech_portrait_kaiju) card.setPortraitHexResource(RSX.boss_kaiju_hex_portrait) card.setFXResource(["FX.Cards.Faction3.GrandmasterNoshRak"]) card.setBaseSoundResource( apply : RSX.sfx_spell_ghostlightning.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_makantorwarbeast_attack_swing.audio receiveDamage : RSX.sfx_f6_boreanbear_hit.audio attackDamage : RSX.sfx_f6_boreanbear_attack_impact.audio death : RSX.sfx_f6_boreanbear_death.audio ) card.setBaseAnimResource( breathing : RSX.bossInvaderBreathing.name idle : RSX.bossInvaderIdle.name walk : RSX.bossInvaderRun.name attack : RSX.bossInvaderAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossInvaderHit.name death : RSX.bossInvaderDeath.name ) card.atk = 3 card.maxHP = 80 damageRandom = ModifierStartTurnWatchDamageRandom.createContextObject(6) damageRandom.isRemovable = false card.setInherentModifiersContextObjects([damageRandom]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss36_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_2_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_36_2_desc")) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction1.IroncliffeGuardian"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossProtectorBreathing.name idle : RSX.bossProtectorIdle.name walk : RSX.bossProtectorRun.name attack : RSX.bossProtectorAttack.name attackReleaseDelay: 0.0 attackDelay: 0.7 damage : RSX.bossProtectorDamage.name death : RSX.bossProtectorDeath.name ) card.atk = 1 card.maxHP = 50 replaceGeneral = ModifierOnSpawnKillMyGeneral.createContextObject() replaceGeneral.isRemovable = false gainAttackOnKill = ModifierDeathWatchGainAttackEqualToEnemyAttack.createContextObject() gainAttackOnKill.isRemovable = false card.setInherentModifiersContextObjects([replaceGeneral, gainAttackOnKill]) if (identifier == Cards.Boss.Boss36_3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_3_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_36_3_desc")) card.raceId = Races.Structure card.setFXResource(["FX.Cards.Faction3.BrazierDuskWind"]) card.setBaseSoundResource( apply : RSX.sfx_spell_divinebond.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_monsterdreamoracle_attack_swing.audio receiveDamage : RSX.sfx_neutral_monsterdreamoracle_hit.audio attackDamage : RSX.sfx_f1_general_attack_impact.audio death : RSX.sfx_neutral_golembloodshard_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCityBreathing.name idle : RSX.bossCityIdle.name walk : RSX.bossCityIdle.name attack : RSX.bossCityAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossCityDamage.name death : RSX.bossCityDeath.name ) card.atk = 0 card.maxHP = 3 buffEnemyGeneralOnDeath = ModifierDyingWishBuffEnemyGeneral.createContextObject(2,6) buffEnemyGeneralOnDeath.isRemovable = false card.setInherentModifiersContextObjects([buffEnemyGeneralOnDeath]) if (identifier == Cards.Boss.Boss37) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_37_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_37_bio")) card.setDescription(i18next.t("boss_battles.boss_37_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_soulstealer) card.setPortraitResource(RSX.speech_portrait_soulstealer) card.setPortraitHexResource(RSX.boss_soulstealer_hex_portrait) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSoulstealerBreathing.name idle : RSX.bossSoulstealerIdle.name walk : RSX.bossSoulstealerRun.name attack : RSX.bossSoulstealerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossSoulstealerDamage.name death : RSX.bossSoulstealerDeath.name ) card.atk = 3 card.maxHP = 30 enemyMinionGeneralSwap = PlayerModifierOpponentSummonWatchSwapGeneral.createContextObject() enemyMinionGeneralSwap.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false backupGeneral.appliedName = i18next.t("modifiers.boss_37_applied_name") backupGeneral.appliedDescription = i18next.t("modifiers.boss_37_applied_desc") applyModifierToSummonedMinions = PlayerModifierSummonWatchApplyModifiers.createContextObject([backupGeneral], i18next.t("modifiers.boss_37_applied_name")) applyModifierToSummonedMinions.isRemovable = false #applyBackUpGeneralApplyingModifierToSummonedMinions = ModifierSummonWatchFromActionBarApplyModifiers.createContextObject([applyModifierToSummonedMinions], "Soul Vessel") #applyBackUpGeneralApplyingModifierToSummonedMinions.isRemovable = false card.setInherentModifiersContextObjects([enemyMinionGeneralSwap, applyModifierToSummonedMinions]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss38) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_38_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_38_bio")) card.setDescription(i18next.t("boss_battles.boss_38_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_spelleater) card.setPortraitResource(RSX.speech_portrait_spelleater) card.setPortraitHexResource(RSX.boss_spelleater_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Grailmaster"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(105) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_neutral_sai_attack_impact.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_spiritscribe_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSpelleaterBreathing.name idle : RSX.bossSpelleaterIdle.name walk : RSX.bossSpelleaterRun.name attack : RSX.bossSpelleaterAttack.name attackReleaseDelay: 0.0 attackDelay: 0.9 damage : RSX.bossSpelleaterHit.name death : RSX.bossSpelleaterDeath.name ) card.atk = 3 card.maxHP = 35 spellWatchGainKeyword = ModifierEnemySpellWatchGainRandomKeyword.createContextObject() spellWatchGainKeyword.isRemovable = false summonsGainKeywords = ModifierAnySummonWatchGainGeneralKeywords.createContextObject() summonsGainKeywords.isRemovable = false card.setInherentModifiersContextObjects([spellWatchGainKeyword, summonsGainKeywords]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.FrostfireImp) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_imp_name") card.manaCost = 0 card.setDescription(i18next.t("cards.faction_1_unit_lysian_brawler_desc")) card.setFXResource(["FX.Cards.Neutral.Zyx"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_emeraldrejuvenator_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_neutral_emeraldrejuvenator_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralZyxFestiveBreathing.name idle : RSX.neutralZyxFestiveIdle.name walk : RSX.neutralZyxFestiveRun.name attack : RSX.neutralZyxFestiveAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralZyxFestiveHit.name death : RSX.neutralZyxFestiveDeath.name ) card.atk = 2 card.maxHP = 3 card.setInherentModifiersContextObjects([ModifierTranscendance.createContextObject()]) if (identifier == Cards.Boss.FrostfireTiger) card = new Unit(gameSession) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_tiger_name") card.setDescription(i18next.t("cards.neutral_saberspine_tiger_desc")) card.setFXResource(["FX.Cards.Neutral.SaberspineTiger"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f6_boreanbear_attack_swing.audio receiveDamage : RSX.sfx_neutral_beastsaberspinetiger_hit.audio attackDamage : RSX.sfx_neutral_beastsaberspinetiger_attack_impact.audio death : RSX.sfx_neutral_beastsaberspinetiger_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralFrostfireTigerBreathing.name idle : RSX.neutralFrostfireTigerIdle.name walk : RSX.neutralFrostfireTigerRun.name attack : RSX.neutralFrostfireTigerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.neutralFrostfireTigerHit.name death : RSX.neutralFrostfireTigerDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 4 card.setInherentModifiersContextObjects([ModifierFirstBlood.createContextObject()]) if (identifier == Cards.Boss.FrostfireSnowchaser) card = new Unit(gameSession) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_snowchser_name") card.setDescription(i18next.t("cards.neutral_vale_hunter_desc")) card.raceId = Races.Vespyr card.setFXResource(["FX.Cards.Faction6.SnowElemental"]) card.setBaseSoundResource( apply : RSX.sfx_spell_amplification.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_artifacthunter_attack_swing.audio receiveDamage : RSX.sfx_neutral_artifacthunter_hit.audio attackDamage : RSX.sfx_neutral_artifacthunter_attack_impact.audio death : RSX.sfx_neutral_artifacthunter_death.audio ) card.setBaseAnimResource( breathing : RSX.f6FestiveSnowchaserBreathing.name idle : RSX.f6FestiveSnowchaserIdle.name walk : RSX.f6FestiveSnowchaserRun.name attack : RSX.f6FestiveSnowchaserAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.f6FestiveSnowchaserDamage.name death : RSX.f6FestiveSnowchaserDeath.name ) card.atk = 2 card.maxHP = 1 card.manaCost = 1 card.setInherentModifiersContextObjects([ModifierRanged.createContextObject()]) if (identifier == Cards.BossSpell.LaceratingFrost) card = new SpellLaceratingFrost(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.LaceratingFrost card.name = "<NAME>" card.setDescription("Deal 2 damage to the enemy General and stun all nearby enemy minions.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.damageAmount = 2 card.setFXResource(["FX.Cards.Spell.LaceratingFrost"]) card.setBaseSoundResource( apply : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( idle : RSX.iconLaceratingFrostIdle.name active : RSX.iconLaceratingFrostActive.name ) if (identifier == Cards.BossSpell.EntanglingShadow) card = new SpellEntanglingShadows(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.EntanglingShadow card.name = "Entangling Shadow" card.setDescription("Summon Wraithlings and Shadow Creep in a 2x2 area.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.setAffectPattern(CONFIG.PATTERN_2X2) card.cardDataOrIndexToSpawn = {id: Cards.Faction4.Wraithling} card.setFXResource(["FX.Cards.Spell.EntanglingShadow"]) card.setBaseSoundResource( apply : RSX.sfx_spell_shadowreflection.audio ) card.setBaseAnimResource( idle : RSX.iconCultivatingDarkIdle.name active : RSX.iconCultivatingDarkActive.name ) if (identifier == Cards.BossSpell.LivingFlame) card = new SpellDamageAndSpawnEntitiesNearbyGeneral(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.LivingFlame card.name = "Living Fl<NAME>" card.setDescription("Deal 2 damage to an enemy and summon two Spellsparks nearby your General.") card.spellFilterType = SpellFilterType.EnemyDirect card.manaCost = 1 card.damageAmount = 2 card.canTargetGeneral = true card.cardDataOrIndexToSpawn = {id: Cards.Neutral.Spellspark} card.setFXResource(["FX.Cards.Spell.LivingFlame"]) card.setBaseSoundResource( apply : RSX.sfx_spell_phoenixfire.audio ) card.setBaseAnimResource( idle : RSX.iconLivingFlameIdle.name active : RSX.iconLivingFlameActive.name ) if (identifier == Cards.BossSpell.MoldingEarth) card = new SpellMoldingEarth(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.MoldingEarth card.name = "Molding Earth" card.setDescription("Summon 3 Magmas with random keywords nearby your General.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.cardDataOrIndexToSpawn = {id: Cards.Faction5.MiniMagmar} card.setFXResource(["FX.Cards.Spell.MoldingEarth"]) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) card.setBaseAnimResource( idle : RSX.iconModlingEarthIdle.name active : RSX.iconModlingEarthActive.name ) if (identifier == Cards.BossSpell.EtherealWind) card = new SpellSilenceAndSpawnEntityNearby(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.EtherealWind card.name = "Ethereal Wind" card.setDescription("Dispel an enemy and summon a Wind Dervish nearby.") card.spellFilterType = SpellFilterType.EnemyDirect card.manaCost = 1 card.canTargetGeneral = true card.cardDataOrIndexToSpawn = {id: Cards.Faction3.Dervish} card.setFXResource(["FX.Cards.Spell.EtherealWind"]) card.setBaseSoundResource( apply : RSX.sfx_spell_entropicdecay.audio ) card.setBaseAnimResource( idle : RSX.iconEtherealWindIdle.name active : RSX.iconEtherealWindActive.name ) if (identifier == Cards.BossSpell.RestoringLight) card = new SpellRestoringLight(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.RestoringLight card.name = "Restoring Light" card.setDescription("Restore 3 Health to your General. Give your friendly minions +1 Health.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 buffContextObject = Modifier.createContextObjectWithAttributeBuffs(0,1) buffContextObject.appliedName = "Restored Light" card.setTargetModifiersContextObjects([ buffContextObject ]) card.setFXResource(["FX.Cards.Spell.RestoringLight"]) card.setBaseSoundResource( apply : RSX.sfx_spell_sunbloom.audio ) card.setBaseAnimResource( idle : RSX.iconRestoringLightIdle.name active : RSX.iconRestoringLightActive.name ) if (identifier == Cards.BossSpell.AncientKnowledge) card = new Spell(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.AncientKnowledge card.name = "<NAME>cient Knowledge" card.setDescription("Draw 2 cards.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.drawCardsPostPlay = 2 card.setFXResource(["FX.Cards.Spell.AncientKnowledge"]) card.setBaseSoundResource( apply : RSX.sfx_spell_scionsfirstwish.audio ) card.setBaseAnimResource( idle : RSX.iconAncientKnowledgeIdle.name active : RSX.iconAncientKnowledgeActive.name ) return card module.exports = CardFactory_Bosses
true
# do not add this file to a package # it is specifically parsed by the package generation script _ = require 'underscore' moment = require 'moment' i18next = require 'i18next' if i18next.t() is undefined i18next.t = (text) -> return text Logger = require 'app/common/logger' CONFIG = require('app/common/config') RSX = require('app/data/resources') Card = require 'app/sdk/cards/card' Cards = require 'app/sdk/cards/cardsLookupComplete' CardType = require 'app/sdk/cards/cardType' Factions = require 'app/sdk/cards/factionsLookup' FactionFactory = require 'app/sdk/cards/factionFactory' Races = require 'app/sdk/cards/racesLookup' Rarity = require 'app/sdk/cards/rarityLookup' Unit = require 'app/sdk/entities/unit' Artifact = require 'app/sdk/artifacts/artifact' Spell = require 'app/sdk/spells/spell' SpellFilterType = require 'app/sdk/spells/spellFilterType' SpellSpawnEntity = require 'app/sdk/spells/spellSpawnEntity' SpellApplyModifiers = require 'app/sdk/spells/spellApplyModifiers' SpellEquipBossArtifacts = require 'app/sdk/spells/spellEquipBossArtifacts' SpellLaceratingFrost = require 'app/sdk/spells/spellLaceratingFrost' SpellEntanglingShadows = require 'app/sdk/spells/spellEntanglingShadows' SpellMoldingEarth = require 'app/sdk/spells/spellMoldingEarth' SpellDamageAndSpawnEntitiesNearbyGeneral = require 'app/sdk/spells/spellDamageAndSpawnEntitiesNearbyGeneral' SpellSilenceAndSpawnEntityNearby = require 'app/sdk/spells/spellSilenceAndSpawnEntityNearby' SpellRestoringLight = require 'app/sdk/spells/spellRestoringLight' Modifier = require 'app/sdk/modifiers/modifier' PlayerModifierManaModifier = require 'app/sdk/playerModifiers/playerModifierManaModifier' ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke' ModifierEndTurnWatchDamageNearbyEnemy = require 'app/sdk/modifiers/modifierEndTurnWatchDamageNearbyEnemy' ModifierFrenzy = require 'app/sdk/modifiers/modifierFrenzy' ModifierFlying = require 'app/sdk/modifiers/modifierFlying' ModifierTranscendance = require 'app/sdk/modifiers/modifierTranscendance' ModifierProvoke = require 'app/sdk/modifiers/modifierProvoke' ModifierRanged = require 'app/sdk/modifiers/modifierRanged' ModifierFirstBlood = require 'app/sdk/modifiers/modifierFirstBlood' ModifierRebirth = require 'app/sdk/modifiers/modifierRebirth' ModifierBlastAttack = require 'app/sdk/modifiers/modifierBlastAttack' ModifierForcefield = require 'app/sdk/modifiers/modifierForcefield' ModifierStartTurnWatchEquipArtifact = require 'app/sdk/modifiers/modifierStartTurnWatchEquipArtifact' ModifierTakeDamageWatchSpawnRandomToken = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnRandomToken' ModifierDealDamageWatchKillTarget = require 'app/sdk/modifiers/modifierDealDamageWatchKillTarget' ModifierStartTurnWatchPlaySpell = require 'app/sdk/modifiers/modifierStartTurnWatchPlaySpell' ModifierDealDamageWatchModifyTarget = require 'app/sdk/modifiers/modifierDealDamageWatchModifyTarget' ModifierStunned = require 'app/sdk/modifiers/modifierStunned' ModifierStunnedVanar = require 'app/sdk/modifiers/modifierStunnedVanar' ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers' ModifierBattlePet = require 'app/sdk/modifiers/modifierBattlePet' ModifierImmuneToDamage = require 'app/sdk/modifiers/modifierImmuneToDamage' ModifierStartTurnWatchDispelAllEnemyMinionsDrawCard = require 'app/sdk/modifiers/modifierStartTurnWatchDispelAllEnemyMinionsDrawCard' ModifierImmuneToSpellsByEnemy = require 'app/sdk/modifiers/modifierImmuneToSpellsByEnemy' ModifierAbsorbDamageGolems = require 'app/sdk/modifiers/modifierAbsorbDamageGolems' ModifierExpireApplyModifiers = require 'app/sdk/modifiers/modifierExpireApplyModifiers' ModifierSecondWind = require 'app/sdk/modifiers/modifierSecondWind' ModifierKillWatchRespawnEntity = require 'app/sdk/modifiers/modifierKillWatchRespawnEntity' ModifierOpponentSummonWatchSpawn1HealthClone = require 'app/sdk/modifiers/modifierOpponentSummonWatchSpawn1HealthClone' ModifierDealOrTakeDamageWatchRandomTeleportOther = require 'app/sdk/modifiers/modifierDealOrTakeDamageWatchRandomTeleportOther' ModifierMyAttackOrAttackedWatchSpawnMinionNearby = require 'app/sdk/modifiers/modifierMyAttackOrAttackedWatchSpawnMinionNearby' ModifierEndTurnWatchTeleportCorner = require 'app/sdk/modifiers/modifierEndTurnWatchTeleportCorner' ModifierBackstab = require 'app/sdk/modifiers/modifierBackstab' ModifierDieSpawnNewGeneral = require 'app/sdk/modifiers/modifierDieSpawnNewGeneral' ModifierKillWatchRefreshExhaustion = require 'app/sdk/modifiers/modifierKillWatchRefreshExhaustion' ModifierEndTurnWatchDealDamageToSelfAndNearbyEnemies = require 'app/sdk/modifiers/modifierEndTurnWatchDealDamageToSelfAndNearbyEnemies' ModifierDispelAreaAttack = require 'app/sdk/modifiers/modifierDispelAreaAttack' ModifierSelfDamageAreaAttack = require 'app/sdk/modifiers/modifierSelfDamageAreaAttack' ModifierMyMinionOrGeneralDamagedWatchBuffSelf = require 'app/sdk/modifiers/modifierMyMinionOrGeneralDamagedWatchBuffSelf' ModifierSummonWatchNearbyAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchNearbyAnyPlayerApplyModifiers' ModifierOpponentSummonWatchOpponentDrawCard = require 'app/sdk/modifiers/modifierOpponentSummonWatchOpponentDrawCard' ModifierOpponentDrawCardWatchOverdrawSummonEntity = require 'app/sdk/modifiers/modifierOpponentDrawCardWatchOverdrawSummonEntity' ModifierEndTurnWatchDamagePlayerBasedOnRemainingMana = require 'app/sdk/modifiers/modifierEndTurnWatchDamagePlayerBasedOnRemainingMana' ModifierHPThresholdGainModifiers = require 'app/sdk/modifiers/modifierHPThresholdGainModifiers' ModifierHealSelfWhenDealingDamage = require 'app/sdk/modifiers/modifierHealSelfWhenDealingDamage' ModifierExtraDamageOnCounterattack = require 'app/sdk/modifiers/modifierExtraDamageOnCounterattack' ModifierOnOpponentDeathWatchSpawnEntityOnSpace = require 'app/sdk/modifiers/modifierOnOpponentDeathWatchSpawnEntityOnSpace' ModifierDyingWishSpawnEgg = require 'app/sdk/modifiers/modifierDyingWishSpawnEgg' ModifierSummonWatchFromActionBarApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchFromActionBarApplyModifiers' ModifierGrowPermanent = require 'app/sdk/modifiers/modifierGrowPermanent' ModifierTakeDamageWatchSpawnWraithlings = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnWraithlings' ModifierTakeDamageWatchDamageAttacker = require 'app/sdk/modifiers/modifierTakeDamageWatchDamageAttacker' ModifierAbsorbDamage = require 'app/sdk/modifiers/modifierAbsorbDamage' ModifierDyingWishDamageNearbyEnemies = require 'app/sdk/modifiers/modifierDyingWishDamageNearbyEnemies' ModifierStartTurnWatchTeleportRandomSpace = require 'app/sdk/modifiers/modifierStartTurnWatchTeleportRandomSpace' ModifierSummonWatchFromActionBarAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchFromActionBarAnyPlayerApplyModifiers' ModifierStartTurnWatchDamageGeneralEqualToMinionsOwned = require 'app/sdk/modifiers/modifierStartTurnWatchDamageGeneralEqualToMinionsOwned' ModifierDeathWatchDamageEnemyGeneralHealMyGeneral = require 'app/sdk/modifiers/modifierDeathWatchDamageEnemyGeneralHealMyGeneral' ModifierRangedProvoke = require 'app/sdk/modifiers/modifierRangedProvoke' ModifierHPChangeSummonEntity = require 'app/sdk/modifiers/modifierHPChangeSummonEntity' ModifierStartTurnWatchDamageAndBuffSelf = require 'app/sdk/modifiers/modifierStartTurnWatchDamageAndBuffSelf' ModifierEnemyTeamMoveWatchSummonEntityBehind = require 'app/sdk/modifiers/modifierEnemyTeamMoveWatchSummonEntityBehind' ModifierMyTeamMoveWatchBuffTarget = require 'app/sdk/modifiers/modifierMyTeamMoveWatchAnyReasonBuffTarget' ModifierDyingWishLoseGame = require 'app/sdk/modifiers/modifierDyingWishLoseGame' ModifierAttacksDamageAllEnemyMinions = require 'app/sdk/modifiers/modifierAttacksDamageAllEnemyMinions' ModifierSummonWatchAnyPlayerApplyModifiers = require 'app/sdk/modifiers/modifierSummonWatchAnyPlayerApplyModifiers' ModifierDoubleDamageToGenerals = require 'app/sdk/modifiers/modifierDoubleDamageToGenerals' ModifierATKThresholdDie = require 'app/sdk/modifiers/modifierATKThresholdDie' ModifierDeathWatchDamageRandomMinionHealMyGeneral = require 'app/sdk/modifiers/modifierDeathWatchDamageRandomMinionHealMyGeneral' ModifierStartTurnWatchSpawnTile = require 'app/sdk/modifiers/modifierStartTurnWatchSpawnTile' ModifierStartTurnWatchSpawnEntity = require 'app/sdk/modifiers/modifierStartTurnWatchSpawnEntity' ModifierEndTurnWatchGainTempBuff = require 'app/sdk/modifiers/modifierEndTurnWatchGainTempBuff' ModifierSentinel = require 'app/sdk/modifiers/modifierSentinel' ModifierSentinelSetup = require 'app/sdk/modifiers/modifierSentinelSetup' ModifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard' ModifierSentinelOpponentSummonBuffItDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentSummonBuffItDrawCard' ModifierSentinelOpponentSpellCastRefundManaDrawCard = require 'app/sdk/modifiers/modifierSentinelOpponentSpellCastRefundManaDrawCard' ModifierTakeDamageWatchSpawnRandomHaunt = require 'app/sdk/modifiers/modifierTakeDamageWatchSpawnRandomHaunt' ModifierDyingWishDrawCard = require "app/sdk/modifiers/modifierDyingWishDrawCard" ModifierCannotAttackGeneral = require 'app/sdk/modifiers/modifierCannotAttackGeneral' ModifierCannotCastBBS = require 'app/sdk/modifiers/modifierCannotCastBBS' ModifierStartTurnWatchPutCardInOpponentsHand = require 'app/sdk/modifiers/modifierStartTurnWatchPutCardInOpponentsHand' ModifierEndTurnWatchHealSelf = require 'app/sdk/modifiers/modifierEndTurnWatchHealSelf' ModifierBackupGeneral = require 'app/sdk/modifiers/modifierBackupGeneral' ModifierStartTurnWatchRespawnClones = require 'app/sdk/modifiers/modifierStartTurnWatchRespawnClones' ModifierCardControlledPlayerModifiers = require 'app/sdk/modifiers/modifierCardControlledPlayerModifiers' ModifierSwitchAllegiancesGainAttack = require 'app/sdk/modifiers/modifierSwitchAllegiancesGainAttack' ModifierOpponentSummonWatchRandomTransform = require 'app/sdk/modifiers/modifierOpponentSummonWatchRandomTransform' ModifierOnSpawnKillMyGeneral = require 'app/sdk/modifiers/modifierOnSpawnKillMyGeneral' ModifierDeathWatchGainAttackEqualToEnemyAttack = require 'app/sdk/modifiers/modifierDeathWatchGainAttackEqualToEnemyAttack' ModifierDyingWishBuffEnemyGeneral = require 'app/sdk/modifiers/modifierDyingWishBuffEnemyGeneral' ModifierStartTurnWatchDamageRandom = require 'app/sdk/modifiers/modifierStartTurnWatchDamageRandom' ModifierOpponentSummonWatchSwapGeneral = require 'app/sdk/modifiers/modifierOpponentSummonWatchSwapGeneral' ModifierDyingWishPutCardInOpponentHand = require 'app/sdk/modifiers/modifierDyingWishPutCardInOpponentHand' ModifierEnemySpellWatchGainRandomKeyword = require 'app/sdk/modifiers/modifierEnemySpellWatchGainRandomKeyword' ModifierAnySummonWatchGainGeneralKeywords = require 'app/sdk/modifiers/modifierAnySummonWatchGainGeneralKeywords' PlayerModifierSummonWatchApplyModifiers = require 'app/sdk/playerModifiers/playerModifierSummonWatchApplyModifiers' PlayerModifierOpponentSummonWatchSwapGeneral = require 'app/sdk/playerModifiers/playerModifierOpponentSummonWatchSwapGeneral' class CardFactory_Bosses ###* * Returns a card that matches the identifier. * @param {Number|String} identifier * @param {GameSession} gameSession * @returns {Card} ### @cardForIdentifier: (identifier,gameSession) -> card = null if (identifier == Cards.Boss.Boss1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_1_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_1_bio")) card.setDescription(i18next.t("boss_battles.boss_1_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_boreal_juggernaut) card.setPortraitResource(RSX.speech_portrait_boreal_juggernaut) card.setPortraitHexResource(RSX.boss_boreal_juggernaut_hex_portrait) card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setBoundingBoxWidth(120) card.setBoundingBoxHeight(95) card.setFXResource(["FX.Cards.Faction5.Dreadnaught"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_rook_attack_impact.audio receiveDamage : RSX.sfx_neutral_makantorwarbeast_hit.audio attackDamage : RSX.sfx_neutral_silitharveteran_attack_impact.audio death : RSX.sfx_neutral_makantorwarbeast_death.audio ) card.setBaseAnimResource( breathing : RSX.bossBorealJuggernautBreathing.name idle : RSX.bossBorealJuggernautIdle.name walk : RSX.bossBorealJuggernautRun.name attack : RSX.bossBorealJuggernautAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossBorealJuggernautHit.name death : RSX.bossBorealJuggernautDeath.name ) card.atk = 5 card.speed = 1 card.maxHP = 40 frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.addKeywordClassToInclude(ModifierStunned) stunContextObject = ModifierDealDamageWatchModifyTarget.createContextObject([ModifierStunnedVanar.createContextObject()], "it is STUNNED",{ name: "PI:NAME:<NAME>END_PI" description: "Enemy minions damaged by your General are Stunned" }) stunContextObject.isRemovable = false #startTurnCastFrostburnObject = ModifierStartTurnWatchPlaySpell.createContextObject({id: Cards.Spell.Frostburn, manaCost: 0}, "Frostburn") #startTurnCastFrostburnObject.isRemovable = false card.setInherentModifiersContextObjects([frenzyContextObject, stunContextObject]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_2_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_2_bio")) card.setDescription(i18next.t("boss_battles.boss_2_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_umbra) card.setPortraitResource(RSX.speech_portrait_umbra) card.setPortraitHexResource(RSX.boss_umbra_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setBoundingBoxWidth(75) card.setBoundingBoxHeight(75) card.setFXResource(["FX.Cards.Neutral.MirkbloodDevourer"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_mirkblooddevourer_attack_swing.audio receiveDamage : RSX.sfx_neutral_mirkblooddevourer_hit.audio attackDamage : RSX.sfx_neutral_mirkblooddevourer_attack_impact.audio death : RSX.sfx_neutral_mirkblooddevourer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossUmbraBreathing.name idle : RSX.bossUmbraIdle.name walk : RSX.bossUmbraRun.name attack : RSX.bossUmbraAttack.name attackReleaseDelay: 0.0 attackDelay: 1.25 damage : RSX.bossUmbraHit.name death : RSX.bossUmbraDeath.name ) card.atk = 2 card.maxHP = 30 modifierSpawnClone = ModifierOpponentSummonWatchSpawn1HealthClone.createContextObject("a 1 health clone") modifierSpawnClone.isRemovable = false card.setInherentModifiersContextObjects([modifierSpawnClone]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_3_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_3_bio")) card.setDescription(i18next.t("boss_battles.boss_3_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 30 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false excludedArtifacts = [ Cards.Artifact.Spinecleaver, Cards.Artifact.IndomitableWill ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, excludedArtifacts) equipArtifactObject.isRemovable = false card.setInherentModifiersContextObjects([ forceFieldObject, equipArtifactObject ]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.QABoss3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = "QA-IBERO" card.manaCost = 0 card.setBossBattleDescription("A Dev Boss for quickly testing flow.") card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 1 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false excludedArtifacts = [ Cards.Artifact.Spinecleaver, Cards.Artifact.IndomitableWill ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, excludedArtifacts) equipArtifactObject.isRemovable = false card.setInherentModifiersContextObjects([ equipArtifactObject ]) if (identifier == Cards.Boss.Boss4) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_4_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_4_bio")) card.setDescription(i18next.t("boss_battles.boss_4_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_chaos_knight) card.setPortraitResource(RSX.speech_portrait_chaos_knight) card.setPortraitHexResource(RSX.boss_chaos_knight_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Ironclad"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossChaosKnightBreathing.name idle : RSX.bossChaosKnightIdle.name walk : RSX.bossChaosKnightRun.name attack : RSX.bossChaosKnightAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.bossChaosKnightHit.name death : RSX.bossChaosKnightDeath.name ) card.atk = 3 card.maxHP = 35 frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false dealOrTakeDamageRandomTeleportObject = ModifierDealOrTakeDamageWatchRandomTeleportOther.createContextObject() dealOrTakeDamageRandomTeleportObject.isRemovable = false card.setInherentModifiersContextObjects([frenzyContextObject, dealOrTakeDamageRandomTeleportObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss5) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_5_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_5_bio")) card.setDescription(i18next.t("boss_battles.boss_5_desc")) card.setBossBattleBattleMapIndex(4) card.setSpeechResource(RSX.speech_portrait_shinkage_zendo) card.setPortraitResource(RSX.speech_portrait_shinkage_zendo) card.setPortraitHexResource(RSX.boss_shinkage_zendo_hex_portrait) card.setConceptResource(RSX.boss_shinkage_zendo_versus_portrait) card.setFXResource(["FX.Cards.Faction2.GrandmasterZendo"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_run_magical_3.audio attack : RSX.sfx_spell_darkseed.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_daggerkiri_attack_swing.audio death : RSX.sfx_neutral_prophetofthewhite_death.audio ) card.setBaseAnimResource( breathing : RSX.bossShinkageZendoBreathing.name idle : RSX.bossShinkageZendoIdle.name walk : RSX.bossShinkageZendoRun.name attack : RSX.bossShinkageZendoAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.bossShinkageZendoHit.name death : RSX.bossShinkageZendoDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 6 card.maxHP = 20 card.speed = 0 immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], i18next.t("modifiers.boss_5_applied_desc")) immunityContextObject.appliedName = i18next.t("modifiers.boss_5_applied_name") applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, null, null, "Cannot be damaged while friendly minions live") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = true zendoBattlePetContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([ModifierBattlePet.createContextObject()], "The enemy General moves and attacks as if they are a Battle Pet") #zendoBattlePetContextObject = Modifier.createContextObjectWithOnBoardAuraForAllEnemies([ModifierBattlePet.createContextObject()], "All enemies move and attack as if they are Battle Pets") zendoBattlePetContextObject.isRemovable = false card.setInherentModifiersContextObjects([applyGeneralImmunityContextObject, zendoBattlePetContextObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss6) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_6_bio")) card.setDescription(i18next.t("boss_battles.boss_6_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_decepticle) card.setPortraitResource(RSX.speech_portrait_decepticle) card.setPortraitHexResource(RSX.boss_decepticle_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Mechaz0rHelm"]) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_wingsmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_wingsmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_wingsmechaz0r_impact.audio death : RSX.sfx_neutral_wingsmechaz0r_hit.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleBreathing.name idle : RSX.bossDecepticleIdle.name walk : RSX.bossDecepticleRun.name attack : RSX.bossDecepticleAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossDecepticleHit.name death : RSX.bossDecepticleDeath.name ) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(50) card.atk = 2 card.maxHP = 1 immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], "Decepticle cannot be damaged while this minion lives.") immunityContextObject.appliedName = i18next.t("modifiers.boss_6_applied_name") mechs = [ Cards.Boss.Boss6Wings, Cards.Boss.Boss6Chassis, Cards.Boss.Boss6Sword, Cards.Boss.Boss6Helm ] applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, mechs, null, "Cannot be damaged while other D3cepticle parts live") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = false provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false spawnPrimeBoss = ModifierDieSpawnNewGeneral.createContextObject({id: Cards.Boss.Boss6Prime}) spawnPrimeBoss.isRemovable = false spawnPrimeBoss.isHiddenToUI = true card.setInherentModifiersContextObjects([applyGeneralImmunityContextObject, provokeObject, spawnPrimeBoss]) #card.setInherentModifiersContextObjects([provokeObject, spawnPrimeBoss]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss6Wings) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part1_name") card.setDescription(i18next.t("boss_battles.boss_6_part1_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rWings"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_wingsmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_wingsmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_wingsmechaz0r_impact.audio death : RSX.sfx_neutral_wingsmechaz0r_hit.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleWingsBreathing.name idle : RSX.bossDecepticleWingsIdle.name walk : RSX.bossDecepticleWingsRun.name attack : RSX.bossDecepticleWingsAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossDecepticleWingsHit.name death : RSX.bossDecepticleWingsDeath.name ) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(50) card.atk = 2 card.maxHP = 3 flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false card.setInherentModifiersContextObjects([flyingObject]) if (identifier == Cards.Boss.Boss6Chassis) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part2_name") card.setDescription(i18next.t("boss_battles.boss_6_part2_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rChassis"]) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio death : RSX.sfx_neutral_hailstonehowler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleChassisBreathing.name idle : RSX.bossDecepticleChassisIdle.name walk : RSX.bossDecepticleChassisRun.name attack : RSX.bossDecepticleChassisAttack.name attackReleaseDelay: 0.0 attackDelay: 0.5 damage : RSX.bossDecepticleChassisHit.name death : RSX.bossDecepticleChassisDeath.name ) card.atk = 5 card.maxHP = 4 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false card.setInherentModifiersContextObjects([forceFieldObject]) if (identifier == Cards.Boss.Boss6Sword) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part3_name") card.setDescription(i18next.t("boss_battles.boss_6_part3_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rSword"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_3.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_swordmechaz0r_attack_swing.audio receiveDamage : RSX.sfx_neutral_swordmechaz0r_hit.audio attackDamage : RSX.sfx_neutral_swordmechaz0r_attack_impact.audio death : RSX.sfx_neutral_swordmechaz0r_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleSwordBreathing.name idle : RSX.bossDecepticleSwordIdle.name walk : RSX.bossDecepticleSwordRun.name attack : RSX.bossDecepticleSwordAttack.name attackReleaseDelay: 0.0 attackDelay: 0.25 damage : RSX.bossDecepticleSwordHit.name death : RSX.bossDecepticleSwordDeath.name ) card.atk = 4 card.maxHP = 2 backstabObject = ModifierBackstab.createContextObject(2) backstabObject.isRemovable = false card.setInherentModifiersContextObjects([backstabObject]) if (identifier == Cards.Boss.Boss6Helm) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_part4_name") card.setDescription(i18next.t("boss_battles.boss_6_part4_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.Mechaz0rHelm"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticleHelmBreathing.name idle : RSX.bossDecepticleHelmIdle.name walk : RSX.bossDecepticleHelmRun.name attack : RSX.bossDecepticleHelmAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossDecepticleHelmHit.name death : RSX.bossDecepticleHelmDeath.name ) card.atk = 3 card.maxHP = 3 celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false card.setInherentModifiersContextObjects([celerityObject]) if (identifier == Cards.Boss.Boss6Prime) card = new Unit(gameSession) card.setIsHiddenInCollection(true) #card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_6_prime_name") card.setDescription(i18next.t("boss_battles.boss_6_prime_desc")) card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.AlterRexx"]) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_ladylocke_attack_impact.audio attack : RSX.sfx_neutral_wingsofparadise_attack_swing.audio receiveDamage : RSX.sfx_f1_oserix_hit.audio attackDamage : RSX.sfx_f1_oserix_attack_impact.audio death : RSX.sfx_neutral_sunelemental_attack_swing.audio ) card.setBaseAnimResource( breathing : RSX.bossDecepticlePrimeBreathing.name idle : RSX.bossDecepticlePrimeIdle.name walk : RSX.bossDecepticlePrimeRun.name attack : RSX.bossDecepticlePrimeAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossDecepticlePrimeHit.name death : RSX.bossDecepticlePrimeDeath.name ) card.atk = 4 card.maxHP = 16 celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false backstabObject = ModifierBackstab.createContextObject(2) backstabObject.isRemovable = false forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false card.setInherentModifiersContextObjects([celerityObject, backstabObject, forceFieldObject, flyingObject, provokeObject]) if (identifier == Cards.Boss.Boss7) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_7_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_7_bio")) card.setDescription(i18next.t("boss_battles.boss_7_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_calibero) card.setPortraitResource(RSX.speech_portrait_calibero) card.setPortraitHexResource(RSX.boss_calibero_hex_portrait) card.setConceptResource(RSX.boss_calibero_versus_portrait) card.setFXResource(["FX.Cards.Faction1.CaliberO"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_neutral_chaoselemental_attack_impact.audio death : RSX.sfx_spell_darkfiresacrifice.audio ) card.setBaseAnimResource( breathing : RSX.f1CaliberOBreathing.name idle : RSX.f1CaliberOIdle.name walk : RSX.f1CaliberORun.name attack : RSX.f1CaliberOAttack.name attackReleaseDelay: 0.0 attackDelay: 1.4 damage : RSX.f1CaliberODamage.name death : RSX.f1CaliberODeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 20 includedArtifacts = [ {id: Cards.Artifact.SunstoneBracers}, {id: Cards.Artifact.ArclyteRegalia}, {id: Cards.Artifact.StaffOfYKir} ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, includedArtifacts) equipArtifactObject.isRemovable = false equipArtifactFirstTurn = ModifierExpireApplyModifiers.createContextObject([equipArtifactObject], 0, 1, true, true, false, 0, true, "At the start of your second turn and every turn thereafter, equip a random artifact") equipArtifactFirstTurn.isRemovable = false card.setInherentModifiersContextObjects([ equipArtifactFirstTurn ]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.BossArtifact.CycloneGenerator) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.DanceOfSteel card.name = i18next.t("boss_battles.boss_7_artifact_name") card.setDescription(i18next.t("boss_battles.boss_7_artifact_desc")) card.addKeywordClassToInclude(ModifierTranscendance) card.manaCost = 0 card.setBossBattleDescription("__Boss Battle Description") card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierTranscendance.createContextObject({ type: "ModifierTranscendance" name: "Cyclone Generator" }) ]) card.setFXResource(["FX.Cards.Artifact.IndomitableWill"]) card.setBaseAnimResource( idle: RSX.iconSkywindGlaivesIdle.name active: RSX.iconSkywindGlaivesActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Boss.Boss8) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_8_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_8_bio")) card.setDescription(i18next.t("boss_battles.boss_8_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_portal_guardian) card.setPortraitResource(RSX.speech_portrait_portal_guardian) card.setPortraitHexResource(RSX.boss_portal_guardian_hex_portrait) card.setConceptResource(RSX.boss_portal_guardian_versus_portrait) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralMysteryBreathing.name idle : RSX.neutralMysteryIdle.name walk : RSX.neutralMysteryRun.name attack : RSX.neutralMysteryAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralMysteryHit.name death : RSX.neutralMysteryDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 2 card.maxHP = 15 respawnKilledEnemy = ModifierKillWatchRespawnEntity.createContextObject() respawnKilledEnemy.isRemovable = false secondWind = ModifierSecondWind.createContextObject(2, 5, false, "Awakened", "Failure prevented. Strength renewed. Systems adapted.") secondWind.isRemovable = false secondWind.isHiddenToUI = true card.setInherentModifiersContextObjects([respawnKilledEnemy, secondWind]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss9) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_9_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_9_bio")) card.setDescription(i18next.t("boss_battles.boss_9_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_wujin) card.setPortraitResource(RSX.speech_portrait_wujin) card.setPortraitHexResource(RSX.boss_wujin_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_f1_oserix_death.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_silitharveteran_hit.audio attackDamage : RSX.sfx_neutral_prophetofthewhite_death.audio death : RSX.sfx_neutral_daggerkiri_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWujinBreathing.name idle : RSX.bossWujinIdle.name walk : RSX.bossWujinRun.name attack : RSX.bossWujinAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWujinHit.name death : RSX.bossWujinDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 3 card.maxHP = 30 spawnCloneObject = ModifierMyAttackOrAttackedWatchSpawnMinionNearby.createContextObject({id: Cards.Boss.Boss9Clone}, "a decoy") spawnCloneObject.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false teleportCornerObject = ModifierEndTurnWatchTeleportCorner.createContextObject() teleportCornerObject.isRemovable = false card.setInherentModifiersContextObjects([flyingObject, spawnCloneObject, teleportCornerObject]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss9Clone) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_9_clone_name") card.manaCost = 0 card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_f1_oserix_death.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_silitharveteran_hit.audio attackDamage : RSX.sfx_neutral_prophetofthewhite_death.audio death : RSX.sfx_neutral_daggerkiri_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWujinBreathing.name idle : RSX.bossWujinIdle.name walk : RSX.bossWujinRun.name attack : RSX.bossWujinAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWujinHit.name death : RSX.bossWujinDeath.name ) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(120) card.atk = 1 card.maxHP = 5 provokeObject = ModifierProvoke.createContextObject() #provokeObject.isRemovable = false card.setInherentModifiersContextObjects([provokeObject]) if (identifier == Cards.Boss.Boss10) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_10_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_10_bio")) card.setDescription(i18next.t("boss_battles.boss_10_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_solfist) card.setPortraitResource(RSX.speech_portrait_solfist) card.setPortraitHexResource(RSX.boss_solfist_hex_portrait) #card.setConceptResource(RSX.boss_boreal_juggernaut_versus_portrait) card.setFXResource(["FX.Cards.Neutral.WarTalon"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSolfistBreathing.name idle : RSX.bossSolfistIdle.name walk : RSX.bossSolfistRun.name attack : RSX.bossSolfistAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossSolfistHit.name death : RSX.bossSolfistDeath.name ) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(95) card.atk = 3 card.maxHP = 35 killWatchRefreshObject = ModifierKillWatchRefreshExhaustion.createContextObject(true, false) killWatchRefreshObject.isRemovable = false #killWatchRefreshObject.description = "Whenever Solfist destroys a minion, reactivate it." modifierDamageSelfAndNearby = ModifierEndTurnWatchDealDamageToSelfAndNearbyEnemies.createContextObject() modifierDamageSelfAndNearby.isRemovable = false #modifierDamageSelfAndNearby.description = "At the end of Solfist's turn, deal 1 damage to self and all nearby enemies." card.setInherentModifiersContextObjects([killWatchRefreshObject, modifierDamageSelfAndNearby]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss11) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.raceId = Races.Golem card.name = i18next.t("boss_battles.boss_11_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_11_bio")) card.setDescription(i18next.t("boss_battles.boss_11_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_nullifier) card.setPortraitResource(RSX.speech_portrait_nullifier) card.setPortraitHexResource(RSX.boss_nullifier_hex_portrait) card.setFXResource(["FX.Cards.Neutral.EMP"]) card.setBoundingBoxWidth(130) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossEMPBreathing.name idle : RSX.bossEMPIdle.name walk : RSX.bossEMPRun.name attack : RSX.bossEMPAttack.name attackReleaseDelay: 0.0 attackDelay: 1.7 damage : RSX.bossEMPHit.name death : RSX.bossEMPDeath.name ) card.atk = 3 card.maxHP = 60 modifierSelfDamageAreaAttack = ModifierSelfDamageAreaAttack.createContextObject() modifierSelfDamageAreaAttack.isRemovable = false rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, modifierSelfDamageAreaAttack]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss12) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_12_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_12_bio")) card.setDescription(i18next.t("boss_battles.boss_12_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_orias) card.setPortraitResource(RSX.speech_portrait_orias) card.setPortraitHexResource(RSX.boss_orias_hex_portrait) card.setFXResource(["FX.Cards.Neutral.ArchonSpellbinder"]) card.setBoundingBoxWidth(55) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_archonspellbinder_attack_swing.audio receiveDamage : RSX.sfx_neutral_archonspellbinder_hit.audio attackDamage : RSX.sfx_neutral_archonspellbinder_attack_impact.audio death : RSX.sfx_neutral_archonspellbinder_death.audio ) card.setBaseAnimResource( breathing : RSX.bossOriasBreathing.name idle : RSX.bossOriasIdle.name walk : RSX.bossOriasRun.name attack : RSX.bossOriasAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossOriasHit.name death : RSX.bossOriasDeath.name ) card.atk = 0 card.maxHP = 35 modifierDamageWatchBuffSelf = ModifierMyMinionOrGeneralDamagedWatchBuffSelf.createContextObject(1, 0) modifierDamageWatchBuffSelf.isRemovable = false card.setInherentModifiersContextObjects([modifierDamageWatchBuffSelf]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss12Idol) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_12_idol_name") card.setDescription(i18next.t("boss_battles.boss_12_idol_desc")) card.manaCost = 0 card.raceId = Races.Structure card.setFXResource(["FX.Cards.Neutral.Bastion"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(125) card.setBaseSoundResource( apply : RSX.sfx_spell_divinebond.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_golembloodshard_death.audio ) card.setBaseAnimResource( breathing : RSX.bossOriasIdolBreathing.name idle : RSX.bossOriasIdolIdle.name walk : RSX.bossOriasIdolIdle.name attack : RSX.bossOriasIdolAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossOriasIdolHit.name death : RSX.bossOriasIdolDeath.name ) card.atk = 0 card.maxHP = 6 card.speed = 0 rushContextObject = ModifierFirstBlood.createContextObject() modifierSummonNearbyRush = ModifierSummonWatchNearbyAnyPlayerApplyModifiers.createContextObject([rushContextObject], "gains Rush") card.setInherentModifiersContextObjects([modifierSummonNearbyRush]) if (identifier == Cards.Boss.Boss13) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_13_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_13_bio")) card.setDescription(i18next.t("boss_battles.boss_13_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_malyk) card.setPortraitResource(RSX.speech_portrait_malyk) card.setPortraitHexResource(RSX.boss_malyk_hex_portrait) card.setFXResource(["FX.Cards.Neutral.TheHighHand"]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(105) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_grimrock_attack_swing.audio receiveDamage : RSX.sfx_neutral_grimrock_hit.audio attackDamage : RSX.sfx_neutral_grimrock_attack_impact.audio death : RSX.sfx_neutral_grimrock_death.audio ) card.setBaseAnimResource( breathing : RSX.bossMalykBreathing.name idle : RSX.bossMalykIdle.name walk : RSX.bossMalykRun.name attack : RSX.bossMalykAttack.name attackReleaseDelay: 0.0 attackDelay: 0.95 damage : RSX.bossMalykHit.name death : RSX.bossMalykDeath.name ) card.atk = 2 card.maxHP = 30 rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false opponentDrawCardOnSummon = ModifierOpponentSummonWatchOpponentDrawCard.createContextObject() opponentDrawCardOnSummon.isRemovable = false summonEntityOnOverdraw = ModifierOpponentDrawCardWatchOverdrawSummonEntity.createContextObject({id: Cards.Faction4.Ooz}, "a 3/3 Ooz") summonEntityOnOverdraw.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, opponentDrawCardOnSummon, summonEntityOnOverdraw]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss14) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_14_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_14_bio")) card.setDescription(i18next.t("boss_battles.boss_14_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_archonis) card.setPortraitResource(RSX.speech_portrait_archonis) card.setPortraitHexResource(RSX.boss_archonis_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction4.BlackSolus"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_blacksolus_attack_swing.audio receiveDamage : RSX.sfx_f4_blacksolus_hit.audio attackDamage : RSX.sfx_f4_blacksolus_attack_impact.audio death : RSX.sfx_f4_blacksolus_death.audio ) card.setBaseAnimResource( breathing : RSX.bossManaManBreathing.name idle : RSX.bossManaManIdle.name walk : RSX.bossManaManRun.name attack : RSX.bossManaManAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossManaManDamage.name death : RSX.bossManaManDeath.name ) card.atk = 6 card.maxHP = 60 damageBasedOnRemainingMana = ModifierEndTurnWatchDamagePlayerBasedOnRemainingMana.createContextObject() damageBasedOnRemainingMana.isRemovable = false card.setInherentModifiersContextObjects([damageBasedOnRemainingMana]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss15) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_15_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_15_bio")) card.setDescription(i18next.t("boss_battles.boss_15_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_paragon) card.setPortraitResource(RSX.speech_portrait_paragon) card.setPortraitHexResource(RSX.boss_paragon_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.EXun"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_hailstonehowler_attack_swing.audio receiveDamage : RSX.sfx_neutral_hailstonehowler_hit.audio attackDamage : RSX.sfx_neutral_hailstonehowler_attack_impact.audio death : RSX.sfx_neutral_hailstonehowler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossParagonBreathing.name idle : RSX.bossParagonIdle.name walk : RSX.bossParagonRun.name attack : RSX.bossParagonAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossParagonHit.name death : RSX.bossParagonDeath.name ) card.atk = 3 card.maxHP = 30 card.setDamage(10) gainModifiersOnHPChange = ModifierHPThresholdGainModifiers.createContextObject() gainModifiersOnHPChange.isRemovable = false card.setInherentModifiersContextObjects([gainModifiersOnHPChange]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss16) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_16_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_16_desc")) card.setBossBattleDescription(i18next.t("boss_battles.boss_16_bio")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_vampire) card.setPortraitResource(RSX.speech_portrait_vampire) card.setPortraitHexResource(RSX.boss_vampire_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.Chakkram"]) card.setBaseSoundResource( apply : RSX.sfx_neutral_prophetofthewhite_hit.audio walk : RSX.sfx_neutral_firestarter_impact.audio attack : RSX.sfx_neutral_firestarter_attack_swing.audio receiveDamage : RSX.sfx_neutral_firestarter_hit.audio attackDamage : RSX.sfx_neutral_firestarter_impact.audio death : RSX.sfx_neutral_alcuinloremaster_death.audio ) card.setBaseAnimResource( breathing : RSX.bossVampireBreathing.name idle : RSX.bossVampireIdle.name walk : RSX.bossVampireRun.name attack : RSX.bossVampireAttack.name attackReleaseDelay: 0.0 attackDelay: 1.5 damage : RSX.bossVampireHit.name death : RSX.bossVampireDeath.name ) card.atk = 2 card.maxHP = 30 lifestealModifier = ModifierHealSelfWhenDealingDamage.createContextObject() lifestealModifier.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false extraDamageCounterAttack = ModifierExtraDamageOnCounterattack.createContextObject(2) extraDamageCounterAttack.isRemovable = false card.setInherentModifiersContextObjects([lifestealModifier, extraDamageCounterAttack, flyingObject]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss17) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_17_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_17_bio")) card.setDescription(i18next.t("boss_battles.boss_17_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_kron) card.setPortraitResource(RSX.speech_portrait_kron) card.setPortraitHexResource(RSX.boss_kron_hex_portrait) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Neutral.WhiteWidow"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_windstopper_attack_impact.audio attack : RSX.sfx_neutral_crossbones_attack_swing.audio receiveDamage : RSX.sfx_neutral_mirkblooddevourer_hit.audio attackDamage : RSX.sfx_neutral_mirkblooddevourer_attack_impact.audio death : RSX.sfx_neutral_mirkblooddevourer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossKronBreathing.name idle : RSX.bossKronIdle.name walk : RSX.bossKronRun.name attack : RSX.bossKronAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossKronHit.name death : RSX.bossKronDeath.name ) card.atk = 2 card.maxHP = 30 spawnPrisoners = ModifierOnOpponentDeathWatchSpawnEntityOnSpace.createContextObject() spawnPrisoners.isRemovable = false contextObject = PlayerModifierManaModifier.createCostChangeContextObject(-2, CardType.Spell) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true contextObject.isRemovable = false card.setInherentModifiersContextObjects([spawnPrisoners, contextObject]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss18) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_18_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_18_bio")) card.setDescription(i18next.t("boss_battles.boss_18_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_serpenti) card.setPortraitResource(RSX.speech_portrait_serpenti) card.setPortraitHexResource(RSX.boss_serpenti_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Serpenti"]) card.setBoundingBoxWidth(105) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_serpenti_attack_swing.audio receiveDamage : RSX.sfx_neutral_serpenti_hit.audio attackDamage : RSX.sfx_neutral_serpenti_attack_impact.audio death : RSX.sfx_neutral_serpenti_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSerpentiBreathing.name idle : RSX.bossSerpentiIdle.name walk : RSX.bossSerpentiRun.name attack : RSX.bossSerpentiAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossSerpentiHit.name death : RSX.bossSerpentiDeath.name ) card.atk = 4 card.maxHP = 40 spawnSerpentiEgg = ModifierDyingWishSpawnEgg.createContextObject({id: Cards.Neutral.Serpenti}, "7/4 Serpenti") spawnSerpentiEgg.isRemovable = false applyModifierToSummonedMinions = ModifierSummonWatchFromActionBarApplyModifiers.createContextObject([spawnSerpentiEgg], "Rebirth: Serpenti") applyModifierToSummonedMinions.isRemovable = false card.setInherentModifiersContextObjects([applyModifierToSummonedMinions]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss19) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_19_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_19_bio")) card.setDescription(i18next.t("boss_battles.boss_19_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_wraith) card.setPortraitResource(RSX.speech_portrait_wraith) card.setPortraitHexResource(RSX.boss_wraith_hex_portrait) card.setFXResource(["FX.Cards.Faction4.ArcaneDevourer"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_spell_icepillar_melt.audio attack : RSX.sfx_f6_waterelemental_death.audio receiveDamage : RSX.sfx_f1windbladecommander_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f1elyxstormblade_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWraithBreathing.name idle : RSX.bossWraithIdle.name walk : RSX.bossWraithRun.name attack : RSX.bossWraithAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossWraithHit.name death : RSX.bossWraithDeath.name ) card.atk = 1 card.maxHP = 40 growAura = Modifier.createContextObjectWithAuraForAllAllies([ModifierGrowPermanent.createContextObject(1)], null, null, null, "Your minions have \"Grow: +1/+1.\"") growAura.isRemovable = false takeDamageSpawnWraithlings = ModifierTakeDamageWatchSpawnWraithlings.createContextObject() takeDamageSpawnWraithlings.isRemovable = false card.setInherentModifiersContextObjects([growAura, takeDamageSpawnWraithlings]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss20) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_20_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_20_bio")) card.setDescription(i18next.t("boss_battles.boss_20_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_skyfall_tyrant) card.setPortraitResource(RSX.speech_portrait_skyfall_tyrant) card.setPortraitHexResource(RSX.boss_skyfall_tyrant_hex_portrait) card.setFXResource(["FX.Cards.Neutral.FlameWing"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_2.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_spell_blindscorch.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2lanternfox_attack_impact.audio death : RSX.sfx_f6_draugarlord_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSkyfallTyrantBreathing.name idle : RSX.bossSkyfallTyrantIdle.name walk : RSX.bossSkyfallTyrantRun.name attack : RSX.bossSkyfallTyrantAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossSkyfallTyrantHit.name death : RSX.bossSkyfallTyrantDeath.name ) card.atk = 2 card.maxHP = 35 card.speed = 0 includedArtifacts = [ {id: Cards.BossArtifact.FrostArmor} ] equipArtifactObject = ModifierStartTurnWatchEquipArtifact.createContextObject(1, includedArtifacts) equipArtifactObject.isRemovable = false rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false card.setInherentModifiersContextObjects([equipArtifactObject, rangedModifier]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.BossArtifact.FrostArmor) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.FrostArmor card.name = i18next.t("boss_battles.boss_20_artifact_name") card.setDescription(i18next.t("boss_battles.boss_20_artifact_desc")) #card.addKeywordClassToInclude(ModifierTranscendance) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierAbsorbDamage.createContextObject(1, { name: "PI:NAME:<NAME>END_PIrost Armor" description: "The first time your General takes damage each turn, prevent 1 of it." }), ModifierTakeDamageWatchDamageAttacker.createContextObject(1, { name: "PI:NAME:<NAME>END_PIrost Armor" description: "Whenever your General takes damage, deal 1 damage to the attacker." }), ]) card.setFXResource(["FX.Cards.Artifact.ArclyteRegalia"]) card.setBaseAnimResource( idle: RSX.iconFrostArmorIdle.name active: RSX.iconFrostArmorActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.Boss.Boss21) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_21_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_21_bio")) card.setDescription(i18next.t("boss_battles.boss_21_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_cindera) card.setPortraitResource(RSX.speech_portrait_cindera) card.setPortraitHexResource(RSX.boss_cindera_hex_portrait) card.setFXResource(["FX.Cards.Faction4.AbyssalCrawler"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f3_aymarahealer_attack_swing.audio receiveDamage : RSX.sfx_f3_aymarahealer_hit.audio attackDamage : RSX.sfx_f3_aymarahealer_impact.audio death : RSX.sfx_f3_aymarahealer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCinderaBreathing.name idle : RSX.bossCinderaIdle.name walk : RSX.bossCinderaRun.name attack : RSX.bossCinderaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCinderaHit.name death : RSX.bossCinderaDeath.name ) card.atk = 2 card.maxHP = 35 explodeAura = Modifier.createContextObjectWithAuraForAllAllies([ModifierDyingWishDamageNearbyEnemies.createContextObject(2)], null, null, null, "Your minions have \"Dying Wish: Deal 2 damage to all nearby enemies\"") explodeAura.isRemovable = false startTurnTeleport = ModifierStartTurnWatchTeleportRandomSpace.createContextObject() startTurnTeleport.isRemovable = false frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.setInherentModifiersContextObjects([explodeAura, startTurnTeleport, frenzyContextObject]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss22) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_22_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_22_bio")) card.setDescription(i18next.t("boss_battles.boss_22_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_crystal) card.setPortraitResource(RSX.speech_portrait_crystal) card.setPortraitHexResource(RSX.boss_crystal_hex_portrait) card.setFXResource(["FX.Cards.Faction1.ArclyteSentinel"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f2stormkage_attack_swing.audio receiveDamage : RSX.sfx_f2stormkage_hit.audio attackDamage : RSX.sfx_f2stormkage_attack_impact.audio death : RSX.sfx_f2stormkage_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCrystalBreathing.name idle : RSX.bossCrystalIdle.name walk : RSX.bossCrystalRun.name attack : RSX.bossCrystalAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossCrystalDamage.name death : RSX.bossCrystalDeath.name ) card.atk = 3 card.maxHP = 30 forceFieldObject = ModifierForcefield.createContextObject() forceFieldObject.isRemovable = false attackBuff = 2 maxHPNerf = -2 followupModifierContextObject = Modifier.createContextObjectWithAttributeBuffs(attackBuff,maxHPNerf) followupModifierContextObject.appliedName = i18next.t("modifiers.boss_22_applied_name") statModifierAura = ModifierSummonWatchFromActionBarAnyPlayerApplyModifiers.createContextObject([followupModifierContextObject], "gain +2 Attack, but -2 Health") statModifierAura.isRemovable = false card.setInherentModifiersContextObjects([forceFieldObject, statModifierAura]) card.signatureCardData = {id: Cards.BossSpell.RestoringLight} if (identifier == Cards.Boss.Boss23) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_23_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_23_bio")) card.setDescription(i18next.t("boss_battles.boss_23_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_antiswarm) card.setPortraitResource(RSX.speech_portrait_antiswarm) card.setPortraitHexResource(RSX.boss_antiswarm_hex_portrait) card.setFXResource(["FX.Cards.Faction5.PrimordialGazer"]) card.setBoundingBoxWidth(90) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_screenshake.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_primordialgazer_attack_swing.audio receiveDamage : RSX.sfx_neutral_primordialgazer_hit.audio attackDamage : RSX.sfx_neutral_primordialgazer_attack_impact.audio death : RSX.sfx_neutral_primordialgazer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossAntiswarmBreathing.name idle : RSX.bossAntiswarmIdle.name walk : RSX.bossAntiswarmRun.name attack : RSX.bossAntiswarmAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossAntiswarmHit.name death : RSX.bossAntiswarmDeath.name ) card.atk = 1 card.maxHP = 30 card.speed = 0 damageGeneralEqualToMinions = ModifierStartTurnWatchDamageGeneralEqualToMinionsOwned.createContextObject() damageGeneralEqualToMinions.isRemovable = false shadowDancerAbility = ModifierDeathWatchDamageEnemyGeneralHealMyGeneral.createContextObject(1,1) shadowDancerAbility.isRemovable = false card.setInherentModifiersContextObjects([damageGeneralEqualToMinions, shadowDancerAbility]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss24) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_24_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_24_bio")) card.setDescription(i18next.t("boss_battles.boss_24_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_skurge) card.setPortraitResource(RSX.speech_portrait_skurge) card.setPortraitHexResource(RSX.boss_skurge_hex_portrait) card.setFXResource(["FX.Cards.Neutral.SwornAvenger"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_swornavenger_attack_swing.audio receiveDamage : RSX.sfx_neutral_swornavenger_hit.audio attackDamage : RSX.sfx_neutral_swornavenger_attack_impact.audio death : RSX.sfx_neutral_swornavenger_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSkurgeBreathing.name idle : RSX.bossSkurgeIdle.name walk : RSX.bossSkurgeRun.name attack : RSX.bossSkurgeAttack.name attackReleaseDelay: 0.2 attackDelay: 0.4 damage : RSX.bossSkurgeHit.name death : RSX.bossSkurgeDeath.name ) card.atk = 1 card.maxHP = 25 rangedModifier = ModifierRanged.createContextObject() rangedModifier.isRemovable = false attackBuffContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) attackBuffContextObject.appliedName = i18next.t("modifiers.boss_24_applied_name_1") #rangedAura = Modifier.createContextObjectWithAuraForAllAllies([attackBuffContextObject], null, null, [ModifierRanged.type], "Your minions with Ranged gain +1/+1") #rangedAura.isRemovable = false immunityContextObject = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([ModifierImmuneToDamage.createContextObject()], "Skurge cannot be damaged while Valiant lives") immunityContextObject.appliedName = i18next.t("modifiers.boss_24_applied_name_2") valiantProtector = [ Cards.Boss.Boss24Valiant ] applyGeneralImmunityContextObject = Modifier.createContextObjectWithAuraForAllAllies([immunityContextObject], null, valiantProtector, null, "Cannot be damaged while Valiant lives") applyGeneralImmunityContextObject.isRemovable = false applyGeneralImmunityContextObject.isHiddenToUI = true summonValiant = ModifierHPChangeSummonEntity.createContextObject({id: Cards.Boss.Boss24Valiant},15,"Valiant") summonValiant.isRemovable = false summonValiant.isHiddenToUI = true damageAndBuffSelf = ModifierStartTurnWatchDamageAndBuffSelf.createContextObject(1,0,3) damageAndBuffSelf.isRemovable = false card.setInherentModifiersContextObjects([rangedModifier, applyGeneralImmunityContextObject, damageAndBuffSelf, summonValiant]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss24Valiant) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_24_valiant_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_24_valiant_desc")) card.setFXResource(["FX.Cards.Neutral.SwornDefender"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(85) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_sunseer_attack_swing.audio receiveDamage : RSX.sfx_neutral_sunseer_hit.audio attackDamage : RSX.sfx_neutral_sunseer_attack_impact.audio death : RSX.sfx_neutral_sunseer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossValiantBreathing.name idle : RSX.bossValiantIdle.name walk : RSX.bossValiantRun.name attack : RSX.bossValiantAttack.name attackReleaseDelay: 0.0 attackDelay: 0.25 damage : RSX.bossValiantHit.name death : RSX.bossValiantDeath.name ) card.atk = 4 card.maxHP = 15 card.speed = 4 provokeObject = ModifierProvoke.createContextObject() provokeObject.isRemovable = false rangedProvoke = ModifierRangedProvoke.createContextObject() rangedProvoke.isRemovable = false card.setInherentModifiersContextObjects([provokeObject, rangedProvoke]) if (identifier == Cards.Boss.Boss25) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_25_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_25_bio")) card.setDescription(i18next.t("boss_battles.boss_25_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_shadow_lord) card.setPortraitResource(RSX.speech_portrait_shadow_lord) card.setPortraitHexResource(RSX.boss_shadow_lord_hex_portrait) card.setFXResource(["FX.Cards.Neutral.QuartermasterGauj"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_unit_run_magical_4.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_neutral_monsterdreamoracle_hit.audio attackDamage : RSX.sfx_neutral_monsterdreamoracle_attack_impact.audio death : RSX.sfx_neutral_monsterdreamoracle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossShadowLordBreathing.name idle : RSX.bossShadowLordIdle.name walk : RSX.bossShadowLordRun.name attack : RSX.bossShadowLordAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossShadowLordHit.name death : RSX.bossShadowLordDeath.name ) card.atk = 3 card.maxHP = 30 summonAssassinOnMove = ModifierEnemyTeamMoveWatchSummonEntityBehind.createContextObject({id: Cards.Faction2.KaidoAssassin},"Kaido Assassin") summonAssassinOnMove.isRemovable = false modContextObject = Modifier.createContextObjectWithAttributeBuffs(1,1) modContextObject.appliedName = i18next.t("modifiers.boss_25_applied_name") allyMinionMoveBuff = ModifierMyTeamMoveWatchBuffTarget.createContextObject([modContextObject], "give it +1/+1") allyMinionMoveBuff.isRemovable = false card.setInherentModifiersContextObjects([summonAssassinOnMove, allyMinionMoveBuff]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss26) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_26_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_26_bio")) card.setDescription(i18next.t("boss_battles.boss_26_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_gol) card.setPortraitResource(RSX.speech_portrait_gol) card.setPortraitHexResource(RSX.boss_gol_hex_portrait) card.setFXResource(["FX.Cards.Neutral.BloodTaura"]) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_neutral_rook_hit.audio attack : RSX.sfx_neutral_khymera_attack_swing.audio receiveDamage : RSX.sfx_neutral_khymera_hit.audio attackDamage : RSX.sfx_neutral_khymera_impact.audio death : RSX.sfx_neutral_khymera_death.audio ) card.setBaseAnimResource( breathing : RSX.bossGolBreathing.name idle : RSX.bossGolIdle.name walk : RSX.bossGolRun.name attack : RSX.bossGolAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossGolHit.name death : RSX.bossGolDeath.name ) card.atk = 2 card.maxHP = 40 card.speed = 0 attacksDamageAllMinions = ModifierAttacksDamageAllEnemyMinions.createContextObject() attacksDamageAllMinions.isRemovable = false card.setInherentModifiersContextObjects([attacksDamageAllMinions]) card.signatureCardData = {id: Cards.BossSpell.LivingFlame} if (identifier == Cards.Boss.Boss26Companion) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_26_zane_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_26_zane_desc")) card.setFXResource(["FX.Cards.Faction1.RadiantDragoon"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_neutral_arcanelimiter_attack_impact.audio attack : RSX.sfx_neutral_rook_attack_swing.audio receiveDamage : RSX.sfx_f2_kaidoassassin_hit.audio attackDamage : RSX.sfx_neutral_rook_attack_impact.audio death : RSX.sfx_neutral_windstopper_death.audio ) card.setBaseAnimResource( breathing : RSX.bossKaneBreathing.name idle : RSX.bossKaneIdle.name walk : RSX.bossKaneRun.name attack : RSX.bossKaneAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossKaneHit.name death : RSX.bossKaneDeath.name ) card.atk = 3 card.maxHP = 20 card.speed = 3 dyingWishKillGeneral = ModifierDyingWishLoseGame.createContextObject() dyingWishKillGeneral.isRemovable = false atkLimiter = ModifierATKThresholdDie.createContextObject(6) atkLimiter.isRemovable = false doubleDamageGenerals = ModifierDoubleDamageToGenerals.createContextObject() doubleDamageGenerals.isRemovable = false card.setInherentModifiersContextObjects([ModifierBattlePet.createContextObject(), doubleDamageGenerals, atkLimiter, dyingWishKillGeneral]) if (identifier == Cards.Boss.Boss27) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_27_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_27_bio")) card.setDescription(i18next.t("boss_battles.boss_27_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_taskmaster) card.setPortraitResource(RSX.speech_portrait_taskmaster) card.setPortraitHexResource(RSX.boss_taskmaster_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Tethermancer"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_neutral_ubo_attack_swing.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_spiritscribe_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTaskmasterBreathing.name idle : RSX.bossTaskmasterIdle.name walk : RSX.bossTaskmasterRun.name attack : RSX.bossTaskmasterAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossTaskmasterHit.name death : RSX.bossTaskmasterDeath.name ) card.atk = 3 card.maxHP = 35 card.speed = 0 battlePetModifier = ModifierBattlePet.createContextObject() battlePetModifier.isRemovable = false summonWatchApplyBattlepet = ModifierSummonWatchAnyPlayerApplyModifiers.createContextObject([battlePetModifier], "act like Battle Pets") summonWatchApplyBattlepet.isRemovable = false speedBuffContextObject = Modifier.createContextObjectOnBoard() speedBuffContextObject.attributeBuffs = {"speed": 0} speedBuffContextObject.attributeBuffsAbsolute = ["speed"] speedBuffContextObject.attributeBuffsFixed = ["speed"] speedBuffContextObject.appliedName = i18next.t("modifiers.faction_3_spell_sand_trap_1") speedBuffContextObject.isRemovable = false speed0Modifier = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([speedBuffContextObject], "The enemy General cannot move") speed0Modifier.isRemovable = false immuneToSpellTargeting = ModifierImmuneToSpellsByEnemy.createContextObject() immuneToSpellTargeting.isRemovable = false card.setInherentModifiersContextObjects([summonWatchApplyBattlepet, speed0Modifier, immuneToSpellTargeting]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss28) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_28_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_28_bio")) card.setDescription(i18next.t("boss_battles.boss_28_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_grym) card.setPortraitResource(RSX.speech_portrait_grym) card.setPortraitHexResource(RSX.boss_grym_hex_portrait) card.setFXResource(["FX.Cards.Faction5.EarthWalker"]) card.setBoundingBoxWidth(70) card.setBoundingBoxHeight(75) card.setBaseSoundResource( apply : RSX.sfx_screenshake.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_earthwalker_attack_swing.audio receiveDamage : RSX.sfx_neutral_earthwalker_hit.audio attackDamage : RSX.sfx_neutral_earthwalker_attack_impact.audio death : RSX.sfx_neutral_earthwalker_death.audio ) card.setBaseAnimResource( breathing : RSX.bossGrymBreathing.name idle : RSX.bossGrymIdle.name walk : RSX.bossGrymRun.name attack : RSX.bossGrymAttack.name attackReleaseDelay: 0.0 attackDelay: 0.9 damage : RSX.bossGrymHit.name death : RSX.bossGrymDeath.name ) card.atk = 3 card.maxHP = 30 deathWatchDamageRandomMinionHealGeneral = ModifierDeathWatchDamageRandomMinionHealMyGeneral.createContextObject() deathWatchDamageRandomMinionHealGeneral.isRemovable = false card.setInherentModifiersContextObjects([deathWatchDamageRandomMinionHealGeneral]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss29) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_29_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_29_bio")) card.setDescription(i18next.t("boss_battles.boss_29_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_sandpanther) card.setPortraitResource(RSX.speech_portrait_sandpanther) card.setPortraitHexResource(RSX.boss_sandpanther_hex_portrait) card.setFXResource(["FX.Cards.Faction3.Pantheran"]) card.setBaseSoundResource( apply : RSX.sfx_spell_ghostlightning.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_makantorwarbeast_attack_swing.audio receiveDamage : RSX.sfx_f6_boreanbear_hit.audio attackDamage : RSX.sfx_f6_boreanbear_attack_impact.audio death : RSX.sfx_f6_boreanbear_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSandPantherBreathing.name idle : RSX.bossSandPantherIdle.name walk : RSX.bossSandPantherRun.name attack : RSX.bossSandPantherAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossSandPantherDamage.name death : RSX.bossSandPantherDeath.name ) card.atk = 2 card.maxHP = 40 spawnSandTile = ModifierStartTurnWatchSpawnTile.createContextObject({id: Cards.Tile.SandPortal}, "Exhuming Sands", 1, CONFIG.PATTERN_WHOLE_BOARD) spawnSandTile.isRemovable = false card.setInherentModifiersContextObjects([spawnSandTile]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss30) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_30_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_30_bio")) card.setDescription(i18next.t("boss_battles.boss_30_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_wolfpunch) card.setPortraitResource(RSX.speech_portrait_wolfpunch) card.setPortraitHexResource(RSX.boss_wolfpunch_hex_portrait) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(75) card.setFXResource(["FX.Cards.Faction1.LysianBrawler"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f1lysianbrawler_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_f1lysianbrawler_death.audio ) card.setBaseAnimResource( breathing : RSX.bossWolfpunchBreathing.name idle : RSX.bossWolfpunchIdle.name walk : RSX.bossWolfpunchRun.name attack : RSX.bossWolfpunchAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossWolfpunchDamage.name death : RSX.bossWolfpunchDeath.name ) card.atk = 2 card.maxHP = 40 gainATKOpponentTurn = ModifierEndTurnWatchGainTempBuff.createContextObject(4,0,i18next.t("modifiers.boss_30_applied_name")) gainATKOpponentTurn.isRemovable = false celerityObject = ModifierTranscendance.createContextObject() celerityObject.isRemovable = false startTurnSpawnWolf = ModifierStartTurnWatchSpawnEntity.createContextObject({id: Cards.Faction6.WolfAspect}) startTurnSpawnWolf.isRemovable = false card.setInherentModifiersContextObjects([gainATKOpponentTurn, celerityObject, startTurnSpawnWolf]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss31) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_31_bio")) card.setDescription(i18next.t("boss_battles.boss_31_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_unhallowed) card.setPortraitResource(RSX.speech_portrait_unhallowed) card.setPortraitHexResource(RSX.boss_unhallowed_hex_portrait) card.setFXResource(["FX.Cards.Faction4.DeathKnell"]) card.setBaseSoundResource( apply : RSX.sfx_f4_blacksolus_attack_swing.audio walk : RSX.sfx_spell_icepillar_melt.audio attack : RSX.sfx_f6_waterelemental_death.audio receiveDamage : RSX.sfx_f1windbladecommander_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f1elyxstormblade_death.audio ) card.setBaseAnimResource( breathing : RSX.bossUnhallowedBreathing.name idle : RSX.bossUnhallowedIdle.name walk : RSX.bossUnhallowedRun.name attack : RSX.bossUnhallowedAttack.name attackReleaseDelay: 0.0 attackDelay: 1.2 damage : RSX.bossUnhallowedHit.name death : RSX.bossUnhallowedDeath.name ) card.atk = 2 card.maxHP = 50 takeDamageSpawnHaunt = ModifierTakeDamageWatchSpawnRandomHaunt.createContextObject() takeDamageSpawnHaunt.isRemovable = false card.setInherentModifiersContextObjects([takeDamageSpawnHaunt]) card.signatureCardData = {id: Cards.BossSpell.EntanglingShadow} if (identifier == Cards.Boss.Boss31Treat1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_1_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction2.SonghaiSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentGeneralAttackHealEnemyGeneralDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat1})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Treat2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_2_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction4.AbyssSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentSummonBuffItDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat2})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Treat3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_treat_name") card.setDescription(i18next.t("boss_battles.boss_31_treat_3_desc")) card.setBoundingBoxWidth(50) card.setBoundingBoxHeight(45) card.setFXResource(["FX.Cards.Faction2.OnyxBear"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_neutral_luxignis_hit.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_neutral_spelljammer_hit.audio attackDamage : RSX.sfx_neutral_spelljammer_attack_impact.audio death : RSX.sfx_neutral_spelljammer_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCandyPandaBreathing.name idle : RSX.bossCandyPandaIdle.name walk : RSX.bossCandyPandaRun.name attack : RSX.bossCandyPandaAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.bossCandyPandaDamage.name death : RSX.bossCandyPandaDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare cannotAttackGenerals = ModifierCannotAttackGeneral.createContextObject() cannotAttackGenerals.isRemovable = false sentinelData = {id: Cards.Faction6.VanarSentinel} sentinelData.additionalModifiersContextObjects ?= [] sentinelData.additionalModifiersContextObjects.push(ModifierSentinelOpponentSpellCastRefundManaDrawCard.createContextObject("transform.", {id: Cards.Boss.Boss31Treat3})) card.setInherentModifiersContextObjects([ModifierSentinelSetup.createContextObject(sentinelData), cannotAttackGenerals]) card.addKeywordClassToInclude(ModifierSentinel) if (identifier == Cards.Boss.Boss31Haunt1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_1_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_1_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatDemonBreathing.name idle : RSX.bossTreatDemonIdle.name walk : RSX.bossTreatDemonRun.name attack : RSX.bossTreatDemonAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatDemonHit.name death : RSX.bossTreatDemonDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Unit) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's minions cost 1 more to play") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss31Haunt2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_2_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_2_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatOniBreathing.name idle : RSX.bossTreatOniIdle.name walk : RSX.bossTreatOniRun.name attack : RSX.bossTreatOniAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatOniHit.name death : RSX.bossTreatOniDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Spell) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's non-Bloodbound spells cost 1 more to cast") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss31Haunt3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_31_haunt_3_name") card.setDescription(i18next.t("boss_battles.boss_31_haunt_3_desc")) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossTreatDrakeBreathing.name idle : RSX.bossTreatDrakeIdle.name walk : RSX.bossTreatDrakeRun.name attack : RSX.bossTreatDrakeAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossTreatDrakeHit.name death : RSX.bossTreatDrakeDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 3 card.rarityId = Rarity.Rare dyingWishDrawCards = ModifierDyingWishDrawCard.createContextObject(2) contextObject = PlayerModifierManaModifier.createCostChangeContextObject(1, CardType.Artifact) contextObject.activeInHand = contextObject.activeInDeck = false contextObject.activeOnBoard = true increasedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetEnemyPlayer([contextObject], "Your opponent's artifacts cost 1 more to cast") card.setInherentModifiersContextObjects([dyingWishDrawCards, increasedManaCost]) if (identifier == Cards.Boss.Boss32) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_32_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_32_bio")) card.setDescription(i18next.t("boss_battles.boss_32_desc")) card.setBossBattleBattleMapIndex(10) card.setSpeechResource(RSX.speech_portrait_christmas) card.setPortraitResource(RSX.speech_portrait_christmas) card.setPortraitHexResource(RSX.boss_christmas_hex_portrait) card.setBoundingBoxWidth(120) card.setBoundingBoxHeight(95) card.setFXResource(["FX.Cards.Faction6.PrismaticGiant"]) card.setBaseSoundResource( apply : RSX.sfx_ui_booster_packexplode.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f6_draugarlord_attack_swing.audio receiveDamage : RSX.sfx_f6_draugarlord_hit.audio attackDamage : RSX.sfx_f6_draugarlord_attack_impact.audio death : RSX.sfx_f6_draugarlord_death.audio ) card.setBaseAnimResource( breathing : RSX.bossChristmasBreathing.name idle : RSX.bossChristmasIdle.name walk : RSX.bossChristmasRun.name attack : RSX.bossChristmasAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossChristmasDamage.name death : RSX.bossChristmasDeath.name ) card.atk = 4 card.maxHP = 50 #giftPlayer = ModifierStartTurnWatchPutCardInOpponentsHand.createContextObject({id: Cards.BossSpell.HolidayGift}) #giftPlayer.isRemovable = false startTurnSpawnElf = ModifierStartTurnWatchSpawnEntity.createContextObject({id: Cards.Boss.Boss32_2}) startTurnSpawnElf.isRemovable = false card.setInherentModifiersContextObjects([startTurnSpawnElf]) card.signatureCardData = {id: Cards.BossSpell.LaceratingFrost} if (identifier == Cards.Boss.Boss32_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_32_elf_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_32_elf_desc")) card.setFXResource(["FX.Cards.Neutral.Zyx"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_emeraldrejuvenator_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_neutral_emeraldrejuvenator_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralZyxFestiveBreathing.name idle : RSX.neutralZyxFestiveIdle.name walk : RSX.neutralZyxFestiveRun.name attack : RSX.neutralZyxFestiveAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralZyxFestiveHit.name death : RSX.neutralZyxFestiveDeath.name ) card.atk = 2 card.maxHP = 3 celerityObject = ModifierTranscendance.createContextObject() rushContextObject = ModifierFirstBlood.createContextObject() dyingWishPresent = ModifierDyingWishPutCardInOpponentHand.createContextObject({id: Cards.BossSpell.HolidayGift}) card.setInherentModifiersContextObjects([celerityObject, dyingWishPresent]) if (identifier == Cards.BossArtifact.FlyingBells) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.FlyingBells card.name = i18next.t("boss_battles.boss_32_gift_1_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_1_desc")) card.addKeywordClassToInclude(ModifierFlying) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierFlying.createContextObject({ type: "ModifierFlying" name: i18next.t("boss_battles.boss_32_gift_1_name") }) ]) card.setFXResource(["FX.Cards.Artifact.MaskOfShadows"]) card.setBaseAnimResource( idle: RSX.bossChristmasJinglebellsIdle.name active: RSX.bossChristmasJinglebellsActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.BossArtifact.Coal) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.Coal card.name = i18next.t("boss_battles.boss_32_gift_2_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_2_desc")) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierCannotCastBBS.createContextObject({ type: "ModifierCannotCastBBS" name: i18next.t("boss_battles.boss_32_gift_2_name") }) ]) card.setFXResource(["FX.Cards.Artifact.PristineScale"]) card.setBaseAnimResource( idle: RSX.bossChristmasCoalIdle.name active: RSX.bossChristmasCoalActive.name ) card.setBaseSoundResource( apply : RSX.sfx_artifact_equip.audio ) if (identifier == Cards.BossArtifact.CostReducer) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.CostReducer card.name = i18next.t("boss_battles.boss_32_gift_3_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_3_desc")) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 artifactContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Artifact) artifactContextObject.activeInHand = artifactContextObject.activeInDeck = false artifactContextObject.activeOnBoard = true spellContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Spell) spellContextObject.activeInHand = spellContextObject.activeInDeck = spellContextObject.activeInSignatureCards = false spellContextObject.activeOnBoard = true minionContextObject = PlayerModifierManaModifier.createCostChangeContextObject(-1, CardType.Unit) minionContextObject.activeInHand = minionContextObject.activeInDeck = false minionContextObject.activeOnBoard = true card.setTargetModifiersContextObjects([ ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetOwnPlayer([artifactContextObject,spellContextObject,minionContextObject], "Cards in your hand cost 1 less to play.") ]) card.setFXResource(["FX.Cards.Artifact.SoulGrimwar"]) card.setBaseAnimResource( idle: RSX.bossChristmasMistletoeIdle.name active: RSX.bossChristmasMistletoeActive.name ) card.setBaseSoundResource( apply : RSX.sfx_victory_crest.audio ) if (identifier == Cards.BossSpell.HolidayGift) card = new SpellEquipBossArtifacts(gameSession) card.setIsHiddenInCollection(true) card.factionId = Factions.Boss card.id = Cards.Spell.HolidayGift card.name = i18next.t("boss_battles.boss_32_gift_spell_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_spell_desc")) card.manaCost = 1 card.rarityId = Rarity.Legendary card.setFXResource(["FX.Cards.Spell.AutarchsGifts"]) card.setBaseSoundResource( apply : RSX.sfx_spell_entropicdecay.audio ) card.setBaseAnimResource( idle : RSX.bossChristmasPresentIdle.name active : RSX.bossChristmasPresentActive.name ) if (identifier == Cards.BossArtifact.Snowball) card = new Artifact(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossArtifact.Snowball card.name = i18next.t("boss_battles.boss_32_gift_4_name") card.setDescription(i18next.t("boss_battles.boss_32_gift_4_desc")) card.addKeywordClassToInclude(ModifierRanged) card.manaCost = 0 card.rarityId = Rarity.Epic card.durability = 3 card.setTargetModifiersContextObjects([ ModifierRanged.createContextObject({ type: "ModifierRanged" name: i18next.t("boss_battles.boss_32_gift_4_name") }), Modifier.createContextObjectWithAttributeBuffs(-1,undefined, { name: "Snowball" description: "-1 Attack." }) ]) card.setFXResource(["FX.Cards.Artifact.EternalHeart"]) card.setBaseAnimResource( idle: RSX.bossChristmasSnowballIdle.name active: RSX.bossChristmasSnowballActive.name ) card.setBaseSoundResource( apply : RSX.sfx_artifact_equip.audio ) if (identifier == Cards.Boss.Boss33) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_33_bio")) card.setDescription(i18next.t("boss_battles.boss_33_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_legion) card.setPortraitResource(RSX.speech_portrait_legion) card.setPortraitHexResource(RSX.boss_legion_hex_portrait) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 healObject = ModifierEndTurnWatchHealSelf.createContextObject(3) healObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] healAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([healObject], null, legion, null, "Heals for 3 at end of turn") healAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([healAura, backupGeneral, respawnClones]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.Boss33_1) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 healObject = ModifierEndTurnWatchHealSelf.createContextObject(3) healObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] healAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([healObject], null, legion, null, "Heals for 3 at end of turn") healAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([healAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_2_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 attackObject = Modifier.createContextObjectWithAttributeBuffs(2,undefined, { name: "Legion's Strength" description: "+2 Attack." }) attackObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] attackAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([attackObject], null, legion, null, "Gains +2 Attack") attackAura.isRemovable = false attackAura.appliedName = i18next.t("modifiers.boss_33_applied_name_2") backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([attackAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_3_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 speedBuffContextObject = Modifier.createContextObjectOnBoard() speedBuffContextObject.attributeBuffs = {"speed": 3} speedBuffContextObject.attributeBuffsAbsolute = ["speed"] speedBuffContextObject.attributeBuffsFixed = ["speed"] speedBuffContextObject.appliedName = i18next.t("modifiers.boss_33_applied_name") speedBuffContextObject.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] speedAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([speedBuffContextObject], null, legion, null, "Can move 2 extra spaces") speedAura.isRemovable = false speedAura.appliedName = i18next.t("modifiers.boss_33_applied_name") backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([speedAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss33_4) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_33_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_33_4_desc")) card.setBoundingBoxWidth(95) card.setBoundingBoxHeight(105) card.setFXResource(["FX.Cards.Neutral.NightWatcher"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f4_engulfingshadow_attack_swing.audio receiveDamage : RSX.sfx_f4_engulfingshadow_attack_impact.audio attackDamage : RSX.sfx_f4_engulfingshadow_hit.audio death : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( breathing : RSX.bossLegionBreathing.name idle : RSX.bossLegionIdle.name walk : RSX.bossLegionRun.name attack : RSX.bossLegionAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossLegionHit.name death : RSX.bossLegionDeath.name ) card.atk = 2 card.maxHP = 8 card.speed = 1 immuneToSpellTargeting = ModifierImmuneToSpellsByEnemy.createContextObject() immuneToSpellTargeting.isRemovable = false legion = [ Cards.Boss.Boss33_1, Cards.Boss.Boss33_2, Cards.Boss.Boss33_3, Cards.Boss.Boss33_4, Cards.Boss.Boss33 ] spellImmuneAura = Modifier.createContextObjectWithOnBoardAuraForAllAlliesAndSelfAndGeneral([immuneToSpellTargeting], null, legion, null, "Cannot be targeted by enemy spells") spellImmuneAura.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false respawnClones = ModifierStartTurnWatchRespawnClones.createContextObject() respawnClones.isRemovable = false card.setInherentModifiersContextObjects([spellImmuneAura, backupGeneral, respawnClones]) if (identifier == Cards.Boss.Boss34) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_34_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_34_bio")) card.setDescription(i18next.t("boss_battles.boss_34_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_harmony) card.setPortraitResource(RSX.speech_portrait_harmony) card.setPortraitHexResource(RSX.boss_harmony_hex_portrait) card.setFXResource(["FX.Cards.Faction2.JadeOgre"]) card.setBoundingBoxWidth(65) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2_jadeogre_attack_impact.audio death : RSX.sfx_f2_jadeogre_death.audio ) card.setBaseAnimResource( breathing : RSX.bossHarmonyBreathing.name idle : RSX.bossHarmonyIdle.name walk : RSX.bossHarmonyRun.name attack : RSX.bossHarmonyAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossHarmonyHit.name death : RSX.bossHarmonyRun.name ) card.atk = 3 card.maxHP = 25 contextObject = PlayerModifierManaModifier.createCostChangeContextObject(-25, CardType.Unit) contextObject.activeInHand = contextObject.activeInDeck = contextObject.activeInSignatureCards = false contextObject.activeOnBoard = true reducedManaCost = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetBothPlayers([contextObject], "Minions cost 0 mana") reducedManaCost.isRemovable = false spawnDissonance = ModifierDieSpawnNewGeneral.createContextObject({id: Cards.Boss.Boss34_2}) spawnDissonance.isRemovable = false spawnDissonance.isHiddenToUI = true #customContextObject = PlayerModifierManaModifier.createCostChangeContextObject(0, CardType.Unit) #customContextObject.modifiersContextObjects[0].attributeBuffsAbsolute = ["manaCost"] #customContextObject.modifiersContextObjects[0].attributeBuffsFixed = ["manaCost"] #manaReduction = ModifierCardControlledPlayerModifiers.createContextObjectOnBoardToTargetBothPlayers([customContextObject], "All minions cost 0 mana.") #manaReduction.isRemovable = false card.setInherentModifiersContextObjects([reducedManaCost, spawnDissonance]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss34_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_34_2_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_34_2_desc")) card.setFXResource(["FX.Cards.Faction2.JadeOgre"]) card.setBoundingBoxWidth(65) card.setBoundingBoxHeight(90) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_unit_physical_4.audio attack : RSX.sfx_f2_jadeogre_attack_swing.audio receiveDamage : RSX.sfx_f2_jadeogre_hit.audio attackDamage : RSX.sfx_f2_jadeogre_attack_impact.audio death : RSX.sfx_f2_jadeogre_death.audio ) card.setBaseAnimResource( breathing : RSX.bossDissonanceBreathing.name idle : RSX.bossDissonanceIdle.name walk : RSX.bossDissonanceRun.name attack : RSX.bossDissonanceAttack.name attackReleaseDelay: 0.0 attackDelay: 0.8 damage : RSX.bossDissonanceHit.name death : RSX.bossDissonanceRun.name ) card.atk = 3 card.maxHP = 25 swapAllegiancesGainAttack = ModifierSwitchAllegiancesGainAttack.createContextObject() swapAllegiancesGainAttack.isRemovable = false frenzyContextObject = ModifierFrenzy.createContextObject() frenzyContextObject.isRemovable = false card.setInherentModifiersContextObjects([swapAllegiancesGainAttack, frenzyContextObject]) if (identifier == Cards.Boss.Boss35) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_35_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_35_bio")) card.setDescription(i18next.t("boss_battles.boss_35_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_andromeda) card.setPortraitResource(RSX.speech_portrait_andromeda) card.setPortraitHexResource(RSX.boss_andromeda_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Pandora"]) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(95) card.setBaseSoundResource( apply : RSX.sfx_summonlegendary.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_pandora_attack_swing.audio receiveDamage : RSX.sfx_neutral_pandora_hit.audio attackDamage : RSX.sfx_neutral_pandora_attack_impact.audio death : RSX.sfx_neutral_pandora_death.audio ) card.setBaseAnimResource( breathing : RSX.bossAndromedaBreathing.name idle : RSX.bossAndromedaIdle.name walk : RSX.bossAndromedaRun.name attack : RSX.bossAndromedaAttack.name attackReleaseDelay: 0.0 attackDelay: 1.0 damage : RSX.bossAndromedaHit.name death : RSX.bossAndromedaDeath.name ) card.atk = 3 card.maxHP = 42 randomTransformMinions = ModifierOpponentSummonWatchRandomTransform.createContextObject() randomTransformMinions.isRemovable = false flyingObject = ModifierFlying.createContextObject() flyingObject.isRemovable = false card.setInherentModifiersContextObjects([randomTransformMinions, flyingObject]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss36) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_36_bio")) card.setDescription(i18next.t("boss_battles.boss_36_desc")) card.setBossBattleBattleMapIndex(7) card.setSpeechResource(RSX.speech_portrait_kaiju) card.setPortraitResource(RSX.speech_portrait_kaiju) card.setPortraitHexResource(RSX.boss_kaiju_hex_portrait) card.setFXResource(["FX.Cards.Faction3.GrandmasterNoshRak"]) card.setBaseSoundResource( apply : RSX.sfx_spell_ghostlightning.audio walk : RSX.sfx_neutral_silitharveteran_death.audio attack : RSX.sfx_neutral_makantorwarbeast_attack_swing.audio receiveDamage : RSX.sfx_f6_boreanbear_hit.audio attackDamage : RSX.sfx_f6_boreanbear_attack_impact.audio death : RSX.sfx_f6_boreanbear_death.audio ) card.setBaseAnimResource( breathing : RSX.bossInvaderBreathing.name idle : RSX.bossInvaderIdle.name walk : RSX.bossInvaderRun.name attack : RSX.bossInvaderAttack.name attackReleaseDelay: 0.0 attackDelay: 1.1 damage : RSX.bossInvaderHit.name death : RSX.bossInvaderDeath.name ) card.atk = 3 card.maxHP = 80 damageRandom = ModifierStartTurnWatchDamageRandom.createContextObject(6) damageRandom.isRemovable = false card.setInherentModifiersContextObjects([damageRandom]) card.signatureCardData = {id: Cards.BossSpell.MoldingEarth} if (identifier == Cards.Boss.Boss36_2) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_2_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_36_2_desc")) card.setBoundingBoxWidth(85) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction1.IroncliffeGuardian"]) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_f1ironcliffeguardian_attack_swing.audio receiveDamage : RSX.sfx_f1ironcliffeguardian_hit.audio attackDamage : RSX.sfx_f1ironcliffeguardian_attack_impact.audio death : RSX.sfx_f1ironcliffeguardian_death.audio ) card.setBaseAnimResource( breathing : RSX.bossProtectorBreathing.name idle : RSX.bossProtectorIdle.name walk : RSX.bossProtectorRun.name attack : RSX.bossProtectorAttack.name attackReleaseDelay: 0.0 attackDelay: 0.7 damage : RSX.bossProtectorDamage.name death : RSX.bossProtectorDeath.name ) card.atk = 1 card.maxHP = 50 replaceGeneral = ModifierOnSpawnKillMyGeneral.createContextObject() replaceGeneral.isRemovable = false gainAttackOnKill = ModifierDeathWatchGainAttackEqualToEnemyAttack.createContextObject() gainAttackOnKill.isRemovable = false card.setInherentModifiersContextObjects([replaceGeneral, gainAttackOnKill]) if (identifier == Cards.Boss.Boss36_3) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_36_3_name") card.manaCost = 0 card.setDescription(i18next.t("boss_battles.boss_36_3_desc")) card.raceId = Races.Structure card.setFXResource(["FX.Cards.Faction3.BrazierDuskWind"]) card.setBaseSoundResource( apply : RSX.sfx_spell_divinebond.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_monsterdreamoracle_attack_swing.audio receiveDamage : RSX.sfx_neutral_monsterdreamoracle_hit.audio attackDamage : RSX.sfx_f1_general_attack_impact.audio death : RSX.sfx_neutral_golembloodshard_death.audio ) card.setBaseAnimResource( breathing : RSX.bossCityBreathing.name idle : RSX.bossCityIdle.name walk : RSX.bossCityIdle.name attack : RSX.bossCityAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.bossCityDamage.name death : RSX.bossCityDeath.name ) card.atk = 0 card.maxHP = 3 buffEnemyGeneralOnDeath = ModifierDyingWishBuffEnemyGeneral.createContextObject(2,6) buffEnemyGeneralOnDeath.isRemovable = false card.setInherentModifiersContextObjects([buffEnemyGeneralOnDeath]) if (identifier == Cards.Boss.Boss37) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_37_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_37_bio")) card.setDescription(i18next.t("boss_battles.boss_37_desc")) card.setBossBattleBattleMapIndex(8) card.setSpeechResource(RSX.speech_portrait_soulstealer) card.setPortraitResource(RSX.speech_portrait_soulstealer) card.setPortraitHexResource(RSX.boss_soulstealer_hex_portrait) card.setBoundingBoxWidth(60) card.setBoundingBoxHeight(90) card.setFXResource(["FX.Cards.Faction2.CelestialPhantom"]) card.setBaseSoundResource( apply : RSX.sfx_spell_deathstrikeseal.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f2_celestialphantom_attack_swing.audio receiveDamage : RSX.sfx_f2_celestialphantom_hit.audio attackDamage : RSX.sfx_f2_celestialphantom_attack_impact.audio death : RSX.sfx_f2_celestialphantom_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSoulstealerBreathing.name idle : RSX.bossSoulstealerIdle.name walk : RSX.bossSoulstealerRun.name attack : RSX.bossSoulstealerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.bossSoulstealerDamage.name death : RSX.bossSoulstealerDeath.name ) card.atk = 3 card.maxHP = 30 enemyMinionGeneralSwap = PlayerModifierOpponentSummonWatchSwapGeneral.createContextObject() enemyMinionGeneralSwap.isRemovable = false backupGeneral = ModifierBackupGeneral.createContextObject() backupGeneral.activeInHand = backupGeneral.activeInDeck = backupGeneral.activeInSignatureCards = false backupGeneral.activeOnBoard = true backupGeneral.isRemovable = false backupGeneral.appliedName = i18next.t("modifiers.boss_37_applied_name") backupGeneral.appliedDescription = i18next.t("modifiers.boss_37_applied_desc") applyModifierToSummonedMinions = PlayerModifierSummonWatchApplyModifiers.createContextObject([backupGeneral], i18next.t("modifiers.boss_37_applied_name")) applyModifierToSummonedMinions.isRemovable = false #applyBackUpGeneralApplyingModifierToSummonedMinions = ModifierSummonWatchFromActionBarApplyModifiers.createContextObject([applyModifierToSummonedMinions], "Soul Vessel") #applyBackUpGeneralApplyingModifierToSummonedMinions.isRemovable = false card.setInherentModifiersContextObjects([enemyMinionGeneralSwap, applyModifierToSummonedMinions]) card.signatureCardData = {id: Cards.BossSpell.AncientKnowledge} if (identifier == Cards.Boss.Boss38) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(true) card.factionId = Factions.Boss card.name = i18next.t("boss_battles.boss_38_name") card.manaCost = 0 card.setBossBattleDescription(i18next.t("boss_battles.boss_38_bio")) card.setDescription(i18next.t("boss_battles.boss_38_desc")) card.setBossBattleBattleMapIndex(9) card.setSpeechResource(RSX.speech_portrait_spelleater) card.setPortraitResource(RSX.speech_portrait_spelleater) card.setPortraitHexResource(RSX.boss_spelleater_hex_portrait) card.setFXResource(["FX.Cards.Neutral.Grailmaster"]) card.setBoundingBoxWidth(100) card.setBoundingBoxHeight(105) card.setBaseSoundResource( apply : RSX.sfx_spell_diretidefrenzy.audio walk : RSX.sfx_neutral_sai_attack_impact.audio attack : RSX.sfx_neutral_spiritscribe_attack_swing.audio receiveDamage : RSX.sfx_neutral_spiritscribe_hit.audio attackDamage : RSX.sfx_neutral_spiritscribe_impact.audio death : RSX.sfx_neutral_spiritscribe_death.audio ) card.setBaseAnimResource( breathing : RSX.bossSpelleaterBreathing.name idle : RSX.bossSpelleaterIdle.name walk : RSX.bossSpelleaterRun.name attack : RSX.bossSpelleaterAttack.name attackReleaseDelay: 0.0 attackDelay: 0.9 damage : RSX.bossSpelleaterHit.name death : RSX.bossSpelleaterDeath.name ) card.atk = 3 card.maxHP = 35 spellWatchGainKeyword = ModifierEnemySpellWatchGainRandomKeyword.createContextObject() spellWatchGainKeyword.isRemovable = false summonsGainKeywords = ModifierAnySummonWatchGainGeneralKeywords.createContextObject() summonsGainKeywords.isRemovable = false card.setInherentModifiersContextObjects([spellWatchGainKeyword, summonsGainKeywords]) card.signatureCardData = {id: Cards.BossSpell.EtherealWind} if (identifier == Cards.Boss.FrostfireImp) card = new Unit(gameSession) card.setIsHiddenInCollection(true) card.setIsGeneral(false) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_imp_name") card.manaCost = 0 card.setDescription(i18next.t("cards.faction_1_unit_lysian_brawler_desc")) card.setFXResource(["FX.Cards.Neutral.Zyx"]) card.setBoundingBoxWidth(80) card.setBoundingBoxHeight(80) card.setBaseSoundResource( apply : RSX.sfx_spell_immolation_b.audio walk : RSX.sfx_unit_run_charge_4.audio attack : RSX.sfx_neutral_emeraldrejuvenator_attack_swing.audio receiveDamage : RSX.sfx_f1lysianbrawler_hit.audio attackDamage : RSX.sfx_f1lysianbrawler_attack_impact.audio death : RSX.sfx_neutral_emeraldrejuvenator_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralZyxFestiveBreathing.name idle : RSX.neutralZyxFestiveIdle.name walk : RSX.neutralZyxFestiveRun.name attack : RSX.neutralZyxFestiveAttack.name attackReleaseDelay: 0.0 attackDelay: 0.6 damage : RSX.neutralZyxFestiveHit.name death : RSX.neutralZyxFestiveDeath.name ) card.atk = 2 card.maxHP = 3 card.setInherentModifiersContextObjects([ModifierTranscendance.createContextObject()]) if (identifier == Cards.Boss.FrostfireTiger) card = new Unit(gameSession) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_tiger_name") card.setDescription(i18next.t("cards.neutral_saberspine_tiger_desc")) card.setFXResource(["FX.Cards.Neutral.SaberspineTiger"]) card.setBaseSoundResource( apply : RSX.sfx_unit_deploy_1.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_f6_boreanbear_attack_swing.audio receiveDamage : RSX.sfx_neutral_beastsaberspinetiger_hit.audio attackDamage : RSX.sfx_neutral_beastsaberspinetiger_attack_impact.audio death : RSX.sfx_neutral_beastsaberspinetiger_death.audio ) card.setBaseAnimResource( breathing : RSX.neutralFrostfireTigerBreathing.name idle : RSX.neutralFrostfireTigerIdle.name walk : RSX.neutralFrostfireTigerRun.name attack : RSX.neutralFrostfireTigerAttack.name attackReleaseDelay: 0.0 attackDelay: 0.4 damage : RSX.neutralFrostfireTigerHit.name death : RSX.neutralFrostfireTigerDeath.name ) card.atk = 3 card.maxHP = 2 card.manaCost = 4 card.setInherentModifiersContextObjects([ModifierFirstBlood.createContextObject()]) if (identifier == Cards.Boss.FrostfireSnowchaser) card = new Unit(gameSession) card.factionId = Factions.Boss card.name = i18next.t("cards.frostfire_snowchser_name") card.setDescription(i18next.t("cards.neutral_vale_hunter_desc")) card.raceId = Races.Vespyr card.setFXResource(["FX.Cards.Faction6.SnowElemental"]) card.setBaseSoundResource( apply : RSX.sfx_spell_amplification.audio walk : RSX.sfx_singe2.audio attack : RSX.sfx_neutral_artifacthunter_attack_swing.audio receiveDamage : RSX.sfx_neutral_artifacthunter_hit.audio attackDamage : RSX.sfx_neutral_artifacthunter_attack_impact.audio death : RSX.sfx_neutral_artifacthunter_death.audio ) card.setBaseAnimResource( breathing : RSX.f6FestiveSnowchaserBreathing.name idle : RSX.f6FestiveSnowchaserIdle.name walk : RSX.f6FestiveSnowchaserRun.name attack : RSX.f6FestiveSnowchaserAttack.name attackReleaseDelay: 0.0 attackDelay: 0.3 damage : RSX.f6FestiveSnowchaserDamage.name death : RSX.f6FestiveSnowchaserDeath.name ) card.atk = 2 card.maxHP = 1 card.manaCost = 1 card.setInherentModifiersContextObjects([ModifierRanged.createContextObject()]) if (identifier == Cards.BossSpell.LaceratingFrost) card = new SpellLaceratingFrost(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.LaceratingFrost card.name = "PI:NAME:<NAME>END_PI" card.setDescription("Deal 2 damage to the enemy General and stun all nearby enemy minions.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.damageAmount = 2 card.setFXResource(["FX.Cards.Spell.LaceratingFrost"]) card.setBaseSoundResource( apply : RSX.sfx_f6_icebeetle_death.audio ) card.setBaseAnimResource( idle : RSX.iconLaceratingFrostIdle.name active : RSX.iconLaceratingFrostActive.name ) if (identifier == Cards.BossSpell.EntanglingShadow) card = new SpellEntanglingShadows(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.EntanglingShadow card.name = "Entangling Shadow" card.setDescription("Summon Wraithlings and Shadow Creep in a 2x2 area.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.setAffectPattern(CONFIG.PATTERN_2X2) card.cardDataOrIndexToSpawn = {id: Cards.Faction4.Wraithling} card.setFXResource(["FX.Cards.Spell.EntanglingShadow"]) card.setBaseSoundResource( apply : RSX.sfx_spell_shadowreflection.audio ) card.setBaseAnimResource( idle : RSX.iconCultivatingDarkIdle.name active : RSX.iconCultivatingDarkActive.name ) if (identifier == Cards.BossSpell.LivingFlame) card = new SpellDamageAndSpawnEntitiesNearbyGeneral(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.LivingFlame card.name = "Living FlPI:NAME:<NAME>END_PI" card.setDescription("Deal 2 damage to an enemy and summon two Spellsparks nearby your General.") card.spellFilterType = SpellFilterType.EnemyDirect card.manaCost = 1 card.damageAmount = 2 card.canTargetGeneral = true card.cardDataOrIndexToSpawn = {id: Cards.Neutral.Spellspark} card.setFXResource(["FX.Cards.Spell.LivingFlame"]) card.setBaseSoundResource( apply : RSX.sfx_spell_phoenixfire.audio ) card.setBaseAnimResource( idle : RSX.iconLivingFlameIdle.name active : RSX.iconLivingFlameActive.name ) if (identifier == Cards.BossSpell.MoldingEarth) card = new SpellMoldingEarth(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.MoldingEarth card.name = "Molding Earth" card.setDescription("Summon 3 Magmas with random keywords nearby your General.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.cardDataOrIndexToSpawn = {id: Cards.Faction5.MiniMagmar} card.setFXResource(["FX.Cards.Spell.MoldingEarth"]) card.setBaseSoundResource( apply : RSX.sfx_spell_disintegrate.audio ) card.setBaseAnimResource( idle : RSX.iconModlingEarthIdle.name active : RSX.iconModlingEarthActive.name ) if (identifier == Cards.BossSpell.EtherealWind) card = new SpellSilenceAndSpawnEntityNearby(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.EtherealWind card.name = "Ethereal Wind" card.setDescription("Dispel an enemy and summon a Wind Dervish nearby.") card.spellFilterType = SpellFilterType.EnemyDirect card.manaCost = 1 card.canTargetGeneral = true card.cardDataOrIndexToSpawn = {id: Cards.Faction3.Dervish} card.setFXResource(["FX.Cards.Spell.EtherealWind"]) card.setBaseSoundResource( apply : RSX.sfx_spell_entropicdecay.audio ) card.setBaseAnimResource( idle : RSX.iconEtherealWindIdle.name active : RSX.iconEtherealWindActive.name ) if (identifier == Cards.BossSpell.RestoringLight) card = new SpellRestoringLight(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.RestoringLight card.name = "Restoring Light" card.setDescription("Restore 3 Health to your General. Give your friendly minions +1 Health.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 buffContextObject = Modifier.createContextObjectWithAttributeBuffs(0,1) buffContextObject.appliedName = "Restored Light" card.setTargetModifiersContextObjects([ buffContextObject ]) card.setFXResource(["FX.Cards.Spell.RestoringLight"]) card.setBaseSoundResource( apply : RSX.sfx_spell_sunbloom.audio ) card.setBaseAnimResource( idle : RSX.iconRestoringLightIdle.name active : RSX.iconRestoringLightActive.name ) if (identifier == Cards.BossSpell.AncientKnowledge) card = new Spell(gameSession) card.factionId = Factions.Boss card.setIsHiddenInCollection(true) card.id = Cards.BossSpell.AncientKnowledge card.name = "PI:NAME:<NAME>END_PIcient Knowledge" card.setDescription("Draw 2 cards.") card.spellFilterType = SpellFilterType.None card.manaCost = 1 card.drawCardsPostPlay = 2 card.setFXResource(["FX.Cards.Spell.AncientKnowledge"]) card.setBaseSoundResource( apply : RSX.sfx_spell_scionsfirstwish.audio ) card.setBaseAnimResource( idle : RSX.iconAncientKnowledgeIdle.name active : RSX.iconAncientKnowledgeActive.name ) return card module.exports = CardFactory_Bosses
[ { "context": "nerate()\n username: data.username\n password: hash\n }\n\n client.respond composer.createResponse('al", "end": 673, "score": 0.9968647360801697, "start": 669, "tag": "PASSWORD", "value": "hash" } ]
src/net/events/register.coffee
habbo5/game-server
8
logger = require '@/utils/logger' shortid = require 'shortid' validator = require 'validator' bcrypt = require 'bcrypt' User = require '@/storage/models/user' composer = require '@/net/composer' handle = (client, data) -> return if client.habbo || !data.password || !data.username userExists = await User.findOne { username: { $regex : new RegExp(data.username, "i") } } client.respond composer.createResponse('alert', { title: 'Notice!' message: 'Username has already been taken.' }) if userExists hash = await bcrypt.hash(data.password, 10) user = await User.create { uid: shortid.generate() username: data.username password: hash } client.respond composer.createResponse('alert', { title: 'Notice!' message: 'Error during user creation. Please try again later.' }) unless user authenticatedMessage = composer.createResponse('authenticated', { username: user.username }) return client.respond authenticatedMessage module.exports = handle
208431
logger = require '@/utils/logger' shortid = require 'shortid' validator = require 'validator' bcrypt = require 'bcrypt' User = require '@/storage/models/user' composer = require '@/net/composer' handle = (client, data) -> return if client.habbo || !data.password || !data.username userExists = await User.findOne { username: { $regex : new RegExp(data.username, "i") } } client.respond composer.createResponse('alert', { title: 'Notice!' message: 'Username has already been taken.' }) if userExists hash = await bcrypt.hash(data.password, 10) user = await User.create { uid: shortid.generate() username: data.username password: <PASSWORD> } client.respond composer.createResponse('alert', { title: 'Notice!' message: 'Error during user creation. Please try again later.' }) unless user authenticatedMessage = composer.createResponse('authenticated', { username: user.username }) return client.respond authenticatedMessage module.exports = handle
true
logger = require '@/utils/logger' shortid = require 'shortid' validator = require 'validator' bcrypt = require 'bcrypt' User = require '@/storage/models/user' composer = require '@/net/composer' handle = (client, data) -> return if client.habbo || !data.password || !data.username userExists = await User.findOne { username: { $regex : new RegExp(data.username, "i") } } client.respond composer.createResponse('alert', { title: 'Notice!' message: 'Username has already been taken.' }) if userExists hash = await bcrypt.hash(data.password, 10) user = await User.create { uid: shortid.generate() username: data.username password: PI:PASSWORD:<PASSWORD>END_PI } client.respond composer.createResponse('alert', { title: 'Notice!' message: 'Error during user creation. Please try again later.' }) unless user authenticatedMessage = composer.createResponse('authenticated', { username: user.username }) return client.respond authenticatedMessage module.exports = handle
[ { "context": "yright (c) 2011\n# Publication date: 06/17/2011\n#\t\tPierre Corsini (pcorsini@polytech.unice.fr)\n#\t\tNicolas Dupont (n", "end": 69, "score": 0.999877393245697, "start": 55, "tag": "NAME", "value": "Pierre Corsini" }, { "context": "# Publication date: 06/17/2011\n#\t\tPierre Corsini (pcorsini@polytech.unice.fr)\n#\t\tNicolas Dupont (npg.dupont@gmail.com)\n#\t\tNico", "end": 97, "score": 0.9999364614486694, "start": 71, "tag": "EMAIL", "value": "pcorsini@polytech.unice.fr" }, { "context": "#\t\tPierre Corsini (pcorsini@polytech.unice.fr)\n#\t\tNicolas Dupont (npg.dupont@gmail.com)\n#\t\tNicolas Fernandez (fern", "end": 116, "score": 0.9998739361763, "start": 102, "tag": "NAME", "value": "Nicolas Dupont" }, { "context": "i (pcorsini@polytech.unice.fr)\n#\t\tNicolas Dupont (npg.dupont@gmail.com)\n#\t\tNicolas Fernandez (fernande@polytech.unice.fr", "end": 138, "score": 0.9999332427978516, "start": 118, "tag": "EMAIL", "value": "npg.dupont@gmail.com" }, { "context": "e.fr)\n#\t\tNicolas Dupont (npg.dupont@gmail.com)\n#\t\tNicolas Fernandez (fernande@polytech.unice.fr)\n#\t\tNima Izadi (nim.i", "end": 160, "score": 0.9998798370361328, "start": 143, "tag": "NAME", "value": "Nicolas Fernandez" }, { "context": "pont (npg.dupont@gmail.com)\n#\t\tNicolas Fernandez (fernande@polytech.unice.fr)\n#\t\tNima Izadi (nim.izadi@gmail.com)\n#\t\tAnd super", "end": 188, "score": 0.999935507774353, "start": 162, "tag": "EMAIL", "value": "fernande@polytech.unice.fr" }, { "context": "Nicolas Fernandez (fernande@polytech.unice.fr)\n#\t\tNima Izadi (nim.izadi@gmail.com)\n#\t\tAnd supervised by Raphaë", "end": 203, "score": 0.9998887777328491, "start": 193, "tag": "NAME", "value": "Nima Izadi" }, { "context": "andez (fernande@polytech.unice.fr)\n#\t\tNima Izadi (nim.izadi@gmail.com)\n#\t\tAnd supervised by Raphaël Bellec (r.bellec@st", "end": 224, "score": 0.9999341368675232, "start": 205, "tag": "EMAIL", "value": "nim.izadi@gmail.com" }, { "context": "a Izadi (nim.izadi@gmail.com)\n#\t\tAnd supervised by Raphaël Bellec (r.bellec@structure-computation.com)\n\n# Analyse a", "end": 261, "score": 0.9998955130577087, "start": 247, "tag": "NAME", "value": "Raphaël Bellec" }, { "context": "i@gmail.com)\n#\t\tAnd supervised by Raphaël Bellec (r.bellec@structure-computation.com)\n\n# Analyse all possible basic gesture of a singl", "end": 297, "score": 0.9999316334724426, "start": 263, "tag": "EMAIL", "value": "r.bellec@structure-computation.com" } ]
src/StateMachine.coffee
Ndpnt/CoffeeTouch.js
1
# Copyright (c) 2011 # Publication date: 06/17/2011 # Pierre Corsini (pcorsini@polytech.unice.fr) # Nicolas Dupont (npg.dupont@gmail.com) # Nicolas Fernandez (fernande@polytech.unice.fr) # Nima Izadi (nim.izadi@gmail.com) # And supervised by Raphaël Bellec (r.bellec@structure-computation.com) # Analyse all possible basic gesture of a single finger class StateMachine constructor: (@identifier, @router)-> @currentState = new NoTouch(this) @analyser = new Analyser apply: (eventName, eventObj) -> @currentState.apply(eventName, eventObj) setState: (newState) -> @currentState = newState getState: -> @currentState class GenericState init: -> # Defined par les sous classes constructor: (@machine) -> @eventObj = if @machine.currentState? then @machine.currentState.eventObj else {} this.init() apply: (eventName, arg) -> CoffeeTouch.Helper.mergeObjects(@eventObj, arg) this[eventName]() touchstart: -> #throw "undefined" touchmove: -> #throw "undefined" touchend: -> #throw "undefined" notify: (name) -> @machine.router.broadcast(name, @eventObj) class NoTouch extends GenericState touchstart: -> @machine.setState(new FirstTouch @machine) class FirstTouch extends GenericState init: -> _machine = @machine @fixedtimer = setTimeout (->(_machine.setState new Fixed _machine)), 300 touchend: -> clearTimeout @fixedtimer @notify "tap" @machine.setState new NoTouch @machine touchmove: -> clearTimeout @fixedtimer @notify "drag" @machine.setState new Drag @machine class Fixed extends GenericState init: -> @notify "fixed" touchend: -> @notify "fixedend" @machine.setState new NoTouch @machine class Drag extends GenericState init: -> @isTap = true @initialX = @eventObj.clientX @initialY = @eventObj.clientY @delta = 15 that = this setTimeout (-> that.isTap = false), 150 touchmove: -> @notify "drag" touchend: -> if @isTap and (Math.abs(@eventObj.clientX - @initialX) < @delta) && (Math.abs(@eventObj.clientY - @initialY) < @delta) @notify "tap" else @notify "dragend" @machine.setState(new NoTouch @machine)
42387
# Copyright (c) 2011 # Publication date: 06/17/2011 # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # <NAME> (<EMAIL>) # And supervised by <NAME> (<EMAIL>) # Analyse all possible basic gesture of a single finger class StateMachine constructor: (@identifier, @router)-> @currentState = new NoTouch(this) @analyser = new Analyser apply: (eventName, eventObj) -> @currentState.apply(eventName, eventObj) setState: (newState) -> @currentState = newState getState: -> @currentState class GenericState init: -> # Defined par les sous classes constructor: (@machine) -> @eventObj = if @machine.currentState? then @machine.currentState.eventObj else {} this.init() apply: (eventName, arg) -> CoffeeTouch.Helper.mergeObjects(@eventObj, arg) this[eventName]() touchstart: -> #throw "undefined" touchmove: -> #throw "undefined" touchend: -> #throw "undefined" notify: (name) -> @machine.router.broadcast(name, @eventObj) class NoTouch extends GenericState touchstart: -> @machine.setState(new FirstTouch @machine) class FirstTouch extends GenericState init: -> _machine = @machine @fixedtimer = setTimeout (->(_machine.setState new Fixed _machine)), 300 touchend: -> clearTimeout @fixedtimer @notify "tap" @machine.setState new NoTouch @machine touchmove: -> clearTimeout @fixedtimer @notify "drag" @machine.setState new Drag @machine class Fixed extends GenericState init: -> @notify "fixed" touchend: -> @notify "fixedend" @machine.setState new NoTouch @machine class Drag extends GenericState init: -> @isTap = true @initialX = @eventObj.clientX @initialY = @eventObj.clientY @delta = 15 that = this setTimeout (-> that.isTap = false), 150 touchmove: -> @notify "drag" touchend: -> if @isTap and (Math.abs(@eventObj.clientX - @initialX) < @delta) && (Math.abs(@eventObj.clientY - @initialY) < @delta) @notify "tap" else @notify "dragend" @machine.setState(new NoTouch @machine)
true
# Copyright (c) 2011 # Publication date: 06/17/2011 # PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # And supervised by PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # Analyse all possible basic gesture of a single finger class StateMachine constructor: (@identifier, @router)-> @currentState = new NoTouch(this) @analyser = new Analyser apply: (eventName, eventObj) -> @currentState.apply(eventName, eventObj) setState: (newState) -> @currentState = newState getState: -> @currentState class GenericState init: -> # Defined par les sous classes constructor: (@machine) -> @eventObj = if @machine.currentState? then @machine.currentState.eventObj else {} this.init() apply: (eventName, arg) -> CoffeeTouch.Helper.mergeObjects(@eventObj, arg) this[eventName]() touchstart: -> #throw "undefined" touchmove: -> #throw "undefined" touchend: -> #throw "undefined" notify: (name) -> @machine.router.broadcast(name, @eventObj) class NoTouch extends GenericState touchstart: -> @machine.setState(new FirstTouch @machine) class FirstTouch extends GenericState init: -> _machine = @machine @fixedtimer = setTimeout (->(_machine.setState new Fixed _machine)), 300 touchend: -> clearTimeout @fixedtimer @notify "tap" @machine.setState new NoTouch @machine touchmove: -> clearTimeout @fixedtimer @notify "drag" @machine.setState new Drag @machine class Fixed extends GenericState init: -> @notify "fixed" touchend: -> @notify "fixedend" @machine.setState new NoTouch @machine class Drag extends GenericState init: -> @isTap = true @initialX = @eventObj.clientX @initialY = @eventObj.clientY @delta = 15 that = this setTimeout (-> that.isTap = false), 150 touchmove: -> @notify "drag" touchend: -> if @isTap and (Math.abs(@eventObj.clientX - @initialX) < @delta) && (Math.abs(@eventObj.clientY - @initialY) < @delta) @notify "tap" else @notify "dragend" @machine.setState(new NoTouch @machine)
[ { "context": "ent: \"&part=snippet,contentDetails&id=\"\n key: \"AIzaSyCxL2W7WQKGQ_IKN9ug37rxeJm-Hr0t7Fw\"\n\n documentation: \"https://developers.google.c", "end": 344, "score": 0.9997319579124451, "start": 305, "tag": "KEY", "value": "AIzaSyCxL2W7WQKGQ_IKN9ug37rxeJm-Hr0t7Fw" }, { "context": "son?consumer_key=\"\n content: \"&url=\"\n key: \"b45b1aa10f1ac2941910a7f0d10f8e28\"\n\n documentation: \"https://developers.soundclo", "end": 575, "score": 0.9997462034225464, "start": 543, "tag": "KEY", "value": "b45b1aa10f1ac2941910a7f0d10f8e28" } ]
app/controllers/getter.coffee
chriscx/Disko
0
#dependencies request = require 'request' colors = require 'colors' Track = require('../models/track').Track Playlist = require('../models/playlist').Playlist sources = youtube: resolver: "https://www.googleapis.com/youtube/v3/videos?key=" content: "&part=snippet,contentDetails&id=" key: "AIzaSyCxL2W7WQKGQ_IKN9ug37rxeJm-Hr0t7Fw" documentation: "https://developers.google.com/youtube/v3/docs/videos?hl=fr" soundcloud: resolver: "https://api.soundcloud.com/resolve.json?consumer_key=" content: "&url=" key: "b45b1aa10f1ac2941910a7f0d10f8e28" documentation: "https://developers.soundcloud.com/docs/api/reference" ### find from which site is the video ### get_source = (track, callback) -> for index of sources if(track.indexOf(index) > -1) res = index callback(res) String.prototype.build_url = (source) -> src = sources[source] src.resolver + src.key + src.content + this #Replace by a redex if you can ytParseDuration = (time) -> res = '' time = time.slice(2) iOh = time.indexOf('H') if(iOh > -1) hours = time.slice(0, iOh) time = time.slice(iOh+1) iOm = time.indexOf('M') if(iOm > -1) minutes = time.slice(0, iOm) time = time.slice(iOm+1) iOs = time.indexOf('S') if(iOs > -1) seconds = time.slice(0, iOs) if seconds < 10 seconds = '0' + seconds if hours > 0 && minutes < 10 minutes = '0' + minutes if hours > 0 && minutes == undefined minutes = '00' unless minutes == 0 || minutes == undefined unless hours >0 minutes + ':' + seconds else hours + ':' + minutes + ':' + seconds else '0:' + seconds convertDuration = (time) -> inSeconds = Math.floor(time/1000) #from ms to s hours = Math.floor(inSeconds/3600) inSeconds = inSeconds - hours * 3600 minutes = Math.floor(inSeconds / 60) seconds = inSeconds - minutes * 60 if seconds < 10 seconds = '0' + seconds if hours > 0 && minutes < 10 minutes = '0' + minutes unless minutes == 0 || minutes == undefined unless hours >0 minutes + ':' + seconds else hours + ':' + minutes + ':' + seconds else seconds request_url = (url, callback) -> request url, (error, response, html) -> if error and (response.statusCode!=200) console.log "Error:" + err else callback response.body infos_yt = (content, callback) -> track = new Track title: content.snippet.title artist: content.snippet.channelTitle url: 'http://www.youtube.com/watch?v=' + content.id src: content.id service: 'Youtube' duration: ytParseDuration content.contentDetails.duration callback track ### get the information from the responses and create objects to be stored in our DB ### infos_sc = (content, callback) -> track = new Track title: content.title artist: content.user.username url: content.permalink_url src: content.id service: 'Soundcloud' duration: convertDuration content.duration callback track ### manages the actions of dispatching between the different sources ### dispatch = (track, callback) -> get_source track, (src) -> url = null switch src when "youtube" # to isolate the video id s = track.split("v=") if(s[1]) s = s[1].split("&") track = s[0] else stop = true when "soundcloud" else console.log "SOURCE NOT SUPPORTED YET".red stop = true unless stop url = track.build_url(src) request_url url, (res) -> switch src when "youtube" parsed = JSON.parse(res) if(parsed.pageInfo.totalResults == 0) callback {code: 0} else infos_yt JSON.parse(res).items[0], callback when "soundcloud" parsed = JSON.parse(res) if(parsed.kind == 'track') infos_sc JSON.parse(res), callback else callback {code: 0} else callback {code: 0} exports.dispatch = dispatch
73299
#dependencies request = require 'request' colors = require 'colors' Track = require('../models/track').Track Playlist = require('../models/playlist').Playlist sources = youtube: resolver: "https://www.googleapis.com/youtube/v3/videos?key=" content: "&part=snippet,contentDetails&id=" key: "<KEY>" documentation: "https://developers.google.com/youtube/v3/docs/videos?hl=fr" soundcloud: resolver: "https://api.soundcloud.com/resolve.json?consumer_key=" content: "&url=" key: "<KEY>" documentation: "https://developers.soundcloud.com/docs/api/reference" ### find from which site is the video ### get_source = (track, callback) -> for index of sources if(track.indexOf(index) > -1) res = index callback(res) String.prototype.build_url = (source) -> src = sources[source] src.resolver + src.key + src.content + this #Replace by a redex if you can ytParseDuration = (time) -> res = '' time = time.slice(2) iOh = time.indexOf('H') if(iOh > -1) hours = time.slice(0, iOh) time = time.slice(iOh+1) iOm = time.indexOf('M') if(iOm > -1) minutes = time.slice(0, iOm) time = time.slice(iOm+1) iOs = time.indexOf('S') if(iOs > -1) seconds = time.slice(0, iOs) if seconds < 10 seconds = '0' + seconds if hours > 0 && minutes < 10 minutes = '0' + minutes if hours > 0 && minutes == undefined minutes = '00' unless minutes == 0 || minutes == undefined unless hours >0 minutes + ':' + seconds else hours + ':' + minutes + ':' + seconds else '0:' + seconds convertDuration = (time) -> inSeconds = Math.floor(time/1000) #from ms to s hours = Math.floor(inSeconds/3600) inSeconds = inSeconds - hours * 3600 minutes = Math.floor(inSeconds / 60) seconds = inSeconds - minutes * 60 if seconds < 10 seconds = '0' + seconds if hours > 0 && minutes < 10 minutes = '0' + minutes unless minutes == 0 || minutes == undefined unless hours >0 minutes + ':' + seconds else hours + ':' + minutes + ':' + seconds else seconds request_url = (url, callback) -> request url, (error, response, html) -> if error and (response.statusCode!=200) console.log "Error:" + err else callback response.body infos_yt = (content, callback) -> track = new Track title: content.snippet.title artist: content.snippet.channelTitle url: 'http://www.youtube.com/watch?v=' + content.id src: content.id service: 'Youtube' duration: ytParseDuration content.contentDetails.duration callback track ### get the information from the responses and create objects to be stored in our DB ### infos_sc = (content, callback) -> track = new Track title: content.title artist: content.user.username url: content.permalink_url src: content.id service: 'Soundcloud' duration: convertDuration content.duration callback track ### manages the actions of dispatching between the different sources ### dispatch = (track, callback) -> get_source track, (src) -> url = null switch src when "youtube" # to isolate the video id s = track.split("v=") if(s[1]) s = s[1].split("&") track = s[0] else stop = true when "soundcloud" else console.log "SOURCE NOT SUPPORTED YET".red stop = true unless stop url = track.build_url(src) request_url url, (res) -> switch src when "youtube" parsed = JSON.parse(res) if(parsed.pageInfo.totalResults == 0) callback {code: 0} else infos_yt JSON.parse(res).items[0], callback when "soundcloud" parsed = JSON.parse(res) if(parsed.kind == 'track') infos_sc JSON.parse(res), callback else callback {code: 0} else callback {code: 0} exports.dispatch = dispatch
true
#dependencies request = require 'request' colors = require 'colors' Track = require('../models/track').Track Playlist = require('../models/playlist').Playlist sources = youtube: resolver: "https://www.googleapis.com/youtube/v3/videos?key=" content: "&part=snippet,contentDetails&id=" key: "PI:KEY:<KEY>END_PI" documentation: "https://developers.google.com/youtube/v3/docs/videos?hl=fr" soundcloud: resolver: "https://api.soundcloud.com/resolve.json?consumer_key=" content: "&url=" key: "PI:KEY:<KEY>END_PI" documentation: "https://developers.soundcloud.com/docs/api/reference" ### find from which site is the video ### get_source = (track, callback) -> for index of sources if(track.indexOf(index) > -1) res = index callback(res) String.prototype.build_url = (source) -> src = sources[source] src.resolver + src.key + src.content + this #Replace by a redex if you can ytParseDuration = (time) -> res = '' time = time.slice(2) iOh = time.indexOf('H') if(iOh > -1) hours = time.slice(0, iOh) time = time.slice(iOh+1) iOm = time.indexOf('M') if(iOm > -1) minutes = time.slice(0, iOm) time = time.slice(iOm+1) iOs = time.indexOf('S') if(iOs > -1) seconds = time.slice(0, iOs) if seconds < 10 seconds = '0' + seconds if hours > 0 && minutes < 10 minutes = '0' + minutes if hours > 0 && minutes == undefined minutes = '00' unless minutes == 0 || minutes == undefined unless hours >0 minutes + ':' + seconds else hours + ':' + minutes + ':' + seconds else '0:' + seconds convertDuration = (time) -> inSeconds = Math.floor(time/1000) #from ms to s hours = Math.floor(inSeconds/3600) inSeconds = inSeconds - hours * 3600 minutes = Math.floor(inSeconds / 60) seconds = inSeconds - minutes * 60 if seconds < 10 seconds = '0' + seconds if hours > 0 && minutes < 10 minutes = '0' + minutes unless minutes == 0 || minutes == undefined unless hours >0 minutes + ':' + seconds else hours + ':' + minutes + ':' + seconds else seconds request_url = (url, callback) -> request url, (error, response, html) -> if error and (response.statusCode!=200) console.log "Error:" + err else callback response.body infos_yt = (content, callback) -> track = new Track title: content.snippet.title artist: content.snippet.channelTitle url: 'http://www.youtube.com/watch?v=' + content.id src: content.id service: 'Youtube' duration: ytParseDuration content.contentDetails.duration callback track ### get the information from the responses and create objects to be stored in our DB ### infos_sc = (content, callback) -> track = new Track title: content.title artist: content.user.username url: content.permalink_url src: content.id service: 'Soundcloud' duration: convertDuration content.duration callback track ### manages the actions of dispatching between the different sources ### dispatch = (track, callback) -> get_source track, (src) -> url = null switch src when "youtube" # to isolate the video id s = track.split("v=") if(s[1]) s = s[1].split("&") track = s[0] else stop = true when "soundcloud" else console.log "SOURCE NOT SUPPORTED YET".red stop = true unless stop url = track.build_url(src) request_url url, (res) -> switch src when "youtube" parsed = JSON.parse(res) if(parsed.pageInfo.totalResults == 0) callback {code: 0} else infos_yt JSON.parse(res).items[0], callback when "soundcloud" parsed = JSON.parse(res) if(parsed.kind == 'track') infos_sc JSON.parse(res), callback else callback {code: 0} else callback {code: 0} exports.dispatch = dispatch
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9985317587852478, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-wget.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") net = require("net") http = require("http") # wget sends an HTTP/1.0 request with Connection: Keep-Alive # # Sending back a chunked response to an HTTP/1.0 client would be wrong, # so what has to happen in this case is that the connection is closed # by the server after the entity body if the Content-Length was not # sent. # # If the Content-Length was sent, we can probably safely honor the # keep-alive request, even though HTTP 1.0 doesn't say that the # connection can be kept open. Presumably any client sending this # header knows that it is extending HTTP/1.0 and can handle the # response. We don't test that here however, just that if the # content-length is not provided, that the connection is in fact # closed. server_response = "" client_got_eof = false connection_was_closed = false server = http.createServer((req, res) -> res.writeHead 200, "Content-Type": "text/plain" res.write "hello " res.write "world\n" res.end() return ) server.listen common.PORT server.on "listening", -> c = net.createConnection(common.PORT) c.setEncoding "utf8" c.on "connect", -> c.write "GET / HTTP/1.0\r\n" + "Connection: Keep-Alive\r\n\r\n" return c.on "data", (chunk) -> console.log chunk server_response += chunk return c.on "end", -> client_got_eof = true console.log "got end" c.end() return c.on "close", -> connection_was_closed = true console.log "got close" server.close() return return process.on "exit", -> m = server_response.split("\r\n\r\n") assert.equal m[1], "hello world\n" assert.ok client_got_eof assert.ok connection_was_closed return
47672
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") net = require("net") http = require("http") # wget sends an HTTP/1.0 request with Connection: Keep-Alive # # Sending back a chunked response to an HTTP/1.0 client would be wrong, # so what has to happen in this case is that the connection is closed # by the server after the entity body if the Content-Length was not # sent. # # If the Content-Length was sent, we can probably safely honor the # keep-alive request, even though HTTP 1.0 doesn't say that the # connection can be kept open. Presumably any client sending this # header knows that it is extending HTTP/1.0 and can handle the # response. We don't test that here however, just that if the # content-length is not provided, that the connection is in fact # closed. server_response = "" client_got_eof = false connection_was_closed = false server = http.createServer((req, res) -> res.writeHead 200, "Content-Type": "text/plain" res.write "hello " res.write "world\n" res.end() return ) server.listen common.PORT server.on "listening", -> c = net.createConnection(common.PORT) c.setEncoding "utf8" c.on "connect", -> c.write "GET / HTTP/1.0\r\n" + "Connection: Keep-Alive\r\n\r\n" return c.on "data", (chunk) -> console.log chunk server_response += chunk return c.on "end", -> client_got_eof = true console.log "got end" c.end() return c.on "close", -> connection_was_closed = true console.log "got close" server.close() return return process.on "exit", -> m = server_response.split("\r\n\r\n") assert.equal m[1], "hello world\n" assert.ok client_got_eof assert.ok connection_was_closed return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") net = require("net") http = require("http") # wget sends an HTTP/1.0 request with Connection: Keep-Alive # # Sending back a chunked response to an HTTP/1.0 client would be wrong, # so what has to happen in this case is that the connection is closed # by the server after the entity body if the Content-Length was not # sent. # # If the Content-Length was sent, we can probably safely honor the # keep-alive request, even though HTTP 1.0 doesn't say that the # connection can be kept open. Presumably any client sending this # header knows that it is extending HTTP/1.0 and can handle the # response. We don't test that here however, just that if the # content-length is not provided, that the connection is in fact # closed. server_response = "" client_got_eof = false connection_was_closed = false server = http.createServer((req, res) -> res.writeHead 200, "Content-Type": "text/plain" res.write "hello " res.write "world\n" res.end() return ) server.listen common.PORT server.on "listening", -> c = net.createConnection(common.PORT) c.setEncoding "utf8" c.on "connect", -> c.write "GET / HTTP/1.0\r\n" + "Connection: Keep-Alive\r\n\r\n" return c.on "data", (chunk) -> console.log chunk server_response += chunk return c.on "end", -> client_got_eof = true console.log "got end" c.end() return c.on "close", -> connection_was_closed = true console.log "got close" server.close() return return process.on "exit", -> m = server_response.split("\r\n\r\n") assert.equal m[1], "hello world\n" assert.ok client_got_eof assert.ok connection_was_closed return
[ { "context": " subject = {}\n assign subject, 'foo.bar[]', 'peter;paul;mary'\n subject.foo.bar.toString().should.", "end": 2264, "score": 0.9978382587432861, "start": 2259, "tag": "NAME", "value": "peter" }, { "context": "ject = {}\n assign subject, 'foo.bar[]', 'peter;paul;mary'\n subject.foo.bar.toString().should.equal", "end": 2269, "score": 0.6792576909065247, "start": 2265, "tag": "NAME", "value": "paul" }, { "context": "ry'\n subject.foo.bar.toString().should.equal ['peter','paul','mary'].toString()\n\n\n it 'should convert", "end": 2327, "score": 0.9982482194900513, "start": 2322, "tag": "NAME", "value": "peter" }, { "context": "subject.foo.bar.toString().should.equal ['peter','paul','mary'].toString()\n\n\n it 'should convert text i", "end": 2334, "score": 0.5936904549598694, "start": 2330, "tag": "NAME", "value": "paul" }, { "context": " subject = {}\n assign subject, 'foo.bar[]', 'peter;-43;mary'\n subject.foo.bar.toString().should.e", "end": 2485, "score": 0.9959760904312134, "start": 2480, "tag": "NAME", "value": "peter" }, { "context": "ry'\n subject.foo.bar.toString().should.equal ['peter',-43,'mary'].toString()\n\n\n it 'should convert te", "end": 2547, "score": 0.997112512588501, "start": 2542, "tag": "NAME", "value": "peter" }, { "context": " subject = {}\n assign subject, 'foo.bar[]', 'peter;false;true'\n subject.foo.bar.toString().should", "end": 2703, "score": 0.9956753253936768, "start": 2698, "tag": "NAME", "value": "peter" }, { "context": "ue'\n subject.foo.bar.toString().should.equal ['peter',false,true].toString()\n\n\n it 'should not split ", "end": 2767, "score": 0.9970499873161316, "start": 2762, "tag": "NAME", "value": "peter" }, { "context": " subject = {}\n assign subject, 'foo.bar[0]', 'peter;paul;mary'\n subject.foo.bar.should.equal 'pete", "end": 2926, "score": 0.9976609945297241, "start": 2921, "tag": "NAME", "value": "peter" }, { "context": "ect = {}\n assign subject, 'foo.bar[0]', 'peter;paul;mary'\n subject.foo.bar.should.equal 'peter;pau", "end": 2931, "score": 0.716999888420105, "start": 2927, "tag": "NAME", "value": "paul" }, { "context": " {}\n assign subject, 'foo.bar[0]', 'peter;paul;mary'\n subject.foo.bar.should.equal 'peter;paul;mar", "end": 2936, "score": 0.6200446486473083, "start": 2932, "tag": "NAME", "value": "mary" }, { "context": "eter;paul;mary'\n subject.foo.bar.should.equal 'peter;paul;mary'\n\n\n it 'should omit empty scalar field", "end": 2977, "score": 0.9956172704696655, "start": 2972, "tag": "NAME", "value": "peter" } ]
test/assign.test.coffee
mrbatista/excel-as-json
1
assign = require('../src/excel-as-json').assign should = require('./helpers').should # NOTE: the excel package uses '' for all empty cells EMPTY_CELL = '' describe 'assign', -> it 'should assign first level properties', -> subject = {} assign subject, 'foo', 'clyde' subject.foo.should.equal 'clyde' it 'should assign second level properties', -> subject = {} assign subject, 'foo.bar', 'wombat' subject.foo.bar.should.equal 'wombat' it 'should assign third level properties', -> subject = {} assign subject, 'foo.bar.bazz', 'honey badger' subject.foo.bar.bazz.should.equal 'honey badger' it 'should convert text to numbers', -> subject = {} assign subject, 'foo.bar.bazz', '42' subject.foo.bar.bazz.should.equal 42 it 'should convert text to booleans', -> subject = {} assign subject, 'foo.bar.bazz', 'true' subject.foo.bar.bazz.should.equal true assign subject, 'foo.bar.bazz', 'false' subject.foo.bar.bazz.should.equal false it 'should overwrite existing values', -> subject = {} assign subject, 'foo.bar.bazz', 'honey badger' subject.foo.bar.bazz.should.equal 'honey badger' assign subject, 'foo.bar.bazz', "don't care" subject.foo.bar.bazz.should.equal "don't care" it 'should assign properties to objects in a list', -> subject = {} assign subject, 'foo.bar[0].what', 'that' subject.foo.bar[0].what.should.equal 'that' it 'should assign properties to objects in a list with first entry out of order', -> subject = {} assign subject, 'foo.bar[1].what', 'that' assign subject, 'foo.bar[0].what', 'this' subject.foo.bar[0].what.should.equal 'this' subject.foo.bar[1].what.should.equal 'that' it 'should assign properties to objects in a list with second entry out of order', -> subject = {} assign subject, 'foo.bar[0].what', 'this' assign subject, 'foo.bar[2].what', 'that' assign subject, 'foo.bar[1].what', 'other' subject.foo.bar[0].what.should.equal 'this' subject.foo.bar[2].what.should.equal 'that' subject.foo.bar[1].what.should.equal 'other' it 'should split a semicolon delimited list for flat arrays', -> subject = {} assign subject, 'foo.bar[]', 'peter;paul;mary' subject.foo.bar.toString().should.equal ['peter','paul','mary'].toString() it 'should convert text in a semicolon delimited list to numbers', -> subject = {} assign subject, 'foo.bar[]', 'peter;-43;mary' subject.foo.bar.toString().should.equal ['peter',-43,'mary'].toString() it 'should convert text in a semicolon delimited list to booleans', -> subject = {} assign subject, 'foo.bar[]', 'peter;false;true' subject.foo.bar.toString().should.equal ['peter',false,true].toString() it 'should not split a semicolon list with a terminal indexed array', -> subject = {} assign subject, 'foo.bar[0]', 'peter;paul;mary' subject.foo.bar.should.equal 'peter;paul;mary' it 'should omit empty scalar fields when directed', -> o = omitEmptyFields: true subject = {} assign subject, 'foo', EMPTY_CELL, o subject.should.not.have.property 'foo' it 'should omit empty nested scalar fields when directed', -> o = omitEmptyFields: true subject = {} assign subject, 'foo.bar', EMPTY_CELL, o subject.should.have.property 'foo' subject.foo.should.not.have.property 'bar' it 'should omit nested array fields when directed', -> o = omitEmptyFields: true # specified as an entire list subject = {} assign subject, 'foo[]', EMPTY_CELL, o subject.should.not.have.property 'foo' # specified as a list subject = {} assign subject, 'foo[0]', EMPTY_CELL, o subject.should.not.have.property 'foo' # specified as a list of objects subject = {} assign subject, 'foo[0].bar', 'bazz', o assign subject, 'foo[1].bar', EMPTY_CELL, o subject.foo[1].should.not.have.property 'bar'
213111
assign = require('../src/excel-as-json').assign should = require('./helpers').should # NOTE: the excel package uses '' for all empty cells EMPTY_CELL = '' describe 'assign', -> it 'should assign first level properties', -> subject = {} assign subject, 'foo', 'clyde' subject.foo.should.equal 'clyde' it 'should assign second level properties', -> subject = {} assign subject, 'foo.bar', 'wombat' subject.foo.bar.should.equal 'wombat' it 'should assign third level properties', -> subject = {} assign subject, 'foo.bar.bazz', 'honey badger' subject.foo.bar.bazz.should.equal 'honey badger' it 'should convert text to numbers', -> subject = {} assign subject, 'foo.bar.bazz', '42' subject.foo.bar.bazz.should.equal 42 it 'should convert text to booleans', -> subject = {} assign subject, 'foo.bar.bazz', 'true' subject.foo.bar.bazz.should.equal true assign subject, 'foo.bar.bazz', 'false' subject.foo.bar.bazz.should.equal false it 'should overwrite existing values', -> subject = {} assign subject, 'foo.bar.bazz', 'honey badger' subject.foo.bar.bazz.should.equal 'honey badger' assign subject, 'foo.bar.bazz', "don't care" subject.foo.bar.bazz.should.equal "don't care" it 'should assign properties to objects in a list', -> subject = {} assign subject, 'foo.bar[0].what', 'that' subject.foo.bar[0].what.should.equal 'that' it 'should assign properties to objects in a list with first entry out of order', -> subject = {} assign subject, 'foo.bar[1].what', 'that' assign subject, 'foo.bar[0].what', 'this' subject.foo.bar[0].what.should.equal 'this' subject.foo.bar[1].what.should.equal 'that' it 'should assign properties to objects in a list with second entry out of order', -> subject = {} assign subject, 'foo.bar[0].what', 'this' assign subject, 'foo.bar[2].what', 'that' assign subject, 'foo.bar[1].what', 'other' subject.foo.bar[0].what.should.equal 'this' subject.foo.bar[2].what.should.equal 'that' subject.foo.bar[1].what.should.equal 'other' it 'should split a semicolon delimited list for flat arrays', -> subject = {} assign subject, 'foo.bar[]', '<NAME>;<NAME>;mary' subject.foo.bar.toString().should.equal ['<NAME>','<NAME>','mary'].toString() it 'should convert text in a semicolon delimited list to numbers', -> subject = {} assign subject, 'foo.bar[]', '<NAME>;-43;mary' subject.foo.bar.toString().should.equal ['<NAME>',-43,'mary'].toString() it 'should convert text in a semicolon delimited list to booleans', -> subject = {} assign subject, 'foo.bar[]', '<NAME>;false;true' subject.foo.bar.toString().should.equal ['<NAME>',false,true].toString() it 'should not split a semicolon list with a terminal indexed array', -> subject = {} assign subject, 'foo.bar[0]', '<NAME>;<NAME>;<NAME>' subject.foo.bar.should.equal '<NAME>;paul;mary' it 'should omit empty scalar fields when directed', -> o = omitEmptyFields: true subject = {} assign subject, 'foo', EMPTY_CELL, o subject.should.not.have.property 'foo' it 'should omit empty nested scalar fields when directed', -> o = omitEmptyFields: true subject = {} assign subject, 'foo.bar', EMPTY_CELL, o subject.should.have.property 'foo' subject.foo.should.not.have.property 'bar' it 'should omit nested array fields when directed', -> o = omitEmptyFields: true # specified as an entire list subject = {} assign subject, 'foo[]', EMPTY_CELL, o subject.should.not.have.property 'foo' # specified as a list subject = {} assign subject, 'foo[0]', EMPTY_CELL, o subject.should.not.have.property 'foo' # specified as a list of objects subject = {} assign subject, 'foo[0].bar', 'bazz', o assign subject, 'foo[1].bar', EMPTY_CELL, o subject.foo[1].should.not.have.property 'bar'
true
assign = require('../src/excel-as-json').assign should = require('./helpers').should # NOTE: the excel package uses '' for all empty cells EMPTY_CELL = '' describe 'assign', -> it 'should assign first level properties', -> subject = {} assign subject, 'foo', 'clyde' subject.foo.should.equal 'clyde' it 'should assign second level properties', -> subject = {} assign subject, 'foo.bar', 'wombat' subject.foo.bar.should.equal 'wombat' it 'should assign third level properties', -> subject = {} assign subject, 'foo.bar.bazz', 'honey badger' subject.foo.bar.bazz.should.equal 'honey badger' it 'should convert text to numbers', -> subject = {} assign subject, 'foo.bar.bazz', '42' subject.foo.bar.bazz.should.equal 42 it 'should convert text to booleans', -> subject = {} assign subject, 'foo.bar.bazz', 'true' subject.foo.bar.bazz.should.equal true assign subject, 'foo.bar.bazz', 'false' subject.foo.bar.bazz.should.equal false it 'should overwrite existing values', -> subject = {} assign subject, 'foo.bar.bazz', 'honey badger' subject.foo.bar.bazz.should.equal 'honey badger' assign subject, 'foo.bar.bazz', "don't care" subject.foo.bar.bazz.should.equal "don't care" it 'should assign properties to objects in a list', -> subject = {} assign subject, 'foo.bar[0].what', 'that' subject.foo.bar[0].what.should.equal 'that' it 'should assign properties to objects in a list with first entry out of order', -> subject = {} assign subject, 'foo.bar[1].what', 'that' assign subject, 'foo.bar[0].what', 'this' subject.foo.bar[0].what.should.equal 'this' subject.foo.bar[1].what.should.equal 'that' it 'should assign properties to objects in a list with second entry out of order', -> subject = {} assign subject, 'foo.bar[0].what', 'this' assign subject, 'foo.bar[2].what', 'that' assign subject, 'foo.bar[1].what', 'other' subject.foo.bar[0].what.should.equal 'this' subject.foo.bar[2].what.should.equal 'that' subject.foo.bar[1].what.should.equal 'other' it 'should split a semicolon delimited list for flat arrays', -> subject = {} assign subject, 'foo.bar[]', 'PI:NAME:<NAME>END_PI;PI:NAME:<NAME>END_PI;mary' subject.foo.bar.toString().should.equal ['PI:NAME:<NAME>END_PI','PI:NAME:<NAME>END_PI','mary'].toString() it 'should convert text in a semicolon delimited list to numbers', -> subject = {} assign subject, 'foo.bar[]', 'PI:NAME:<NAME>END_PI;-43;mary' subject.foo.bar.toString().should.equal ['PI:NAME:<NAME>END_PI',-43,'mary'].toString() it 'should convert text in a semicolon delimited list to booleans', -> subject = {} assign subject, 'foo.bar[]', 'PI:NAME:<NAME>END_PI;false;true' subject.foo.bar.toString().should.equal ['PI:NAME:<NAME>END_PI',false,true].toString() it 'should not split a semicolon list with a terminal indexed array', -> subject = {} assign subject, 'foo.bar[0]', 'PI:NAME:<NAME>END_PI;PI:NAME:<NAME>END_PI;PI:NAME:<NAME>END_PI' subject.foo.bar.should.equal 'PI:NAME:<NAME>END_PI;paul;mary' it 'should omit empty scalar fields when directed', -> o = omitEmptyFields: true subject = {} assign subject, 'foo', EMPTY_CELL, o subject.should.not.have.property 'foo' it 'should omit empty nested scalar fields when directed', -> o = omitEmptyFields: true subject = {} assign subject, 'foo.bar', EMPTY_CELL, o subject.should.have.property 'foo' subject.foo.should.not.have.property 'bar' it 'should omit nested array fields when directed', -> o = omitEmptyFields: true # specified as an entire list subject = {} assign subject, 'foo[]', EMPTY_CELL, o subject.should.not.have.property 'foo' # specified as a list subject = {} assign subject, 'foo[0]', EMPTY_CELL, o subject.should.not.have.property 'foo' # specified as a list of objects subject = {} assign subject, 'foo[0].bar', 'bazz', o assign subject, 'foo[1].bar', EMPTY_CELL, o subject.foo[1].should.not.have.property 'bar'
[ { "context": "VOTAL_TOKEN = <API token>\n#HUBOT_PIVOTAL_TOKEN = \"ddb2187632ade586c12fa4442b1055b8\"\n#\n# If you're working on a single project, you c", "end": 181, "score": 0.941301703453064, "start": 149, "tag": "KEY", "value": "ddb2187632ade586c12fa4442b1055b8" }, { "context": ".exports = (robot) ->\n HARD_CODED_PIVOTAL_TOKEN=\"a1ed4421da846021e6fa9facb5f1b2c2\"\n #robot.respond /show\\s+(me\\s+)?stories\\s+(for\\", "end": 705, "score": 0.7846161723136902, "start": 673, "tag": "KEY", "value": "a1ed4421da846021e6fa9facb5f1b2c2" }, { "context": "oken = process.env.HUBOT_PIVOTAL_TOKEN\n token = HARD_CODED_PIVOTAL_TOKEN\n msg.http(\"http://www.pivotaltracker.com/servi", "end": 3843, "score": 0.7997148633003235, "start": 3819, "tag": "PASSWORD", "value": "HARD_CODED_PIVOTAL_TOKEN" } ]
src/scripts/pivotal.coffee
unepwcmc/hubot
0
# Get current stories from PivotalTracker # # You need to set the following variables: # HUBOT_PIVOTAL_TOKEN = <API token> #HUBOT_PIVOTAL_TOKEN = "ddb2187632ade586c12fa4442b1055b8" # # If you're working on a single project, you can set it once: # HUBOT_PIVOTAL_PROJECT = <project name> # # Otherwise, include the project name in your message to Hubot. # # show me <state> stories for <project> -- shows stories for <project> that have <state> (unstarted,started,finished,delivered); ommit for all states. # list all projects -- list all your (atm Simao's) projects # ls projects -- alias for list all projects # module.exports = (robot) -> HARD_CODED_PIVOTAL_TOKEN="a1ed4421da846021e6fa9facb5f1b2c2" #robot.respond /show\s+(me\s+)?stories\s+(for\s+)?(.*)/i, (msg)-> robot.respond /show\s+(me\s+)?(unstarted|started|finished|unfinished|delivered)?\s*stories\s+(for\s+)?(.*)/i, (msg)-> Parser = require("xml2js").Parser #token = process.env.HUBOT_PIVOTAL_TOKEN token = HARD_CODED_PIVOTAL_TOKEN if msg.match[2] && msg.match[2] != "" state = msg.match[2] else state = "unstarted,started,finished,delivered" project_name = msg.match[5] if !project_name? || project_name == "" project_name = RegExp(process.env.HUBOT_PIVOTAL_PROJECT, "i") else project_name = RegExp(project_name + ".*", "i") msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for the_project in json.project if project_name.test(the_project.name) msg.http("https://www.pivotaltracker.com/services/v3/projects/#{the_project.id}/stories").headers("X-TrackerToken": token).query(filter: "state:#{state}").get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for story in json.story message = "##{story.id['#']} #{story.name}" message += " (#{story.owned_by})" if story.owned_by message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted" msg.send message return msg.send "No project #{project_name}" robot.respond /(pivotal story)? (.*)/i, (msg)-> Parser = require("xml2js").Parser token = process.env.HUBOT_PIVOTAL_TOKEN project_id = process.env.HUBOT_PIVOTAL_PROJECT story_id = msg.match[2] msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for project in json.project msg.http("https://www.pivotaltracker.com/services/v3/projects/#{project.id}/stories/#{story_id}").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return if res.statusCode != 500 (new Parser).parseString body, (err, story)-> if !story.id return message = "##{story.id['#']} #{story.name}" message += " (#{story.owned_by})" if story.owned_by message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted" msg.send message storyReturned = true return return robot.respond /(ls|list all) projects/i, (msg) -> Parser = require("xml2js").Parser #token = process.env.HUBOT_PIVOTAL_TOKEN token = HARD_CODED_PIVOTAL_TOKEN msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken":token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> msg.send "Here are your projects:" for project in json.project message = "#{project.name} ; #{project.id}" msg.send message return robot.hear /wasup(\?)?/i, (msg) -> msg.send "nothin" return
168400
# Get current stories from PivotalTracker # # You need to set the following variables: # HUBOT_PIVOTAL_TOKEN = <API token> #HUBOT_PIVOTAL_TOKEN = "<KEY>" # # If you're working on a single project, you can set it once: # HUBOT_PIVOTAL_PROJECT = <project name> # # Otherwise, include the project name in your message to Hubot. # # show me <state> stories for <project> -- shows stories for <project> that have <state> (unstarted,started,finished,delivered); ommit for all states. # list all projects -- list all your (atm Simao's) projects # ls projects -- alias for list all projects # module.exports = (robot) -> HARD_CODED_PIVOTAL_TOKEN="<KEY>" #robot.respond /show\s+(me\s+)?stories\s+(for\s+)?(.*)/i, (msg)-> robot.respond /show\s+(me\s+)?(unstarted|started|finished|unfinished|delivered)?\s*stories\s+(for\s+)?(.*)/i, (msg)-> Parser = require("xml2js").Parser #token = process.env.HUBOT_PIVOTAL_TOKEN token = HARD_CODED_PIVOTAL_TOKEN if msg.match[2] && msg.match[2] != "" state = msg.match[2] else state = "unstarted,started,finished,delivered" project_name = msg.match[5] if !project_name? || project_name == "" project_name = RegExp(process.env.HUBOT_PIVOTAL_PROJECT, "i") else project_name = RegExp(project_name + ".*", "i") msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for the_project in json.project if project_name.test(the_project.name) msg.http("https://www.pivotaltracker.com/services/v3/projects/#{the_project.id}/stories").headers("X-TrackerToken": token).query(filter: "state:#{state}").get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for story in json.story message = "##{story.id['#']} #{story.name}" message += " (#{story.owned_by})" if story.owned_by message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted" msg.send message return msg.send "No project #{project_name}" robot.respond /(pivotal story)? (.*)/i, (msg)-> Parser = require("xml2js").Parser token = process.env.HUBOT_PIVOTAL_TOKEN project_id = process.env.HUBOT_PIVOTAL_PROJECT story_id = msg.match[2] msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for project in json.project msg.http("https://www.pivotaltracker.com/services/v3/projects/#{project.id}/stories/#{story_id}").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return if res.statusCode != 500 (new Parser).parseString body, (err, story)-> if !story.id return message = "##{story.id['#']} #{story.name}" message += " (#{story.owned_by})" if story.owned_by message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted" msg.send message storyReturned = true return return robot.respond /(ls|list all) projects/i, (msg) -> Parser = require("xml2js").Parser #token = process.env.HUBOT_PIVOTAL_TOKEN token = <PASSWORD> msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken":token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> msg.send "Here are your projects:" for project in json.project message = "#{project.name} ; #{project.id}" msg.send message return robot.hear /wasup(\?)?/i, (msg) -> msg.send "nothin" return
true
# Get current stories from PivotalTracker # # You need to set the following variables: # HUBOT_PIVOTAL_TOKEN = <API token> #HUBOT_PIVOTAL_TOKEN = "PI:KEY:<KEY>END_PI" # # If you're working on a single project, you can set it once: # HUBOT_PIVOTAL_PROJECT = <project name> # # Otherwise, include the project name in your message to Hubot. # # show me <state> stories for <project> -- shows stories for <project> that have <state> (unstarted,started,finished,delivered); ommit for all states. # list all projects -- list all your (atm Simao's) projects # ls projects -- alias for list all projects # module.exports = (robot) -> HARD_CODED_PIVOTAL_TOKEN="PI:KEY:<KEY>END_PI" #robot.respond /show\s+(me\s+)?stories\s+(for\s+)?(.*)/i, (msg)-> robot.respond /show\s+(me\s+)?(unstarted|started|finished|unfinished|delivered)?\s*stories\s+(for\s+)?(.*)/i, (msg)-> Parser = require("xml2js").Parser #token = process.env.HUBOT_PIVOTAL_TOKEN token = HARD_CODED_PIVOTAL_TOKEN if msg.match[2] && msg.match[2] != "" state = msg.match[2] else state = "unstarted,started,finished,delivered" project_name = msg.match[5] if !project_name? || project_name == "" project_name = RegExp(process.env.HUBOT_PIVOTAL_PROJECT, "i") else project_name = RegExp(project_name + ".*", "i") msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for the_project in json.project if project_name.test(the_project.name) msg.http("https://www.pivotaltracker.com/services/v3/projects/#{the_project.id}/stories").headers("X-TrackerToken": token).query(filter: "state:#{state}").get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for story in json.story message = "##{story.id['#']} #{story.name}" message += " (#{story.owned_by})" if story.owned_by message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted" msg.send message return msg.send "No project #{project_name}" robot.respond /(pivotal story)? (.*)/i, (msg)-> Parser = require("xml2js").Parser token = process.env.HUBOT_PIVOTAL_TOKEN project_id = process.env.HUBOT_PIVOTAL_PROJECT story_id = msg.match[2] msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> for project in json.project msg.http("https://www.pivotaltracker.com/services/v3/projects/#{project.id}/stories/#{story_id}").headers("X-TrackerToken": token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return if res.statusCode != 500 (new Parser).parseString body, (err, story)-> if !story.id return message = "##{story.id['#']} #{story.name}" message += " (#{story.owned_by})" if story.owned_by message += " is #{story.current_state}" if story.current_state && story.current_state != "unstarted" msg.send message storyReturned = true return return robot.respond /(ls|list all) projects/i, (msg) -> Parser = require("xml2js").Parser #token = process.env.HUBOT_PIVOTAL_TOKEN token = PI:PASSWORD:<PASSWORD>END_PI msg.http("http://www.pivotaltracker.com/services/v3/projects").headers("X-TrackerToken":token).get() (err, res, body) -> if err msg.send "Pivotal says: #{err}" return (new Parser).parseString body, (err, json)-> msg.send "Here are your projects:" for project in json.project message = "#{project.name} ; #{project.id}" msg.send message return robot.hear /wasup(\?)?/i, (msg) -> msg.send "nothin" return
[ { "context": "scover.bind 3702, () ->\n discover.addMembership '239.255.255.250'\n\nserver = http\n .createServer listener\n .liste", "end": 2430, "score": 0.9997705221176147, "start": 2415, "tag": "IP_ADDRESS", "value": "239.255.255.250" } ]
test/serverMockup.coffee
nickw444/onvif
0
http = require 'http' dgram = require 'dgram' fs = require 'fs' Buffer = (require 'buffer').Buffer template = (require 'dot').template reBody = /<s:Body xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance" xmlns:xsd="http:\/\/www.w3.org\/2001\/XMLSchema">(.*)<\/s:Body>/ reCommand = /<(\S*) / reNS = /xmlns="http:\/\/www.onvif.org\/\S*\/(\S*)\/wsdl"/ __xmldir = __dirname + '/serverMockup/' conf = { port: process.env.PORT || 10101 # server port hostname: process.env.HOSTNAME || 'localhost' pullPointUrl: '/onvif/subscription?Idx=6' } listener = (req, res) -> req.setEncoding('utf8') buf = [] req.on 'data', (chunk) -> buf.push chunk req.on 'end', () -> if (Buffer.isBuffer(buf)) # Node.js > 0.12 fix when `data` event produces strings instead of Buffer request = Buffer.concat buf else request = buf.join('') # Find body and command name body = reBody.exec(request) return res.end() if !body body = body[1] command = reCommand.exec(body)[1] ns = reNS.exec(body)[1] return res.end() if !command switch when fs.existsSync(__xmldir + ns + '.' + command + '.xml') then command = ns + '.' + command when not fs.existsSync(__xmldir + command + '.xml') then command = 'Error' fileName = __xmldir + command + '.xml' #console.log 'serving', fileName #fs.createReadStream(__dirname + '/serverMockup/' + command + '.xml').pipe(res) res.end(template(fs.readFileSync(fileName))(conf)) # Discovery service discover = dgram.createSocket('udp4') discover.msg = new Buffer(fs .readFileSync __xmldir + 'Probe.xml' .toString() .replace 'SERVICE_URI', 'http://localhost:' + (process.env.PORT || 10101) + '/onvif/device_service' ) discover.on 'error', (err) -> throw err discover.on 'message', (msg, rinfo) -> msgId = /urn:uuid:([0-9a-f\-]+)</.exec(msg.toString())[1] if msgId switch msgId # Wrong message test when 'e7707' then discover.send (new Buffer 'lollipop'), 0, 8, rinfo.port, rinfo.address # Double sending test when 'd0-61e' discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address # Discovery test else discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address discover.bind 3702, () -> discover.addMembership '239.255.255.250' server = http .createServer listener .listen conf.port module.exports = { server: server , conf: conf }
182620
http = require 'http' dgram = require 'dgram' fs = require 'fs' Buffer = (require 'buffer').Buffer template = (require 'dot').template reBody = /<s:Body xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance" xmlns:xsd="http:\/\/www.w3.org\/2001\/XMLSchema">(.*)<\/s:Body>/ reCommand = /<(\S*) / reNS = /xmlns="http:\/\/www.onvif.org\/\S*\/(\S*)\/wsdl"/ __xmldir = __dirname + '/serverMockup/' conf = { port: process.env.PORT || 10101 # server port hostname: process.env.HOSTNAME || 'localhost' pullPointUrl: '/onvif/subscription?Idx=6' } listener = (req, res) -> req.setEncoding('utf8') buf = [] req.on 'data', (chunk) -> buf.push chunk req.on 'end', () -> if (Buffer.isBuffer(buf)) # Node.js > 0.12 fix when `data` event produces strings instead of Buffer request = Buffer.concat buf else request = buf.join('') # Find body and command name body = reBody.exec(request) return res.end() if !body body = body[1] command = reCommand.exec(body)[1] ns = reNS.exec(body)[1] return res.end() if !command switch when fs.existsSync(__xmldir + ns + '.' + command + '.xml') then command = ns + '.' + command when not fs.existsSync(__xmldir + command + '.xml') then command = 'Error' fileName = __xmldir + command + '.xml' #console.log 'serving', fileName #fs.createReadStream(__dirname + '/serverMockup/' + command + '.xml').pipe(res) res.end(template(fs.readFileSync(fileName))(conf)) # Discovery service discover = dgram.createSocket('udp4') discover.msg = new Buffer(fs .readFileSync __xmldir + 'Probe.xml' .toString() .replace 'SERVICE_URI', 'http://localhost:' + (process.env.PORT || 10101) + '/onvif/device_service' ) discover.on 'error', (err) -> throw err discover.on 'message', (msg, rinfo) -> msgId = /urn:uuid:([0-9a-f\-]+)</.exec(msg.toString())[1] if msgId switch msgId # Wrong message test when 'e7707' then discover.send (new Buffer 'lollipop'), 0, 8, rinfo.port, rinfo.address # Double sending test when 'd0-61e' discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address # Discovery test else discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address discover.bind 3702, () -> discover.addMembership '192.168.127.12' server = http .createServer listener .listen conf.port module.exports = { server: server , conf: conf }
true
http = require 'http' dgram = require 'dgram' fs = require 'fs' Buffer = (require 'buffer').Buffer template = (require 'dot').template reBody = /<s:Body xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance" xmlns:xsd="http:\/\/www.w3.org\/2001\/XMLSchema">(.*)<\/s:Body>/ reCommand = /<(\S*) / reNS = /xmlns="http:\/\/www.onvif.org\/\S*\/(\S*)\/wsdl"/ __xmldir = __dirname + '/serverMockup/' conf = { port: process.env.PORT || 10101 # server port hostname: process.env.HOSTNAME || 'localhost' pullPointUrl: '/onvif/subscription?Idx=6' } listener = (req, res) -> req.setEncoding('utf8') buf = [] req.on 'data', (chunk) -> buf.push chunk req.on 'end', () -> if (Buffer.isBuffer(buf)) # Node.js > 0.12 fix when `data` event produces strings instead of Buffer request = Buffer.concat buf else request = buf.join('') # Find body and command name body = reBody.exec(request) return res.end() if !body body = body[1] command = reCommand.exec(body)[1] ns = reNS.exec(body)[1] return res.end() if !command switch when fs.existsSync(__xmldir + ns + '.' + command + '.xml') then command = ns + '.' + command when not fs.existsSync(__xmldir + command + '.xml') then command = 'Error' fileName = __xmldir + command + '.xml' #console.log 'serving', fileName #fs.createReadStream(__dirname + '/serverMockup/' + command + '.xml').pipe(res) res.end(template(fs.readFileSync(fileName))(conf)) # Discovery service discover = dgram.createSocket('udp4') discover.msg = new Buffer(fs .readFileSync __xmldir + 'Probe.xml' .toString() .replace 'SERVICE_URI', 'http://localhost:' + (process.env.PORT || 10101) + '/onvif/device_service' ) discover.on 'error', (err) -> throw err discover.on 'message', (msg, rinfo) -> msgId = /urn:uuid:([0-9a-f\-]+)</.exec(msg.toString())[1] if msgId switch msgId # Wrong message test when 'e7707' then discover.send (new Buffer 'lollipop'), 0, 8, rinfo.port, rinfo.address # Double sending test when 'd0-61e' discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address # Discovery test else discover.send discover.msg, 0, discover.msg.length, rinfo.port, rinfo.address discover.bind 3702, () -> discover.addMembership 'PI:IP_ADDRESS:192.168.127.12END_PI' server = http .createServer listener .listen conf.port module.exports = { server: server , conf: conf }
[ { "context": "oser - dynamic, AJAX-enabled pick-list\n#\n# @author James LastName\n# v2.0 (rewritten in CoffeeScript)\n#\n# Configurat", "end": 76, "score": 0.929677426815033, "start": 62, "tag": "NAME", "value": "James LastName" } ]
app/assets/javascripts/widgets/Chooser/Chooser.coffee
MAAP-Project/mmt
83
### # # Chooser - dynamic, AJAX-enabled pick-list # # @author James LastName # v2.0 (rewritten in CoffeeScript) # # Configuration parameters: # id (string): Unique ID for this widget. All HTML elements within this widget will # have IDs based on this. # url (string): URL of resource to retrieve initial selections. # target (element): DOM element where this widget will be placed. # fromLabel: Label to appear over "from" list # toLabel: Label to appear over "to" list # forceUnique (boolean): When true, only allows unique options to be added to the "to" list, # e.g., if "ABC" is already in the "to" list, it will not be added. Default is false. # size (int): Height of select control in number of options. # resetSize (int): When user scrolls to top, the entire list is trimmed to this size. Not required, # default is 50. # filterChars (sting): Number of characters to allow typing into filter textbox before AJAX call is triggered. # Default is 1. # showNumChosen (int): Always show the number of chosen items in the "to" list. # attachTo (element): DOM element where a value can be stored (hidden or text input). # errorCallback (function): Callback function to execute if an AJAX error occurs. # fromFilterText (string): Text for the "from" filter textbox placeholder (default is "filter") # toFilterText (string): Text for the "to" filter textbox placeholder (default is "filter") # removeAdded (boolean): Remove selections from the FROM list as they are added to the TO list. Default is true, # allowRemoveAll (boolean): Show the remove all button # lowerFromLabel (string): Text to display under the FROM list. Can be used with a template, e.g., # 'Showing {{x}} of {{n}} items.' where x is the number of items loaded in the FROM list # and x is the total number of hits that come back from the server (both are optional). # toMax (int or boolean): Total number of items that can be in the right ("to") box. Default: 500. Set to false # allow any number. A message is displayed if the user attempts to add more than the max. # # # Public methods: # # init() Initialize and render the widget. # val() Get the currently selected "to" values. # getDOMNode() Returns the DOM node for customization. # addValues(list) Adds values to the "from" list # setValues(list) Removes current values from "from" list and adds new ones. # removeFromBottom(n) Remove n values from bottom of "from" list. # # NOTES: Data format shall be formatted in the following ways: # # 1) An array of strings. Every value will be used for the option value and display value. # For example, ["lorem", "ipsum", "dolor", "sit", "amet"] # # 2) An array of 2-element arrays. First element is the option value, the second is the display value. # For example, [ ["lorem", "Lorem"], ["ipsum", "Ipsum"] ... ] # # 3) A mixed array: [ ["lorem", "Lorem"], "ipsum", "dolor", ["sit", "Sit"] ... ] # # 4) An array of single- or dual-element arrays. # For example, [ ["lorem", "Lorem"], ["ipsum"] ... ] # # 5) Any combination of the above. # ### # Constructor window.Chooser = (config) -> # Globals OUTER_CONTAINER = undefined FROM_CONTAINER = undefined TO_CONTAINER = undefined BUTTON_CONTAINER = undefined FROM_BOX = undefined FROM_LIST = undefined TO_BOX = undefined TO_LIST = undefined ADD_BUTTON = undefined REMOVE_BUTTON = undefined REMOVE_ALL_BUTTON = undefined FROM_LABEL = undefined TO_LABEL = undefined FROM_FILTER_TEXTBOX = undefined TO_FILTER_TEXTBOX = undefined TO_MESSAGE = undefined CHOOSER_OPTS_STORAGE_KEY = 'Chooser_opts_' + config.id PAGE_NUM = 1 LOWER_FROM_LABEL = undefined LOWER_TO_LABEL = undefined TOTAL_HITS = undefined SELF = undefined ### # init - initializes the widget. ### @init = -> SELF = this # Set defaults: setDefault('id', 'Chooser_' + Math.random().toString(36).slice(2)) setDefault('fromLabel', 'Available') setDefault('toLabel', 'Selected') setDefault('forceUnique', true) setDefault('size', 20) setDefault('filterChars', 1) setDefault('resetSize', 50) setDefault('showNumChosen', true) setDefault('fromFilterText', 'Enter text to narrow search results') setDefault('toFilterText', 'Enter text to narrow selected items') setDefault('removeAdded', false) setDefault('allowRemoveAll', true) setDefault('lowerFromLabel', 'Showing {{x}} of {{n}} item{{s}}') setDefault('lowerToLabel', 'Showing {{x}} of {{n}} item{{s}}') setDefault('toMax', false) setDefault('endlessScroll', false) setDefault('uniqueMsg', 'Value already added') setDefault('delimiter', ',') setDefault('tooltipObject', 'Collections') # Construct each component OUTER_CONTAINER = $('<div>').addClass('Chooser').attr('id', config.id) FROM_CONTAINER = $('<div>').addClass('from-container') TO_CONTAINER = $('<div>').addClass('to-container') BUTTON_CONTAINER = $('<div>').addClass('button-container') FROM_BOX = $('<div>') TO_BOX = $('<div>') addButtonText = if hasProp('addButton', 'object') then config.addButton.text else '&#x2192;' addButtonCssClass = if hasProp('addButton', 'object') then config.addButton.cssClass else '' ADD_BUTTON = $('<button>').attr('title', "Add highlighted items to 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(addButtonCssClass).addClass('add_button').text(addButtonText) if hasProp('addButton') and config.addButton.arrowCssClass $(ADD_BUTTON).append('<span>').addClass(config.addButton.arrowCssClass) delButtonText = if hasProp('delButton', 'object') then config.delButton.text else '&#x2190;' delButtonCssClass = if hasProp('delButton', 'object') then config.delButton.cssClass else '' REMOVE_BUTTON = $('<button>').attr('title', "Remove highlighted items from 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(delButtonCssClass).addClass('remove_button').text(delButtonText) if hasProp('delButton') and config.delButton.arrowCssClass $(REMOVE_BUTTON).prepend('<span>').addClass(config.delButton.arrowCssClass) allowRemoveAll = if hasProp('allowRemoveAll', 'boolean') then config.allowRemoveAll else true if allowRemoveAll == true delAllButtonText = if hasProp('delAllButton', 'object') then config.delAllButton.text else '&#x2190;' delAllButtonCssClass = if hasProp('delAllButton', 'object') then config.delAllButton.cssClass else '' REMOVE_ALL_BUTTON = $('<button>').attr('title', "Remove all entries from 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(delAllButtonCssClass).addClass('remove_all_button').text(delAllButtonText) if hasProp('delAllButton') and config.delAllButton.arrowCssClass $(REMOVE_ALL_BUTTON).prepend('<span>').addClass(config.delAllButton.arrowCssClass) FROM_LIST = $('<select>').addClass('___fromList').attr('id', config.id + '_fromList').attr( 'multiple', true).attr('size', config.size) TO_LIST = $('<select>').addClass('___toList').attr('name', config.id + '_toList[]').attr('id', config.id + '_toList').attr('multiple', true).attr('size', config.size) fromPlaceHolderText = if hasProp('fromFilterText', 'string') then config.fromFilterText else 'filter' FROM_FILTER_TEXTBOX = $('<input>').attr('type', 'text').attr('placeholder', fromPlaceHolderText).attr('id', 'from-filter') toPlaceHolderText = if hasProp('toFilterText', 'string') then config.toFilterText else 'filter' TO_FILTER_TEXTBOX = $('<input>').attr('type', 'text').attr('placeholder', toPlaceHolderText).attr('id', 'to-filter') if !config.hasOwnProperty('resetSize') config.resetSize = 50 if hasProp('fromLabel', 'string') FROM_LABEL = $('<label>').attr('for', config.id + '_fromList').text(config.fromLabel) if ! hasProp('lowerFromLabel') || hasProp('lowerFromLabel', 'string') LOWER_FROM_LABEL = $('<p>').addClass('form-description') if ! hasProp('lowerToLabel') || hasProp('lowerToLabel', 'string') LOWER_TO_LABEL = $('<p>').addClass('form-description') if config.toLabel TO_LABEL = $('<label>').attr('for', config.id + '_toList').text(config.toLabel) $(TO_CONTAINER).append TO_LABEL # Assemble the components $(OUTER_CONTAINER).append FROM_CONTAINER $(OUTER_CONTAINER).append BUTTON_CONTAINER $(OUTER_CONTAINER).append TO_CONTAINER $(FROM_CONTAINER).append FROM_LABEL $(FROM_CONTAINER).append FROM_FILTER_TEXTBOX $(FROM_CONTAINER).append FROM_LIST $(FROM_CONTAINER).append LOWER_FROM_LABEL $(TO_CONTAINER).append TO_FILTER_TEXTBOX $(TO_CONTAINER).append TO_LIST $(TO_CONTAINER).append LOWER_TO_LABEL $(BUTTON_CONTAINER).append ADD_BUTTON $(BUTTON_CONTAINER).append REMOVE_BUTTON $(BUTTON_CONTAINER).append REMOVE_ALL_BUTTON $(OUTER_CONTAINER).appendTo $(config.target) TO_MESSAGE = $('<span>').addClass('to_message') $(TO_CONTAINER).append TO_MESSAGE $(ADD_BUTTON).click addButtonClick $(REMOVE_BUTTON).click removeButtonClick $(REMOVE_ALL_BUTTON).click removeAllButtonClick SELF.getRemoteData 'first' $(FROM_LIST).on 'scroll', (evt) -> if config.endlessScroll == false return lowerBoundary = $(this).position().top + parseInt($(this).css('height')) upperBoundary = $(this).position().top lastOpt = $(this).find('option').last() lastOptPos = $(lastOpt).position().top firstOpt = $(this).find('option').first() firstOptPos = $(firstOpt).position().top lastOptHeight = parseInt($(lastOpt).css('height')) if lastOptPos <= lowerBoundary dist = lowerBoundary - lastOptPos offset = lastOptHeight - dist if offset > 1 and offset < 5 SELF.getRemoteData 'next' if firstOptPos >= upperBoundary SELF.removeFromBottom() PAGE_NUM = 1 return $(TO_LIST).change -> numChosen = $(TO_LIST).find('option').length if ! hasProp('lowerToLabel') || hasProp('lowerToLabel', 'string') x = $(TO_LIST).find('option').not('.is-hidden').length lowerToLabelText = config.lowerToLabel lowerToLabelText = lowerToLabelText.replace '{{x}}', x lowerToLabelText = lowerToLabelText.replace '{{n}}', numChosen lowerToLabelText = lowerToLabelText.replace('{{s}}', pluralize(numChosen)) $(LOWER_TO_LABEL).text(lowerToLabelText) if hasProp('toLabel') and hasProp('showNumChosen') if config.showNumChosen == true and numChosen > 0 $(TO_LABEL).text config.toLabel + ' (' + numChosen + ')' else $(TO_LABEL).text config.toLabel if hasProp('attachTo', 'object') $(config.attachTo).val SELF.val().join(config.delimiter) return $(FROM_LIST).change -> if ! hasProp('lowerFromLabel') || hasProp('lowerFromLabel', 'string') x = $(FROM_LIST).find('option').length n = TOTAL_HITS lowerFromLabelText = config.lowerFromLabel lowerFromLabelText = lowerFromLabelText.replace '{{x}}', x lowerFromLabelText = lowerFromLabelText.replace '{{n}}', n lowerFromLabelText = lowerFromLabelText.replace('{{s}}', pluralize(n)) $(LOWER_FROM_LABEL).text(lowerFromLabelText) return $(FROM_FILTER_TEXTBOX).keyup initFromFilter $(TO_FILTER_TEXTBOX).keyup initToFilter $(FROM_LIST).dblclick -> $(ADD_BUTTON).click() return $(TO_LIST).dblclick -> $(REMOVE_BUTTON).click() return ### # Set provided config values # ### @setConfig = (key, value) -> config[key] = value ### # Sets the values in the "TO" list. # ### @setToVal = (values) -> setVal(values, $(TO_LIST)) ### # Sets the values in the "FROM" list. # ### @setFromVal = (values) -> setVal(values, $(FROM_LIST)) ### # Returns the widget's "value" (selected values). # # @returns {*|object} ### @val = () -> vals = $(TO_LIST).find('option').map((tmpKey, tmpVal) -> $(tmpVal).text() ) valsAsArray = [] $.each vals, (tmpKey, tmpVal) -> valsAsArray.push tmpVal return valsAsArray ### # Returns the top-level DOM node of this widget. # @returns {*|jQuery|HTMLElement} ### @getDOMNode = -> $ OUTER_CONTAINER ### # Removes N values from top of FROM list. # # @param n - number of values to remove. ### @removeFromTop = (n) -> list = $(FROM_LIST).find('option') listSize = $(list).length numOptsToRemove = listSize - (config.resetSize) $(FROM_LIST).find('option').each (tmpKey, tmpVal) -> if tmpKey < numOptsToRemove $(tmpVal).remove() return return ### # Remove N values from bottom of list. ### @removeFromBottom = -> list = $(FROM_LIST).find('option') listSize = $(list).length numOptsToRemove = listSize - (config.resetSize) if listSize < 1 return revList = [] # reverse the list $.each list, (tmpKey, tmpVal) -> revList.unshift tmpVal return $.each revList, (tmpKey, tmpVal) -> if tmpKey < numOptsToRemove $(tmpVal).remove() return return ### # Remove any stored selections. ### @clearSelections = -> if sessionStorage sessionStorage.removeItem CHOOSER_OPTS_STORAGE_KEY return # Private functions: ----------------------------- flashToMsg = (msg) -> $(TO_MESSAGE).text(msg) setTimeout (-> $(TO_MESSAGE).text '' return ), 2000 setVal = (values, which) -> if values and typeof values == 'object' $(which).empty() $.each values, (tmpKey, tmpVal) -> s3Prefixes = tmpVal[2] if config.showS3Buckets if typeof tmpVal == 'object' and tmpVal.length > 1 optVal = tmpVal[0] dispVal = tmpVal[1] else if typeof tmpVal == 'object' and tmpVal.length == 1 dispVal = optVal = tmpVal[0] else dispVal = optVal = tmpVal opt = $('<option>') .val(optVal) .text(if s3Prefixes then "🟠 #{dispVal}" else dispVal) .attr('title', if s3Prefixes then dispVal + s3Prefixes else dispVal) .addClass('icon-s3' if s3Prefixes) $(which).append opt return $(which).trigger 'change' sortOptions(which) ### # Trigger the filter textbox action. # # @param e ### initFromFilter = (e) -> if $(this).val().length >= config.filterChars SELF.getRemoteData 'filter' else SELF.getRemoteData 'first' return # Filter the TO side of the chooser # This only fiters based on the visible text initToFilter = -> # Clear the selected values first so that the user cannot have options # that are both selected and invisible because they've been filtered. $('.___toList').val('') SELF.toFilter($(this).val()) $(TO_LIST).trigger 'change' @toFilter = (filterText) -> $(TO_LIST).find('option').each (index, option) -> if $(option).text().toLowerCase().indexOf(filterText.toLowerCase()) == -1 $(option).addClass('is-hidden') else $(option).removeClass('is-hidden') ### # Makes the AJAX calls to get the data from the remote server. # # @param type ### @getRemoteData = (type) -> url = config.url queryJoinChar = '?' if url.match(/\?/) queryJoinChar = '&' overwrite = false if type == 'first' overwrite = true url += queryJoinChar + config.nextPageParm + '=1' PAGE_NUM = 1 else if type == 'next' PAGE_NUM++ url += queryJoinChar + config.nextPageParm + '=' + PAGE_NUM else if type == 'filter' overwrite = true url += queryJoinChar + config.filterParm + '=' + $(FROM_FILTER_TEXTBOX).val() $.ajax('url': url).done((resp) -> TOTAL_HITS = resp.hits SELF.setFromVal resp.items return ).fail (resp) -> console.error 'ERROR--->Could not retrieve values. Reason:' console.error resp.statusCode console.error resp.responseText if hasProp('errorCallback', 'function') config.errorCallback.call() return return ### # Add button click action. # # @param e - the click event ### addButtonClick = (e) -> e.preventDefault() removeAdded = if hasProp('removeAdded', 'boolean') then config.removeAdded else true if ! hasProp('toMax') || hasProp('toMax', 'number') toListSize = $(TO_LIST).find('option').length fromListSize = $(FROM_LIST).find('option:selected').length if (toListSize + fromListSize) > config.toMax flashToMsg('Only ' + config.toMax + ' items may be selected.') return if hasProp("removeAdded", "boolean") && config.removeAdded $(FROM_LIST).find('option:selected').appendTo($(TO_LIST)) else $(FROM_LIST).find('option:selected').clone().appendTo($(TO_LIST)) # disable the selected values in FROM_LIST $(FROM_LIST).find('option:selected').prop('disabled', true) # apply filter to TO_LIST # initToFilter SELF.toFilter($(TO_FILTER_TEXTBOX).val()) if ( hasProp('forceUnique', 'boolean') && hasProp('removeAdded', 'boolean') ) && ( config.forceUnique && ! config.removeAdded ) found = [] $(TO_LIST).find('option').each () -> if($.inArray(this.value, found) != -1) flashToMsg(config.uniqueMsg) $(this).remove() found.push(this.value) return $(TO_LIST).trigger 'change' # Sort the list every time sortOptions(TO_LIST) $(TO_LIST).blur() return return ### # Remove button click action. # # @param e - the click event # @param remAll - boolean indicating whether or not to remove # all values from the FROM list. ### removeButtonClick = (e, remAll) -> e.preventDefault() query = if remAll then 'option' else 'option:selected' $(TO_LIST).find(query).each (tmpKey, tmpVal) -> fromListVal = $(tmpVal).attr('value') # enable the FROM_LIST option $(FROM_LIST).find("option[value='#{fromListVal}']").prop('disabled', false) toListVal = $(TO_LIST).find('option').filter () -> if fromListVal == $(this).val() return true toListVal = $(toListVal).val() if fromListVal != toListVal clonedOpt = $(tmpVal).clone() $(FROM_LIST).prepend clonedOpt $(tmpVal).remove() return $(TO_LIST).trigger 'change' # Sort the list every time sortOptions(TO_LIST) $(TO_LIST).blur() return removeAllButtonClick = (e) -> removeButtonClick e, true return ### # Convenience method to test for presence of # a config option. # # Examples: # hasProp("someProp", "object") # hasProp("foo", "string") # hasProp("bar", "function") # hasProp("baz") # # @param name - config key # @param type - data type # @returns {boolean} ### hasProp = (name, type) -> if config.hasOwnProperty(name) if type _t = typeof config[name] if _t == type true else false else true else false ### # Sets a default value for a configuration property. # Example: setDefault('someMax', 200) sets config.max to 200 unless # it was already set. ### setDefault = (name, value) -> if ! hasProp(name) config[name] = value ### # Convenience method to handle logic of plural words. # # Examples: # pluraize(4) --> 's' # pluraize(1) --> '' # pluraize(0) --> 's' ### pluralize = (count) -> if count > 1 || count < 1 return 's' else return '' ### # Sorts a list of select options alphabetically by the option text ### sortOptions = (selectElem) -> sorted = $(selectElem).find('option').sort( (a,b) -> # we replace '🟠 ' to inhibit the emoji's unicode from interfering with # the alpha-sorting. If no '🟠 ' is found, nothing is changed an = $(a).text().toLowerCase().replace('🟠 ','') bn = $(b).text().toLowerCase().replace('🟠 ','') if(an > bn) return 1 if(an < bn) return -1 return 0 ).clone() $(selectElem).find("option").remove() $(selectElem).append(sorted) return
209585
### # # Chooser - dynamic, AJAX-enabled pick-list # # @author <NAME> # v2.0 (rewritten in CoffeeScript) # # Configuration parameters: # id (string): Unique ID for this widget. All HTML elements within this widget will # have IDs based on this. # url (string): URL of resource to retrieve initial selections. # target (element): DOM element where this widget will be placed. # fromLabel: Label to appear over "from" list # toLabel: Label to appear over "to" list # forceUnique (boolean): When true, only allows unique options to be added to the "to" list, # e.g., if "ABC" is already in the "to" list, it will not be added. Default is false. # size (int): Height of select control in number of options. # resetSize (int): When user scrolls to top, the entire list is trimmed to this size. Not required, # default is 50. # filterChars (sting): Number of characters to allow typing into filter textbox before AJAX call is triggered. # Default is 1. # showNumChosen (int): Always show the number of chosen items in the "to" list. # attachTo (element): DOM element where a value can be stored (hidden or text input). # errorCallback (function): Callback function to execute if an AJAX error occurs. # fromFilterText (string): Text for the "from" filter textbox placeholder (default is "filter") # toFilterText (string): Text for the "to" filter textbox placeholder (default is "filter") # removeAdded (boolean): Remove selections from the FROM list as they are added to the TO list. Default is true, # allowRemoveAll (boolean): Show the remove all button # lowerFromLabel (string): Text to display under the FROM list. Can be used with a template, e.g., # 'Showing {{x}} of {{n}} items.' where x is the number of items loaded in the FROM list # and x is the total number of hits that come back from the server (both are optional). # toMax (int or boolean): Total number of items that can be in the right ("to") box. Default: 500. Set to false # allow any number. A message is displayed if the user attempts to add more than the max. # # # Public methods: # # init() Initialize and render the widget. # val() Get the currently selected "to" values. # getDOMNode() Returns the DOM node for customization. # addValues(list) Adds values to the "from" list # setValues(list) Removes current values from "from" list and adds new ones. # removeFromBottom(n) Remove n values from bottom of "from" list. # # NOTES: Data format shall be formatted in the following ways: # # 1) An array of strings. Every value will be used for the option value and display value. # For example, ["lorem", "ipsum", "dolor", "sit", "amet"] # # 2) An array of 2-element arrays. First element is the option value, the second is the display value. # For example, [ ["lorem", "Lorem"], ["ipsum", "Ipsum"] ... ] # # 3) A mixed array: [ ["lorem", "Lorem"], "ipsum", "dolor", ["sit", "Sit"] ... ] # # 4) An array of single- or dual-element arrays. # For example, [ ["lorem", "Lorem"], ["ipsum"] ... ] # # 5) Any combination of the above. # ### # Constructor window.Chooser = (config) -> # Globals OUTER_CONTAINER = undefined FROM_CONTAINER = undefined TO_CONTAINER = undefined BUTTON_CONTAINER = undefined FROM_BOX = undefined FROM_LIST = undefined TO_BOX = undefined TO_LIST = undefined ADD_BUTTON = undefined REMOVE_BUTTON = undefined REMOVE_ALL_BUTTON = undefined FROM_LABEL = undefined TO_LABEL = undefined FROM_FILTER_TEXTBOX = undefined TO_FILTER_TEXTBOX = undefined TO_MESSAGE = undefined CHOOSER_OPTS_STORAGE_KEY = 'Chooser_opts_' + config.id PAGE_NUM = 1 LOWER_FROM_LABEL = undefined LOWER_TO_LABEL = undefined TOTAL_HITS = undefined SELF = undefined ### # init - initializes the widget. ### @init = -> SELF = this # Set defaults: setDefault('id', 'Chooser_' + Math.random().toString(36).slice(2)) setDefault('fromLabel', 'Available') setDefault('toLabel', 'Selected') setDefault('forceUnique', true) setDefault('size', 20) setDefault('filterChars', 1) setDefault('resetSize', 50) setDefault('showNumChosen', true) setDefault('fromFilterText', 'Enter text to narrow search results') setDefault('toFilterText', 'Enter text to narrow selected items') setDefault('removeAdded', false) setDefault('allowRemoveAll', true) setDefault('lowerFromLabel', 'Showing {{x}} of {{n}} item{{s}}') setDefault('lowerToLabel', 'Showing {{x}} of {{n}} item{{s}}') setDefault('toMax', false) setDefault('endlessScroll', false) setDefault('uniqueMsg', 'Value already added') setDefault('delimiter', ',') setDefault('tooltipObject', 'Collections') # Construct each component OUTER_CONTAINER = $('<div>').addClass('Chooser').attr('id', config.id) FROM_CONTAINER = $('<div>').addClass('from-container') TO_CONTAINER = $('<div>').addClass('to-container') BUTTON_CONTAINER = $('<div>').addClass('button-container') FROM_BOX = $('<div>') TO_BOX = $('<div>') addButtonText = if hasProp('addButton', 'object') then config.addButton.text else '&#x2192;' addButtonCssClass = if hasProp('addButton', 'object') then config.addButton.cssClass else '' ADD_BUTTON = $('<button>').attr('title', "Add highlighted items to 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(addButtonCssClass).addClass('add_button').text(addButtonText) if hasProp('addButton') and config.addButton.arrowCssClass $(ADD_BUTTON).append('<span>').addClass(config.addButton.arrowCssClass) delButtonText = if hasProp('delButton', 'object') then config.delButton.text else '&#x2190;' delButtonCssClass = if hasProp('delButton', 'object') then config.delButton.cssClass else '' REMOVE_BUTTON = $('<button>').attr('title', "Remove highlighted items from 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(delButtonCssClass).addClass('remove_button').text(delButtonText) if hasProp('delButton') and config.delButton.arrowCssClass $(REMOVE_BUTTON).prepend('<span>').addClass(config.delButton.arrowCssClass) allowRemoveAll = if hasProp('allowRemoveAll', 'boolean') then config.allowRemoveAll else true if allowRemoveAll == true delAllButtonText = if hasProp('delAllButton', 'object') then config.delAllButton.text else '&#x2190;' delAllButtonCssClass = if hasProp('delAllButton', 'object') then config.delAllButton.cssClass else '' REMOVE_ALL_BUTTON = $('<button>').attr('title', "Remove all entries from 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(delAllButtonCssClass).addClass('remove_all_button').text(delAllButtonText) if hasProp('delAllButton') and config.delAllButton.arrowCssClass $(REMOVE_ALL_BUTTON).prepend('<span>').addClass(config.delAllButton.arrowCssClass) FROM_LIST = $('<select>').addClass('___fromList').attr('id', config.id + '_fromList').attr( 'multiple', true).attr('size', config.size) TO_LIST = $('<select>').addClass('___toList').attr('name', config.id + '_toList[]').attr('id', config.id + '_toList').attr('multiple', true).attr('size', config.size) fromPlaceHolderText = if hasProp('fromFilterText', 'string') then config.fromFilterText else 'filter' FROM_FILTER_TEXTBOX = $('<input>').attr('type', 'text').attr('placeholder', fromPlaceHolderText).attr('id', 'from-filter') toPlaceHolderText = if hasProp('toFilterText', 'string') then config.toFilterText else 'filter' TO_FILTER_TEXTBOX = $('<input>').attr('type', 'text').attr('placeholder', toPlaceHolderText).attr('id', 'to-filter') if !config.hasOwnProperty('resetSize') config.resetSize = 50 if hasProp('fromLabel', 'string') FROM_LABEL = $('<label>').attr('for', config.id + '_fromList').text(config.fromLabel) if ! hasProp('lowerFromLabel') || hasProp('lowerFromLabel', 'string') LOWER_FROM_LABEL = $('<p>').addClass('form-description') if ! hasProp('lowerToLabel') || hasProp('lowerToLabel', 'string') LOWER_TO_LABEL = $('<p>').addClass('form-description') if config.toLabel TO_LABEL = $('<label>').attr('for', config.id + '_toList').text(config.toLabel) $(TO_CONTAINER).append TO_LABEL # Assemble the components $(OUTER_CONTAINER).append FROM_CONTAINER $(OUTER_CONTAINER).append BUTTON_CONTAINER $(OUTER_CONTAINER).append TO_CONTAINER $(FROM_CONTAINER).append FROM_LABEL $(FROM_CONTAINER).append FROM_FILTER_TEXTBOX $(FROM_CONTAINER).append FROM_LIST $(FROM_CONTAINER).append LOWER_FROM_LABEL $(TO_CONTAINER).append TO_FILTER_TEXTBOX $(TO_CONTAINER).append TO_LIST $(TO_CONTAINER).append LOWER_TO_LABEL $(BUTTON_CONTAINER).append ADD_BUTTON $(BUTTON_CONTAINER).append REMOVE_BUTTON $(BUTTON_CONTAINER).append REMOVE_ALL_BUTTON $(OUTER_CONTAINER).appendTo $(config.target) TO_MESSAGE = $('<span>').addClass('to_message') $(TO_CONTAINER).append TO_MESSAGE $(ADD_BUTTON).click addButtonClick $(REMOVE_BUTTON).click removeButtonClick $(REMOVE_ALL_BUTTON).click removeAllButtonClick SELF.getRemoteData 'first' $(FROM_LIST).on 'scroll', (evt) -> if config.endlessScroll == false return lowerBoundary = $(this).position().top + parseInt($(this).css('height')) upperBoundary = $(this).position().top lastOpt = $(this).find('option').last() lastOptPos = $(lastOpt).position().top firstOpt = $(this).find('option').first() firstOptPos = $(firstOpt).position().top lastOptHeight = parseInt($(lastOpt).css('height')) if lastOptPos <= lowerBoundary dist = lowerBoundary - lastOptPos offset = lastOptHeight - dist if offset > 1 and offset < 5 SELF.getRemoteData 'next' if firstOptPos >= upperBoundary SELF.removeFromBottom() PAGE_NUM = 1 return $(TO_LIST).change -> numChosen = $(TO_LIST).find('option').length if ! hasProp('lowerToLabel') || hasProp('lowerToLabel', 'string') x = $(TO_LIST).find('option').not('.is-hidden').length lowerToLabelText = config.lowerToLabel lowerToLabelText = lowerToLabelText.replace '{{x}}', x lowerToLabelText = lowerToLabelText.replace '{{n}}', numChosen lowerToLabelText = lowerToLabelText.replace('{{s}}', pluralize(numChosen)) $(LOWER_TO_LABEL).text(lowerToLabelText) if hasProp('toLabel') and hasProp('showNumChosen') if config.showNumChosen == true and numChosen > 0 $(TO_LABEL).text config.toLabel + ' (' + numChosen + ')' else $(TO_LABEL).text config.toLabel if hasProp('attachTo', 'object') $(config.attachTo).val SELF.val().join(config.delimiter) return $(FROM_LIST).change -> if ! hasProp('lowerFromLabel') || hasProp('lowerFromLabel', 'string') x = $(FROM_LIST).find('option').length n = TOTAL_HITS lowerFromLabelText = config.lowerFromLabel lowerFromLabelText = lowerFromLabelText.replace '{{x}}', x lowerFromLabelText = lowerFromLabelText.replace '{{n}}', n lowerFromLabelText = lowerFromLabelText.replace('{{s}}', pluralize(n)) $(LOWER_FROM_LABEL).text(lowerFromLabelText) return $(FROM_FILTER_TEXTBOX).keyup initFromFilter $(TO_FILTER_TEXTBOX).keyup initToFilter $(FROM_LIST).dblclick -> $(ADD_BUTTON).click() return $(TO_LIST).dblclick -> $(REMOVE_BUTTON).click() return ### # Set provided config values # ### @setConfig = (key, value) -> config[key] = value ### # Sets the values in the "TO" list. # ### @setToVal = (values) -> setVal(values, $(TO_LIST)) ### # Sets the values in the "FROM" list. # ### @setFromVal = (values) -> setVal(values, $(FROM_LIST)) ### # Returns the widget's "value" (selected values). # # @returns {*|object} ### @val = () -> vals = $(TO_LIST).find('option').map((tmpKey, tmpVal) -> $(tmpVal).text() ) valsAsArray = [] $.each vals, (tmpKey, tmpVal) -> valsAsArray.push tmpVal return valsAsArray ### # Returns the top-level DOM node of this widget. # @returns {*|jQuery|HTMLElement} ### @getDOMNode = -> $ OUTER_CONTAINER ### # Removes N values from top of FROM list. # # @param n - number of values to remove. ### @removeFromTop = (n) -> list = $(FROM_LIST).find('option') listSize = $(list).length numOptsToRemove = listSize - (config.resetSize) $(FROM_LIST).find('option').each (tmpKey, tmpVal) -> if tmpKey < numOptsToRemove $(tmpVal).remove() return return ### # Remove N values from bottom of list. ### @removeFromBottom = -> list = $(FROM_LIST).find('option') listSize = $(list).length numOptsToRemove = listSize - (config.resetSize) if listSize < 1 return revList = [] # reverse the list $.each list, (tmpKey, tmpVal) -> revList.unshift tmpVal return $.each revList, (tmpKey, tmpVal) -> if tmpKey < numOptsToRemove $(tmpVal).remove() return return ### # Remove any stored selections. ### @clearSelections = -> if sessionStorage sessionStorage.removeItem CHOOSER_OPTS_STORAGE_KEY return # Private functions: ----------------------------- flashToMsg = (msg) -> $(TO_MESSAGE).text(msg) setTimeout (-> $(TO_MESSAGE).text '' return ), 2000 setVal = (values, which) -> if values and typeof values == 'object' $(which).empty() $.each values, (tmpKey, tmpVal) -> s3Prefixes = tmpVal[2] if config.showS3Buckets if typeof tmpVal == 'object' and tmpVal.length > 1 optVal = tmpVal[0] dispVal = tmpVal[1] else if typeof tmpVal == 'object' and tmpVal.length == 1 dispVal = optVal = tmpVal[0] else dispVal = optVal = tmpVal opt = $('<option>') .val(optVal) .text(if s3Prefixes then "🟠 #{dispVal}" else dispVal) .attr('title', if s3Prefixes then dispVal + s3Prefixes else dispVal) .addClass('icon-s3' if s3Prefixes) $(which).append opt return $(which).trigger 'change' sortOptions(which) ### # Trigger the filter textbox action. # # @param e ### initFromFilter = (e) -> if $(this).val().length >= config.filterChars SELF.getRemoteData 'filter' else SELF.getRemoteData 'first' return # Filter the TO side of the chooser # This only fiters based on the visible text initToFilter = -> # Clear the selected values first so that the user cannot have options # that are both selected and invisible because they've been filtered. $('.___toList').val('') SELF.toFilter($(this).val()) $(TO_LIST).trigger 'change' @toFilter = (filterText) -> $(TO_LIST).find('option').each (index, option) -> if $(option).text().toLowerCase().indexOf(filterText.toLowerCase()) == -1 $(option).addClass('is-hidden') else $(option).removeClass('is-hidden') ### # Makes the AJAX calls to get the data from the remote server. # # @param type ### @getRemoteData = (type) -> url = config.url queryJoinChar = '?' if url.match(/\?/) queryJoinChar = '&' overwrite = false if type == 'first' overwrite = true url += queryJoinChar + config.nextPageParm + '=1' PAGE_NUM = 1 else if type == 'next' PAGE_NUM++ url += queryJoinChar + config.nextPageParm + '=' + PAGE_NUM else if type == 'filter' overwrite = true url += queryJoinChar + config.filterParm + '=' + $(FROM_FILTER_TEXTBOX).val() $.ajax('url': url).done((resp) -> TOTAL_HITS = resp.hits SELF.setFromVal resp.items return ).fail (resp) -> console.error 'ERROR--->Could not retrieve values. Reason:' console.error resp.statusCode console.error resp.responseText if hasProp('errorCallback', 'function') config.errorCallback.call() return return ### # Add button click action. # # @param e - the click event ### addButtonClick = (e) -> e.preventDefault() removeAdded = if hasProp('removeAdded', 'boolean') then config.removeAdded else true if ! hasProp('toMax') || hasProp('toMax', 'number') toListSize = $(TO_LIST).find('option').length fromListSize = $(FROM_LIST).find('option:selected').length if (toListSize + fromListSize) > config.toMax flashToMsg('Only ' + config.toMax + ' items may be selected.') return if hasProp("removeAdded", "boolean") && config.removeAdded $(FROM_LIST).find('option:selected').appendTo($(TO_LIST)) else $(FROM_LIST).find('option:selected').clone().appendTo($(TO_LIST)) # disable the selected values in FROM_LIST $(FROM_LIST).find('option:selected').prop('disabled', true) # apply filter to TO_LIST # initToFilter SELF.toFilter($(TO_FILTER_TEXTBOX).val()) if ( hasProp('forceUnique', 'boolean') && hasProp('removeAdded', 'boolean') ) && ( config.forceUnique && ! config.removeAdded ) found = [] $(TO_LIST).find('option').each () -> if($.inArray(this.value, found) != -1) flashToMsg(config.uniqueMsg) $(this).remove() found.push(this.value) return $(TO_LIST).trigger 'change' # Sort the list every time sortOptions(TO_LIST) $(TO_LIST).blur() return return ### # Remove button click action. # # @param e - the click event # @param remAll - boolean indicating whether or not to remove # all values from the FROM list. ### removeButtonClick = (e, remAll) -> e.preventDefault() query = if remAll then 'option' else 'option:selected' $(TO_LIST).find(query).each (tmpKey, tmpVal) -> fromListVal = $(tmpVal).attr('value') # enable the FROM_LIST option $(FROM_LIST).find("option[value='#{fromListVal}']").prop('disabled', false) toListVal = $(TO_LIST).find('option').filter () -> if fromListVal == $(this).val() return true toListVal = $(toListVal).val() if fromListVal != toListVal clonedOpt = $(tmpVal).clone() $(FROM_LIST).prepend clonedOpt $(tmpVal).remove() return $(TO_LIST).trigger 'change' # Sort the list every time sortOptions(TO_LIST) $(TO_LIST).blur() return removeAllButtonClick = (e) -> removeButtonClick e, true return ### # Convenience method to test for presence of # a config option. # # Examples: # hasProp("someProp", "object") # hasProp("foo", "string") # hasProp("bar", "function") # hasProp("baz") # # @param name - config key # @param type - data type # @returns {boolean} ### hasProp = (name, type) -> if config.hasOwnProperty(name) if type _t = typeof config[name] if _t == type true else false else true else false ### # Sets a default value for a configuration property. # Example: setDefault('someMax', 200) sets config.max to 200 unless # it was already set. ### setDefault = (name, value) -> if ! hasProp(name) config[name] = value ### # Convenience method to handle logic of plural words. # # Examples: # pluraize(4) --> 's' # pluraize(1) --> '' # pluraize(0) --> 's' ### pluralize = (count) -> if count > 1 || count < 1 return 's' else return '' ### # Sorts a list of select options alphabetically by the option text ### sortOptions = (selectElem) -> sorted = $(selectElem).find('option').sort( (a,b) -> # we replace '🟠 ' to inhibit the emoji's unicode from interfering with # the alpha-sorting. If no '🟠 ' is found, nothing is changed an = $(a).text().toLowerCase().replace('🟠 ','') bn = $(b).text().toLowerCase().replace('🟠 ','') if(an > bn) return 1 if(an < bn) return -1 return 0 ).clone() $(selectElem).find("option").remove() $(selectElem).append(sorted) return
true
### # # Chooser - dynamic, AJAX-enabled pick-list # # @author PI:NAME:<NAME>END_PI # v2.0 (rewritten in CoffeeScript) # # Configuration parameters: # id (string): Unique ID for this widget. All HTML elements within this widget will # have IDs based on this. # url (string): URL of resource to retrieve initial selections. # target (element): DOM element where this widget will be placed. # fromLabel: Label to appear over "from" list # toLabel: Label to appear over "to" list # forceUnique (boolean): When true, only allows unique options to be added to the "to" list, # e.g., if "ABC" is already in the "to" list, it will not be added. Default is false. # size (int): Height of select control in number of options. # resetSize (int): When user scrolls to top, the entire list is trimmed to this size. Not required, # default is 50. # filterChars (sting): Number of characters to allow typing into filter textbox before AJAX call is triggered. # Default is 1. # showNumChosen (int): Always show the number of chosen items in the "to" list. # attachTo (element): DOM element where a value can be stored (hidden or text input). # errorCallback (function): Callback function to execute if an AJAX error occurs. # fromFilterText (string): Text for the "from" filter textbox placeholder (default is "filter") # toFilterText (string): Text for the "to" filter textbox placeholder (default is "filter") # removeAdded (boolean): Remove selections from the FROM list as they are added to the TO list. Default is true, # allowRemoveAll (boolean): Show the remove all button # lowerFromLabel (string): Text to display under the FROM list. Can be used with a template, e.g., # 'Showing {{x}} of {{n}} items.' where x is the number of items loaded in the FROM list # and x is the total number of hits that come back from the server (both are optional). # toMax (int or boolean): Total number of items that can be in the right ("to") box. Default: 500. Set to false # allow any number. A message is displayed if the user attempts to add more than the max. # # # Public methods: # # init() Initialize and render the widget. # val() Get the currently selected "to" values. # getDOMNode() Returns the DOM node for customization. # addValues(list) Adds values to the "from" list # setValues(list) Removes current values from "from" list and adds new ones. # removeFromBottom(n) Remove n values from bottom of "from" list. # # NOTES: Data format shall be formatted in the following ways: # # 1) An array of strings. Every value will be used for the option value and display value. # For example, ["lorem", "ipsum", "dolor", "sit", "amet"] # # 2) An array of 2-element arrays. First element is the option value, the second is the display value. # For example, [ ["lorem", "Lorem"], ["ipsum", "Ipsum"] ... ] # # 3) A mixed array: [ ["lorem", "Lorem"], "ipsum", "dolor", ["sit", "Sit"] ... ] # # 4) An array of single- or dual-element arrays. # For example, [ ["lorem", "Lorem"], ["ipsum"] ... ] # # 5) Any combination of the above. # ### # Constructor window.Chooser = (config) -> # Globals OUTER_CONTAINER = undefined FROM_CONTAINER = undefined TO_CONTAINER = undefined BUTTON_CONTAINER = undefined FROM_BOX = undefined FROM_LIST = undefined TO_BOX = undefined TO_LIST = undefined ADD_BUTTON = undefined REMOVE_BUTTON = undefined REMOVE_ALL_BUTTON = undefined FROM_LABEL = undefined TO_LABEL = undefined FROM_FILTER_TEXTBOX = undefined TO_FILTER_TEXTBOX = undefined TO_MESSAGE = undefined CHOOSER_OPTS_STORAGE_KEY = 'Chooser_opts_' + config.id PAGE_NUM = 1 LOWER_FROM_LABEL = undefined LOWER_TO_LABEL = undefined TOTAL_HITS = undefined SELF = undefined ### # init - initializes the widget. ### @init = -> SELF = this # Set defaults: setDefault('id', 'Chooser_' + Math.random().toString(36).slice(2)) setDefault('fromLabel', 'Available') setDefault('toLabel', 'Selected') setDefault('forceUnique', true) setDefault('size', 20) setDefault('filterChars', 1) setDefault('resetSize', 50) setDefault('showNumChosen', true) setDefault('fromFilterText', 'Enter text to narrow search results') setDefault('toFilterText', 'Enter text to narrow selected items') setDefault('removeAdded', false) setDefault('allowRemoveAll', true) setDefault('lowerFromLabel', 'Showing {{x}} of {{n}} item{{s}}') setDefault('lowerToLabel', 'Showing {{x}} of {{n}} item{{s}}') setDefault('toMax', false) setDefault('endlessScroll', false) setDefault('uniqueMsg', 'Value already added') setDefault('delimiter', ',') setDefault('tooltipObject', 'Collections') # Construct each component OUTER_CONTAINER = $('<div>').addClass('Chooser').attr('id', config.id) FROM_CONTAINER = $('<div>').addClass('from-container') TO_CONTAINER = $('<div>').addClass('to-container') BUTTON_CONTAINER = $('<div>').addClass('button-container') FROM_BOX = $('<div>') TO_BOX = $('<div>') addButtonText = if hasProp('addButton', 'object') then config.addButton.text else '&#x2192;' addButtonCssClass = if hasProp('addButton', 'object') then config.addButton.cssClass else '' ADD_BUTTON = $('<button>').attr('title', "Add highlighted items to 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(addButtonCssClass).addClass('add_button').text(addButtonText) if hasProp('addButton') and config.addButton.arrowCssClass $(ADD_BUTTON).append('<span>').addClass(config.addButton.arrowCssClass) delButtonText = if hasProp('delButton', 'object') then config.delButton.text else '&#x2190;' delButtonCssClass = if hasProp('delButton', 'object') then config.delButton.cssClass else '' REMOVE_BUTTON = $('<button>').attr('title', "Remove highlighted items from 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(delButtonCssClass).addClass('remove_button').text(delButtonText) if hasProp('delButton') and config.delButton.arrowCssClass $(REMOVE_BUTTON).prepend('<span>').addClass(config.delButton.arrowCssClass) allowRemoveAll = if hasProp('allowRemoveAll', 'boolean') then config.allowRemoveAll else true if allowRemoveAll == true delAllButtonText = if hasProp('delAllButton', 'object') then config.delAllButton.text else '&#x2190;' delAllButtonCssClass = if hasProp('delAllButton', 'object') then config.delAllButton.cssClass else '' REMOVE_ALL_BUTTON = $('<button>').attr('title', "Remove all entries from 'Selected #{config.tooltipObject}'").attr('type', 'button').addClass(delAllButtonCssClass).addClass('remove_all_button').text(delAllButtonText) if hasProp('delAllButton') and config.delAllButton.arrowCssClass $(REMOVE_ALL_BUTTON).prepend('<span>').addClass(config.delAllButton.arrowCssClass) FROM_LIST = $('<select>').addClass('___fromList').attr('id', config.id + '_fromList').attr( 'multiple', true).attr('size', config.size) TO_LIST = $('<select>').addClass('___toList').attr('name', config.id + '_toList[]').attr('id', config.id + '_toList').attr('multiple', true).attr('size', config.size) fromPlaceHolderText = if hasProp('fromFilterText', 'string') then config.fromFilterText else 'filter' FROM_FILTER_TEXTBOX = $('<input>').attr('type', 'text').attr('placeholder', fromPlaceHolderText).attr('id', 'from-filter') toPlaceHolderText = if hasProp('toFilterText', 'string') then config.toFilterText else 'filter' TO_FILTER_TEXTBOX = $('<input>').attr('type', 'text').attr('placeholder', toPlaceHolderText).attr('id', 'to-filter') if !config.hasOwnProperty('resetSize') config.resetSize = 50 if hasProp('fromLabel', 'string') FROM_LABEL = $('<label>').attr('for', config.id + '_fromList').text(config.fromLabel) if ! hasProp('lowerFromLabel') || hasProp('lowerFromLabel', 'string') LOWER_FROM_LABEL = $('<p>').addClass('form-description') if ! hasProp('lowerToLabel') || hasProp('lowerToLabel', 'string') LOWER_TO_LABEL = $('<p>').addClass('form-description') if config.toLabel TO_LABEL = $('<label>').attr('for', config.id + '_toList').text(config.toLabel) $(TO_CONTAINER).append TO_LABEL # Assemble the components $(OUTER_CONTAINER).append FROM_CONTAINER $(OUTER_CONTAINER).append BUTTON_CONTAINER $(OUTER_CONTAINER).append TO_CONTAINER $(FROM_CONTAINER).append FROM_LABEL $(FROM_CONTAINER).append FROM_FILTER_TEXTBOX $(FROM_CONTAINER).append FROM_LIST $(FROM_CONTAINER).append LOWER_FROM_LABEL $(TO_CONTAINER).append TO_FILTER_TEXTBOX $(TO_CONTAINER).append TO_LIST $(TO_CONTAINER).append LOWER_TO_LABEL $(BUTTON_CONTAINER).append ADD_BUTTON $(BUTTON_CONTAINER).append REMOVE_BUTTON $(BUTTON_CONTAINER).append REMOVE_ALL_BUTTON $(OUTER_CONTAINER).appendTo $(config.target) TO_MESSAGE = $('<span>').addClass('to_message') $(TO_CONTAINER).append TO_MESSAGE $(ADD_BUTTON).click addButtonClick $(REMOVE_BUTTON).click removeButtonClick $(REMOVE_ALL_BUTTON).click removeAllButtonClick SELF.getRemoteData 'first' $(FROM_LIST).on 'scroll', (evt) -> if config.endlessScroll == false return lowerBoundary = $(this).position().top + parseInt($(this).css('height')) upperBoundary = $(this).position().top lastOpt = $(this).find('option').last() lastOptPos = $(lastOpt).position().top firstOpt = $(this).find('option').first() firstOptPos = $(firstOpt).position().top lastOptHeight = parseInt($(lastOpt).css('height')) if lastOptPos <= lowerBoundary dist = lowerBoundary - lastOptPos offset = lastOptHeight - dist if offset > 1 and offset < 5 SELF.getRemoteData 'next' if firstOptPos >= upperBoundary SELF.removeFromBottom() PAGE_NUM = 1 return $(TO_LIST).change -> numChosen = $(TO_LIST).find('option').length if ! hasProp('lowerToLabel') || hasProp('lowerToLabel', 'string') x = $(TO_LIST).find('option').not('.is-hidden').length lowerToLabelText = config.lowerToLabel lowerToLabelText = lowerToLabelText.replace '{{x}}', x lowerToLabelText = lowerToLabelText.replace '{{n}}', numChosen lowerToLabelText = lowerToLabelText.replace('{{s}}', pluralize(numChosen)) $(LOWER_TO_LABEL).text(lowerToLabelText) if hasProp('toLabel') and hasProp('showNumChosen') if config.showNumChosen == true and numChosen > 0 $(TO_LABEL).text config.toLabel + ' (' + numChosen + ')' else $(TO_LABEL).text config.toLabel if hasProp('attachTo', 'object') $(config.attachTo).val SELF.val().join(config.delimiter) return $(FROM_LIST).change -> if ! hasProp('lowerFromLabel') || hasProp('lowerFromLabel', 'string') x = $(FROM_LIST).find('option').length n = TOTAL_HITS lowerFromLabelText = config.lowerFromLabel lowerFromLabelText = lowerFromLabelText.replace '{{x}}', x lowerFromLabelText = lowerFromLabelText.replace '{{n}}', n lowerFromLabelText = lowerFromLabelText.replace('{{s}}', pluralize(n)) $(LOWER_FROM_LABEL).text(lowerFromLabelText) return $(FROM_FILTER_TEXTBOX).keyup initFromFilter $(TO_FILTER_TEXTBOX).keyup initToFilter $(FROM_LIST).dblclick -> $(ADD_BUTTON).click() return $(TO_LIST).dblclick -> $(REMOVE_BUTTON).click() return ### # Set provided config values # ### @setConfig = (key, value) -> config[key] = value ### # Sets the values in the "TO" list. # ### @setToVal = (values) -> setVal(values, $(TO_LIST)) ### # Sets the values in the "FROM" list. # ### @setFromVal = (values) -> setVal(values, $(FROM_LIST)) ### # Returns the widget's "value" (selected values). # # @returns {*|object} ### @val = () -> vals = $(TO_LIST).find('option').map((tmpKey, tmpVal) -> $(tmpVal).text() ) valsAsArray = [] $.each vals, (tmpKey, tmpVal) -> valsAsArray.push tmpVal return valsAsArray ### # Returns the top-level DOM node of this widget. # @returns {*|jQuery|HTMLElement} ### @getDOMNode = -> $ OUTER_CONTAINER ### # Removes N values from top of FROM list. # # @param n - number of values to remove. ### @removeFromTop = (n) -> list = $(FROM_LIST).find('option') listSize = $(list).length numOptsToRemove = listSize - (config.resetSize) $(FROM_LIST).find('option').each (tmpKey, tmpVal) -> if tmpKey < numOptsToRemove $(tmpVal).remove() return return ### # Remove N values from bottom of list. ### @removeFromBottom = -> list = $(FROM_LIST).find('option') listSize = $(list).length numOptsToRemove = listSize - (config.resetSize) if listSize < 1 return revList = [] # reverse the list $.each list, (tmpKey, tmpVal) -> revList.unshift tmpVal return $.each revList, (tmpKey, tmpVal) -> if tmpKey < numOptsToRemove $(tmpVal).remove() return return ### # Remove any stored selections. ### @clearSelections = -> if sessionStorage sessionStorage.removeItem CHOOSER_OPTS_STORAGE_KEY return # Private functions: ----------------------------- flashToMsg = (msg) -> $(TO_MESSAGE).text(msg) setTimeout (-> $(TO_MESSAGE).text '' return ), 2000 setVal = (values, which) -> if values and typeof values == 'object' $(which).empty() $.each values, (tmpKey, tmpVal) -> s3Prefixes = tmpVal[2] if config.showS3Buckets if typeof tmpVal == 'object' and tmpVal.length > 1 optVal = tmpVal[0] dispVal = tmpVal[1] else if typeof tmpVal == 'object' and tmpVal.length == 1 dispVal = optVal = tmpVal[0] else dispVal = optVal = tmpVal opt = $('<option>') .val(optVal) .text(if s3Prefixes then "🟠 #{dispVal}" else dispVal) .attr('title', if s3Prefixes then dispVal + s3Prefixes else dispVal) .addClass('icon-s3' if s3Prefixes) $(which).append opt return $(which).trigger 'change' sortOptions(which) ### # Trigger the filter textbox action. # # @param e ### initFromFilter = (e) -> if $(this).val().length >= config.filterChars SELF.getRemoteData 'filter' else SELF.getRemoteData 'first' return # Filter the TO side of the chooser # This only fiters based on the visible text initToFilter = -> # Clear the selected values first so that the user cannot have options # that are both selected and invisible because they've been filtered. $('.___toList').val('') SELF.toFilter($(this).val()) $(TO_LIST).trigger 'change' @toFilter = (filterText) -> $(TO_LIST).find('option').each (index, option) -> if $(option).text().toLowerCase().indexOf(filterText.toLowerCase()) == -1 $(option).addClass('is-hidden') else $(option).removeClass('is-hidden') ### # Makes the AJAX calls to get the data from the remote server. # # @param type ### @getRemoteData = (type) -> url = config.url queryJoinChar = '?' if url.match(/\?/) queryJoinChar = '&' overwrite = false if type == 'first' overwrite = true url += queryJoinChar + config.nextPageParm + '=1' PAGE_NUM = 1 else if type == 'next' PAGE_NUM++ url += queryJoinChar + config.nextPageParm + '=' + PAGE_NUM else if type == 'filter' overwrite = true url += queryJoinChar + config.filterParm + '=' + $(FROM_FILTER_TEXTBOX).val() $.ajax('url': url).done((resp) -> TOTAL_HITS = resp.hits SELF.setFromVal resp.items return ).fail (resp) -> console.error 'ERROR--->Could not retrieve values. Reason:' console.error resp.statusCode console.error resp.responseText if hasProp('errorCallback', 'function') config.errorCallback.call() return return ### # Add button click action. # # @param e - the click event ### addButtonClick = (e) -> e.preventDefault() removeAdded = if hasProp('removeAdded', 'boolean') then config.removeAdded else true if ! hasProp('toMax') || hasProp('toMax', 'number') toListSize = $(TO_LIST).find('option').length fromListSize = $(FROM_LIST).find('option:selected').length if (toListSize + fromListSize) > config.toMax flashToMsg('Only ' + config.toMax + ' items may be selected.') return if hasProp("removeAdded", "boolean") && config.removeAdded $(FROM_LIST).find('option:selected').appendTo($(TO_LIST)) else $(FROM_LIST).find('option:selected').clone().appendTo($(TO_LIST)) # disable the selected values in FROM_LIST $(FROM_LIST).find('option:selected').prop('disabled', true) # apply filter to TO_LIST # initToFilter SELF.toFilter($(TO_FILTER_TEXTBOX).val()) if ( hasProp('forceUnique', 'boolean') && hasProp('removeAdded', 'boolean') ) && ( config.forceUnique && ! config.removeAdded ) found = [] $(TO_LIST).find('option').each () -> if($.inArray(this.value, found) != -1) flashToMsg(config.uniqueMsg) $(this).remove() found.push(this.value) return $(TO_LIST).trigger 'change' # Sort the list every time sortOptions(TO_LIST) $(TO_LIST).blur() return return ### # Remove button click action. # # @param e - the click event # @param remAll - boolean indicating whether or not to remove # all values from the FROM list. ### removeButtonClick = (e, remAll) -> e.preventDefault() query = if remAll then 'option' else 'option:selected' $(TO_LIST).find(query).each (tmpKey, tmpVal) -> fromListVal = $(tmpVal).attr('value') # enable the FROM_LIST option $(FROM_LIST).find("option[value='#{fromListVal}']").prop('disabled', false) toListVal = $(TO_LIST).find('option').filter () -> if fromListVal == $(this).val() return true toListVal = $(toListVal).val() if fromListVal != toListVal clonedOpt = $(tmpVal).clone() $(FROM_LIST).prepend clonedOpt $(tmpVal).remove() return $(TO_LIST).trigger 'change' # Sort the list every time sortOptions(TO_LIST) $(TO_LIST).blur() return removeAllButtonClick = (e) -> removeButtonClick e, true return ### # Convenience method to test for presence of # a config option. # # Examples: # hasProp("someProp", "object") # hasProp("foo", "string") # hasProp("bar", "function") # hasProp("baz") # # @param name - config key # @param type - data type # @returns {boolean} ### hasProp = (name, type) -> if config.hasOwnProperty(name) if type _t = typeof config[name] if _t == type true else false else true else false ### # Sets a default value for a configuration property. # Example: setDefault('someMax', 200) sets config.max to 200 unless # it was already set. ### setDefault = (name, value) -> if ! hasProp(name) config[name] = value ### # Convenience method to handle logic of plural words. # # Examples: # pluraize(4) --> 's' # pluraize(1) --> '' # pluraize(0) --> 's' ### pluralize = (count) -> if count > 1 || count < 1 return 's' else return '' ### # Sorts a list of select options alphabetically by the option text ### sortOptions = (selectElem) -> sorted = $(selectElem).find('option').sort( (a,b) -> # we replace '🟠 ' to inhibit the emoji's unicode from interfering with # the alpha-sorting. If no '🟠 ' is found, nothing is changed an = $(a).text().toLowerCase().replace('🟠 ','') bn = $(b).text().toLowerCase().replace('🟠 ','') if(an > bn) return 1 if(an < bn) return -1 return 0 ).clone() $(selectElem).find("option").remove() $(selectElem).append(sorted) return
[ { "context": "yte_count = null\n\n execute: (rs) ->\n key = rs.pop()\n throw new BranchException(\n rs.curr_pc", "end": 4741, "score": 0.594798743724823, "start": 4738, "tag": "KEY", "value": "pop" } ]
src/opcodes.coffee
Jivings/doppio
1
gLong ?= require '../third_party/gLong.js' util ?= require './util' types ?= require './types' {java_throw,BranchException,ReturnException,JavaException} = util {c2t} = types root = exports ? this.opcodes = {} class root.Opcode constructor: (@name, params={}) -> (@[prop] = val for prop, val of params) @execute ?= @_execute @byte_count = params.byte_count ? 0 take_args: (code_array) -> @args = (code_array.get_uint(1) for [0...@byte_count]) class root.FieldOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @field_spec_ref = code_array.get_uint(2) @field_spec = constant_pool.get(@field_spec_ref).deref() class root.ClassOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @class_ref = code_array.get_uint(2) @class = constant_pool.get(@class_ref).deref() class root.InvokeOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @method_spec_ref = code_array.get_uint(2) # invokeinterface has two redundant bytes if @name == 'invokeinterface' @count = code_array.get_uint 1 code_array.skip 1 @byte_count += 2 @method_spec = constant_pool.get(@method_spec_ref).deref() class root.LoadConstantOpcode extends root.Opcode take_args: (code_array, constant_pool) -> @cls = constant_pool.cls @constant_ref = code_array.get_uint @byte_count @constant = constant_pool.get @constant_ref _execute: (rs) -> val = @constant.value if @constant.type is 'String' val = rs.string_redirect(val, @cls) if @constant.type is 'class' jvm_str = rs.string_redirect(val,@cls) val = rs.class_lookup c2t(rs.jvm2js_str(jvm_str)), true rs.push val rs.push null if @name is 'ldc2_w' class root.BranchOpcode extends root.Opcode constructor: (name, params={}) -> params.byte_count ?= 2 super name, params take_args: (code_array) -> @offset = code_array.get_int @byte_count class root.UnaryBranchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, { execute: (rs) -> v = rs.pop() throw new BranchException rs.curr_pc() + @offset if params.cmp v } class root.BinaryBranchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, { execute: (rs) -> v2 = rs.pop() v1 = rs.pop() throw new BranchException rs.curr_pc() + @offset if params.cmp v1, v2 } class root.PushOpcode extends root.Opcode take_args: (code_array) -> @value = code_array.get_int @byte_count _execute: (rs) -> rs.push @value class root.IIncOpcode extends root.Opcode constructor: (name, params) -> super name, params take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" arg_size = 2 @byte_count = 5 else arg_size = 1 @byte_count = 2 @index = code_array.get_uint arg_size @const = code_array.get_int arg_size _execute: (rs) -> rs.put_cl(@index,rs.cl(@index)+@const) class root.LoadOpcode extends root.Opcode constructor: (name, params={}) -> params.execute ?= if name.match /[ld]load/ (rs) -> rs.push rs.cl(@var_num), null else (rs) -> rs.push rs.cl(@var_num) super name, params take_args: (code_array) -> @var_num = parseInt @name[6] # sneaky hack, works for name =~ /.load_\d/ class root.LoadVarOpcode extends root.LoadOpcode take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" @byte_count = 3 @var_num = code_array.get_uint 2 else @byte_count = 1 @var_num = code_array.get_uint 1 class root.StoreOpcode extends root.Opcode constructor: (name, params={}) -> params.execute ?= if name.match /[ld]store/ (rs) -> rs.put_cl2(@var_num,rs.pop2()) else (rs) -> rs.put_cl(@var_num,rs.pop()) super name, params take_args: (code_array) -> @var_num = parseInt @name[7] # sneaky hack, works for name =~ /.store_\d/ class root.StoreVarOpcode extends root.StoreOpcode constructor: (name, params) -> super name, params take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" @byte_count = 3 @var_num = code_array.get_uint 2 else @byte_count = 1 @var_num = code_array.get_uint 1 class root.SwitchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, params @byte_count = null execute: (rs) -> key = rs.pop() throw new BranchException( rs.curr_pc() + if @offsets[key]? then @offsets[key] else @_default ) class root.LookupSwitchOpcode extends root.SwitchOpcode take_args: (code_array, constant_pool) -> # account for padding that ensures alignment padding_size = (4 - code_array.pos() % 4) % 4 code_array.skip padding_size @_default = code_array.get_int(4) @npairs = code_array.get_int(4) @offsets = {} for [0...@npairs] match = code_array.get_int(4) offset = code_array.get_int(4) @offsets[match] = offset @byte_count = padding_size + 8 * (@npairs + 1) class root.TableSwitchOpcode extends root.SwitchOpcode take_args: (code_array, constant_pool) -> # account for padding that ensures alignment padding_size = (4 - code_array.pos() % 4) % 4 code_array.skip padding_size @_default = code_array.get_int(4) @low = code_array.get_int(4) @high = code_array.get_int(4) @offsets = {} total_offsets = @high - @low + 1 for i in [0...total_offsets] offset = code_array.get_int(4) @offsets[@low + i] = offset @byte_count = padding_size + 12 + 4 * total_offsets class root.NewArrayOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 1 @arr_types = {4:'Z',5:'C',6:'F',7:'D',8:'B',9:'S',10:'I',11:'J'} take_args: (code_array,constant_pool) -> type_code = code_array.get_uint 1 @element_type = @arr_types[type_code] class root.MultiArrayOpcode extends root.Opcode constructor: (name, params={}) -> params.byte_count ?= 3 super name, params take_args: (code_array, constant_pool) -> @class_ref = code_array.get_uint 2 @class = constant_pool.get(@class_ref).deref() @dim = code_array.get_uint 1 execute: (rs) -> counts = rs.curr_frame().stack.splice(rs.length-@dim) init_arr = (curr_dim) => return 0 if curr_dim == @dim typestr = @class[curr_dim..] rs.init_object typestr, (init_arr(curr_dim+1) for [0...counts[curr_dim]]) rs.push init_arr 0 class root.ArrayLoadOpcode extends root.Opcode execute: (rs) -> idx = rs.pop() array = rs.check_null(rs.pop()).array java_throw rs, 'java/lang/ArrayIndexOutOfBoundsException', "#{idx} not in [0,#{array.length})" unless 0 <= idx < array.length rs.push array[idx] rs.push null if @name.match /[ld]aload/ towards_zero = (a) -> Math[if a > 0 then 'floor' else 'ceil'](a) int_mod = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b == 0 a % b int_div = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b == 0 towards_zero a / b # TODO spec: "if the dividend is the negative integer of largest possible magnitude # for the int type, and the divisor is -1, then overflow occurs, and the # result is equal to the dividend." long_mod = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b.isZero() a.modulo(b) long_div = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b.isZero() a.div(b) float2int = (a) -> INT_MAX = Math.pow(2, 31) - 1 INT_MIN = - Math.pow 2, 31 if a == NaN then 0 else if a > INT_MAX then INT_MAX # these two cases handle d2i issues else if a < INT_MIN then INT_MIN else unless a == Infinity or a == -Infinity then towards_zero a else if a > 0 then INT_MAX else INT_MIN # sign-preserving number truncate, with overflow and such truncate = (a, n_bits) -> a = (a + Math.pow 2, n_bits) % Math.pow 2, n_bits util.uint2int a, n_bits/8 wrap_int = (a) -> truncate a, 32 wrap_float = (a) -> return Infinity if a > 3.40282346638528860e+38 return 0 if 0 < a < 1.40129846432481707e-45 return -Infinity if a < -3.40282346638528860e+38 return 0 if 0 > a > -1.40129846432481707e-45 a jsr = (rs) -> rs.push(rs.curr_pc()+@byte_count+1); throw new BranchException rs.curr_pc() + @offset # these objects are used as prototypes for the parsed instructions in the # classfile root.opcodes = { 0: new root.Opcode 'nop', { execute: -> } 1: new root.Opcode 'aconst_null', { execute: (rs) -> rs.push null } 2: new root.Opcode 'iconst_m1', { execute: (rs) -> rs.push -1 } 3: new root.Opcode 'iconst_0', { execute: (rs) -> rs.push 0 } 4: new root.Opcode 'iconst_1', { execute: (rs) -> rs.push 1 } 5: new root.Opcode 'iconst_2', { execute: (rs) -> rs.push 2 } 6: new root.Opcode 'iconst_3', { execute: (rs) -> rs.push 3 } 7: new root.Opcode 'iconst_4', { execute: (rs) -> rs.push 4 } 8: new root.Opcode 'iconst_5', { execute: (rs) -> rs.push 5 } 9: new root.Opcode 'lconst_0', { execute: (rs) -> rs.push gLong.ZERO, null } 10: new root.Opcode 'lconst_1', { execute: (rs) -> rs.push gLong.ONE, null } 11: new root.Opcode 'fconst_0', { execute: (rs) -> rs.push 0 } 12: new root.Opcode 'fconst_1', { execute: (rs) -> rs.push 1 } 13: new root.Opcode 'fconst_2', { execute: (rs) -> rs.push 2 } 14: new root.Opcode 'dconst_0', { execute: (rs) -> rs.push 0, null } 15: new root.Opcode 'dconst_1', { execute: (rs) -> rs.push 1, null } 16: new root.PushOpcode 'bipush', { byte_count: 1 } 17: new root.PushOpcode 'sipush', { byte_count: 2 } 18: new root.LoadConstantOpcode 'ldc', { byte_count: 1 } 19: new root.LoadConstantOpcode 'ldc_w', { byte_count: 2 } 20: new root.LoadConstantOpcode 'ldc2_w', { byte_count: 2 } 21: new root.LoadVarOpcode 'iload' 22: new root.LoadVarOpcode 'lload' 23: new root.LoadVarOpcode 'fload' 24: new root.LoadVarOpcode 'dload' 25: new root.LoadVarOpcode 'aload' 26: new root.LoadOpcode 'iload_0' 27: new root.LoadOpcode 'iload_1' 28: new root.LoadOpcode 'iload_2' 29: new root.LoadOpcode 'iload_3' 30: new root.LoadOpcode 'lload_0' 31: new root.LoadOpcode 'lload_1' 32: new root.LoadOpcode 'lload_2' 33: new root.LoadOpcode 'lload_3' 34: new root.LoadOpcode 'fload_0' 35: new root.LoadOpcode 'fload_1' 36: new root.LoadOpcode 'fload_2' 37: new root.LoadOpcode 'fload_3' 38: new root.LoadOpcode 'dload_0' 39: new root.LoadOpcode 'dload_1' 40: new root.LoadOpcode 'dload_2' 41: new root.LoadOpcode 'dload_3' 42: new root.LoadOpcode 'aload_0' 43: new root.LoadOpcode 'aload_1' 44: new root.LoadOpcode 'aload_2' 45: new root.LoadOpcode 'aload_3' 46: new root.ArrayLoadOpcode 'iaload' 47: new root.ArrayLoadOpcode 'laload' 48: new root.ArrayLoadOpcode 'faload' 49: new root.ArrayLoadOpcode 'daload' 50: new root.ArrayLoadOpcode 'aaload' 51: new root.ArrayLoadOpcode 'baload' 52: new root.ArrayLoadOpcode 'caload' 53: new root.ArrayLoadOpcode 'saload' 54: new root.StoreVarOpcode 'istore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 55: new root.StoreVarOpcode 'lstore', { execute: (rs) -> rs.put_cl2(@var_num,rs.pop2()) } 56: new root.StoreVarOpcode 'fstore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 57: new root.StoreVarOpcode 'dstore', { execute: (rs) -> rs.put_cl2(@var_num,rs.pop2()) } 58: new root.StoreVarOpcode 'astore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 59: new root.StoreOpcode 'istore_0' 60: new root.StoreOpcode 'istore_1' 61: new root.StoreOpcode 'istore_2' 62: new root.StoreOpcode 'istore_3' 63: new root.StoreOpcode 'lstore_0' 64: new root.StoreOpcode 'lstore_1' 65: new root.StoreOpcode 'lstore_2' 66: new root.StoreOpcode 'lstore_3' 67: new root.StoreOpcode 'fstore_0' 68: new root.StoreOpcode 'fstore_1' 69: new root.StoreOpcode 'fstore_2' 70: new root.StoreOpcode 'fstore_3' 71: new root.StoreOpcode 'dstore_0' 72: new root.StoreOpcode 'dstore_1' 73: new root.StoreOpcode 'dstore_2' 74: new root.StoreOpcode 'dstore_3' 75: new root.StoreOpcode 'astore_0' 76: new root.StoreOpcode 'astore_1' 77: new root.StoreOpcode 'astore_2' 78: new root.StoreOpcode 'astore_3' 79: new root.Opcode 'iastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 80: new root.Opcode 'lastore', {execute: (rs) -> v=rs.pop2();i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 81: new root.Opcode 'fastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 82: new root.Opcode 'dastore', {execute: (rs) -> v=rs.pop2();i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 83: new root.Opcode 'aastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 84: new root.Opcode 'bastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 85: new root.Opcode 'castore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 86: new root.Opcode 'sastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 87: new root.Opcode 'pop', { execute: (rs) -> rs.pop() } 88: new root.Opcode 'pop2', { execute: (rs) -> rs.pop2() } 89: new root.Opcode 'dup', { execute: (rs) -> v=rs.pop(); rs.push(v,v) } 90: new root.Opcode 'dup_x1', { execute: (rs) -> v1=rs.pop(); v2=rs.pop(); rs.push(v1,v2,v1) } 91: new root.Opcode 'dup_x2', {execute: (rs) -> [v1,v2,v3]=[rs.pop(),rs.pop(),rs.pop()];rs.push(v1,v3,v2,v1)} 92: new root.Opcode 'dup2', {execute: (rs) -> v1=rs.pop(); v2=rs.pop(); rs.push(v2,v1,v2,v1)} 93: new root.Opcode 'dup2_x1', {execute: (rs) -> [v1,v2,v3]=[rs.pop(),rs.pop(),rs.pop()];rs.push(v2,v1,v3,v2,v1)} 94: new root.Opcode 'dup2_x2', {execute: (rs) -> [v1,v2,v3,v4]=[rs.pop(),rs.pop(),rs.pop(),rs.pop()];rs.push(v2,v1,v4,v3,v2,v1)} 95: new root.Opcode 'swap', {execute: (rs) -> v2=rs.pop(); v1=rs.pop(); rs.push(v2,v1)} 96: new root.Opcode 'iadd', { execute: (rs) -> rs.push wrap_int(rs.pop()+rs.pop()) } 97: new root.Opcode 'ladd', { execute: (rs) -> rs.push(rs.pop2().add(rs.pop2()), null) } 98: new root.Opcode 'fadd', { execute: (rs) -> rs.push wrap_float(rs.pop()+rs.pop()) } 99: new root.Opcode 'dadd', { execute: (rs) -> rs.push(rs.pop2()+rs.pop2(), null) } 100: new root.Opcode 'isub', { execute: (rs) -> rs.push wrap_int(-rs.pop()+rs.pop()) } 101: new root.Opcode 'lsub', { execute: (rs) -> rs.push(rs.pop2().negate().add(rs.pop2()), null) } 102: new root.Opcode 'fsub', { execute: (rs) -> rs.push wrap_float(-rs.pop()+rs.pop()) } 103: new root.Opcode 'dsub', { execute: (rs) -> rs.push(-rs.pop2()+rs.pop2(), null) } 104: new root.Opcode 'imul', { execute: (rs) -> rs.push gLong.fromInt(rs.pop()).multiply(gLong.fromInt rs.pop()).toInt() } 105: new root.Opcode 'lmul', { execute: (rs) -> rs.push(rs.pop2().multiply(rs.pop2()), null) } 106: new root.Opcode 'fmul', { execute: (rs) -> rs.push wrap_float(rs.pop()*rs.pop()) } 107: new root.Opcode 'dmul', { execute: (rs) -> rs.push(rs.pop2()*rs.pop2(), null) } 108: new root.Opcode 'idiv', { execute: (rs) -> v=rs.pop();rs.push(int_div rs, rs.pop(), v) } 109: new root.Opcode 'ldiv', { execute: (rs) -> v=rs.pop2();rs.push(long_div(rs, rs.pop2(), v), null) } 110: new root.Opcode 'fdiv', { execute: (rs) -> v=rs.pop();rs.push wrap_float(rs.pop()/v) } 111: new root.Opcode 'ddiv', { execute: (rs) -> v=rs.pop2();rs.push(rs.pop2()/v, null) } 112: new root.Opcode 'irem', { execute: (rs) -> v2=rs.pop(); rs.push int_mod(rs,rs.pop(),v2) } 113: new root.Opcode 'lrem', { execute: (rs) -> v2=rs.pop2(); rs.push long_mod(rs,rs.pop2(),v2), null } 114: new root.Opcode 'frem', { execute: (rs) -> v2=rs.pop(); rs.push rs.pop() %v2 } 115: new root.Opcode 'drem', { execute: (rs) -> v2=rs.pop2(); rs.push rs.pop2()%v2, null } 116: new root.Opcode 'ineg', { execute: (rs) -> rs.push -rs.pop() } 117: new root.Opcode 'lneg', { execute: (rs) -> rs.push rs.pop2().negate(), null } 118: new root.Opcode 'fneg', { execute: (rs) -> rs.push -rs.pop() } 119: new root.Opcode 'dneg', { execute: (rs) -> rs.push -rs.pop2(), null } 120: new root.Opcode 'ishl', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()<<s) } 121: new root.Opcode 'lshl', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftLeft(gLong.fromInt(s)),null) } 122: new root.Opcode 'ishr', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()>>s) } 123: new root.Opcode 'lshr', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftRight(gLong.fromInt(s)), null) } 124: new root.Opcode 'iushr', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()>>>s) } 125: new root.Opcode 'lushr', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftRightUnsigned(gLong.fromInt(s)), null)} 126: new root.Opcode 'iand', { execute: (rs) -> rs.push(rs.pop()&rs.pop()) } 127: new root.Opcode 'land', { execute: (rs) -> rs.push(rs.pop2().and(rs.pop2()), null) } 128: new root.Opcode 'ior', { execute: (rs) -> rs.push(rs.pop()|rs.pop()) } 129: new root.Opcode 'lor', { execute: (rs) -> rs.push(rs.pop2().or(rs.pop2()), null) } 130: new root.Opcode 'ixor', { execute: (rs) -> rs.push(rs.pop()^rs.pop()) } 131: new root.Opcode 'lxor', { execute: (rs) -> rs.push(rs.pop2().xor(rs.pop2()), null) } 132: new root.IIncOpcode 'iinc' 133: new root.Opcode 'i2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop()), null } 134: new root.Opcode 'i2f', { execute: (rs) -> } 135: new root.Opcode 'i2d', { execute: (rs) -> rs.push null } 136: new root.Opcode 'l2i', { execute: (rs) -> rs.push rs.pop2().toInt() } 137: new root.Opcode 'l2f', { execute: (rs) -> rs.push rs.pop2().toNumber() } 138: new root.Opcode 'l2d', { execute: (rs) -> rs.push rs.pop2().toNumber(), null } 139: new root.Opcode 'f2i', { execute: (rs) -> rs.push float2int rs.pop() } 140: new root.Opcode 'f2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop()), null } 141: new root.Opcode 'f2d', { execute: (rs) -> rs.push null } 142: new root.Opcode 'd2i', { execute: (rs) -> rs.push float2int rs.pop2() } 143: new root.Opcode 'd2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop2()), null } 144: new root.Opcode 'd2f', { execute: (rs) -> rs.push wrap_float rs.pop2() } 145: new root.Opcode 'i2b', { execute: (rs) -> rs.push truncate rs.pop(), 8 } 146: new root.Opcode 'i2c', { execute: (rs) -> rs.push truncate rs.pop(), 8 } 147: new root.Opcode 'i2s', { execute: (rs) -> rs.push truncate rs.pop(), 16 } 148: new root.Opcode 'lcmp', { execute: (rs) -> v2=rs.pop2(); rs.push rs.pop2().compare(v2) } 149: new root.Opcode 'fcmpl', { execute: (rs) -> v2=rs.pop(); rs.push util.cmp(rs.pop(),v2) ? -1 } 150: new root.Opcode 'fcmpg', { execute: (rs) -> v2=rs.pop(); rs.push util.cmp(rs.pop(),v2) ? 1 } 151: new root.Opcode 'dcmpl', { execute: (rs) -> v2=rs.pop2(); rs.push util.cmp(rs.pop2(),v2) ? -1 } 152: new root.Opcode 'dcmpg', { execute: (rs) -> v2=rs.pop2(); rs.push util.cmp(rs.pop2(),v2) ? 1 } 153: new root.UnaryBranchOpcode 'ifeq', { cmp: (v) -> v == 0 } 154: new root.UnaryBranchOpcode 'ifne', { cmp: (v) -> v != 0 } 155: new root.UnaryBranchOpcode 'iflt', { cmp: (v) -> v < 0 } 156: new root.UnaryBranchOpcode 'ifge', { cmp: (v) -> v >= 0 } 157: new root.UnaryBranchOpcode 'ifgt', { cmp: (v) -> v > 0 } 158: new root.UnaryBranchOpcode 'ifle', { cmp: (v) -> v <= 0 } 159: new root.BinaryBranchOpcode 'if_icmpeq', { cmp: (v1, v2) -> v1 == v2 } 160: new root.BinaryBranchOpcode 'if_icmpne', { cmp: (v1, v2) -> v1 != v2 } 161: new root.BinaryBranchOpcode 'if_icmplt', { cmp: (v1, v2) -> v1 < v2 } 162: new root.BinaryBranchOpcode 'if_icmpge', { cmp: (v1, v2) -> v1 >= v2 } 163: new root.BinaryBranchOpcode 'if_icmpgt', { cmp: (v1, v2) -> v1 > v2 } 164: new root.BinaryBranchOpcode 'if_icmple', { cmp: (v1, v2) -> v1 <= v2 } 165: new root.BinaryBranchOpcode 'if_acmpeq', { cmp: (v1, v2) -> v1 == v2 } 166: new root.BinaryBranchOpcode 'if_acmpne', { cmp: (v1, v2) -> v1 != v2 } 167: new root.BranchOpcode 'goto', { execute: (rs) -> throw new BranchException rs.curr_pc() + @offset } 168: new root.BranchOpcode 'jsr', { execute: jsr } 169: new root.Opcode 'ret', { byte_count: 1, execute: (rs) -> throw new BranchException rs.cl @args[0] } 170: new root.TableSwitchOpcode 'tableswitch' 171: new root.LookupSwitchOpcode 'lookupswitch' 172: new root.Opcode 'ireturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 173: new root.Opcode 'lreturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0], null } 174: new root.Opcode 'freturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 175: new root.Opcode 'dreturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0], null } 176: new root.Opcode 'areturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 177: new root.Opcode 'return', { execute: (rs) -> throw new Error("too many values on stack for void return") if rs.curr_frame().stack.length > 0 throw new ReturnException } 178: new root.FieldOpcode 'getstatic', {execute: (rs)-> rs.push rs.static_get @field_spec; rs.push null if @field_spec.type in ['J','D']} 179: new root.FieldOpcode 'putstatic', {execute: (rs)-> rs.static_put @field_spec } 180: new root.FieldOpcode 'getfield', {execute: (rs)-> rs.heap_get @field_spec, rs.pop() } 181: new root.FieldOpcode 'putfield', {execute: (rs)-> rs.heap_put @field_spec } 182: new root.InvokeOpcode 'invokevirtual', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs,true)} 183: new root.InvokeOpcode 'invokespecial', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs)} 184: new root.InvokeOpcode 'invokestatic', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs)} 185: new root.InvokeOpcode 'invokeinterface',{ execute: (rs)-> rs.method_lookup(@method_spec).run(rs,true)} 187: new root.ClassOpcode 'new', { execute: (rs) -> rs.push rs.init_object @class } 188: new root.NewArrayOpcode 'newarray', { execute: (rs) -> rs.push rs.heap_newarray @element_type, rs.pop() } 189: new root.ClassOpcode 'anewarray', { execute: (rs) -> rs.push rs.heap_newarray "L#{@class};", rs.pop() } 190: new root.Opcode 'arraylength', { execute: (rs) -> rs.push rs.check_null(rs.pop()).array.length } 191: new root.Opcode 'athrow', { execute: (rs) -> throw new JavaException rs, rs.pop() } 192: new root.ClassOpcode 'checkcast', { execute: (rs) -> o = rs.pop() if (not o?) or types.check_cast(rs,o,@class) rs.push o else target_class = c2t(@class).toExternalString() # class we wish to cast to candidate_class = if o? then o.type.toExternalString() else "null" java_throw rs, 'java/lang/ClassCastException', "#{candidate_class} cannot be cast to #{target_class}" } 193: new root.ClassOpcode 'instanceof', { execute: (rs) -> o=rs.pop(); rs.push if o? then types.check_cast(rs,o,@class)+0 else 0 } 194: new root.Opcode 'monitorenter', { execute: (rs)-> rs.pop() } #TODO: actually implement locks? 195: new root.Opcode 'monitorexit', { execute: (rs)-> rs.pop() } #TODO: actually implement locks? 197: new root.MultiArrayOpcode 'multianewarray' 198: new root.UnaryBranchOpcode 'ifnull', { cmp: (v) -> not v? } 199: new root.UnaryBranchOpcode 'ifnonnull', { cmp: (v) -> v? } 200: new root.BranchOpcode 'goto_w', { byte_count: 4, execute: (rs) -> throw new BranchException rs.curr_pc() + @offset } 201: new root.BranchOpcode 'jsr_w', { byte_count: 4, execute: jsr } }
153663
gLong ?= require '../third_party/gLong.js' util ?= require './util' types ?= require './types' {java_throw,BranchException,ReturnException,JavaException} = util {c2t} = types root = exports ? this.opcodes = {} class root.Opcode constructor: (@name, params={}) -> (@[prop] = val for prop, val of params) @execute ?= @_execute @byte_count = params.byte_count ? 0 take_args: (code_array) -> @args = (code_array.get_uint(1) for [0...@byte_count]) class root.FieldOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @field_spec_ref = code_array.get_uint(2) @field_spec = constant_pool.get(@field_spec_ref).deref() class root.ClassOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @class_ref = code_array.get_uint(2) @class = constant_pool.get(@class_ref).deref() class root.InvokeOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @method_spec_ref = code_array.get_uint(2) # invokeinterface has two redundant bytes if @name == 'invokeinterface' @count = code_array.get_uint 1 code_array.skip 1 @byte_count += 2 @method_spec = constant_pool.get(@method_spec_ref).deref() class root.LoadConstantOpcode extends root.Opcode take_args: (code_array, constant_pool) -> @cls = constant_pool.cls @constant_ref = code_array.get_uint @byte_count @constant = constant_pool.get @constant_ref _execute: (rs) -> val = @constant.value if @constant.type is 'String' val = rs.string_redirect(val, @cls) if @constant.type is 'class' jvm_str = rs.string_redirect(val,@cls) val = rs.class_lookup c2t(rs.jvm2js_str(jvm_str)), true rs.push val rs.push null if @name is 'ldc2_w' class root.BranchOpcode extends root.Opcode constructor: (name, params={}) -> params.byte_count ?= 2 super name, params take_args: (code_array) -> @offset = code_array.get_int @byte_count class root.UnaryBranchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, { execute: (rs) -> v = rs.pop() throw new BranchException rs.curr_pc() + @offset if params.cmp v } class root.BinaryBranchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, { execute: (rs) -> v2 = rs.pop() v1 = rs.pop() throw new BranchException rs.curr_pc() + @offset if params.cmp v1, v2 } class root.PushOpcode extends root.Opcode take_args: (code_array) -> @value = code_array.get_int @byte_count _execute: (rs) -> rs.push @value class root.IIncOpcode extends root.Opcode constructor: (name, params) -> super name, params take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" arg_size = 2 @byte_count = 5 else arg_size = 1 @byte_count = 2 @index = code_array.get_uint arg_size @const = code_array.get_int arg_size _execute: (rs) -> rs.put_cl(@index,rs.cl(@index)+@const) class root.LoadOpcode extends root.Opcode constructor: (name, params={}) -> params.execute ?= if name.match /[ld]load/ (rs) -> rs.push rs.cl(@var_num), null else (rs) -> rs.push rs.cl(@var_num) super name, params take_args: (code_array) -> @var_num = parseInt @name[6] # sneaky hack, works for name =~ /.load_\d/ class root.LoadVarOpcode extends root.LoadOpcode take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" @byte_count = 3 @var_num = code_array.get_uint 2 else @byte_count = 1 @var_num = code_array.get_uint 1 class root.StoreOpcode extends root.Opcode constructor: (name, params={}) -> params.execute ?= if name.match /[ld]store/ (rs) -> rs.put_cl2(@var_num,rs.pop2()) else (rs) -> rs.put_cl(@var_num,rs.pop()) super name, params take_args: (code_array) -> @var_num = parseInt @name[7] # sneaky hack, works for name =~ /.store_\d/ class root.StoreVarOpcode extends root.StoreOpcode constructor: (name, params) -> super name, params take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" @byte_count = 3 @var_num = code_array.get_uint 2 else @byte_count = 1 @var_num = code_array.get_uint 1 class root.SwitchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, params @byte_count = null execute: (rs) -> key = rs.<KEY>() throw new BranchException( rs.curr_pc() + if @offsets[key]? then @offsets[key] else @_default ) class root.LookupSwitchOpcode extends root.SwitchOpcode take_args: (code_array, constant_pool) -> # account for padding that ensures alignment padding_size = (4 - code_array.pos() % 4) % 4 code_array.skip padding_size @_default = code_array.get_int(4) @npairs = code_array.get_int(4) @offsets = {} for [0...@npairs] match = code_array.get_int(4) offset = code_array.get_int(4) @offsets[match] = offset @byte_count = padding_size + 8 * (@npairs + 1) class root.TableSwitchOpcode extends root.SwitchOpcode take_args: (code_array, constant_pool) -> # account for padding that ensures alignment padding_size = (4 - code_array.pos() % 4) % 4 code_array.skip padding_size @_default = code_array.get_int(4) @low = code_array.get_int(4) @high = code_array.get_int(4) @offsets = {} total_offsets = @high - @low + 1 for i in [0...total_offsets] offset = code_array.get_int(4) @offsets[@low + i] = offset @byte_count = padding_size + 12 + 4 * total_offsets class root.NewArrayOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 1 @arr_types = {4:'Z',5:'C',6:'F',7:'D',8:'B',9:'S',10:'I',11:'J'} take_args: (code_array,constant_pool) -> type_code = code_array.get_uint 1 @element_type = @arr_types[type_code] class root.MultiArrayOpcode extends root.Opcode constructor: (name, params={}) -> params.byte_count ?= 3 super name, params take_args: (code_array, constant_pool) -> @class_ref = code_array.get_uint 2 @class = constant_pool.get(@class_ref).deref() @dim = code_array.get_uint 1 execute: (rs) -> counts = rs.curr_frame().stack.splice(rs.length-@dim) init_arr = (curr_dim) => return 0 if curr_dim == @dim typestr = @class[curr_dim..] rs.init_object typestr, (init_arr(curr_dim+1) for [0...counts[curr_dim]]) rs.push init_arr 0 class root.ArrayLoadOpcode extends root.Opcode execute: (rs) -> idx = rs.pop() array = rs.check_null(rs.pop()).array java_throw rs, 'java/lang/ArrayIndexOutOfBoundsException', "#{idx} not in [0,#{array.length})" unless 0 <= idx < array.length rs.push array[idx] rs.push null if @name.match /[ld]aload/ towards_zero = (a) -> Math[if a > 0 then 'floor' else 'ceil'](a) int_mod = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b == 0 a % b int_div = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b == 0 towards_zero a / b # TODO spec: "if the dividend is the negative integer of largest possible magnitude # for the int type, and the divisor is -1, then overflow occurs, and the # result is equal to the dividend." long_mod = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b.isZero() a.modulo(b) long_div = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b.isZero() a.div(b) float2int = (a) -> INT_MAX = Math.pow(2, 31) - 1 INT_MIN = - Math.pow 2, 31 if a == NaN then 0 else if a > INT_MAX then INT_MAX # these two cases handle d2i issues else if a < INT_MIN then INT_MIN else unless a == Infinity or a == -Infinity then towards_zero a else if a > 0 then INT_MAX else INT_MIN # sign-preserving number truncate, with overflow and such truncate = (a, n_bits) -> a = (a + Math.pow 2, n_bits) % Math.pow 2, n_bits util.uint2int a, n_bits/8 wrap_int = (a) -> truncate a, 32 wrap_float = (a) -> return Infinity if a > 3.40282346638528860e+38 return 0 if 0 < a < 1.40129846432481707e-45 return -Infinity if a < -3.40282346638528860e+38 return 0 if 0 > a > -1.40129846432481707e-45 a jsr = (rs) -> rs.push(rs.curr_pc()+@byte_count+1); throw new BranchException rs.curr_pc() + @offset # these objects are used as prototypes for the parsed instructions in the # classfile root.opcodes = { 0: new root.Opcode 'nop', { execute: -> } 1: new root.Opcode 'aconst_null', { execute: (rs) -> rs.push null } 2: new root.Opcode 'iconst_m1', { execute: (rs) -> rs.push -1 } 3: new root.Opcode 'iconst_0', { execute: (rs) -> rs.push 0 } 4: new root.Opcode 'iconst_1', { execute: (rs) -> rs.push 1 } 5: new root.Opcode 'iconst_2', { execute: (rs) -> rs.push 2 } 6: new root.Opcode 'iconst_3', { execute: (rs) -> rs.push 3 } 7: new root.Opcode 'iconst_4', { execute: (rs) -> rs.push 4 } 8: new root.Opcode 'iconst_5', { execute: (rs) -> rs.push 5 } 9: new root.Opcode 'lconst_0', { execute: (rs) -> rs.push gLong.ZERO, null } 10: new root.Opcode 'lconst_1', { execute: (rs) -> rs.push gLong.ONE, null } 11: new root.Opcode 'fconst_0', { execute: (rs) -> rs.push 0 } 12: new root.Opcode 'fconst_1', { execute: (rs) -> rs.push 1 } 13: new root.Opcode 'fconst_2', { execute: (rs) -> rs.push 2 } 14: new root.Opcode 'dconst_0', { execute: (rs) -> rs.push 0, null } 15: new root.Opcode 'dconst_1', { execute: (rs) -> rs.push 1, null } 16: new root.PushOpcode 'bipush', { byte_count: 1 } 17: new root.PushOpcode 'sipush', { byte_count: 2 } 18: new root.LoadConstantOpcode 'ldc', { byte_count: 1 } 19: new root.LoadConstantOpcode 'ldc_w', { byte_count: 2 } 20: new root.LoadConstantOpcode 'ldc2_w', { byte_count: 2 } 21: new root.LoadVarOpcode 'iload' 22: new root.LoadVarOpcode 'lload' 23: new root.LoadVarOpcode 'fload' 24: new root.LoadVarOpcode 'dload' 25: new root.LoadVarOpcode 'aload' 26: new root.LoadOpcode 'iload_0' 27: new root.LoadOpcode 'iload_1' 28: new root.LoadOpcode 'iload_2' 29: new root.LoadOpcode 'iload_3' 30: new root.LoadOpcode 'lload_0' 31: new root.LoadOpcode 'lload_1' 32: new root.LoadOpcode 'lload_2' 33: new root.LoadOpcode 'lload_3' 34: new root.LoadOpcode 'fload_0' 35: new root.LoadOpcode 'fload_1' 36: new root.LoadOpcode 'fload_2' 37: new root.LoadOpcode 'fload_3' 38: new root.LoadOpcode 'dload_0' 39: new root.LoadOpcode 'dload_1' 40: new root.LoadOpcode 'dload_2' 41: new root.LoadOpcode 'dload_3' 42: new root.LoadOpcode 'aload_0' 43: new root.LoadOpcode 'aload_1' 44: new root.LoadOpcode 'aload_2' 45: new root.LoadOpcode 'aload_3' 46: new root.ArrayLoadOpcode 'iaload' 47: new root.ArrayLoadOpcode 'laload' 48: new root.ArrayLoadOpcode 'faload' 49: new root.ArrayLoadOpcode 'daload' 50: new root.ArrayLoadOpcode 'aaload' 51: new root.ArrayLoadOpcode 'baload' 52: new root.ArrayLoadOpcode 'caload' 53: new root.ArrayLoadOpcode 'saload' 54: new root.StoreVarOpcode 'istore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 55: new root.StoreVarOpcode 'lstore', { execute: (rs) -> rs.put_cl2(@var_num,rs.pop2()) } 56: new root.StoreVarOpcode 'fstore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 57: new root.StoreVarOpcode 'dstore', { execute: (rs) -> rs.put_cl2(@var_num,rs.pop2()) } 58: new root.StoreVarOpcode 'astore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 59: new root.StoreOpcode 'istore_0' 60: new root.StoreOpcode 'istore_1' 61: new root.StoreOpcode 'istore_2' 62: new root.StoreOpcode 'istore_3' 63: new root.StoreOpcode 'lstore_0' 64: new root.StoreOpcode 'lstore_1' 65: new root.StoreOpcode 'lstore_2' 66: new root.StoreOpcode 'lstore_3' 67: new root.StoreOpcode 'fstore_0' 68: new root.StoreOpcode 'fstore_1' 69: new root.StoreOpcode 'fstore_2' 70: new root.StoreOpcode 'fstore_3' 71: new root.StoreOpcode 'dstore_0' 72: new root.StoreOpcode 'dstore_1' 73: new root.StoreOpcode 'dstore_2' 74: new root.StoreOpcode 'dstore_3' 75: new root.StoreOpcode 'astore_0' 76: new root.StoreOpcode 'astore_1' 77: new root.StoreOpcode 'astore_2' 78: new root.StoreOpcode 'astore_3' 79: new root.Opcode 'iastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 80: new root.Opcode 'lastore', {execute: (rs) -> v=rs.pop2();i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 81: new root.Opcode 'fastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 82: new root.Opcode 'dastore', {execute: (rs) -> v=rs.pop2();i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 83: new root.Opcode 'aastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 84: new root.Opcode 'bastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 85: new root.Opcode 'castore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 86: new root.Opcode 'sastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 87: new root.Opcode 'pop', { execute: (rs) -> rs.pop() } 88: new root.Opcode 'pop2', { execute: (rs) -> rs.pop2() } 89: new root.Opcode 'dup', { execute: (rs) -> v=rs.pop(); rs.push(v,v) } 90: new root.Opcode 'dup_x1', { execute: (rs) -> v1=rs.pop(); v2=rs.pop(); rs.push(v1,v2,v1) } 91: new root.Opcode 'dup_x2', {execute: (rs) -> [v1,v2,v3]=[rs.pop(),rs.pop(),rs.pop()];rs.push(v1,v3,v2,v1)} 92: new root.Opcode 'dup2', {execute: (rs) -> v1=rs.pop(); v2=rs.pop(); rs.push(v2,v1,v2,v1)} 93: new root.Opcode 'dup2_x1', {execute: (rs) -> [v1,v2,v3]=[rs.pop(),rs.pop(),rs.pop()];rs.push(v2,v1,v3,v2,v1)} 94: new root.Opcode 'dup2_x2', {execute: (rs) -> [v1,v2,v3,v4]=[rs.pop(),rs.pop(),rs.pop(),rs.pop()];rs.push(v2,v1,v4,v3,v2,v1)} 95: new root.Opcode 'swap', {execute: (rs) -> v2=rs.pop(); v1=rs.pop(); rs.push(v2,v1)} 96: new root.Opcode 'iadd', { execute: (rs) -> rs.push wrap_int(rs.pop()+rs.pop()) } 97: new root.Opcode 'ladd', { execute: (rs) -> rs.push(rs.pop2().add(rs.pop2()), null) } 98: new root.Opcode 'fadd', { execute: (rs) -> rs.push wrap_float(rs.pop()+rs.pop()) } 99: new root.Opcode 'dadd', { execute: (rs) -> rs.push(rs.pop2()+rs.pop2(), null) } 100: new root.Opcode 'isub', { execute: (rs) -> rs.push wrap_int(-rs.pop()+rs.pop()) } 101: new root.Opcode 'lsub', { execute: (rs) -> rs.push(rs.pop2().negate().add(rs.pop2()), null) } 102: new root.Opcode 'fsub', { execute: (rs) -> rs.push wrap_float(-rs.pop()+rs.pop()) } 103: new root.Opcode 'dsub', { execute: (rs) -> rs.push(-rs.pop2()+rs.pop2(), null) } 104: new root.Opcode 'imul', { execute: (rs) -> rs.push gLong.fromInt(rs.pop()).multiply(gLong.fromInt rs.pop()).toInt() } 105: new root.Opcode 'lmul', { execute: (rs) -> rs.push(rs.pop2().multiply(rs.pop2()), null) } 106: new root.Opcode 'fmul', { execute: (rs) -> rs.push wrap_float(rs.pop()*rs.pop()) } 107: new root.Opcode 'dmul', { execute: (rs) -> rs.push(rs.pop2()*rs.pop2(), null) } 108: new root.Opcode 'idiv', { execute: (rs) -> v=rs.pop();rs.push(int_div rs, rs.pop(), v) } 109: new root.Opcode 'ldiv', { execute: (rs) -> v=rs.pop2();rs.push(long_div(rs, rs.pop2(), v), null) } 110: new root.Opcode 'fdiv', { execute: (rs) -> v=rs.pop();rs.push wrap_float(rs.pop()/v) } 111: new root.Opcode 'ddiv', { execute: (rs) -> v=rs.pop2();rs.push(rs.pop2()/v, null) } 112: new root.Opcode 'irem', { execute: (rs) -> v2=rs.pop(); rs.push int_mod(rs,rs.pop(),v2) } 113: new root.Opcode 'lrem', { execute: (rs) -> v2=rs.pop2(); rs.push long_mod(rs,rs.pop2(),v2), null } 114: new root.Opcode 'frem', { execute: (rs) -> v2=rs.pop(); rs.push rs.pop() %v2 } 115: new root.Opcode 'drem', { execute: (rs) -> v2=rs.pop2(); rs.push rs.pop2()%v2, null } 116: new root.Opcode 'ineg', { execute: (rs) -> rs.push -rs.pop() } 117: new root.Opcode 'lneg', { execute: (rs) -> rs.push rs.pop2().negate(), null } 118: new root.Opcode 'fneg', { execute: (rs) -> rs.push -rs.pop() } 119: new root.Opcode 'dneg', { execute: (rs) -> rs.push -rs.pop2(), null } 120: new root.Opcode 'ishl', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()<<s) } 121: new root.Opcode 'lshl', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftLeft(gLong.fromInt(s)),null) } 122: new root.Opcode 'ishr', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()>>s) } 123: new root.Opcode 'lshr', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftRight(gLong.fromInt(s)), null) } 124: new root.Opcode 'iushr', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()>>>s) } 125: new root.Opcode 'lushr', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftRightUnsigned(gLong.fromInt(s)), null)} 126: new root.Opcode 'iand', { execute: (rs) -> rs.push(rs.pop()&rs.pop()) } 127: new root.Opcode 'land', { execute: (rs) -> rs.push(rs.pop2().and(rs.pop2()), null) } 128: new root.Opcode 'ior', { execute: (rs) -> rs.push(rs.pop()|rs.pop()) } 129: new root.Opcode 'lor', { execute: (rs) -> rs.push(rs.pop2().or(rs.pop2()), null) } 130: new root.Opcode 'ixor', { execute: (rs) -> rs.push(rs.pop()^rs.pop()) } 131: new root.Opcode 'lxor', { execute: (rs) -> rs.push(rs.pop2().xor(rs.pop2()), null) } 132: new root.IIncOpcode 'iinc' 133: new root.Opcode 'i2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop()), null } 134: new root.Opcode 'i2f', { execute: (rs) -> } 135: new root.Opcode 'i2d', { execute: (rs) -> rs.push null } 136: new root.Opcode 'l2i', { execute: (rs) -> rs.push rs.pop2().toInt() } 137: new root.Opcode 'l2f', { execute: (rs) -> rs.push rs.pop2().toNumber() } 138: new root.Opcode 'l2d', { execute: (rs) -> rs.push rs.pop2().toNumber(), null } 139: new root.Opcode 'f2i', { execute: (rs) -> rs.push float2int rs.pop() } 140: new root.Opcode 'f2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop()), null } 141: new root.Opcode 'f2d', { execute: (rs) -> rs.push null } 142: new root.Opcode 'd2i', { execute: (rs) -> rs.push float2int rs.pop2() } 143: new root.Opcode 'd2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop2()), null } 144: new root.Opcode 'd2f', { execute: (rs) -> rs.push wrap_float rs.pop2() } 145: new root.Opcode 'i2b', { execute: (rs) -> rs.push truncate rs.pop(), 8 } 146: new root.Opcode 'i2c', { execute: (rs) -> rs.push truncate rs.pop(), 8 } 147: new root.Opcode 'i2s', { execute: (rs) -> rs.push truncate rs.pop(), 16 } 148: new root.Opcode 'lcmp', { execute: (rs) -> v2=rs.pop2(); rs.push rs.pop2().compare(v2) } 149: new root.Opcode 'fcmpl', { execute: (rs) -> v2=rs.pop(); rs.push util.cmp(rs.pop(),v2) ? -1 } 150: new root.Opcode 'fcmpg', { execute: (rs) -> v2=rs.pop(); rs.push util.cmp(rs.pop(),v2) ? 1 } 151: new root.Opcode 'dcmpl', { execute: (rs) -> v2=rs.pop2(); rs.push util.cmp(rs.pop2(),v2) ? -1 } 152: new root.Opcode 'dcmpg', { execute: (rs) -> v2=rs.pop2(); rs.push util.cmp(rs.pop2(),v2) ? 1 } 153: new root.UnaryBranchOpcode 'ifeq', { cmp: (v) -> v == 0 } 154: new root.UnaryBranchOpcode 'ifne', { cmp: (v) -> v != 0 } 155: new root.UnaryBranchOpcode 'iflt', { cmp: (v) -> v < 0 } 156: new root.UnaryBranchOpcode 'ifge', { cmp: (v) -> v >= 0 } 157: new root.UnaryBranchOpcode 'ifgt', { cmp: (v) -> v > 0 } 158: new root.UnaryBranchOpcode 'ifle', { cmp: (v) -> v <= 0 } 159: new root.BinaryBranchOpcode 'if_icmpeq', { cmp: (v1, v2) -> v1 == v2 } 160: new root.BinaryBranchOpcode 'if_icmpne', { cmp: (v1, v2) -> v1 != v2 } 161: new root.BinaryBranchOpcode 'if_icmplt', { cmp: (v1, v2) -> v1 < v2 } 162: new root.BinaryBranchOpcode 'if_icmpge', { cmp: (v1, v2) -> v1 >= v2 } 163: new root.BinaryBranchOpcode 'if_icmpgt', { cmp: (v1, v2) -> v1 > v2 } 164: new root.BinaryBranchOpcode 'if_icmple', { cmp: (v1, v2) -> v1 <= v2 } 165: new root.BinaryBranchOpcode 'if_acmpeq', { cmp: (v1, v2) -> v1 == v2 } 166: new root.BinaryBranchOpcode 'if_acmpne', { cmp: (v1, v2) -> v1 != v2 } 167: new root.BranchOpcode 'goto', { execute: (rs) -> throw new BranchException rs.curr_pc() + @offset } 168: new root.BranchOpcode 'jsr', { execute: jsr } 169: new root.Opcode 'ret', { byte_count: 1, execute: (rs) -> throw new BranchException rs.cl @args[0] } 170: new root.TableSwitchOpcode 'tableswitch' 171: new root.LookupSwitchOpcode 'lookupswitch' 172: new root.Opcode 'ireturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 173: new root.Opcode 'lreturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0], null } 174: new root.Opcode 'freturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 175: new root.Opcode 'dreturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0], null } 176: new root.Opcode 'areturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 177: new root.Opcode 'return', { execute: (rs) -> throw new Error("too many values on stack for void return") if rs.curr_frame().stack.length > 0 throw new ReturnException } 178: new root.FieldOpcode 'getstatic', {execute: (rs)-> rs.push rs.static_get @field_spec; rs.push null if @field_spec.type in ['J','D']} 179: new root.FieldOpcode 'putstatic', {execute: (rs)-> rs.static_put @field_spec } 180: new root.FieldOpcode 'getfield', {execute: (rs)-> rs.heap_get @field_spec, rs.pop() } 181: new root.FieldOpcode 'putfield', {execute: (rs)-> rs.heap_put @field_spec } 182: new root.InvokeOpcode 'invokevirtual', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs,true)} 183: new root.InvokeOpcode 'invokespecial', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs)} 184: new root.InvokeOpcode 'invokestatic', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs)} 185: new root.InvokeOpcode 'invokeinterface',{ execute: (rs)-> rs.method_lookup(@method_spec).run(rs,true)} 187: new root.ClassOpcode 'new', { execute: (rs) -> rs.push rs.init_object @class } 188: new root.NewArrayOpcode 'newarray', { execute: (rs) -> rs.push rs.heap_newarray @element_type, rs.pop() } 189: new root.ClassOpcode 'anewarray', { execute: (rs) -> rs.push rs.heap_newarray "L#{@class};", rs.pop() } 190: new root.Opcode 'arraylength', { execute: (rs) -> rs.push rs.check_null(rs.pop()).array.length } 191: new root.Opcode 'athrow', { execute: (rs) -> throw new JavaException rs, rs.pop() } 192: new root.ClassOpcode 'checkcast', { execute: (rs) -> o = rs.pop() if (not o?) or types.check_cast(rs,o,@class) rs.push o else target_class = c2t(@class).toExternalString() # class we wish to cast to candidate_class = if o? then o.type.toExternalString() else "null" java_throw rs, 'java/lang/ClassCastException', "#{candidate_class} cannot be cast to #{target_class}" } 193: new root.ClassOpcode 'instanceof', { execute: (rs) -> o=rs.pop(); rs.push if o? then types.check_cast(rs,o,@class)+0 else 0 } 194: new root.Opcode 'monitorenter', { execute: (rs)-> rs.pop() } #TODO: actually implement locks? 195: new root.Opcode 'monitorexit', { execute: (rs)-> rs.pop() } #TODO: actually implement locks? 197: new root.MultiArrayOpcode 'multianewarray' 198: new root.UnaryBranchOpcode 'ifnull', { cmp: (v) -> not v? } 199: new root.UnaryBranchOpcode 'ifnonnull', { cmp: (v) -> v? } 200: new root.BranchOpcode 'goto_w', { byte_count: 4, execute: (rs) -> throw new BranchException rs.curr_pc() + @offset } 201: new root.BranchOpcode 'jsr_w', { byte_count: 4, execute: jsr } }
true
gLong ?= require '../third_party/gLong.js' util ?= require './util' types ?= require './types' {java_throw,BranchException,ReturnException,JavaException} = util {c2t} = types root = exports ? this.opcodes = {} class root.Opcode constructor: (@name, params={}) -> (@[prop] = val for prop, val of params) @execute ?= @_execute @byte_count = params.byte_count ? 0 take_args: (code_array) -> @args = (code_array.get_uint(1) for [0...@byte_count]) class root.FieldOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @field_spec_ref = code_array.get_uint(2) @field_spec = constant_pool.get(@field_spec_ref).deref() class root.ClassOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @class_ref = code_array.get_uint(2) @class = constant_pool.get(@class_ref).deref() class root.InvokeOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 2 take_args: (code_array, constant_pool) -> @method_spec_ref = code_array.get_uint(2) # invokeinterface has two redundant bytes if @name == 'invokeinterface' @count = code_array.get_uint 1 code_array.skip 1 @byte_count += 2 @method_spec = constant_pool.get(@method_spec_ref).deref() class root.LoadConstantOpcode extends root.Opcode take_args: (code_array, constant_pool) -> @cls = constant_pool.cls @constant_ref = code_array.get_uint @byte_count @constant = constant_pool.get @constant_ref _execute: (rs) -> val = @constant.value if @constant.type is 'String' val = rs.string_redirect(val, @cls) if @constant.type is 'class' jvm_str = rs.string_redirect(val,@cls) val = rs.class_lookup c2t(rs.jvm2js_str(jvm_str)), true rs.push val rs.push null if @name is 'ldc2_w' class root.BranchOpcode extends root.Opcode constructor: (name, params={}) -> params.byte_count ?= 2 super name, params take_args: (code_array) -> @offset = code_array.get_int @byte_count class root.UnaryBranchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, { execute: (rs) -> v = rs.pop() throw new BranchException rs.curr_pc() + @offset if params.cmp v } class root.BinaryBranchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, { execute: (rs) -> v2 = rs.pop() v1 = rs.pop() throw new BranchException rs.curr_pc() + @offset if params.cmp v1, v2 } class root.PushOpcode extends root.Opcode take_args: (code_array) -> @value = code_array.get_int @byte_count _execute: (rs) -> rs.push @value class root.IIncOpcode extends root.Opcode constructor: (name, params) -> super name, params take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" arg_size = 2 @byte_count = 5 else arg_size = 1 @byte_count = 2 @index = code_array.get_uint arg_size @const = code_array.get_int arg_size _execute: (rs) -> rs.put_cl(@index,rs.cl(@index)+@const) class root.LoadOpcode extends root.Opcode constructor: (name, params={}) -> params.execute ?= if name.match /[ld]load/ (rs) -> rs.push rs.cl(@var_num), null else (rs) -> rs.push rs.cl(@var_num) super name, params take_args: (code_array) -> @var_num = parseInt @name[6] # sneaky hack, works for name =~ /.load_\d/ class root.LoadVarOpcode extends root.LoadOpcode take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" @byte_count = 3 @var_num = code_array.get_uint 2 else @byte_count = 1 @var_num = code_array.get_uint 1 class root.StoreOpcode extends root.Opcode constructor: (name, params={}) -> params.execute ?= if name.match /[ld]store/ (rs) -> rs.put_cl2(@var_num,rs.pop2()) else (rs) -> rs.put_cl(@var_num,rs.pop()) super name, params take_args: (code_array) -> @var_num = parseInt @name[7] # sneaky hack, works for name =~ /.store_\d/ class root.StoreVarOpcode extends root.StoreOpcode constructor: (name, params) -> super name, params take_args: (code_array, constant_pool, @wide=false) -> if @wide @name += "_w" @byte_count = 3 @var_num = code_array.get_uint 2 else @byte_count = 1 @var_num = code_array.get_uint 1 class root.SwitchOpcode extends root.BranchOpcode constructor: (name, params) -> super name, params @byte_count = null execute: (rs) -> key = rs.PI:KEY:<KEY>END_PI() throw new BranchException( rs.curr_pc() + if @offsets[key]? then @offsets[key] else @_default ) class root.LookupSwitchOpcode extends root.SwitchOpcode take_args: (code_array, constant_pool) -> # account for padding that ensures alignment padding_size = (4 - code_array.pos() % 4) % 4 code_array.skip padding_size @_default = code_array.get_int(4) @npairs = code_array.get_int(4) @offsets = {} for [0...@npairs] match = code_array.get_int(4) offset = code_array.get_int(4) @offsets[match] = offset @byte_count = padding_size + 8 * (@npairs + 1) class root.TableSwitchOpcode extends root.SwitchOpcode take_args: (code_array, constant_pool) -> # account for padding that ensures alignment padding_size = (4 - code_array.pos() % 4) % 4 code_array.skip padding_size @_default = code_array.get_int(4) @low = code_array.get_int(4) @high = code_array.get_int(4) @offsets = {} total_offsets = @high - @low + 1 for i in [0...total_offsets] offset = code_array.get_int(4) @offsets[@low + i] = offset @byte_count = padding_size + 12 + 4 * total_offsets class root.NewArrayOpcode extends root.Opcode constructor: (name, params) -> super name, params @byte_count = 1 @arr_types = {4:'Z',5:'C',6:'F',7:'D',8:'B',9:'S',10:'I',11:'J'} take_args: (code_array,constant_pool) -> type_code = code_array.get_uint 1 @element_type = @arr_types[type_code] class root.MultiArrayOpcode extends root.Opcode constructor: (name, params={}) -> params.byte_count ?= 3 super name, params take_args: (code_array, constant_pool) -> @class_ref = code_array.get_uint 2 @class = constant_pool.get(@class_ref).deref() @dim = code_array.get_uint 1 execute: (rs) -> counts = rs.curr_frame().stack.splice(rs.length-@dim) init_arr = (curr_dim) => return 0 if curr_dim == @dim typestr = @class[curr_dim..] rs.init_object typestr, (init_arr(curr_dim+1) for [0...counts[curr_dim]]) rs.push init_arr 0 class root.ArrayLoadOpcode extends root.Opcode execute: (rs) -> idx = rs.pop() array = rs.check_null(rs.pop()).array java_throw rs, 'java/lang/ArrayIndexOutOfBoundsException', "#{idx} not in [0,#{array.length})" unless 0 <= idx < array.length rs.push array[idx] rs.push null if @name.match /[ld]aload/ towards_zero = (a) -> Math[if a > 0 then 'floor' else 'ceil'](a) int_mod = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b == 0 a % b int_div = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b == 0 towards_zero a / b # TODO spec: "if the dividend is the negative integer of largest possible magnitude # for the int type, and the divisor is -1, then overflow occurs, and the # result is equal to the dividend." long_mod = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b.isZero() a.modulo(b) long_div = (rs, a, b) -> java_throw rs, 'java/lang/ArithmeticException', '/ by zero' if b.isZero() a.div(b) float2int = (a) -> INT_MAX = Math.pow(2, 31) - 1 INT_MIN = - Math.pow 2, 31 if a == NaN then 0 else if a > INT_MAX then INT_MAX # these two cases handle d2i issues else if a < INT_MIN then INT_MIN else unless a == Infinity or a == -Infinity then towards_zero a else if a > 0 then INT_MAX else INT_MIN # sign-preserving number truncate, with overflow and such truncate = (a, n_bits) -> a = (a + Math.pow 2, n_bits) % Math.pow 2, n_bits util.uint2int a, n_bits/8 wrap_int = (a) -> truncate a, 32 wrap_float = (a) -> return Infinity if a > 3.40282346638528860e+38 return 0 if 0 < a < 1.40129846432481707e-45 return -Infinity if a < -3.40282346638528860e+38 return 0 if 0 > a > -1.40129846432481707e-45 a jsr = (rs) -> rs.push(rs.curr_pc()+@byte_count+1); throw new BranchException rs.curr_pc() + @offset # these objects are used as prototypes for the parsed instructions in the # classfile root.opcodes = { 0: new root.Opcode 'nop', { execute: -> } 1: new root.Opcode 'aconst_null', { execute: (rs) -> rs.push null } 2: new root.Opcode 'iconst_m1', { execute: (rs) -> rs.push -1 } 3: new root.Opcode 'iconst_0', { execute: (rs) -> rs.push 0 } 4: new root.Opcode 'iconst_1', { execute: (rs) -> rs.push 1 } 5: new root.Opcode 'iconst_2', { execute: (rs) -> rs.push 2 } 6: new root.Opcode 'iconst_3', { execute: (rs) -> rs.push 3 } 7: new root.Opcode 'iconst_4', { execute: (rs) -> rs.push 4 } 8: new root.Opcode 'iconst_5', { execute: (rs) -> rs.push 5 } 9: new root.Opcode 'lconst_0', { execute: (rs) -> rs.push gLong.ZERO, null } 10: new root.Opcode 'lconst_1', { execute: (rs) -> rs.push gLong.ONE, null } 11: new root.Opcode 'fconst_0', { execute: (rs) -> rs.push 0 } 12: new root.Opcode 'fconst_1', { execute: (rs) -> rs.push 1 } 13: new root.Opcode 'fconst_2', { execute: (rs) -> rs.push 2 } 14: new root.Opcode 'dconst_0', { execute: (rs) -> rs.push 0, null } 15: new root.Opcode 'dconst_1', { execute: (rs) -> rs.push 1, null } 16: new root.PushOpcode 'bipush', { byte_count: 1 } 17: new root.PushOpcode 'sipush', { byte_count: 2 } 18: new root.LoadConstantOpcode 'ldc', { byte_count: 1 } 19: new root.LoadConstantOpcode 'ldc_w', { byte_count: 2 } 20: new root.LoadConstantOpcode 'ldc2_w', { byte_count: 2 } 21: new root.LoadVarOpcode 'iload' 22: new root.LoadVarOpcode 'lload' 23: new root.LoadVarOpcode 'fload' 24: new root.LoadVarOpcode 'dload' 25: new root.LoadVarOpcode 'aload' 26: new root.LoadOpcode 'iload_0' 27: new root.LoadOpcode 'iload_1' 28: new root.LoadOpcode 'iload_2' 29: new root.LoadOpcode 'iload_3' 30: new root.LoadOpcode 'lload_0' 31: new root.LoadOpcode 'lload_1' 32: new root.LoadOpcode 'lload_2' 33: new root.LoadOpcode 'lload_3' 34: new root.LoadOpcode 'fload_0' 35: new root.LoadOpcode 'fload_1' 36: new root.LoadOpcode 'fload_2' 37: new root.LoadOpcode 'fload_3' 38: new root.LoadOpcode 'dload_0' 39: new root.LoadOpcode 'dload_1' 40: new root.LoadOpcode 'dload_2' 41: new root.LoadOpcode 'dload_3' 42: new root.LoadOpcode 'aload_0' 43: new root.LoadOpcode 'aload_1' 44: new root.LoadOpcode 'aload_2' 45: new root.LoadOpcode 'aload_3' 46: new root.ArrayLoadOpcode 'iaload' 47: new root.ArrayLoadOpcode 'laload' 48: new root.ArrayLoadOpcode 'faload' 49: new root.ArrayLoadOpcode 'daload' 50: new root.ArrayLoadOpcode 'aaload' 51: new root.ArrayLoadOpcode 'baload' 52: new root.ArrayLoadOpcode 'caload' 53: new root.ArrayLoadOpcode 'saload' 54: new root.StoreVarOpcode 'istore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 55: new root.StoreVarOpcode 'lstore', { execute: (rs) -> rs.put_cl2(@var_num,rs.pop2()) } 56: new root.StoreVarOpcode 'fstore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 57: new root.StoreVarOpcode 'dstore', { execute: (rs) -> rs.put_cl2(@var_num,rs.pop2()) } 58: new root.StoreVarOpcode 'astore', { execute: (rs) -> rs.put_cl(@var_num,rs.pop()) } 59: new root.StoreOpcode 'istore_0' 60: new root.StoreOpcode 'istore_1' 61: new root.StoreOpcode 'istore_2' 62: new root.StoreOpcode 'istore_3' 63: new root.StoreOpcode 'lstore_0' 64: new root.StoreOpcode 'lstore_1' 65: new root.StoreOpcode 'lstore_2' 66: new root.StoreOpcode 'lstore_3' 67: new root.StoreOpcode 'fstore_0' 68: new root.StoreOpcode 'fstore_1' 69: new root.StoreOpcode 'fstore_2' 70: new root.StoreOpcode 'fstore_3' 71: new root.StoreOpcode 'dstore_0' 72: new root.StoreOpcode 'dstore_1' 73: new root.StoreOpcode 'dstore_2' 74: new root.StoreOpcode 'dstore_3' 75: new root.StoreOpcode 'astore_0' 76: new root.StoreOpcode 'astore_1' 77: new root.StoreOpcode 'astore_2' 78: new root.StoreOpcode 'astore_3' 79: new root.Opcode 'iastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 80: new root.Opcode 'lastore', {execute: (rs) -> v=rs.pop2();i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 81: new root.Opcode 'fastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 82: new root.Opcode 'dastore', {execute: (rs) -> v=rs.pop2();i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 83: new root.Opcode 'aastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 84: new root.Opcode 'bastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 85: new root.Opcode 'castore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 86: new root.Opcode 'sastore', {execute: (rs) -> v=rs.pop(); i=rs.pop();rs.check_null(rs.pop()).array[i]=v } 87: new root.Opcode 'pop', { execute: (rs) -> rs.pop() } 88: new root.Opcode 'pop2', { execute: (rs) -> rs.pop2() } 89: new root.Opcode 'dup', { execute: (rs) -> v=rs.pop(); rs.push(v,v) } 90: new root.Opcode 'dup_x1', { execute: (rs) -> v1=rs.pop(); v2=rs.pop(); rs.push(v1,v2,v1) } 91: new root.Opcode 'dup_x2', {execute: (rs) -> [v1,v2,v3]=[rs.pop(),rs.pop(),rs.pop()];rs.push(v1,v3,v2,v1)} 92: new root.Opcode 'dup2', {execute: (rs) -> v1=rs.pop(); v2=rs.pop(); rs.push(v2,v1,v2,v1)} 93: new root.Opcode 'dup2_x1', {execute: (rs) -> [v1,v2,v3]=[rs.pop(),rs.pop(),rs.pop()];rs.push(v2,v1,v3,v2,v1)} 94: new root.Opcode 'dup2_x2', {execute: (rs) -> [v1,v2,v3,v4]=[rs.pop(),rs.pop(),rs.pop(),rs.pop()];rs.push(v2,v1,v4,v3,v2,v1)} 95: new root.Opcode 'swap', {execute: (rs) -> v2=rs.pop(); v1=rs.pop(); rs.push(v2,v1)} 96: new root.Opcode 'iadd', { execute: (rs) -> rs.push wrap_int(rs.pop()+rs.pop()) } 97: new root.Opcode 'ladd', { execute: (rs) -> rs.push(rs.pop2().add(rs.pop2()), null) } 98: new root.Opcode 'fadd', { execute: (rs) -> rs.push wrap_float(rs.pop()+rs.pop()) } 99: new root.Opcode 'dadd', { execute: (rs) -> rs.push(rs.pop2()+rs.pop2(), null) } 100: new root.Opcode 'isub', { execute: (rs) -> rs.push wrap_int(-rs.pop()+rs.pop()) } 101: new root.Opcode 'lsub', { execute: (rs) -> rs.push(rs.pop2().negate().add(rs.pop2()), null) } 102: new root.Opcode 'fsub', { execute: (rs) -> rs.push wrap_float(-rs.pop()+rs.pop()) } 103: new root.Opcode 'dsub', { execute: (rs) -> rs.push(-rs.pop2()+rs.pop2(), null) } 104: new root.Opcode 'imul', { execute: (rs) -> rs.push gLong.fromInt(rs.pop()).multiply(gLong.fromInt rs.pop()).toInt() } 105: new root.Opcode 'lmul', { execute: (rs) -> rs.push(rs.pop2().multiply(rs.pop2()), null) } 106: new root.Opcode 'fmul', { execute: (rs) -> rs.push wrap_float(rs.pop()*rs.pop()) } 107: new root.Opcode 'dmul', { execute: (rs) -> rs.push(rs.pop2()*rs.pop2(), null) } 108: new root.Opcode 'idiv', { execute: (rs) -> v=rs.pop();rs.push(int_div rs, rs.pop(), v) } 109: new root.Opcode 'ldiv', { execute: (rs) -> v=rs.pop2();rs.push(long_div(rs, rs.pop2(), v), null) } 110: new root.Opcode 'fdiv', { execute: (rs) -> v=rs.pop();rs.push wrap_float(rs.pop()/v) } 111: new root.Opcode 'ddiv', { execute: (rs) -> v=rs.pop2();rs.push(rs.pop2()/v, null) } 112: new root.Opcode 'irem', { execute: (rs) -> v2=rs.pop(); rs.push int_mod(rs,rs.pop(),v2) } 113: new root.Opcode 'lrem', { execute: (rs) -> v2=rs.pop2(); rs.push long_mod(rs,rs.pop2(),v2), null } 114: new root.Opcode 'frem', { execute: (rs) -> v2=rs.pop(); rs.push rs.pop() %v2 } 115: new root.Opcode 'drem', { execute: (rs) -> v2=rs.pop2(); rs.push rs.pop2()%v2, null } 116: new root.Opcode 'ineg', { execute: (rs) -> rs.push -rs.pop() } 117: new root.Opcode 'lneg', { execute: (rs) -> rs.push rs.pop2().negate(), null } 118: new root.Opcode 'fneg', { execute: (rs) -> rs.push -rs.pop() } 119: new root.Opcode 'dneg', { execute: (rs) -> rs.push -rs.pop2(), null } 120: new root.Opcode 'ishl', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()<<s) } 121: new root.Opcode 'lshl', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftLeft(gLong.fromInt(s)),null) } 122: new root.Opcode 'ishr', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()>>s) } 123: new root.Opcode 'lshr', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftRight(gLong.fromInt(s)), null) } 124: new root.Opcode 'iushr', { execute: (rs) -> s=rs.pop()&0x1F; rs.push(rs.pop()>>>s) } 125: new root.Opcode 'lushr', { execute: (rs) -> s=rs.pop()&0x3F; rs.push(rs.pop2().shiftRightUnsigned(gLong.fromInt(s)), null)} 126: new root.Opcode 'iand', { execute: (rs) -> rs.push(rs.pop()&rs.pop()) } 127: new root.Opcode 'land', { execute: (rs) -> rs.push(rs.pop2().and(rs.pop2()), null) } 128: new root.Opcode 'ior', { execute: (rs) -> rs.push(rs.pop()|rs.pop()) } 129: new root.Opcode 'lor', { execute: (rs) -> rs.push(rs.pop2().or(rs.pop2()), null) } 130: new root.Opcode 'ixor', { execute: (rs) -> rs.push(rs.pop()^rs.pop()) } 131: new root.Opcode 'lxor', { execute: (rs) -> rs.push(rs.pop2().xor(rs.pop2()), null) } 132: new root.IIncOpcode 'iinc' 133: new root.Opcode 'i2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop()), null } 134: new root.Opcode 'i2f', { execute: (rs) -> } 135: new root.Opcode 'i2d', { execute: (rs) -> rs.push null } 136: new root.Opcode 'l2i', { execute: (rs) -> rs.push rs.pop2().toInt() } 137: new root.Opcode 'l2f', { execute: (rs) -> rs.push rs.pop2().toNumber() } 138: new root.Opcode 'l2d', { execute: (rs) -> rs.push rs.pop2().toNumber(), null } 139: new root.Opcode 'f2i', { execute: (rs) -> rs.push float2int rs.pop() } 140: new root.Opcode 'f2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop()), null } 141: new root.Opcode 'f2d', { execute: (rs) -> rs.push null } 142: new root.Opcode 'd2i', { execute: (rs) -> rs.push float2int rs.pop2() } 143: new root.Opcode 'd2l', { execute: (rs) -> rs.push gLong.fromNumber(rs.pop2()), null } 144: new root.Opcode 'd2f', { execute: (rs) -> rs.push wrap_float rs.pop2() } 145: new root.Opcode 'i2b', { execute: (rs) -> rs.push truncate rs.pop(), 8 } 146: new root.Opcode 'i2c', { execute: (rs) -> rs.push truncate rs.pop(), 8 } 147: new root.Opcode 'i2s', { execute: (rs) -> rs.push truncate rs.pop(), 16 } 148: new root.Opcode 'lcmp', { execute: (rs) -> v2=rs.pop2(); rs.push rs.pop2().compare(v2) } 149: new root.Opcode 'fcmpl', { execute: (rs) -> v2=rs.pop(); rs.push util.cmp(rs.pop(),v2) ? -1 } 150: new root.Opcode 'fcmpg', { execute: (rs) -> v2=rs.pop(); rs.push util.cmp(rs.pop(),v2) ? 1 } 151: new root.Opcode 'dcmpl', { execute: (rs) -> v2=rs.pop2(); rs.push util.cmp(rs.pop2(),v2) ? -1 } 152: new root.Opcode 'dcmpg', { execute: (rs) -> v2=rs.pop2(); rs.push util.cmp(rs.pop2(),v2) ? 1 } 153: new root.UnaryBranchOpcode 'ifeq', { cmp: (v) -> v == 0 } 154: new root.UnaryBranchOpcode 'ifne', { cmp: (v) -> v != 0 } 155: new root.UnaryBranchOpcode 'iflt', { cmp: (v) -> v < 0 } 156: new root.UnaryBranchOpcode 'ifge', { cmp: (v) -> v >= 0 } 157: new root.UnaryBranchOpcode 'ifgt', { cmp: (v) -> v > 0 } 158: new root.UnaryBranchOpcode 'ifle', { cmp: (v) -> v <= 0 } 159: new root.BinaryBranchOpcode 'if_icmpeq', { cmp: (v1, v2) -> v1 == v2 } 160: new root.BinaryBranchOpcode 'if_icmpne', { cmp: (v1, v2) -> v1 != v2 } 161: new root.BinaryBranchOpcode 'if_icmplt', { cmp: (v1, v2) -> v1 < v2 } 162: new root.BinaryBranchOpcode 'if_icmpge', { cmp: (v1, v2) -> v1 >= v2 } 163: new root.BinaryBranchOpcode 'if_icmpgt', { cmp: (v1, v2) -> v1 > v2 } 164: new root.BinaryBranchOpcode 'if_icmple', { cmp: (v1, v2) -> v1 <= v2 } 165: new root.BinaryBranchOpcode 'if_acmpeq', { cmp: (v1, v2) -> v1 == v2 } 166: new root.BinaryBranchOpcode 'if_acmpne', { cmp: (v1, v2) -> v1 != v2 } 167: new root.BranchOpcode 'goto', { execute: (rs) -> throw new BranchException rs.curr_pc() + @offset } 168: new root.BranchOpcode 'jsr', { execute: jsr } 169: new root.Opcode 'ret', { byte_count: 1, execute: (rs) -> throw new BranchException rs.cl @args[0] } 170: new root.TableSwitchOpcode 'tableswitch' 171: new root.LookupSwitchOpcode 'lookupswitch' 172: new root.Opcode 'ireturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 173: new root.Opcode 'lreturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0], null } 174: new root.Opcode 'freturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 175: new root.Opcode 'dreturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0], null } 176: new root.Opcode 'areturn', { execute: (rs) -> throw new ReturnException rs.curr_frame().stack[0] } 177: new root.Opcode 'return', { execute: (rs) -> throw new Error("too many values on stack for void return") if rs.curr_frame().stack.length > 0 throw new ReturnException } 178: new root.FieldOpcode 'getstatic', {execute: (rs)-> rs.push rs.static_get @field_spec; rs.push null if @field_spec.type in ['J','D']} 179: new root.FieldOpcode 'putstatic', {execute: (rs)-> rs.static_put @field_spec } 180: new root.FieldOpcode 'getfield', {execute: (rs)-> rs.heap_get @field_spec, rs.pop() } 181: new root.FieldOpcode 'putfield', {execute: (rs)-> rs.heap_put @field_spec } 182: new root.InvokeOpcode 'invokevirtual', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs,true)} 183: new root.InvokeOpcode 'invokespecial', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs)} 184: new root.InvokeOpcode 'invokestatic', { execute: (rs)-> rs.method_lookup(@method_spec).run(rs)} 185: new root.InvokeOpcode 'invokeinterface',{ execute: (rs)-> rs.method_lookup(@method_spec).run(rs,true)} 187: new root.ClassOpcode 'new', { execute: (rs) -> rs.push rs.init_object @class } 188: new root.NewArrayOpcode 'newarray', { execute: (rs) -> rs.push rs.heap_newarray @element_type, rs.pop() } 189: new root.ClassOpcode 'anewarray', { execute: (rs) -> rs.push rs.heap_newarray "L#{@class};", rs.pop() } 190: new root.Opcode 'arraylength', { execute: (rs) -> rs.push rs.check_null(rs.pop()).array.length } 191: new root.Opcode 'athrow', { execute: (rs) -> throw new JavaException rs, rs.pop() } 192: new root.ClassOpcode 'checkcast', { execute: (rs) -> o = rs.pop() if (not o?) or types.check_cast(rs,o,@class) rs.push o else target_class = c2t(@class).toExternalString() # class we wish to cast to candidate_class = if o? then o.type.toExternalString() else "null" java_throw rs, 'java/lang/ClassCastException', "#{candidate_class} cannot be cast to #{target_class}" } 193: new root.ClassOpcode 'instanceof', { execute: (rs) -> o=rs.pop(); rs.push if o? then types.check_cast(rs,o,@class)+0 else 0 } 194: new root.Opcode 'monitorenter', { execute: (rs)-> rs.pop() } #TODO: actually implement locks? 195: new root.Opcode 'monitorexit', { execute: (rs)-> rs.pop() } #TODO: actually implement locks? 197: new root.MultiArrayOpcode 'multianewarray' 198: new root.UnaryBranchOpcode 'ifnull', { cmp: (v) -> not v? } 199: new root.UnaryBranchOpcode 'ifnonnull', { cmp: (v) -> v? } 200: new root.BranchOpcode 'goto_w', { byte_count: 4, execute: (rs) -> throw new BranchException rs.curr_pc() + @offset } 201: new root.BranchOpcode 'jsr_w', { byte_count: 4, execute: jsr } }
[ { "context": "ssword2) and $scope.user.password isnt $scope.user.password2\n $scope.passwordMismatch = true\n els", "end": 870, "score": 0.8685727715492249, "start": 862, "tag": "PASSWORD", "value": "password" } ]
ownblock/app/coffee/controllers/account.coffee
danjac/ownblock
3
angular.module("ownblock.controllers.account", [ "ownblock" "ownblock.services" ]).controller("account.EditCtrl", [ "$scope" "$state" "auth" "api" "notifier" ($scope, $state, auth, api, notifier) -> $scope.save = -> api.Auth.update auth.user, ((response) -> auth.update response notifier.success "Your account has been updated" $state.go "residents.detail", id: auth.user.id ), (response) -> $scope.serverErrors = response.data $scope.cancel = -> $state.go "residents.detail", id: auth.user.id ]).controller("account.ChangePasswordCtrl", [ "$scope" "$state" "api" "auth" "notifier" ($scope, $state, api, auth, notifier) -> checkMatchingPassword = -> if ($scope.user.password and $scope.user.password2) and $scope.user.password isnt $scope.user.password2 $scope.passwordMismatch = true else $scope.passwordMismatch = false $scope.user = {} $scope.passwordMismatch = false $scope.$watch "user.password", -> checkMatchingPassword() $scope.$watch "user.password2", -> checkMatchingPassword() $scope.save = -> api.Auth.changePassword $scope.user, -> notifier.success "Your password has been updated" $state.go "residents.detail", id: auth.user.id $scope.cancel = -> $state.go "residents.detail", id: auth.user.id ])
14183
angular.module("ownblock.controllers.account", [ "ownblock" "ownblock.services" ]).controller("account.EditCtrl", [ "$scope" "$state" "auth" "api" "notifier" ($scope, $state, auth, api, notifier) -> $scope.save = -> api.Auth.update auth.user, ((response) -> auth.update response notifier.success "Your account has been updated" $state.go "residents.detail", id: auth.user.id ), (response) -> $scope.serverErrors = response.data $scope.cancel = -> $state.go "residents.detail", id: auth.user.id ]).controller("account.ChangePasswordCtrl", [ "$scope" "$state" "api" "auth" "notifier" ($scope, $state, api, auth, notifier) -> checkMatchingPassword = -> if ($scope.user.password and $scope.user.password2) and $scope.user.password isnt $scope.user.<PASSWORD>2 $scope.passwordMismatch = true else $scope.passwordMismatch = false $scope.user = {} $scope.passwordMismatch = false $scope.$watch "user.password", -> checkMatchingPassword() $scope.$watch "user.password2", -> checkMatchingPassword() $scope.save = -> api.Auth.changePassword $scope.user, -> notifier.success "Your password has been updated" $state.go "residents.detail", id: auth.user.id $scope.cancel = -> $state.go "residents.detail", id: auth.user.id ])
true
angular.module("ownblock.controllers.account", [ "ownblock" "ownblock.services" ]).controller("account.EditCtrl", [ "$scope" "$state" "auth" "api" "notifier" ($scope, $state, auth, api, notifier) -> $scope.save = -> api.Auth.update auth.user, ((response) -> auth.update response notifier.success "Your account has been updated" $state.go "residents.detail", id: auth.user.id ), (response) -> $scope.serverErrors = response.data $scope.cancel = -> $state.go "residents.detail", id: auth.user.id ]).controller("account.ChangePasswordCtrl", [ "$scope" "$state" "api" "auth" "notifier" ($scope, $state, api, auth, notifier) -> checkMatchingPassword = -> if ($scope.user.password and $scope.user.password2) and $scope.user.password isnt $scope.user.PI:PASSWORD:<PASSWORD>END_PI2 $scope.passwordMismatch = true else $scope.passwordMismatch = false $scope.user = {} $scope.passwordMismatch = false $scope.$watch "user.password", -> checkMatchingPassword() $scope.$watch "user.password2", -> checkMatchingPassword() $scope.save = -> api.Auth.changePassword $scope.user, -> notifier.success "Your password has been updated" $state.go "residents.detail", id: auth.user.id $scope.cancel = -> $state.go "residents.detail", id: auth.user.id ])
[ { "context": "t'\n AXYA_DB: './data.db'\n # Use \"github.com/gorilla/securecookie\" bas64 encoded to generate keys\n ", "end": 307, "score": 0.9330759048461914, "start": 300, "tag": "USERNAME", "value": "gorilla" }, { "context": "bas64 encoded to generate keys\n AXYA_HASHKEY: 'NpSXuT5UPub9Fkzrmjmx23z1Swh5ZAH+OY3mSxExuQ5IG54FMphhB9rQC1ETRv+HQ78ZImVcs6OxQmNLD9LbRg=='\n AXYA_BLOCKKEY: 'K6rqSB5ZbmeiD8vLtyCM1de5VRhgx", "end": 461, "score": 0.9997490048408508, "start": 372, "tag": "KEY", "value": "NpSXuT5UPub9Fkzrmjmx23z1Swh5ZAH+OY3mSxExuQ5IG54FMphhB9rQC1ETRv+HQ78ZImVcs6OxQmNLD9LbRg=='" }, { "context": "Rv+HQ78ZImVcs6OxQmNLD9LbRg=='\n AXYA_BLOCKKEY: 'K6rqSB5ZbmeiD8vLtyCM1de5VRhgxtQHe4+1Q+wngq0='\n all: localEnv\n\nmodule.exports = (env = 'develop", "end": 527, "score": 0.9997676610946655, "start": 482, "tag": "KEY", "value": "K6rqSB5ZbmeiD8vLtyCM1de5VRhgxtQHe4+1Q+wngq0='" } ]
gulp/env.coffee
asartalo/axya
0
"use strict" _ = require('lodash') try localEnv = require('../local.env') catch e localEnv = {} envs = test: AXYA_ENV: 'test' AXYA_DB: './data_test.db' production: AXYA_ENV: 'production' development: AXYA_ENV: 'development' AXYA_DB: './data.db' # Use "github.com/gorilla/securecookie" bas64 encoded to generate keys AXYA_HASHKEY: 'NpSXuT5UPub9Fkzrmjmx23z1Swh5ZAH+OY3mSxExuQ5IG54FMphhB9rQC1ETRv+HQ78ZImVcs6OxQmNLD9LbRg==' AXYA_BLOCKKEY: 'K6rqSB5ZbmeiD8vLtyCM1de5VRhgxtQHe4+1Q+wngq0=' all: localEnv module.exports = (env = 'development') -> _.extend({}, process.env, envs.all, envs[env] || {})
32665
"use strict" _ = require('lodash') try localEnv = require('../local.env') catch e localEnv = {} envs = test: AXYA_ENV: 'test' AXYA_DB: './data_test.db' production: AXYA_ENV: 'production' development: AXYA_ENV: 'development' AXYA_DB: './data.db' # Use "github.com/gorilla/securecookie" bas64 encoded to generate keys AXYA_HASHKEY: '<KEY> AXYA_BLOCKKEY: '<KEY> all: localEnv module.exports = (env = 'development') -> _.extend({}, process.env, envs.all, envs[env] || {})
true
"use strict" _ = require('lodash') try localEnv = require('../local.env') catch e localEnv = {} envs = test: AXYA_ENV: 'test' AXYA_DB: './data_test.db' production: AXYA_ENV: 'production' development: AXYA_ENV: 'development' AXYA_DB: './data.db' # Use "github.com/gorilla/securecookie" bas64 encoded to generate keys AXYA_HASHKEY: 'PI:KEY:<KEY>END_PI AXYA_BLOCKKEY: 'PI:KEY:<KEY>END_PI all: localEnv module.exports = (env = 'development') -> _.extend({}, process.env, envs.all, envs[env] || {})
[ { "context": "ss IsyInsteonFanMotorNode extends IsyNode\n key: 'insteonFanMotor'\n\n SPEED_MAP:\n off: 0\n low: 63\n", "end": 132, "score": 0.5190673470497131, "start": 128, "tag": "KEY", "value": "inst" }, { "context": "syInsteonFanMotorNode extends IsyNode\n key: 'insteonFanMotor'\n\n SPEED_MAP:\n off: 0\n low: 63\n med: 19", "end": 143, "score": 0.5656260848045349, "start": 132, "tag": "USERNAME", "value": "eonFanMotor" } ]
lib/adapters/isy/IsyInsteonFanMotorNode.coffee
monitron/jarvis-ha
1
_ = require('underscore') IsyNode = require('./IsyNode') module.exports = class IsyInsteonFanMotorNode extends IsyNode key: 'insteonFanMotor' SPEED_MAP: off: 0 low: 63 med: 191 high: 255 aspects: discreteSpeed: commands: set: (node, value) -> operative = node.getAspect('discreteSpeed').getDatum('state') != value node.adapter.executeCommand node.id, 'DON', [node.SPEED_MAP[value]], operative attributes: choices: [ {id: 'off', shortName: 'Off', longName: 'Off'} {id: 'low', shortName: 'Low', longName: 'Low'} {id: 'med', shortName: 'Med', longName: 'Medium'} {id: 'high', shortName: 'High', longName: 'High'}] processData: (data) -> if data.ST? @getAspect('discreteSpeed').setData state: _.findKey(@SPEED_MAP, (value) -> value.toString() == data.ST)
93440
_ = require('underscore') IsyNode = require('./IsyNode') module.exports = class IsyInsteonFanMotorNode extends IsyNode key: '<KEY>eonFanMotor' SPEED_MAP: off: 0 low: 63 med: 191 high: 255 aspects: discreteSpeed: commands: set: (node, value) -> operative = node.getAspect('discreteSpeed').getDatum('state') != value node.adapter.executeCommand node.id, 'DON', [node.SPEED_MAP[value]], operative attributes: choices: [ {id: 'off', shortName: 'Off', longName: 'Off'} {id: 'low', shortName: 'Low', longName: 'Low'} {id: 'med', shortName: 'Med', longName: 'Medium'} {id: 'high', shortName: 'High', longName: 'High'}] processData: (data) -> if data.ST? @getAspect('discreteSpeed').setData state: _.findKey(@SPEED_MAP, (value) -> value.toString() == data.ST)
true
_ = require('underscore') IsyNode = require('./IsyNode') module.exports = class IsyInsteonFanMotorNode extends IsyNode key: 'PI:KEY:<KEY>END_PIeonFanMotor' SPEED_MAP: off: 0 low: 63 med: 191 high: 255 aspects: discreteSpeed: commands: set: (node, value) -> operative = node.getAspect('discreteSpeed').getDatum('state') != value node.adapter.executeCommand node.id, 'DON', [node.SPEED_MAP[value]], operative attributes: choices: [ {id: 'off', shortName: 'Off', longName: 'Off'} {id: 'low', shortName: 'Low', longName: 'Low'} {id: 'med', shortName: 'Med', longName: 'Medium'} {id: 'high', shortName: 'High', longName: 'High'}] processData: (data) -> if data.ST? @getAspect('discreteSpeed').setData state: _.findKey(@SPEED_MAP, (value) -> value.toString() == data.ST)
[ { "context": "class window.MeetupMap\n MAPS_API_KEY: \"AIzaSyA7wI0GezpAtXC4DPXQg5kEXYrKg4vC8Hc\"\n\n constructor: (@address) ->\n\n url: ->\n \"ht", "end": 79, "score": 0.9997422099113464, "start": 40, "tag": "KEY", "value": "AIzaSyA7wI0GezpAtXC4DPXQg5kEXYrKg4vC8Hc" } ]
source/assets/javascripts/meetup_map.coffee
Trianglerb/trianglerb
0
class window.MeetupMap MAPS_API_KEY: "AIzaSyA7wI0GezpAtXC4DPXQg5kEXYrKg4vC8Hc" constructor: (@address) -> url: -> "https://www.google.com/maps/embed/v1/place?q=#{@_encodedAddress()}&key=#{@MAPS_API_KEY}" _encodedAddress: -> encodeURIComponent(@address)
191852
class window.MeetupMap MAPS_API_KEY: "<KEY>" constructor: (@address) -> url: -> "https://www.google.com/maps/embed/v1/place?q=#{@_encodedAddress()}&key=#{@MAPS_API_KEY}" _encodedAddress: -> encodeURIComponent(@address)
true
class window.MeetupMap MAPS_API_KEY: "PI:KEY:<KEY>END_PI" constructor: (@address) -> url: -> "https://www.google.com/maps/embed/v1/place?q=#{@_encodedAddress()}&key=#{@MAPS_API_KEY}" _encodedAddress: -> encodeURIComponent(@address)
[ { "context": " _sessionUserId: app.user1._id\n q: 'user2@teambition.com'\n request options, (err, res, users) ->\n ", "end": 892, "score": 0.9998965263366699, "start": 872, "tag": "EMAIL", "value": "user2@teambition.com" }, { "context": "ngth.should.eql 1\n users[0].name.should.eql 'dajiangyou2'\n done err\n\n it 'should read the users by m", "end": 1011, "score": 0.9996670484542847, "start": 1000, "tag": "USERNAME", "value": "dajiangyou2" }, { "context": "e', 'avatarUrl'\n data.name.should.eql 'xjx'\n callback()\n update: (callback) ", "end": 1936, "score": 0.9213405847549438, "start": 1933, "tag": "NAME", "value": "xjx" }, { "context": " body: JSON.stringify\n name: 'xjx'\n _sessionUserId: app.user1._id\n ", "end": 2124, "score": 0.901079535484314, "start": 2121, "tag": "NAME", "value": "xjx" }, { "context": "rLogin', 'mobile'\n user.name.should.eql 'xjx'\n user.pinyin.should.eql 'xjx'\n ", "end": 2312, "score": 0.9329413771629333, "start": 2309, "tag": "NAME", "value": "xjx" }, { "context": " ->\n user = new UserModel\n name: \"jianliao\"\n accountId: \"55f7d19c85efe377996a1232\"\n", "end": 3692, "score": 0.9993461966514587, "start": 3684, "tag": "USERNAME", "value": "jianliao" }, { "context": "\n name: \"jianliao\"\n accountId: \"55f7d19c85efe377996a1232\"\n app.user = user\n user.$save().nod", "end": 3740, "score": 0.9988645315170288, "start": 3716, "tag": "KEY", "value": "55f7d19c85efe377996a1232" }, { "context": "onUserId: app.user._id\n accountToken: 'OKKKKKKK'\n app.request options, callback\n ", "end": 4034, "score": 0.6371331214904785, "start": 4030, "tag": "KEY", "value": "OKKK" }, { "context": "erId: app.user._id\n accountToken: 'OKKKKKKK'\n app.request options, callback\n ]\n ", "end": 4038, "score": 0.5092953443527222, "start": 4034, "tag": "PASSWORD", "value": "KKKK" } ]
talk-api2x/test/controllers/user.coffee
ikingye/talk-os
3,084
should = require 'should' limbo = require 'limbo' uuid = require 'uuid' db = limbo.use 'talk' async = require 'async' jwt = require 'jsonwebtoken' util = require '../../server/util' config = require 'config' app = require '../app' {prepare, clear, request} = app { MemberModel UserModel } = db describe 'User#ReadOne', -> before prepare it 'should read infomation of myself', (done) -> options = method: 'get' url: 'users/me' qs: _sessionUserId: app.user1._id request options, (err, res, user) -> user.should.have.properties 'name', 'avatarUrl', 'email', 'phoneForLogin', 'mobile' done(err) after clear describe 'User#Read', -> before prepare it 'should read the users by email', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id q: 'user2@teambition.com' request options, (err, res, users) -> users.length.should.eql 1 users[0].name.should.eql 'dajiangyou2' done err it 'should read the users by mobile number', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id q: '13388888881' request options, (err, res, users) -> users.length.should.eql 1 done err it 'should read the users by mobiles', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id mobiles: '13388888881,13388888882' request options, (err, res, users) -> users.length.should.eql 2 done err after clear describe 'User#Update', -> before prepare it 'should update user name to xjx', (done) -> async.auto broadcast: (callback) -> app.broadcast = (room, event, data, socketId) -> if event is 'user:update' data.should.have.properties 'name', 'avatarUrl' data.name.should.eql 'xjx' callback() update: (callback) -> options = method: 'put' url: "users/#{app.user1._id}" body: JSON.stringify name: 'xjx' _sessionUserId: app.user1._id request options, (err, res, user) -> user.should.have.properties 'phoneForLogin', 'mobile' user.name.should.eql 'xjx' user.pinyin.should.eql 'xjx' user.pinyins.should.eql ['xjx'] callback err , done after clear describe 'User#Subscribe', -> before prepare it 'should subscribe to the user channel', (done) -> options = method: 'post' url: 'users/subscribe' headers: "X-Socket-Id": uuid.v1() body: _sessionUserId: app.user1._id app.request options, (err, res, result) -> result.should.eql ok: 1 done err after clear describe 'User#Unsubscribe', -> before prepare it 'should unsubscribe to the user channel', (done) -> options = method: 'post' url: 'users/unsubscribe' headers: "X-Socket-Id": uuid.v1() body: _sessionUserId: app.user1._id app.request options, (err, res, result) -> result.should.eql ok: 1 done err after clear describe 'User#landing', -> before prepare it "should broadcast union's access token and refer attributes", (done) -> async.auto broadcast: (callback) -> app.broadcast = (room, event, data) -> if event is 'integration:gettoken' data.should.have.properties "accessToken", "showname", 'openId', 'avatarUrl', 'openId' data.showname.should.eql "github" callback() createUser: (callback) -> user = new UserModel name: "jianliao" accountId: "55f7d19c85efe377996a1232" app.user = user user.$save().nodeify callback gettoken: ['createUser', (callback) -> options = method: 'get' url: '/union/github/landing' body: JSON.stringify _sessionUserId: app.user._id accountToken: 'OKKKKKKK' app.request options, callback ] , done after clear
169025
should = require 'should' limbo = require 'limbo' uuid = require 'uuid' db = limbo.use 'talk' async = require 'async' jwt = require 'jsonwebtoken' util = require '../../server/util' config = require 'config' app = require '../app' {prepare, clear, request} = app { MemberModel UserModel } = db describe 'User#ReadOne', -> before prepare it 'should read infomation of myself', (done) -> options = method: 'get' url: 'users/me' qs: _sessionUserId: app.user1._id request options, (err, res, user) -> user.should.have.properties 'name', 'avatarUrl', 'email', 'phoneForLogin', 'mobile' done(err) after clear describe 'User#Read', -> before prepare it 'should read the users by email', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id q: '<EMAIL>' request options, (err, res, users) -> users.length.should.eql 1 users[0].name.should.eql 'dajiangyou2' done err it 'should read the users by mobile number', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id q: '13388888881' request options, (err, res, users) -> users.length.should.eql 1 done err it 'should read the users by mobiles', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id mobiles: '13388888881,13388888882' request options, (err, res, users) -> users.length.should.eql 2 done err after clear describe 'User#Update', -> before prepare it 'should update user name to xjx', (done) -> async.auto broadcast: (callback) -> app.broadcast = (room, event, data, socketId) -> if event is 'user:update' data.should.have.properties 'name', 'avatarUrl' data.name.should.eql '<NAME>' callback() update: (callback) -> options = method: 'put' url: "users/#{app.user1._id}" body: JSON.stringify name: '<NAME>' _sessionUserId: app.user1._id request options, (err, res, user) -> user.should.have.properties 'phoneForLogin', 'mobile' user.name.should.eql '<NAME>' user.pinyin.should.eql 'xjx' user.pinyins.should.eql ['xjx'] callback err , done after clear describe 'User#Subscribe', -> before prepare it 'should subscribe to the user channel', (done) -> options = method: 'post' url: 'users/subscribe' headers: "X-Socket-Id": uuid.v1() body: _sessionUserId: app.user1._id app.request options, (err, res, result) -> result.should.eql ok: 1 done err after clear describe 'User#Unsubscribe', -> before prepare it 'should unsubscribe to the user channel', (done) -> options = method: 'post' url: 'users/unsubscribe' headers: "X-Socket-Id": uuid.v1() body: _sessionUserId: app.user1._id app.request options, (err, res, result) -> result.should.eql ok: 1 done err after clear describe 'User#landing', -> before prepare it "should broadcast union's access token and refer attributes", (done) -> async.auto broadcast: (callback) -> app.broadcast = (room, event, data) -> if event is 'integration:gettoken' data.should.have.properties "accessToken", "showname", 'openId', 'avatarUrl', 'openId' data.showname.should.eql "github" callback() createUser: (callback) -> user = new UserModel name: "jianliao" accountId: "<KEY>" app.user = user user.$save().nodeify callback gettoken: ['createUser', (callback) -> options = method: 'get' url: '/union/github/landing' body: JSON.stringify _sessionUserId: app.user._id accountToken: '<KEY> <PASSWORD>' app.request options, callback ] , done after clear
true
should = require 'should' limbo = require 'limbo' uuid = require 'uuid' db = limbo.use 'talk' async = require 'async' jwt = require 'jsonwebtoken' util = require '../../server/util' config = require 'config' app = require '../app' {prepare, clear, request} = app { MemberModel UserModel } = db describe 'User#ReadOne', -> before prepare it 'should read infomation of myself', (done) -> options = method: 'get' url: 'users/me' qs: _sessionUserId: app.user1._id request options, (err, res, user) -> user.should.have.properties 'name', 'avatarUrl', 'email', 'phoneForLogin', 'mobile' done(err) after clear describe 'User#Read', -> before prepare it 'should read the users by email', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id q: 'PI:EMAIL:<EMAIL>END_PI' request options, (err, res, users) -> users.length.should.eql 1 users[0].name.should.eql 'dajiangyou2' done err it 'should read the users by mobile number', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id q: '13388888881' request options, (err, res, users) -> users.length.should.eql 1 done err it 'should read the users by mobiles', (done) -> options = method: 'GET' url: '/users' qs: _sessionUserId: app.user1._id mobiles: '13388888881,13388888882' request options, (err, res, users) -> users.length.should.eql 2 done err after clear describe 'User#Update', -> before prepare it 'should update user name to xjx', (done) -> async.auto broadcast: (callback) -> app.broadcast = (room, event, data, socketId) -> if event is 'user:update' data.should.have.properties 'name', 'avatarUrl' data.name.should.eql 'PI:NAME:<NAME>END_PI' callback() update: (callback) -> options = method: 'put' url: "users/#{app.user1._id}" body: JSON.stringify name: 'PI:NAME:<NAME>END_PI' _sessionUserId: app.user1._id request options, (err, res, user) -> user.should.have.properties 'phoneForLogin', 'mobile' user.name.should.eql 'PI:NAME:<NAME>END_PI' user.pinyin.should.eql 'xjx' user.pinyins.should.eql ['xjx'] callback err , done after clear describe 'User#Subscribe', -> before prepare it 'should subscribe to the user channel', (done) -> options = method: 'post' url: 'users/subscribe' headers: "X-Socket-Id": uuid.v1() body: _sessionUserId: app.user1._id app.request options, (err, res, result) -> result.should.eql ok: 1 done err after clear describe 'User#Unsubscribe', -> before prepare it 'should unsubscribe to the user channel', (done) -> options = method: 'post' url: 'users/unsubscribe' headers: "X-Socket-Id": uuid.v1() body: _sessionUserId: app.user1._id app.request options, (err, res, result) -> result.should.eql ok: 1 done err after clear describe 'User#landing', -> before prepare it "should broadcast union's access token and refer attributes", (done) -> async.auto broadcast: (callback) -> app.broadcast = (room, event, data) -> if event is 'integration:gettoken' data.should.have.properties "accessToken", "showname", 'openId', 'avatarUrl', 'openId' data.showname.should.eql "github" callback() createUser: (callback) -> user = new UserModel name: "jianliao" accountId: "PI:KEY:<KEY>END_PI" app.user = user user.$save().nodeify callback gettoken: ['createUser', (callback) -> options = method: 'get' url: '/union/github/landing' body: JSON.stringify _sessionUserId: app.user._id accountToken: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' app.request options, callback ] , done after clear
[ { "context": "serve\": \"preserve.js\"\npreferGlobal: true\nauthor: \"Hoàng Văn Khải <hvksmr1996@gmail.com>\"\ncontributors: [\n \"Hoàng ", "end": 371, "score": 0.9998732805252075, "start": 357, "tag": "NAME", "value": "Hoàng Văn Khải" }, { "context": "e.js\"\npreferGlobal: true\nauthor: \"Hoàng Văn Khải <hvksmr1996@gmail.com>\"\ncontributors: [\n \"Hoàng Văn Khải <hvksmr1996@g", "end": 393, "score": 0.99993497133255, "start": 373, "tag": "EMAIL", "value": "hvksmr1996@gmail.com" }, { "context": "n Khải <hvksmr1996@gmail.com>\"\ncontributors: [\n \"Hoàng Văn Khải <hvksmr1996@gmail.com>\"\n]\nlicense: \"MIT\"\nreposito", "end": 429, "score": 0.9998722672462463, "start": 415, "tag": "NAME", "value": "Hoàng Văn Khải" }, { "context": "96@gmail.com>\"\ncontributors: [\n \"Hoàng Văn Khải <hvksmr1996@gmail.com>\"\n]\nlicense: \"MIT\"\nrepository:\n type: \"git\"\n ur", "end": 451, "score": 0.9999353289604187, "start": 431, "tag": "EMAIL", "value": "hvksmr1996@gmail.com" }, { "context": "ository:\n type: \"git\"\n url: \"https://github.com/ksxnodeapps/package-alt-cson.git\"\ndependencies:\n \"package-al", "end": 535, "score": 0.9665938019752502, "start": 524, "tag": "USERNAME", "value": "ksxnodeapps" }, { "context": "cson\"\n \"cnpm\"\n]\nbugs:\n url: \"https://github.com/ksxnodeapps/package-alt-cson/issues\"\nhomepage: \"https://githu", "end": 949, "score": 0.9896178841590881, "start": 938, "tag": "USERNAME", "value": "ksxnodeapps" }, { "context": "ge-alt-cson/issues\"\nhomepage: \"https://github.com/ksxnodeapps/package-alt-cson#readme\"\n", "end": 1016, "score": 0.9304891228675842, "start": 1005, "tag": "USERNAME", "value": "ksxnodeapps" } ]
package.cson
ksxnodeapps/package-alt-cson
1
name: "package-alt-cson" description: "Use package.cson instead of package.json" version: "0.0.2" main: "help.js" bin: "package-alt-cson": "help.js" "npm-cson": "update.js" cnpm: "update.js" "npm-cson-update": "update.js" "cnpm-update": "update.js" "npm-cson-preserve": "preserve.js" "cnpm-preserve": "preserve.js" preferGlobal: true author: "Hoàng Văn Khải <hvksmr1996@gmail.com>" contributors: [ "Hoàng Văn Khải <hvksmr1996@gmail.com>" ] license: "MIT" repository: type: "git" url: "https://github.com/ksxnodeapps/package-alt-cson.git" dependencies: "package-alt": "^0.0.5" cson: "^4.1.0" devDependencies: standard: "^10.0.1" engines: node: ">= 6.0.0" scripts: "remake-package-json": "node sh/remake-package-json" clean: "bash 'sh/clean.sh'" fix: "bash 'sh/fix.sh'" test: "bash 'sh/test.sh'" keywords: [ "package.cson" "alternate" "npm" "npm-cson" "cnpm" ] bugs: url: "https://github.com/ksxnodeapps/package-alt-cson/issues" homepage: "https://github.com/ksxnodeapps/package-alt-cson#readme"
92669
name: "package-alt-cson" description: "Use package.cson instead of package.json" version: "0.0.2" main: "help.js" bin: "package-alt-cson": "help.js" "npm-cson": "update.js" cnpm: "update.js" "npm-cson-update": "update.js" "cnpm-update": "update.js" "npm-cson-preserve": "preserve.js" "cnpm-preserve": "preserve.js" preferGlobal: true author: "<NAME> <<EMAIL>>" contributors: [ "<NAME> <<EMAIL>>" ] license: "MIT" repository: type: "git" url: "https://github.com/ksxnodeapps/package-alt-cson.git" dependencies: "package-alt": "^0.0.5" cson: "^4.1.0" devDependencies: standard: "^10.0.1" engines: node: ">= 6.0.0" scripts: "remake-package-json": "node sh/remake-package-json" clean: "bash 'sh/clean.sh'" fix: "bash 'sh/fix.sh'" test: "bash 'sh/test.sh'" keywords: [ "package.cson" "alternate" "npm" "npm-cson" "cnpm" ] bugs: url: "https://github.com/ksxnodeapps/package-alt-cson/issues" homepage: "https://github.com/ksxnodeapps/package-alt-cson#readme"
true
name: "package-alt-cson" description: "Use package.cson instead of package.json" version: "0.0.2" main: "help.js" bin: "package-alt-cson": "help.js" "npm-cson": "update.js" cnpm: "update.js" "npm-cson-update": "update.js" "cnpm-update": "update.js" "npm-cson-preserve": "preserve.js" "cnpm-preserve": "preserve.js" preferGlobal: true author: "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" contributors: [ "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>" ] license: "MIT" repository: type: "git" url: "https://github.com/ksxnodeapps/package-alt-cson.git" dependencies: "package-alt": "^0.0.5" cson: "^4.1.0" devDependencies: standard: "^10.0.1" engines: node: ">= 6.0.0" scripts: "remake-package-json": "node sh/remake-package-json" clean: "bash 'sh/clean.sh'" fix: "bash 'sh/fix.sh'" test: "bash 'sh/test.sh'" keywords: [ "package.cson" "alternate" "npm" "npm-cson" "cnpm" ] bugs: url: "https://github.com/ksxnodeapps/package-alt-cson/issues" homepage: "https://github.com/ksxnodeapps/package-alt-cson#readme"
[ { "context": "#########################\n#\n#\tMooqita\n# Created by Markus on 20/8/2017.\n#\n#################################", "end": 87, "score": 0.9996915459632874, "start": 81, "tag": "NAME", "value": "Markus" } ]
server/publications/user.coffee
MooqitaSFH/worklearn
0
####################################################### # # Mooqita # Created by Markus on 20/8/2017. # ####################################################### ####################################################### Meteor.publish "find_users_by_mail": (mail_fragment) -> user = Meteor.user() if not user throw new Meteor.Error('Not permitted.') if mail_fragment.length < 5 return [] check mail_fragment, String filter = emails: $elemMatch: address: $regex : new RegExp(mail_fragment, "i") options = fields: emails: 1 skip: 0, limit: 10 crs = Meteor.users.find filter, options users = crs.fetch() return users ####################################################### Meteor.publish "my_profile", () -> user_id = this.userId if not user_id user_id = "" filter = user_id: user_id crs = Profiles.find filter log_publication crs, user_id, "my_profile" return crs ####################################################### # Resumes ####################################################### ####################################################### Meteor.publish "user_resumes", (user_id) -> if user_id check user_id, String if not has_role Profiles, WILDCARD, this.userId, ADMIN if this.userId != user_id profile = get_document user_id, "owner", Profiles if profile.locale throw new Meteor.Error("Not permitted.") if !user_id user_id = this.userId if !user_id throw new Meteor.Error("Not permitted.") self = this prepare_resume = (user) -> resume = {} profile = get_profile user if profile resume.name = get_profile_name profile, false, false resume.self_description = profile.resume resume.avatar = get_avatar profile solution_list = [] solution_cursor = get_documents user, OWNER, Solutions, {published: true} solution_cursor.forEach (s) -> solution = {} solution.reviews = [] solution.solution = if !s.confidential then s.content else null challenge = Challenges.findOne(s.challenge_id) if challenge solution.challenge = if !challenge.confidential then challenge.content else null solution.challenge_title = challenge.title owner = get_document_owner Challenges, challenge profile = get_document owner, OWNER, Profiles if profile solution.challenge_owner_avatar = get_avatar profile abs_rating = 0 num_ratings = 0 review_filter = solution_id: s._id review_cursor = Reviews.find(review_filter) review_cursor.forEach (r) -> review = {} filter = review_id: r._id feedback = Feedback.findOne filter owner = get_document_owner Profiles, r profile = get_profile owner if feedback.published review.feedback = {} review.feedback.content = feedback.content review.feedback.rating = feedback.rating review.rating = r.rating abs_rating += parseInt(r.rating) num_ratings += 1 if profile review.name = get_profile_name profile ,false ,false review.avatar = get_avatar profile review.review = r.content solution.reviews.push(review) if abs_rating avg = Math.round(abs_rating / num_ratings, 1) solution.average = avg solution_list.push(solution) resume.solutions = solution_list self.added("user_resumes", user._id, resume) filter = _id: user_id crs = Meteor.users.find(filter) crs.forEach(prepare_resume) log_publication crs, user_id, "user_resumes" self.ready() ####################################################### Meteor.publish "user_summary", (user_id, challenge_id) -> check user_id, String check challenge_id, String if user_id if not has_role Challenges, challenge_id, this.userId, DESIGNER throw new Meteor.Error("Not permitted.") if !user_id user_id = this.userId if !user_id throw new Meteor.Error("Not permitted.") ########################################## # Initialize user summary through users # database object ########################################## mod = fields: emails: 1 user = Meteor.users.findOne user_id, mod ########################################## # Same fields for solution review feedback ########################################## mod = fields: rating: 1 content: 1 material: 1 ########################################## # Find Solutions ########################################## ########################################## filter = {challenge_id: challenge_id} solutions = get_my_documents filter, mod ########################################## # Find relevant Feedback and Reviews ########################################## rev_given = get_my_documents Reviews.find filter, mod fed_given = get_my_documents Feedback.find filter, mod filter = requester_id: user_id challenge_id: challenge_id rev_received = Reviews.find filter, mod fed_received = Feedback.find filter, mod ########################################## # # Calculate statistics # ########################################## ########################################## # Solutions ########################################## material = 0 length = 0 count = solutions.count() solutions.forEach (entry) -> if entry.content length += entry.content.split(" ").length if entry.material material += 1 user.solutions_count = count user.solutions_average_length = length / count user.solutions_average_material = material / count ########################################## # Given Reviews ########################################## user = calc_statistics user, rev_given, "reviews_given" user = calc_statistics user, rev_received, "reviews_received" user = calc_statistics user, fed_given, "feedback_given" user = calc_statistics user, fed_received, "feedback_received" log_publication crs, this.userId, "user_summary" this.added "user_summaries", user_id, user this.ready() ############################################################################### Meteor.publish "team_members_by_organization_id", (organization_id) -> check organization_id, String user_id = this.userId if !user_id throw new Meteor.Error "Not permitted." member_ids = [] admission_cursor = get_admissions IGNORE, IGNORE, Organizations, organization_id admission_cursor.forEach (admission) -> member_ids.push admission.u options = fields: given_name: 1 middle_name: 1 family_name: 1 big_five: 1 avatar:1 self = this for user_id in member_ids profile = Profiles.findOne {user_id: user_id}, options mail = get_user_mail(user_id) name = get_profile_name profile, false, false member = name: name email: mail big_five: profile.big_five avatar: profile.avatar owner: user_id == self.userId self.added("team_members", user_id, member) log_publication admission_cursor, user_id, "team_members_by_organization_id" self.ready()
225022
####################################################### # # Mooqita # Created by <NAME> on 20/8/2017. # ####################################################### ####################################################### Meteor.publish "find_users_by_mail": (mail_fragment) -> user = Meteor.user() if not user throw new Meteor.Error('Not permitted.') if mail_fragment.length < 5 return [] check mail_fragment, String filter = emails: $elemMatch: address: $regex : new RegExp(mail_fragment, "i") options = fields: emails: 1 skip: 0, limit: 10 crs = Meteor.users.find filter, options users = crs.fetch() return users ####################################################### Meteor.publish "my_profile", () -> user_id = this.userId if not user_id user_id = "" filter = user_id: user_id crs = Profiles.find filter log_publication crs, user_id, "my_profile" return crs ####################################################### # Resumes ####################################################### ####################################################### Meteor.publish "user_resumes", (user_id) -> if user_id check user_id, String if not has_role Profiles, WILDCARD, this.userId, ADMIN if this.userId != user_id profile = get_document user_id, "owner", Profiles if profile.locale throw new Meteor.Error("Not permitted.") if !user_id user_id = this.userId if !user_id throw new Meteor.Error("Not permitted.") self = this prepare_resume = (user) -> resume = {} profile = get_profile user if profile resume.name = get_profile_name profile, false, false resume.self_description = profile.resume resume.avatar = get_avatar profile solution_list = [] solution_cursor = get_documents user, OWNER, Solutions, {published: true} solution_cursor.forEach (s) -> solution = {} solution.reviews = [] solution.solution = if !s.confidential then s.content else null challenge = Challenges.findOne(s.challenge_id) if challenge solution.challenge = if !challenge.confidential then challenge.content else null solution.challenge_title = challenge.title owner = get_document_owner Challenges, challenge profile = get_document owner, OWNER, Profiles if profile solution.challenge_owner_avatar = get_avatar profile abs_rating = 0 num_ratings = 0 review_filter = solution_id: s._id review_cursor = Reviews.find(review_filter) review_cursor.forEach (r) -> review = {} filter = review_id: r._id feedback = Feedback.findOne filter owner = get_document_owner Profiles, r profile = get_profile owner if feedback.published review.feedback = {} review.feedback.content = feedback.content review.feedback.rating = feedback.rating review.rating = r.rating abs_rating += parseInt(r.rating) num_ratings += 1 if profile review.name = get_profile_name profile ,false ,false review.avatar = get_avatar profile review.review = r.content solution.reviews.push(review) if abs_rating avg = Math.round(abs_rating / num_ratings, 1) solution.average = avg solution_list.push(solution) resume.solutions = solution_list self.added("user_resumes", user._id, resume) filter = _id: user_id crs = Meteor.users.find(filter) crs.forEach(prepare_resume) log_publication crs, user_id, "user_resumes" self.ready() ####################################################### Meteor.publish "user_summary", (user_id, challenge_id) -> check user_id, String check challenge_id, String if user_id if not has_role Challenges, challenge_id, this.userId, DESIGNER throw new Meteor.Error("Not permitted.") if !user_id user_id = this.userId if !user_id throw new Meteor.Error("Not permitted.") ########################################## # Initialize user summary through users # database object ########################################## mod = fields: emails: 1 user = Meteor.users.findOne user_id, mod ########################################## # Same fields for solution review feedback ########################################## mod = fields: rating: 1 content: 1 material: 1 ########################################## # Find Solutions ########################################## ########################################## filter = {challenge_id: challenge_id} solutions = get_my_documents filter, mod ########################################## # Find relevant Feedback and Reviews ########################################## rev_given = get_my_documents Reviews.find filter, mod fed_given = get_my_documents Feedback.find filter, mod filter = requester_id: user_id challenge_id: challenge_id rev_received = Reviews.find filter, mod fed_received = Feedback.find filter, mod ########################################## # # Calculate statistics # ########################################## ########################################## # Solutions ########################################## material = 0 length = 0 count = solutions.count() solutions.forEach (entry) -> if entry.content length += entry.content.split(" ").length if entry.material material += 1 user.solutions_count = count user.solutions_average_length = length / count user.solutions_average_material = material / count ########################################## # Given Reviews ########################################## user = calc_statistics user, rev_given, "reviews_given" user = calc_statistics user, rev_received, "reviews_received" user = calc_statistics user, fed_given, "feedback_given" user = calc_statistics user, fed_received, "feedback_received" log_publication crs, this.userId, "user_summary" this.added "user_summaries", user_id, user this.ready() ############################################################################### Meteor.publish "team_members_by_organization_id", (organization_id) -> check organization_id, String user_id = this.userId if !user_id throw new Meteor.Error "Not permitted." member_ids = [] admission_cursor = get_admissions IGNORE, IGNORE, Organizations, organization_id admission_cursor.forEach (admission) -> member_ids.push admission.u options = fields: given_name: 1 middle_name: 1 family_name: 1 big_five: 1 avatar:1 self = this for user_id in member_ids profile = Profiles.findOne {user_id: user_id}, options mail = get_user_mail(user_id) name = get_profile_name profile, false, false member = name: name email: mail big_five: profile.big_five avatar: profile.avatar owner: user_id == self.userId self.added("team_members", user_id, member) log_publication admission_cursor, user_id, "team_members_by_organization_id" self.ready()
true
####################################################### # # Mooqita # Created by PI:NAME:<NAME>END_PI on 20/8/2017. # ####################################################### ####################################################### Meteor.publish "find_users_by_mail": (mail_fragment) -> user = Meteor.user() if not user throw new Meteor.Error('Not permitted.') if mail_fragment.length < 5 return [] check mail_fragment, String filter = emails: $elemMatch: address: $regex : new RegExp(mail_fragment, "i") options = fields: emails: 1 skip: 0, limit: 10 crs = Meteor.users.find filter, options users = crs.fetch() return users ####################################################### Meteor.publish "my_profile", () -> user_id = this.userId if not user_id user_id = "" filter = user_id: user_id crs = Profiles.find filter log_publication crs, user_id, "my_profile" return crs ####################################################### # Resumes ####################################################### ####################################################### Meteor.publish "user_resumes", (user_id) -> if user_id check user_id, String if not has_role Profiles, WILDCARD, this.userId, ADMIN if this.userId != user_id profile = get_document user_id, "owner", Profiles if profile.locale throw new Meteor.Error("Not permitted.") if !user_id user_id = this.userId if !user_id throw new Meteor.Error("Not permitted.") self = this prepare_resume = (user) -> resume = {} profile = get_profile user if profile resume.name = get_profile_name profile, false, false resume.self_description = profile.resume resume.avatar = get_avatar profile solution_list = [] solution_cursor = get_documents user, OWNER, Solutions, {published: true} solution_cursor.forEach (s) -> solution = {} solution.reviews = [] solution.solution = if !s.confidential then s.content else null challenge = Challenges.findOne(s.challenge_id) if challenge solution.challenge = if !challenge.confidential then challenge.content else null solution.challenge_title = challenge.title owner = get_document_owner Challenges, challenge profile = get_document owner, OWNER, Profiles if profile solution.challenge_owner_avatar = get_avatar profile abs_rating = 0 num_ratings = 0 review_filter = solution_id: s._id review_cursor = Reviews.find(review_filter) review_cursor.forEach (r) -> review = {} filter = review_id: r._id feedback = Feedback.findOne filter owner = get_document_owner Profiles, r profile = get_profile owner if feedback.published review.feedback = {} review.feedback.content = feedback.content review.feedback.rating = feedback.rating review.rating = r.rating abs_rating += parseInt(r.rating) num_ratings += 1 if profile review.name = get_profile_name profile ,false ,false review.avatar = get_avatar profile review.review = r.content solution.reviews.push(review) if abs_rating avg = Math.round(abs_rating / num_ratings, 1) solution.average = avg solution_list.push(solution) resume.solutions = solution_list self.added("user_resumes", user._id, resume) filter = _id: user_id crs = Meteor.users.find(filter) crs.forEach(prepare_resume) log_publication crs, user_id, "user_resumes" self.ready() ####################################################### Meteor.publish "user_summary", (user_id, challenge_id) -> check user_id, String check challenge_id, String if user_id if not has_role Challenges, challenge_id, this.userId, DESIGNER throw new Meteor.Error("Not permitted.") if !user_id user_id = this.userId if !user_id throw new Meteor.Error("Not permitted.") ########################################## # Initialize user summary through users # database object ########################################## mod = fields: emails: 1 user = Meteor.users.findOne user_id, mod ########################################## # Same fields for solution review feedback ########################################## mod = fields: rating: 1 content: 1 material: 1 ########################################## # Find Solutions ########################################## ########################################## filter = {challenge_id: challenge_id} solutions = get_my_documents filter, mod ########################################## # Find relevant Feedback and Reviews ########################################## rev_given = get_my_documents Reviews.find filter, mod fed_given = get_my_documents Feedback.find filter, mod filter = requester_id: user_id challenge_id: challenge_id rev_received = Reviews.find filter, mod fed_received = Feedback.find filter, mod ########################################## # # Calculate statistics # ########################################## ########################################## # Solutions ########################################## material = 0 length = 0 count = solutions.count() solutions.forEach (entry) -> if entry.content length += entry.content.split(" ").length if entry.material material += 1 user.solutions_count = count user.solutions_average_length = length / count user.solutions_average_material = material / count ########################################## # Given Reviews ########################################## user = calc_statistics user, rev_given, "reviews_given" user = calc_statistics user, rev_received, "reviews_received" user = calc_statistics user, fed_given, "feedback_given" user = calc_statistics user, fed_received, "feedback_received" log_publication crs, this.userId, "user_summary" this.added "user_summaries", user_id, user this.ready() ############################################################################### Meteor.publish "team_members_by_organization_id", (organization_id) -> check organization_id, String user_id = this.userId if !user_id throw new Meteor.Error "Not permitted." member_ids = [] admission_cursor = get_admissions IGNORE, IGNORE, Organizations, organization_id admission_cursor.forEach (admission) -> member_ids.push admission.u options = fields: given_name: 1 middle_name: 1 family_name: 1 big_five: 1 avatar:1 self = this for user_id in member_ids profile = Profiles.findOne {user_id: user_id}, options mail = get_user_mail(user_id) name = get_profile_name profile, false, false member = name: name email: mail big_five: profile.big_five avatar: profile.avatar owner: user_id == self.userId self.added("team_members", user_id, member) log_publication admission_cursor, user_id, "team_members_by_organization_id" self.ready()
[ { "context": " update count key for redefine\n cnt_key = \"update#\"+key\n\n # reset counter\n if Listener[cnt_", "end": 1781, "score": 0.9137815237045288, "start": 1769, "tag": "KEY", "value": "update#\"+key" }, { "context": " writable: true\n\n instance_key = \"_\" + key\n Object.defineProperty Listener.protot", "end": 2038, "score": 0.9625080227851868, "start": 2033, "tag": "KEY", "value": "\"_\" +" } ]
src/injector.coffee
mizchi/injector.js
1
root = window ? exports ? this class root.Injector # rootInjector pass Injector#[method] rootInjector = new this @register : -> rootInjector.register arguments... @unregister : -> rootInjector.unregister arguments... @mapSingleton: -> rootInjector.mapSingleton arguments... @mapValue : -> rootInjector.mapValue arguments... @unmap : -> rootInjector.unmap arguments... @ensureProperties: (instance)-> for key of instance.constructor.inject if instance.hasOwnProperty key then throw new Error "Injected property must not be object own property" unless instance[key] then throw new Error "lack of [#{key}] on initialize" true _getInjectClass: (name) -> if (typeof name) is "string" val = @root for n in name.split('.') val = val[n] return val else if name instanceof Function return name() else return name constructor: (@root = root)-> @known_list = [] register: (Listener, inject = null) -> @known_list.push Listener for key of Listener.inject Object.defineProperty Listener.prototype, key, value: null writable: false configurable: true if inject then Listener.inject = inject unregister: (Listener)-> n = @known_list.indexOf(Listener) for key of Listener.inject Object.defineProperty Listener.prototype, key, get: -> @['_' + key] = null null configurable: true @known_list.splice n, 1 mapValue: (InjectClass, args...) -> @known_list.forEach (Listener) => for key, f of Listener.inject val = @_getInjectClass(f) if val isnt InjectClass then continue # update count key for redefine cnt_key = "update#"+key # reset counter if Listener[cnt_key]? Listener[cnt_key]++ else Object.defineProperty Listener, cnt_key, value: 0 enumerable: false writable: true instance_key = "_" + key Object.defineProperty Listener.prototype, key, enumerable: false configurable: true get: -> # remove instnace if value is redefined if Listener[cnt_key] > @[cnt_key] then delete @[instance_key] # when instance is not defined, create new unless @[instance_key] @[instance_key] = new InjectClass args... # reset counter Object.defineProperty @, cnt_key, value: Listener[cnt_key] enumerable: false configurable: true return @[instance_key] mapSingleton: (InjectClass, instance) -> unless instance instanceof InjectClass throw "#{instance} is not #{InjectorClass} instance" @known_list.forEach (Listener) => for key, f of Listener.inject val = @_getInjectClass(f) if val isnt InjectClass then continue # if Listener::[key] then throw "#{key} already exists" Listener::[key] = instance unmap: (InjectClass = null) -> @known_list.forEach (Listener) => for key, f of Listener.inject when !(InjectClass?) or @_getInjectClass(f) is InjectClass val = @_getInjectClass(f) Object.defineProperty Listener.prototype, key, value: null writable: false configurable: true if typeof define is 'function' and typeof define.amd is 'object' and define.amd define -> Injector
87354
root = window ? exports ? this class root.Injector # rootInjector pass Injector#[method] rootInjector = new this @register : -> rootInjector.register arguments... @unregister : -> rootInjector.unregister arguments... @mapSingleton: -> rootInjector.mapSingleton arguments... @mapValue : -> rootInjector.mapValue arguments... @unmap : -> rootInjector.unmap arguments... @ensureProperties: (instance)-> for key of instance.constructor.inject if instance.hasOwnProperty key then throw new Error "Injected property must not be object own property" unless instance[key] then throw new Error "lack of [#{key}] on initialize" true _getInjectClass: (name) -> if (typeof name) is "string" val = @root for n in name.split('.') val = val[n] return val else if name instanceof Function return name() else return name constructor: (@root = root)-> @known_list = [] register: (Listener, inject = null) -> @known_list.push Listener for key of Listener.inject Object.defineProperty Listener.prototype, key, value: null writable: false configurable: true if inject then Listener.inject = inject unregister: (Listener)-> n = @known_list.indexOf(Listener) for key of Listener.inject Object.defineProperty Listener.prototype, key, get: -> @['_' + key] = null null configurable: true @known_list.splice n, 1 mapValue: (InjectClass, args...) -> @known_list.forEach (Listener) => for key, f of Listener.inject val = @_getInjectClass(f) if val isnt InjectClass then continue # update count key for redefine cnt_key = "<KEY> # reset counter if Listener[cnt_key]? Listener[cnt_key]++ else Object.defineProperty Listener, cnt_key, value: 0 enumerable: false writable: true instance_key = <KEY> key Object.defineProperty Listener.prototype, key, enumerable: false configurable: true get: -> # remove instnace if value is redefined if Listener[cnt_key] > @[cnt_key] then delete @[instance_key] # when instance is not defined, create new unless @[instance_key] @[instance_key] = new InjectClass args... # reset counter Object.defineProperty @, cnt_key, value: Listener[cnt_key] enumerable: false configurable: true return @[instance_key] mapSingleton: (InjectClass, instance) -> unless instance instanceof InjectClass throw "#{instance} is not #{InjectorClass} instance" @known_list.forEach (Listener) => for key, f of Listener.inject val = @_getInjectClass(f) if val isnt InjectClass then continue # if Listener::[key] then throw "#{key} already exists" Listener::[key] = instance unmap: (InjectClass = null) -> @known_list.forEach (Listener) => for key, f of Listener.inject when !(InjectClass?) or @_getInjectClass(f) is InjectClass val = @_getInjectClass(f) Object.defineProperty Listener.prototype, key, value: null writable: false configurable: true if typeof define is 'function' and typeof define.amd is 'object' and define.amd define -> Injector
true
root = window ? exports ? this class root.Injector # rootInjector pass Injector#[method] rootInjector = new this @register : -> rootInjector.register arguments... @unregister : -> rootInjector.unregister arguments... @mapSingleton: -> rootInjector.mapSingleton arguments... @mapValue : -> rootInjector.mapValue arguments... @unmap : -> rootInjector.unmap arguments... @ensureProperties: (instance)-> for key of instance.constructor.inject if instance.hasOwnProperty key then throw new Error "Injected property must not be object own property" unless instance[key] then throw new Error "lack of [#{key}] on initialize" true _getInjectClass: (name) -> if (typeof name) is "string" val = @root for n in name.split('.') val = val[n] return val else if name instanceof Function return name() else return name constructor: (@root = root)-> @known_list = [] register: (Listener, inject = null) -> @known_list.push Listener for key of Listener.inject Object.defineProperty Listener.prototype, key, value: null writable: false configurable: true if inject then Listener.inject = inject unregister: (Listener)-> n = @known_list.indexOf(Listener) for key of Listener.inject Object.defineProperty Listener.prototype, key, get: -> @['_' + key] = null null configurable: true @known_list.splice n, 1 mapValue: (InjectClass, args...) -> @known_list.forEach (Listener) => for key, f of Listener.inject val = @_getInjectClass(f) if val isnt InjectClass then continue # update count key for redefine cnt_key = "PI:KEY:<KEY>END_PI # reset counter if Listener[cnt_key]? Listener[cnt_key]++ else Object.defineProperty Listener, cnt_key, value: 0 enumerable: false writable: true instance_key = PI:KEY:<KEY>END_PI key Object.defineProperty Listener.prototype, key, enumerable: false configurable: true get: -> # remove instnace if value is redefined if Listener[cnt_key] > @[cnt_key] then delete @[instance_key] # when instance is not defined, create new unless @[instance_key] @[instance_key] = new InjectClass args... # reset counter Object.defineProperty @, cnt_key, value: Listener[cnt_key] enumerable: false configurable: true return @[instance_key] mapSingleton: (InjectClass, instance) -> unless instance instanceof InjectClass throw "#{instance} is not #{InjectorClass} instance" @known_list.forEach (Listener) => for key, f of Listener.inject val = @_getInjectClass(f) if val isnt InjectClass then continue # if Listener::[key] then throw "#{key} already exists" Listener::[key] = instance unmap: (InjectClass = null) -> @known_list.forEach (Listener) => for key, f of Listener.inject when !(InjectClass?) or @_getInjectClass(f) is InjectClass val = @_getInjectClass(f) Object.defineProperty Listener.prototype, key, value: null writable: false configurable: true if typeof define is 'function' and typeof define.amd is 'object' and define.amd define -> Injector
[ { "context": "rce \"#{database}/#{collection}/:id\"\n , {apiKey: 'h18zCyIluqeZTTcASk1tJBv-zOfNGgFi'}\n , update:\n method: 'PUT'\n\n Res.prototyp", "end": 239, "score": 0.9997599124908447, "start": 207, "tag": "KEY", "value": "h18zCyIluqeZTTcASk1tJBv-zOfNGgFi" } ]
app/scripts/services.coffee
kynan/UniversityChallenge
0
'use strict' mongolabResource = (collection, $resource) -> database = 'https://api.mongolab.com/api/1/databases/uni-challenge/collections' Res = $resource "#{database}/#{collection}/:id" , {apiKey: 'h18zCyIluqeZTTcASk1tJBv-zOfNGgFi'} , update: method: 'PUT' Res.prototype.update = (cb) -> Res.update {id: @_id.$oid} , angular.extend({}, @, {_id: undefined}) , cb Res.prototype.destroy = (cb) -> Res.remove id: @_id.$oid, cb return Res angular.module('mongolab', ['ngResource']) .factory 'Team', ($resource) -> mongolabResource 'teams', $resource .factory 'Game', ($resource) -> mongolabResource 'games', $resource
70808
'use strict' mongolabResource = (collection, $resource) -> database = 'https://api.mongolab.com/api/1/databases/uni-challenge/collections' Res = $resource "#{database}/#{collection}/:id" , {apiKey: '<KEY>'} , update: method: 'PUT' Res.prototype.update = (cb) -> Res.update {id: @_id.$oid} , angular.extend({}, @, {_id: undefined}) , cb Res.prototype.destroy = (cb) -> Res.remove id: @_id.$oid, cb return Res angular.module('mongolab', ['ngResource']) .factory 'Team', ($resource) -> mongolabResource 'teams', $resource .factory 'Game', ($resource) -> mongolabResource 'games', $resource
true
'use strict' mongolabResource = (collection, $resource) -> database = 'https://api.mongolab.com/api/1/databases/uni-challenge/collections' Res = $resource "#{database}/#{collection}/:id" , {apiKey: 'PI:KEY:<KEY>END_PI'} , update: method: 'PUT' Res.prototype.update = (cb) -> Res.update {id: @_id.$oid} , angular.extend({}, @, {_id: undefined}) , cb Res.prototype.destroy = (cb) -> Res.remove id: @_id.$oid, cb return Res angular.module('mongolab', ['ngResource']) .factory 'Team', ($resource) -> mongolabResource 'teams', $resource .factory 'Game', ($resource) -> mongolabResource 'games', $resource
[ { "context": " hal.formatter( req, res, body ).should.equal( 'VGhlIHJvb3RzIG9mIGVkdWNhdGlvbiBhcmUgYml0dGVyLCBidXQgdGhlIGZydWl0IGlzIHN3ZWV0Lg==' )\n res.setHeader.should.have.been.calledWith", "end": 1493, "score": 0.9879952073097229, "start": 1412, "tag": "KEY", "value": "VGhlIHJvb3RzIG9mIGVkdWNhdGlvbiBhcmUgYml0dGVyLCBidXQgdGhlIGZydWl0IGlzIHN3ZWV0Lg=='" }, { "context": "er: sinon.stub()\n body =\n person: 'Dr. Seuss'\n quote: 'Today you are you! That is truer", "end": 2353, "score": 0.9995713233947754, "start": 2348, "tag": "NAME", "value": "Seuss" }, { "context": " req, res, body ).should.equal( \"{\\\"person\\\":\\\"Dr. Seuss\\\",\\\"quote\\\":\\\"Today you are you! That is truer th", "end": 2603, "score": 0.9994540214538574, "start": 2598, "tag": "NAME", "value": "Seuss" }, { "context": "e': [\n {\n href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0'\n ", "end": 3855, "score": 0.9989749193191528, "start": 3819, "tag": "KEY", "value": "66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf" }, { "context": "rcle': [\n {\n personaKey: '66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf'\n circleKey: 'fc097d4b-95a9-4c21-b7c", "end": 4206, "score": 0.9997093081474304, "start": 4170, "tag": "KEY", "value": "66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf" }, { "context": "47fb-bc4d-c5bf4f5d2abf'\n circleKey: 'fc097d4b-95a9-4c21-b7cd-5164253e05b0'\n }\n ]\n )\n\n specify '", "end": 4270, "score": 0.9997043609619141, "start": 4234, "tag": "KEY", "value": "fc097d4b-95a9-4c21-b7cd-5164253e05b0" }, { "context": " 'joukou:circle':\n href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0'\n ", "end": 4502, "score": 0.9985378384590149, "start": 4466, "tag": "KEY", "value": "66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf" }, { "context": "rcle': [\n {\n personaKey: '66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf'\n circleKey: 'fc097d4b-95a9-4c21-b7c", "end": 4865, "score": 0.9997215270996094, "start": 4829, "tag": "KEY", "value": "66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf" }, { "context": "47fb-bc4d-c5bf4f5d2abf'\n circleKey: 'fc097d4b-95a9-4c21-b7cd-5164253e05b0'\n }\n ]\n )\n\n specify '", "end": 4929, "score": 0.999704897403717, "start": 4893, "tag": "KEY", "value": "fc097d4b-95a9-4c21-b7cd-5164253e05b0" }, { "context": "oukou:agent': [\n {\n key: '01b2b14c-1d1b-4112-85f0-1f4bc6c9961c'\n name: 'admin'\n }\n ", "end": 5578, "score": 0.9997469186782837, "start": 5542, "tag": "KEY", "value": "01b2b14c-1d1b-4112-85f0-1f4bc6c9961c" }, { "context": "1d1b-4112-85f0-1f4bc6c9961c'\n name: 'admin'\n }\n ]\n )\n\n specify '", "end": 5606, "score": 0.6549388766288757, "start": 5601, "tag": "NAME", "value": "admin" }, { "context": "\n {\n href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0'\n ", "end": 7655, "score": 0.5475263595581055, "start": 7620, "tag": "PASSWORD", "value": "6d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf" }, { "context": " }\n {\n name: 'bogus'\n }\n ]\n ,\n ", "end": 8497, "score": 0.9932242631912231, "start": 8492, "tag": "NAME", "value": "bogus" } ]
test/hal.coffee
joukou/joukou-api
0
###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### assert = require( 'assert' ) chai = require( 'chai' ) should = chai.should() sinonChai = require( 'sinon-chai' ) sinon = require( 'sinon' ) chai.use( sinonChai ) _ = require( 'lodash' ) http = require( 'http' ) hal = require( '../dist/hal' ) { RestError, ForbiddenError } = require( 'restify' ) describe 'joukou-api/hal', -> describe '.formatter( req, res, body )', -> specify 'is defined', -> should.exist( hal.formatter ) hal.formatter.should.be.a( 'function' ) specify 'is the base64 encoded representation of a Buffer', -> req = {} res = setHeader: sinon.stub() body = new Buffer( 'The roots of education are bitter, but the fruit is sweet.' ) hal.formatter( req, res, body ).should.equal( 'VGhlIHJvb3RzIG9mIGVkdWNhdGlvbiBhcmUgYml0dGVyLCBidXQgdGhlIGZydWl0IGlzIHN3ZWV0Lg==' ) res.setHeader.should.have.been.calledWith( 'Content-Length', 80 ) specify 'is the application/vnd.error+json representation of an Error', -> req = {} res = setHeader: sinon.stub() body = new RestError( restCode: 'TeapotError' statusCode: 418 message: 'I\'m a teapot' ) hal.formatter( req, res, body ).should.equal( '{"logref":"TeapotError","message":"I\'m a teapot"}' ) res.statusCode.should.equal( 418 ) res.setHeader.should.have.been.calledWith( 'Content-Length', 49 ) res.setHeader.should.have.been.calledWith( 'Content-Type', 'application/vnd.error+json' ) specify 'is the application/hal+json representation of an object', -> req = path: -> '/test' res = setHeader: sinon.stub() body = person: 'Dr. Seuss' quote: 'Today you are you! That is truer than true! There is no one alive who is you-er than you!' middleware = hal.link() middleware( req, res, -> ) hal.formatter( req, res, body ).should.equal( "{\"person\":\"Dr. Seuss\",\"quote\":\"Today you are you! That is truer than true! There is no one alive who is you-er than you!\",\"_links\":{\"self\":{\"href\":\"/test\"},\"curies\":[{\"name\":\"joukou\",\"templated\":true,\"href\":\"https://rels.joukou.com/{rel}\"}]}}" ) res.setHeader.should.have.been.calledWith( 'Content-Length', 242 ) describe '.link() middleware', -> specify 'is defined', -> should.exist( hal.link ) hal.link.should.be.a( 'function' ) specify 'returns a middleware function', -> fn = hal.link() should.exist( fn ) fn.should.be.a( 'function' ) specify 'the returned middleware function adds a .link() method to the response object', ( done ) -> fn = hal.link() req = {} res = {} next = -> should.exist( res.link ) res.link.should.be.a( 'function' ) done() fn( req, res, next ) describe '.parse( hal, schema )', -> specify 'parses an empty document', -> hal.parse( {}, {} ).should.deep.equal( embedded: {} links: {} ) specify 'parses a joukou:circle link', -> hal.parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ).should.deep.equal( embedded: {} links: 'joukou:circle': [ { personaKey: '66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf' circleKey: 'fc097d4b-95a9-4c21-b7cd-5164253e05b0' } ] ) specify 'normalizes a Link Object to an array of Link Objects', -> hal.parse( _links: 'joukou:circle': href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' , links: 'joukou:circle': min: 1 max: 1 match: '/persona/:personaKey/circle/:circleKey' ).should.deep.equal( embedded: {} links: 'joukou:circle': [ { personaKey: '66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf' circleKey: 'fc097d4b-95a9-4c21-b7cd-5164253e05b0' } ] ) specify 'parses a joukou:agent link with a name property', -> hal.parse( _links: 'joukou:agent': [ { href: '/agent/01b2b14c-1d1b-4112-85f0-1f4bc6c9961c' name: 'admin' } ] , links: 'joukou:agent': match: '/agent/:key' name: required: true type: 'enum' values: [ 'admin' ] ).should.deep.equal( embedded: {} links: 'joukou:agent': [ { key: '01b2b14c-1d1b-4112-85f0-1f4bc6c9961c' name: 'admin' } ] ) specify 'throws ForbiddenError if _links is not an object', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: true , {} ) ) fn.should.throw( ForbiddenError, /_links must be an object/ ) specify 'throws ForbiddenError if the link relation type is not defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:bogus': [ { href: '/bogus/01b2b14c-1d1b-4112-85f0-1f4bc6c9961c' } ] , links: 'joukou:agent': match: '/bogus/:key' ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:bogus is not supported for this resource/ ) specify 'throws ForbiddenError if a link relation type is not defined and the schema has a minimum defined', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: {} , links: 'joukou:circle': min: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support less than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a link relation type has less Link Objects than the minimum defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [] , links: 'joukou:circle': min: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support less than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a link relation type has more Link Objects than the maximum defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } { href: '/persona/87191f78-e4c0-438c-80d4-2fff7301ff52/circle/ebfa28dc-e262-4f8d-a2b2-03874e5950d3' } ] , links: 'joukou:circle': max: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support more than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a Link Object does not have a href property', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } { name: 'bogus' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ) ) fn.should.throw( ForbiddenError, /Link Objects must have a href property/ ) specify 'throws ForbiddenError if a Link Object\'s href property does not match the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ) ) fn.should.throw( ForbiddenError, /failed to extract keys from href property/ ) specify 'throws ForbiddenError if a Link Object is missing a required name property', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' name: required: true ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle requires a name property/ ) specify 'throws ForbiddenError if a Link Object\'s name property does not match an enum type', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' name: 'bogus' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' name: required: true type: 'enum' values: [ 'an_enum' ] ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle requires a name property value that is one of: an_enum/ )
92178
###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### assert = require( 'assert' ) chai = require( 'chai' ) should = chai.should() sinonChai = require( 'sinon-chai' ) sinon = require( 'sinon' ) chai.use( sinonChai ) _ = require( 'lodash' ) http = require( 'http' ) hal = require( '../dist/hal' ) { RestError, ForbiddenError } = require( 'restify' ) describe 'joukou-api/hal', -> describe '.formatter( req, res, body )', -> specify 'is defined', -> should.exist( hal.formatter ) hal.formatter.should.be.a( 'function' ) specify 'is the base64 encoded representation of a Buffer', -> req = {} res = setHeader: sinon.stub() body = new Buffer( 'The roots of education are bitter, but the fruit is sweet.' ) hal.formatter( req, res, body ).should.equal( '<KEY> ) res.setHeader.should.have.been.calledWith( 'Content-Length', 80 ) specify 'is the application/vnd.error+json representation of an Error', -> req = {} res = setHeader: sinon.stub() body = new RestError( restCode: 'TeapotError' statusCode: 418 message: 'I\'m a teapot' ) hal.formatter( req, res, body ).should.equal( '{"logref":"TeapotError","message":"I\'m a teapot"}' ) res.statusCode.should.equal( 418 ) res.setHeader.should.have.been.calledWith( 'Content-Length', 49 ) res.setHeader.should.have.been.calledWith( 'Content-Type', 'application/vnd.error+json' ) specify 'is the application/hal+json representation of an object', -> req = path: -> '/test' res = setHeader: sinon.stub() body = person: 'Dr. <NAME>' quote: 'Today you are you! That is truer than true! There is no one alive who is you-er than you!' middleware = hal.link() middleware( req, res, -> ) hal.formatter( req, res, body ).should.equal( "{\"person\":\"Dr. <NAME>\",\"quote\":\"Today you are you! That is truer than true! There is no one alive who is you-er than you!\",\"_links\":{\"self\":{\"href\":\"/test\"},\"curies\":[{\"name\":\"joukou\",\"templated\":true,\"href\":\"https://rels.joukou.com/{rel}\"}]}}" ) res.setHeader.should.have.been.calledWith( 'Content-Length', 242 ) describe '.link() middleware', -> specify 'is defined', -> should.exist( hal.link ) hal.link.should.be.a( 'function' ) specify 'returns a middleware function', -> fn = hal.link() should.exist( fn ) fn.should.be.a( 'function' ) specify 'the returned middleware function adds a .link() method to the response object', ( done ) -> fn = hal.link() req = {} res = {} next = -> should.exist( res.link ) res.link.should.be.a( 'function' ) done() fn( req, res, next ) describe '.parse( hal, schema )', -> specify 'parses an empty document', -> hal.parse( {}, {} ).should.deep.equal( embedded: {} links: {} ) specify 'parses a joukou:circle link', -> hal.parse( _links: 'joukou:circle': [ { href: '/persona/<KEY>/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ).should.deep.equal( embedded: {} links: 'joukou:circle': [ { personaKey: '<KEY>' circleKey: '<KEY>' } ] ) specify 'normalizes a Link Object to an array of Link Objects', -> hal.parse( _links: 'joukou:circle': href: '/persona/<KEY>/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' , links: 'joukou:circle': min: 1 max: 1 match: '/persona/:personaKey/circle/:circleKey' ).should.deep.equal( embedded: {} links: 'joukou:circle': [ { personaKey: '<KEY>' circleKey: '<KEY>' } ] ) specify 'parses a joukou:agent link with a name property', -> hal.parse( _links: 'joukou:agent': [ { href: '/agent/01b2b14c-1d1b-4112-85f0-1f4bc6c9961c' name: 'admin' } ] , links: 'joukou:agent': match: '/agent/:key' name: required: true type: 'enum' values: [ 'admin' ] ).should.deep.equal( embedded: {} links: 'joukou:agent': [ { key: '<KEY>' name: '<NAME>' } ] ) specify 'throws ForbiddenError if _links is not an object', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: true , {} ) ) fn.should.throw( ForbiddenError, /_links must be an object/ ) specify 'throws ForbiddenError if the link relation type is not defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:bogus': [ { href: '/bogus/01b2b14c-1d1b-4112-85f0-1f4bc6c9961c' } ] , links: 'joukou:agent': match: '/bogus/:key' ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:bogus is not supported for this resource/ ) specify 'throws ForbiddenError if a link relation type is not defined and the schema has a minimum defined', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: {} , links: 'joukou:circle': min: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support less than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a link relation type has less Link Objects than the minimum defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [] , links: 'joukou:circle': min: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support less than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a link relation type has more Link Objects than the maximum defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/6<PASSWORD>/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } { href: '/persona/87191f78-e4c0-438c-80d4-2fff7301ff52/circle/ebfa28dc-e262-4f8d-a2b2-03874e5950d3' } ] , links: 'joukou:circle': max: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support more than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a Link Object does not have a href property', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } { name: '<NAME>' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ) ) fn.should.throw( ForbiddenError, /Link Objects must have a href property/ ) specify 'throws ForbiddenError if a Link Object\'s href property does not match the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ) ) fn.should.throw( ForbiddenError, /failed to extract keys from href property/ ) specify 'throws ForbiddenError if a Link Object is missing a required name property', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' name: required: true ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle requires a name property/ ) specify 'throws ForbiddenError if a Link Object\'s name property does not match an enum type', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' name: 'bogus' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' name: required: true type: 'enum' values: [ 'an_enum' ] ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle requires a name property value that is one of: an_enum/ )
true
###* Copyright 2014 Joukou Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### assert = require( 'assert' ) chai = require( 'chai' ) should = chai.should() sinonChai = require( 'sinon-chai' ) sinon = require( 'sinon' ) chai.use( sinonChai ) _ = require( 'lodash' ) http = require( 'http' ) hal = require( '../dist/hal' ) { RestError, ForbiddenError } = require( 'restify' ) describe 'joukou-api/hal', -> describe '.formatter( req, res, body )', -> specify 'is defined', -> should.exist( hal.formatter ) hal.formatter.should.be.a( 'function' ) specify 'is the base64 encoded representation of a Buffer', -> req = {} res = setHeader: sinon.stub() body = new Buffer( 'The roots of education are bitter, but the fruit is sweet.' ) hal.formatter( req, res, body ).should.equal( 'PI:KEY:<KEY>END_PI ) res.setHeader.should.have.been.calledWith( 'Content-Length', 80 ) specify 'is the application/vnd.error+json representation of an Error', -> req = {} res = setHeader: sinon.stub() body = new RestError( restCode: 'TeapotError' statusCode: 418 message: 'I\'m a teapot' ) hal.formatter( req, res, body ).should.equal( '{"logref":"TeapotError","message":"I\'m a teapot"}' ) res.statusCode.should.equal( 418 ) res.setHeader.should.have.been.calledWith( 'Content-Length', 49 ) res.setHeader.should.have.been.calledWith( 'Content-Type', 'application/vnd.error+json' ) specify 'is the application/hal+json representation of an object', -> req = path: -> '/test' res = setHeader: sinon.stub() body = person: 'Dr. PI:NAME:<NAME>END_PI' quote: 'Today you are you! That is truer than true! There is no one alive who is you-er than you!' middleware = hal.link() middleware( req, res, -> ) hal.formatter( req, res, body ).should.equal( "{\"person\":\"Dr. PI:NAME:<NAME>END_PI\",\"quote\":\"Today you are you! That is truer than true! There is no one alive who is you-er than you!\",\"_links\":{\"self\":{\"href\":\"/test\"},\"curies\":[{\"name\":\"joukou\",\"templated\":true,\"href\":\"https://rels.joukou.com/{rel}\"}]}}" ) res.setHeader.should.have.been.calledWith( 'Content-Length', 242 ) describe '.link() middleware', -> specify 'is defined', -> should.exist( hal.link ) hal.link.should.be.a( 'function' ) specify 'returns a middleware function', -> fn = hal.link() should.exist( fn ) fn.should.be.a( 'function' ) specify 'the returned middleware function adds a .link() method to the response object', ( done ) -> fn = hal.link() req = {} res = {} next = -> should.exist( res.link ) res.link.should.be.a( 'function' ) done() fn( req, res, next ) describe '.parse( hal, schema )', -> specify 'parses an empty document', -> hal.parse( {}, {} ).should.deep.equal( embedded: {} links: {} ) specify 'parses a joukou:circle link', -> hal.parse( _links: 'joukou:circle': [ { href: '/persona/PI:KEY:<KEY>END_PI/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ).should.deep.equal( embedded: {} links: 'joukou:circle': [ { personaKey: 'PI:KEY:<KEY>END_PI' circleKey: 'PI:KEY:<KEY>END_PI' } ] ) specify 'normalizes a Link Object to an array of Link Objects', -> hal.parse( _links: 'joukou:circle': href: '/persona/PI:KEY:<KEY>END_PI/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' , links: 'joukou:circle': min: 1 max: 1 match: '/persona/:personaKey/circle/:circleKey' ).should.deep.equal( embedded: {} links: 'joukou:circle': [ { personaKey: 'PI:KEY:<KEY>END_PI' circleKey: 'PI:KEY:<KEY>END_PI' } ] ) specify 'parses a joukou:agent link with a name property', -> hal.parse( _links: 'joukou:agent': [ { href: '/agent/01b2b14c-1d1b-4112-85f0-1f4bc6c9961c' name: 'admin' } ] , links: 'joukou:agent': match: '/agent/:key' name: required: true type: 'enum' values: [ 'admin' ] ).should.deep.equal( embedded: {} links: 'joukou:agent': [ { key: 'PI:KEY:<KEY>END_PI' name: 'PI:NAME:<NAME>END_PI' } ] ) specify 'throws ForbiddenError if _links is not an object', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: true , {} ) ) fn.should.throw( ForbiddenError, /_links must be an object/ ) specify 'throws ForbiddenError if the link relation type is not defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:bogus': [ { href: '/bogus/01b2b14c-1d1b-4112-85f0-1f4bc6c9961c' } ] , links: 'joukou:agent': match: '/bogus/:key' ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:bogus is not supported for this resource/ ) specify 'throws ForbiddenError if a link relation type is not defined and the schema has a minimum defined', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: {} , links: 'joukou:circle': min: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support less than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a link relation type has less Link Objects than the minimum defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [] , links: 'joukou:circle': min: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support less than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a link relation type has more Link Objects than the maximum defined in the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/6PI:PASSWORD:<PASSWORD>END_PI/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } { href: '/persona/87191f78-e4c0-438c-80d4-2fff7301ff52/circle/ebfa28dc-e262-4f8d-a2b2-03874e5950d3' } ] , links: 'joukou:circle': max: 1 ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle does not support more than 1 Link Objects for this resource/ ) specify 'throws ForbiddenError if a Link Object does not have a href property', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } { name: 'PI:NAME:<NAME>END_PI' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ) ) fn.should.throw( ForbiddenError, /Link Objects must have a href property/ ) specify 'throws ForbiddenError if a Link Object\'s href property does not match the schema', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' ) ) fn.should.throw( ForbiddenError, /failed to extract keys from href property/ ) specify 'throws ForbiddenError if a Link Object is missing a required name property', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' name: required: true ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle requires a name property/ ) specify 'throws ForbiddenError if a Link Object\'s name property does not match an enum type', -> fn = _.wrap( hal.parse, ( parse ) -> parse( _links: 'joukou:circle': [ { href: '/persona/66d223ce-bb6c-47fb-bc4d-c5bf4f5d2abf/circle/fc097d4b-95a9-4c21-b7cd-5164253e05b0' name: 'bogus' } ] , links: 'joukou:circle': match: '/persona/:personaKey/circle/:circleKey' name: required: true type: 'enum' values: [ 'an_enum' ] ) ) fn.should.throw( ForbiddenError, /the link relation type joukou:circle requires a name property value that is one of: an_enum/ )
[ { "context": " })\n @txt2 = new PIXI.Text('¡Hola! Mi nombre es Terrence y yo seré \\n el encargado de guiarte en esta aven", "end": 5400, "score": 0.9997307062149048, "start": 5392, "tag": "NAME", "value": "Terrence" } ]
sockets/client/desktop/appDesktop.coffee
ArtIsaacs/ExtRun
0
$ = require 'jquery' gsap = require 'gsap' mathjs = require 'mathjs' PIXI = require 'pixi.js' ExDino = require './elements/ExDino' Rect = require './elements/Rect' BgImageBonita = './scripts/assets/bottombonito2.png' BgImageBonita2 = './scripts/assets/bottombonito2-2.png' BgCieloBonito = './scripts/assets/cielobonito.png' BgCieloBonito2 = './scripts/assets/cielobonito-2.png' BgVolcanBonito = './scripts/assets/intro4.png' BgVolcanBonito2 = './scripts/assets/intro4-2.png' BgNubesBonito = './scripts/assets/intro6.png' BgNubesBonito2 = './scripts/assets/intro6-2.png' BgBosqueBonitoBh = './scripts/assets/intro5.png' BgBosqueBonitoBh2 = './scripts/assets/intro5-2.png' BgBosqueBonitoFr = './scripts/assets/intro7.png' BgBosqueBonitoFr2 = './scripts/assets/intro7-2.png' Terrence = './scripts/assets/Terrence2.jpg' BgInstrucciones = './scripts/assets/boton1.png' Backgrounds = require './elements/backgroundDesktop' Instrucciones = require './elements/Instrucciones' DinoData = 'http://localhost:3000/scripts/assets/sprites.json' ShadowData = 'http://localhost:3000/scripts/assets/sombra.json' EnemyData = 'http://localhost:3000/scripts/assets/enemyjson.json' Obstacles = require './elements/Obstacles' ObstaclesAnimations = require './elements/ObstaclesAnimations' Shadow = require './elements/Shadows' class DesktopApp extends PIXI.Application animation:true animationNodes:[] obstaculos: [] pause: false score: 0 jumpcount: 0 constructor: (config, socket) -> super(config) @socket = socket @socket.on 'send:accelerometer', @movimiento PIXI.loader.add(DinoData).add(ShadowData).add(EnemyData).load(@buildApp) getResponse: (r) => @data = r PIXI.loader.add(DinoData).load(@buildApp) buildApp:=> @sheet = PIXI.loader.resources["http://localhost:3000/scripts/assets/sprites.json"] @sheet2 = PIXI.loader.resources["http://localhost:3000/scripts/assets/sombra.json"] $('body').html @view @buildBackgrounds() @dino = new ExDino(@, @sheet.spritesheet) @sombras = new Shadow(@, @sheet2.spritesheet) @dino.width = 351 @dino.height = 162 @buildObstacles() @animate() @buildText() @buildInstrucciones() @movimiento() buildBackgrounds: () => @bgCieloBonito = new Backgrounds(BgCieloBonito) @bgCieloBonito.width = 2100 @bgCieloBonito.height = 780 @stage.addChild(@bgCieloBonito) @bgCieloBonito2 = new Backgrounds(BgCieloBonito) @bgCieloBonito2.x = 2100 @bgCieloBonito2.width = 2100 @bgCieloBonito2.height = 780 @stage.addChild(@bgCieloBonito2) @bgVolcan = new Backgrounds(BgVolcanBonito) @bgVolcan.x = 0 @bgVolcan.y = 140 @bgVolcan.height = 540 @bgVolcan.width = 1920 @stage.addChild(@bgVolcan) @bgNubes = new Backgrounds(BgNubesBonito) @bgNubes.width = 1610 @bgNubes.height = 250 @stage.addChild(@bgNubes) @bgNubes2 = new Backgrounds(BgNubesBonito) @bgNubes2.width = 1610 @bgNubes2.height = 250 @bgNubes2.x = 1610 @stage.addChild(@bgNubes2) @bgForestBehind = new Backgrounds(BgBosqueBonitoBh) @bgForestBehind.width = 1920 @bgForestBehind.height = 342 @bgForestBehind.y = 300 @stage.addChild(@bgForestBehind) @bgForestBehind2 = new Backgrounds(BgBosqueBonitoBh) @bgForestBehind2.width = 1920 @bgForestBehind2.height = 342 @bgForestBehind2.y = 300 @bgForestBehind2.x = 1920 @stage.addChild(@bgForestBehind2) @bgForestFront = new Backgrounds(BgBosqueBonitoFr) @bgForestFront.y = 380 @bgForestFront.width = 2100 @bgForestFront.height = 240 @stage.addChild(@bgForestFront) @bgForestFront2 = new Backgrounds(BgBosqueBonitoFr) @bgForestFront2.y = 380 @bgForestFront2.width = 2100 @bgForestFront2.height = 240 @bgForestFront2.x = 2100 @stage.addChild(@bgForestFront2) @bgPath = new Backgrounds(BgImageBonita) @bgPath.y = 440 @bgPath.height = 318 @bgPath.width = 2880 @stage.addChild(@bgPath) @bgPath2 = new Backgrounds(BgImageBonita) @bgPath2.y = 440 @bgPath2.height = 318 @bgPath2.width = 2880 @bgPath2.x = 2880 @stage.addChild(@bgPath2) buildObstacles: () => @sheet3 = PIXI.loader.resources["http://localhost:3000/scripts/assets/enemyjson.json"] return if @pause setTimeout => setInterval => type = mathjs.randomInt(1,3) @obstacles = new ObstaclesAnimations(type, @, @sheet3.spritesheet) , 6000 ,5000 buildText: () -> textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 26 }) @txt = new PIXI.Text("Score \n #{@score}", textStyle) @txt.x = window.innerWidth / 2 - @txt.width / 2 @txt.y = 20 rect = new Rect(100, 100) @stage.addChild(rect) @stage.addChild(@txt) buildInstrucciones: () => @bgInstrucciones = new Instrucciones(BgInstrucciones) @bgInstrucciones.alpha = 1 @stage.addChild(@bgInstrucciones) @terrence = new Instrucciones(Terrence) @terrence.width = 200 @terrence.height = 200 @terrence.x = @bgInstrucciones.x + 70 @terrence.y = @bgInstrucciones.y + 30 @terrence.alpha = 1 @stage.addChild(@terrence) textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 23 }) @txt2 = new PIXI.Text('¡Hola! Mi nombre es Terrence y yo seré \n el encargado de guiarte en esta aventura. \n Para saltar, debes hacerlo con tu celular \n en el bolsillo', textStyle) @txt2.x = @bgInstrucciones.x + 300 @txt2.y = @bgInstrucciones.y + 70 @txt2.alpha = 1 @stage.addChild(@txt2) movimiento: (evt) => @obj = JSON.parse(evt) moveY = @obj.y moveX = @obj.x moveZ = @obj.z return if @pause == true @bgCieloBonito.x -= 2 @bgCieloBonito2.x -= 2 @bgNubes.x -= 3.5 @bgNubes2.x -= 3.5 @bgForestBehind.x -= 4 @bgForestBehind2.x -= 4 @bgForestFront.x -= 4.5 @bgForestFront2.x -= 4.5 @bgPath.x -= 9 @bgPath2.x -= 9 if @bgCieloBonito.x is 0 @bgCieloBonito2.x = 2100 if @bgCieloBonito2.x is 0 @bgCieloBonito.x = 2100 if @bgNubes.x is 0 @bgNubes2.x = 1610 if @bgNubes2.x is 0 @bgNubes.x = 1610 if @bgForestBehind.x is 0 @bgForestBehind2.x = 1920 if @bgForestBehind2.x is 0 @bgForestBehind.x = 1920 if @bgForestFront.x is 0 @bgForestFront2.x = 2100 if @bgForestFront2.x is 0 @bgForestFront.x = 2100 if @bgPath.x is 0 @bgPath2.x = 2880 if @bgPath2.x is 0 @bgPath.x = 2880 if moveX >= 9 || moveX <= -9 @dino.isRunning = true @sombras.isRunning = true else @dino.isRunning = false @sombras.isRunning = false if moveY >= 30 && @dino.isJumping == false && @dino.isRunning == false @dino.jump() @jumpcount = @jumpcount + 1 if moveY >= 30 && @sombras.isJumping == false && @sombras.isRunning == false @sombras.jump() if @jumpcount == 1 @bgInstrucciones.alpha = 0 @terrence.alpha = 0 @txt2.alpha = 0 return if @jumpcount == 0 @score = @score += 1 @txt.text = "Score \n #{@score}" colisiones: (obj1, rect) => if (obj1.x < rect.x + rect.width && obj1.x + obj1.width > rect.x) if (obj1.y < rect.y + rect.height && obj1.y + obj1.height > rect.y) if obj1.isJumping == false obj1.isDead = true obj1.dead() @sombras.isDead = true @sombras.dead() @pause = true textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 23 }) @txt3 = new PIXI.Text('Para volver a jugar, refresca la pagina en tu celular y en tu computadora', textStyle) @txt3.x = window.innerWidth / 2 - @txt3.width / 2 @txt3.y = window.innerHeight / 4 @txt3.alpha = 1 @stage.addChild(@txt3) @bgInstrucciones.alpha = 1 @bgInstrucciones.x = @txt3.x - 60 @bgInstrucciones.y = @txt3.y - 50 @bgInstrucciones.width = @txt3.width + 150 @bgInstrucciones.height = @txt.height + 90 garbageCollector: (item) => animationChild = @animationNodes.indexOf(item) if (animationChild > -1) @animationNodes.splice(animationChild, 1) stageChild = @stage.children.indexOf(item) if (stageChild > -1) @stage.children.splice(stageChild, 1) addAnimationNodes:(child)=> @animationNodes.push child null animate:=> @ticker.add ()=> for n in @animationNodes n.animate?() module.exports = DesktopApp
62458
$ = require 'jquery' gsap = require 'gsap' mathjs = require 'mathjs' PIXI = require 'pixi.js' ExDino = require './elements/ExDino' Rect = require './elements/Rect' BgImageBonita = './scripts/assets/bottombonito2.png' BgImageBonita2 = './scripts/assets/bottombonito2-2.png' BgCieloBonito = './scripts/assets/cielobonito.png' BgCieloBonito2 = './scripts/assets/cielobonito-2.png' BgVolcanBonito = './scripts/assets/intro4.png' BgVolcanBonito2 = './scripts/assets/intro4-2.png' BgNubesBonito = './scripts/assets/intro6.png' BgNubesBonito2 = './scripts/assets/intro6-2.png' BgBosqueBonitoBh = './scripts/assets/intro5.png' BgBosqueBonitoBh2 = './scripts/assets/intro5-2.png' BgBosqueBonitoFr = './scripts/assets/intro7.png' BgBosqueBonitoFr2 = './scripts/assets/intro7-2.png' Terrence = './scripts/assets/Terrence2.jpg' BgInstrucciones = './scripts/assets/boton1.png' Backgrounds = require './elements/backgroundDesktop' Instrucciones = require './elements/Instrucciones' DinoData = 'http://localhost:3000/scripts/assets/sprites.json' ShadowData = 'http://localhost:3000/scripts/assets/sombra.json' EnemyData = 'http://localhost:3000/scripts/assets/enemyjson.json' Obstacles = require './elements/Obstacles' ObstaclesAnimations = require './elements/ObstaclesAnimations' Shadow = require './elements/Shadows' class DesktopApp extends PIXI.Application animation:true animationNodes:[] obstaculos: [] pause: false score: 0 jumpcount: 0 constructor: (config, socket) -> super(config) @socket = socket @socket.on 'send:accelerometer', @movimiento PIXI.loader.add(DinoData).add(ShadowData).add(EnemyData).load(@buildApp) getResponse: (r) => @data = r PIXI.loader.add(DinoData).load(@buildApp) buildApp:=> @sheet = PIXI.loader.resources["http://localhost:3000/scripts/assets/sprites.json"] @sheet2 = PIXI.loader.resources["http://localhost:3000/scripts/assets/sombra.json"] $('body').html @view @buildBackgrounds() @dino = new ExDino(@, @sheet.spritesheet) @sombras = new Shadow(@, @sheet2.spritesheet) @dino.width = 351 @dino.height = 162 @buildObstacles() @animate() @buildText() @buildInstrucciones() @movimiento() buildBackgrounds: () => @bgCieloBonito = new Backgrounds(BgCieloBonito) @bgCieloBonito.width = 2100 @bgCieloBonito.height = 780 @stage.addChild(@bgCieloBonito) @bgCieloBonito2 = new Backgrounds(BgCieloBonito) @bgCieloBonito2.x = 2100 @bgCieloBonito2.width = 2100 @bgCieloBonito2.height = 780 @stage.addChild(@bgCieloBonito2) @bgVolcan = new Backgrounds(BgVolcanBonito) @bgVolcan.x = 0 @bgVolcan.y = 140 @bgVolcan.height = 540 @bgVolcan.width = 1920 @stage.addChild(@bgVolcan) @bgNubes = new Backgrounds(BgNubesBonito) @bgNubes.width = 1610 @bgNubes.height = 250 @stage.addChild(@bgNubes) @bgNubes2 = new Backgrounds(BgNubesBonito) @bgNubes2.width = 1610 @bgNubes2.height = 250 @bgNubes2.x = 1610 @stage.addChild(@bgNubes2) @bgForestBehind = new Backgrounds(BgBosqueBonitoBh) @bgForestBehind.width = 1920 @bgForestBehind.height = 342 @bgForestBehind.y = 300 @stage.addChild(@bgForestBehind) @bgForestBehind2 = new Backgrounds(BgBosqueBonitoBh) @bgForestBehind2.width = 1920 @bgForestBehind2.height = 342 @bgForestBehind2.y = 300 @bgForestBehind2.x = 1920 @stage.addChild(@bgForestBehind2) @bgForestFront = new Backgrounds(BgBosqueBonitoFr) @bgForestFront.y = 380 @bgForestFront.width = 2100 @bgForestFront.height = 240 @stage.addChild(@bgForestFront) @bgForestFront2 = new Backgrounds(BgBosqueBonitoFr) @bgForestFront2.y = 380 @bgForestFront2.width = 2100 @bgForestFront2.height = 240 @bgForestFront2.x = 2100 @stage.addChild(@bgForestFront2) @bgPath = new Backgrounds(BgImageBonita) @bgPath.y = 440 @bgPath.height = 318 @bgPath.width = 2880 @stage.addChild(@bgPath) @bgPath2 = new Backgrounds(BgImageBonita) @bgPath2.y = 440 @bgPath2.height = 318 @bgPath2.width = 2880 @bgPath2.x = 2880 @stage.addChild(@bgPath2) buildObstacles: () => @sheet3 = PIXI.loader.resources["http://localhost:3000/scripts/assets/enemyjson.json"] return if @pause setTimeout => setInterval => type = mathjs.randomInt(1,3) @obstacles = new ObstaclesAnimations(type, @, @sheet3.spritesheet) , 6000 ,5000 buildText: () -> textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 26 }) @txt = new PIXI.Text("Score \n #{@score}", textStyle) @txt.x = window.innerWidth / 2 - @txt.width / 2 @txt.y = 20 rect = new Rect(100, 100) @stage.addChild(rect) @stage.addChild(@txt) buildInstrucciones: () => @bgInstrucciones = new Instrucciones(BgInstrucciones) @bgInstrucciones.alpha = 1 @stage.addChild(@bgInstrucciones) @terrence = new Instrucciones(Terrence) @terrence.width = 200 @terrence.height = 200 @terrence.x = @bgInstrucciones.x + 70 @terrence.y = @bgInstrucciones.y + 30 @terrence.alpha = 1 @stage.addChild(@terrence) textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 23 }) @txt2 = new PIXI.Text('¡Hola! Mi nombre es <NAME> y yo seré \n el encargado de guiarte en esta aventura. \n Para saltar, debes hacerlo con tu celular \n en el bolsillo', textStyle) @txt2.x = @bgInstrucciones.x + 300 @txt2.y = @bgInstrucciones.y + 70 @txt2.alpha = 1 @stage.addChild(@txt2) movimiento: (evt) => @obj = JSON.parse(evt) moveY = @obj.y moveX = @obj.x moveZ = @obj.z return if @pause == true @bgCieloBonito.x -= 2 @bgCieloBonito2.x -= 2 @bgNubes.x -= 3.5 @bgNubes2.x -= 3.5 @bgForestBehind.x -= 4 @bgForestBehind2.x -= 4 @bgForestFront.x -= 4.5 @bgForestFront2.x -= 4.5 @bgPath.x -= 9 @bgPath2.x -= 9 if @bgCieloBonito.x is 0 @bgCieloBonito2.x = 2100 if @bgCieloBonito2.x is 0 @bgCieloBonito.x = 2100 if @bgNubes.x is 0 @bgNubes2.x = 1610 if @bgNubes2.x is 0 @bgNubes.x = 1610 if @bgForestBehind.x is 0 @bgForestBehind2.x = 1920 if @bgForestBehind2.x is 0 @bgForestBehind.x = 1920 if @bgForestFront.x is 0 @bgForestFront2.x = 2100 if @bgForestFront2.x is 0 @bgForestFront.x = 2100 if @bgPath.x is 0 @bgPath2.x = 2880 if @bgPath2.x is 0 @bgPath.x = 2880 if moveX >= 9 || moveX <= -9 @dino.isRunning = true @sombras.isRunning = true else @dino.isRunning = false @sombras.isRunning = false if moveY >= 30 && @dino.isJumping == false && @dino.isRunning == false @dino.jump() @jumpcount = @jumpcount + 1 if moveY >= 30 && @sombras.isJumping == false && @sombras.isRunning == false @sombras.jump() if @jumpcount == 1 @bgInstrucciones.alpha = 0 @terrence.alpha = 0 @txt2.alpha = 0 return if @jumpcount == 0 @score = @score += 1 @txt.text = "Score \n #{@score}" colisiones: (obj1, rect) => if (obj1.x < rect.x + rect.width && obj1.x + obj1.width > rect.x) if (obj1.y < rect.y + rect.height && obj1.y + obj1.height > rect.y) if obj1.isJumping == false obj1.isDead = true obj1.dead() @sombras.isDead = true @sombras.dead() @pause = true textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 23 }) @txt3 = new PIXI.Text('Para volver a jugar, refresca la pagina en tu celular y en tu computadora', textStyle) @txt3.x = window.innerWidth / 2 - @txt3.width / 2 @txt3.y = window.innerHeight / 4 @txt3.alpha = 1 @stage.addChild(@txt3) @bgInstrucciones.alpha = 1 @bgInstrucciones.x = @txt3.x - 60 @bgInstrucciones.y = @txt3.y - 50 @bgInstrucciones.width = @txt3.width + 150 @bgInstrucciones.height = @txt.height + 90 garbageCollector: (item) => animationChild = @animationNodes.indexOf(item) if (animationChild > -1) @animationNodes.splice(animationChild, 1) stageChild = @stage.children.indexOf(item) if (stageChild > -1) @stage.children.splice(stageChild, 1) addAnimationNodes:(child)=> @animationNodes.push child null animate:=> @ticker.add ()=> for n in @animationNodes n.animate?() module.exports = DesktopApp
true
$ = require 'jquery' gsap = require 'gsap' mathjs = require 'mathjs' PIXI = require 'pixi.js' ExDino = require './elements/ExDino' Rect = require './elements/Rect' BgImageBonita = './scripts/assets/bottombonito2.png' BgImageBonita2 = './scripts/assets/bottombonito2-2.png' BgCieloBonito = './scripts/assets/cielobonito.png' BgCieloBonito2 = './scripts/assets/cielobonito-2.png' BgVolcanBonito = './scripts/assets/intro4.png' BgVolcanBonito2 = './scripts/assets/intro4-2.png' BgNubesBonito = './scripts/assets/intro6.png' BgNubesBonito2 = './scripts/assets/intro6-2.png' BgBosqueBonitoBh = './scripts/assets/intro5.png' BgBosqueBonitoBh2 = './scripts/assets/intro5-2.png' BgBosqueBonitoFr = './scripts/assets/intro7.png' BgBosqueBonitoFr2 = './scripts/assets/intro7-2.png' Terrence = './scripts/assets/Terrence2.jpg' BgInstrucciones = './scripts/assets/boton1.png' Backgrounds = require './elements/backgroundDesktop' Instrucciones = require './elements/Instrucciones' DinoData = 'http://localhost:3000/scripts/assets/sprites.json' ShadowData = 'http://localhost:3000/scripts/assets/sombra.json' EnemyData = 'http://localhost:3000/scripts/assets/enemyjson.json' Obstacles = require './elements/Obstacles' ObstaclesAnimations = require './elements/ObstaclesAnimations' Shadow = require './elements/Shadows' class DesktopApp extends PIXI.Application animation:true animationNodes:[] obstaculos: [] pause: false score: 0 jumpcount: 0 constructor: (config, socket) -> super(config) @socket = socket @socket.on 'send:accelerometer', @movimiento PIXI.loader.add(DinoData).add(ShadowData).add(EnemyData).load(@buildApp) getResponse: (r) => @data = r PIXI.loader.add(DinoData).load(@buildApp) buildApp:=> @sheet = PIXI.loader.resources["http://localhost:3000/scripts/assets/sprites.json"] @sheet2 = PIXI.loader.resources["http://localhost:3000/scripts/assets/sombra.json"] $('body').html @view @buildBackgrounds() @dino = new ExDino(@, @sheet.spritesheet) @sombras = new Shadow(@, @sheet2.spritesheet) @dino.width = 351 @dino.height = 162 @buildObstacles() @animate() @buildText() @buildInstrucciones() @movimiento() buildBackgrounds: () => @bgCieloBonito = new Backgrounds(BgCieloBonito) @bgCieloBonito.width = 2100 @bgCieloBonito.height = 780 @stage.addChild(@bgCieloBonito) @bgCieloBonito2 = new Backgrounds(BgCieloBonito) @bgCieloBonito2.x = 2100 @bgCieloBonito2.width = 2100 @bgCieloBonito2.height = 780 @stage.addChild(@bgCieloBonito2) @bgVolcan = new Backgrounds(BgVolcanBonito) @bgVolcan.x = 0 @bgVolcan.y = 140 @bgVolcan.height = 540 @bgVolcan.width = 1920 @stage.addChild(@bgVolcan) @bgNubes = new Backgrounds(BgNubesBonito) @bgNubes.width = 1610 @bgNubes.height = 250 @stage.addChild(@bgNubes) @bgNubes2 = new Backgrounds(BgNubesBonito) @bgNubes2.width = 1610 @bgNubes2.height = 250 @bgNubes2.x = 1610 @stage.addChild(@bgNubes2) @bgForestBehind = new Backgrounds(BgBosqueBonitoBh) @bgForestBehind.width = 1920 @bgForestBehind.height = 342 @bgForestBehind.y = 300 @stage.addChild(@bgForestBehind) @bgForestBehind2 = new Backgrounds(BgBosqueBonitoBh) @bgForestBehind2.width = 1920 @bgForestBehind2.height = 342 @bgForestBehind2.y = 300 @bgForestBehind2.x = 1920 @stage.addChild(@bgForestBehind2) @bgForestFront = new Backgrounds(BgBosqueBonitoFr) @bgForestFront.y = 380 @bgForestFront.width = 2100 @bgForestFront.height = 240 @stage.addChild(@bgForestFront) @bgForestFront2 = new Backgrounds(BgBosqueBonitoFr) @bgForestFront2.y = 380 @bgForestFront2.width = 2100 @bgForestFront2.height = 240 @bgForestFront2.x = 2100 @stage.addChild(@bgForestFront2) @bgPath = new Backgrounds(BgImageBonita) @bgPath.y = 440 @bgPath.height = 318 @bgPath.width = 2880 @stage.addChild(@bgPath) @bgPath2 = new Backgrounds(BgImageBonita) @bgPath2.y = 440 @bgPath2.height = 318 @bgPath2.width = 2880 @bgPath2.x = 2880 @stage.addChild(@bgPath2) buildObstacles: () => @sheet3 = PIXI.loader.resources["http://localhost:3000/scripts/assets/enemyjson.json"] return if @pause setTimeout => setInterval => type = mathjs.randomInt(1,3) @obstacles = new ObstaclesAnimations(type, @, @sheet3.spritesheet) , 6000 ,5000 buildText: () -> textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 26 }) @txt = new PIXI.Text("Score \n #{@score}", textStyle) @txt.x = window.innerWidth / 2 - @txt.width / 2 @txt.y = 20 rect = new Rect(100, 100) @stage.addChild(rect) @stage.addChild(@txt) buildInstrucciones: () => @bgInstrucciones = new Instrucciones(BgInstrucciones) @bgInstrucciones.alpha = 1 @stage.addChild(@bgInstrucciones) @terrence = new Instrucciones(Terrence) @terrence.width = 200 @terrence.height = 200 @terrence.x = @bgInstrucciones.x + 70 @terrence.y = @bgInstrucciones.y + 30 @terrence.alpha = 1 @stage.addChild(@terrence) textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 23 }) @txt2 = new PIXI.Text('¡Hola! Mi nombre es PI:NAME:<NAME>END_PI y yo seré \n el encargado de guiarte en esta aventura. \n Para saltar, debes hacerlo con tu celular \n en el bolsillo', textStyle) @txt2.x = @bgInstrucciones.x + 300 @txt2.y = @bgInstrucciones.y + 70 @txt2.alpha = 1 @stage.addChild(@txt2) movimiento: (evt) => @obj = JSON.parse(evt) moveY = @obj.y moveX = @obj.x moveZ = @obj.z return if @pause == true @bgCieloBonito.x -= 2 @bgCieloBonito2.x -= 2 @bgNubes.x -= 3.5 @bgNubes2.x -= 3.5 @bgForestBehind.x -= 4 @bgForestBehind2.x -= 4 @bgForestFront.x -= 4.5 @bgForestFront2.x -= 4.5 @bgPath.x -= 9 @bgPath2.x -= 9 if @bgCieloBonito.x is 0 @bgCieloBonito2.x = 2100 if @bgCieloBonito2.x is 0 @bgCieloBonito.x = 2100 if @bgNubes.x is 0 @bgNubes2.x = 1610 if @bgNubes2.x is 0 @bgNubes.x = 1610 if @bgForestBehind.x is 0 @bgForestBehind2.x = 1920 if @bgForestBehind2.x is 0 @bgForestBehind.x = 1920 if @bgForestFront.x is 0 @bgForestFront2.x = 2100 if @bgForestFront2.x is 0 @bgForestFront.x = 2100 if @bgPath.x is 0 @bgPath2.x = 2880 if @bgPath2.x is 0 @bgPath.x = 2880 if moveX >= 9 || moveX <= -9 @dino.isRunning = true @sombras.isRunning = true else @dino.isRunning = false @sombras.isRunning = false if moveY >= 30 && @dino.isJumping == false && @dino.isRunning == false @dino.jump() @jumpcount = @jumpcount + 1 if moveY >= 30 && @sombras.isJumping == false && @sombras.isRunning == false @sombras.jump() if @jumpcount == 1 @bgInstrucciones.alpha = 0 @terrence.alpha = 0 @txt2.alpha = 0 return if @jumpcount == 0 @score = @score += 1 @txt.text = "Score \n #{@score}" colisiones: (obj1, rect) => if (obj1.x < rect.x + rect.width && obj1.x + obj1.width > rect.x) if (obj1.y < rect.y + rect.height && obj1.y + obj1.height > rect.y) if obj1.isJumping == false obj1.isDead = true obj1.dead() @sombras.isDead = true @sombras.dead() @pause = true textStyle = new PIXI.TextStyle({ fontFamily: 'Arial' fill: 'white' fontSize: 23 }) @txt3 = new PIXI.Text('Para volver a jugar, refresca la pagina en tu celular y en tu computadora', textStyle) @txt3.x = window.innerWidth / 2 - @txt3.width / 2 @txt3.y = window.innerHeight / 4 @txt3.alpha = 1 @stage.addChild(@txt3) @bgInstrucciones.alpha = 1 @bgInstrucciones.x = @txt3.x - 60 @bgInstrucciones.y = @txt3.y - 50 @bgInstrucciones.width = @txt3.width + 150 @bgInstrucciones.height = @txt.height + 90 garbageCollector: (item) => animationChild = @animationNodes.indexOf(item) if (animationChild > -1) @animationNodes.splice(animationChild, 1) stageChild = @stage.children.indexOf(item) if (stageChild > -1) @stage.children.splice(stageChild, 1) addAnimationNodes:(child)=> @animationNodes.push child null animate:=> @ticker.add ()=> for n in @animationNodes n.animate?() module.exports = DesktopApp
[ { "context": "s when spellThang.thang.exists).join(', ') # + \", Marcus, Robert, Phoebe, Will Smith, Zap Brannigan, You, ", "end": 1239, "score": 0.999809741973877, "start": 1233, "tag": "NAME", "value": "Marcus" }, { "context": "pellThang.thang.exists).join(', ') # + \", Marcus, Robert, Phoebe, Will Smith, Zap Brannigan, You, Gandaaaa", "end": 1247, "score": 0.9752433896064758, "start": 1241, "tag": "NAME", "value": "Robert" }, { "context": "g.thang.exists).join(', ') # + \", Marcus, Robert, Phoebe, Will Smith, Zap Brannigan, You, Gandaaaaalf\"\n ", "end": 1255, "score": 0.9969565272331238, "start": 1249, "tag": "NAME", "value": "Phoebe" }, { "context": "exists).join(', ') # + \", Marcus, Robert, Phoebe, Will Smith, Zap Brannigan, You, Gandaaaaalf\"\n context.sho", "end": 1267, "score": 0.9996633529663086, "start": 1257, "tag": "NAME", "value": "Will Smith" }, { "context": "(', ') # + \", Marcus, Robert, Phoebe, Will Smith, Zap Brannigan, You, Gandaaaaalf\"\n context.showTopDivider = @", "end": 1282, "score": 0.9996480941772461, "start": 1269, "tag": "NAME", "value": "Zap Brannigan" }, { "context": "s, Robert, Phoebe, Will Smith, Zap Brannigan, You, Gandaaaaalf\"\n context.showTopDivider = @showTopDivider\n ", "end": 1300, "score": 0.9916996359825134, "start": 1289, "tag": "NAME", "value": "Gandaaaaalf" } ]
app/views/play/level/tome/spell_list_entry_view.coffee
madawei2699/codecombat
1
# TODO: This still needs a way to send problem states to its Thang View = require 'views/kinds/CocoView' ThangAvatarView = require 'views/play/level/thang_avatar_view' SpellListEntryThangsView = require 'views/play/level/tome/spell_list_entry_thangs_view' template = require 'templates/play/level/tome/spell_list_entry' module.exports = class SpellListEntryView extends View tagName: 'div' #'li' className: 'spell-list-entry-view' template: template controlsEnabled: true subscriptions: 'tome:problems-updated': "onProblemsUpdated" 'level-disable-controls': 'onDisableControls' 'level-enable-controls': 'onEnableControls' 'god:new-world-created': 'onNewWorld' events: 'click': 'onClick' 'mouseenter .thang-avatar-view': 'onMouseEnterAvatar' 'mouseleave .thang-avatar-view': 'onMouseLeaveAvatar' constructor: (options) -> super options @spell = options.spell @showTopDivider = options.showTopDivider getRenderData: (context={}) -> context = super context context.spell = @spell context.parameters = (@spell.parameters or []).join ', ' context.thangNames = (thangID for thangID, spellThang of @spell.thangs when spellThang.thang.exists).join(', ') # + ", Marcus, Robert, Phoebe, Will Smith, Zap Brannigan, You, Gandaaaaalf" context.showTopDivider = @showTopDivider context getPrimarySpellThang: -> if @lastSelectedThang spellThang = _.find @spell.thangs, (spellThang) => spellThang.thang.id is @lastSelectedThang.id return spellThang if spellThang for thangID, spellThang of @spell.thangs continue unless spellThang.thang.exists return spellThang # Just do the first one else afterRender: -> super() return unless @options.showTopDivider # Don't repeat Thang avatars when not changed from previous entry return @$el.hide() unless spellThang = @getPrimarySpellThang() @$el.show() @avatar?.destroy() @avatar = new ThangAvatarView thang: spellThang.thang, includeName: false, supermodel: @supermodel @$el.prepend @avatar.el # Before rendering, so render can use parent for popover @avatar.render() @avatar.setSharedThangs _.size @spell.thangs @$el.addClass 'shows-top-divider' if @options.showTopDivider setSelected: (selected, @lastSelectedThang) -> @avatar?.setSelected selected onClick: (e) -> spellThang = @getPrimarySpellThang() Backbone.Mediator.publish "level-select-sprite", thangID: spellThang.thang.id, spellName: @spell.name onMouseEnterAvatar: (e) -> return unless @controlsEnabled and _.size(@spell.thangs) > 1 @showThangs() onMouseLeaveAvatar: (e) -> return unless @controlsEnabled and _.size(@spell.thangs) > 1 @hideThangsTimeout = _.delay @hideThangs, 100 showThangs: -> clearTimeout @hideThangsTimeout if @hideThangsTimeout return if @thangsView spellThang = @getPrimarySpellThang() return unless spellThang @thangsView = new SpellListEntryThangsView thangs: (spellThang.thang for thangID, spellThang of @spell.thangs), thang: spellTHang.thang, spell: @spell, supermodel: @supermodel @thangsView.render() @$el.append @thangsView.el @thangsView.$el.mouseenter (e) => @onMouseEnterAvatar() @thangsView.$el.mouseleave (e) => @onMouseLeaveAvatar() hideThangs: => return unless @thangsView @thangsView.off 'mouseenter mouseleave' @thangsView.$el.remove() @thangsView.destroy() @thangsView = null onProblemsUpdated: (e) -> return unless e.spell is @spell @$el.toggleClass "user-code-problem", e.problems.length onDisableControls: (e) -> @toggleControls e, false onEnableControls: (e) -> @toggleControls e, true toggleControls: (e, enabled) -> return if e.controls and not ('editor' in e.controls) return if enabled is @controlsEnabled @controlsEnabled = enabled disabled = not enabled # Should refactor the disabling list so we can target the spell list separately? # Should not call it 'editor' any more? @$el.toggleClass('disabled', disabled).find('*').prop('disabled', disabled) onNewWorld: (e) -> @lastSelectedThang = e.world.thangMap[@lastSelectedThang.id] if @lastSelectedThang destroy: -> @avatar?.destroy() super()
213947
# TODO: This still needs a way to send problem states to its Thang View = require 'views/kinds/CocoView' ThangAvatarView = require 'views/play/level/thang_avatar_view' SpellListEntryThangsView = require 'views/play/level/tome/spell_list_entry_thangs_view' template = require 'templates/play/level/tome/spell_list_entry' module.exports = class SpellListEntryView extends View tagName: 'div' #'li' className: 'spell-list-entry-view' template: template controlsEnabled: true subscriptions: 'tome:problems-updated': "onProblemsUpdated" 'level-disable-controls': 'onDisableControls' 'level-enable-controls': 'onEnableControls' 'god:new-world-created': 'onNewWorld' events: 'click': 'onClick' 'mouseenter .thang-avatar-view': 'onMouseEnterAvatar' 'mouseleave .thang-avatar-view': 'onMouseLeaveAvatar' constructor: (options) -> super options @spell = options.spell @showTopDivider = options.showTopDivider getRenderData: (context={}) -> context = super context context.spell = @spell context.parameters = (@spell.parameters or []).join ', ' context.thangNames = (thangID for thangID, spellThang of @spell.thangs when spellThang.thang.exists).join(', ') # + ", <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, You, <NAME>" context.showTopDivider = @showTopDivider context getPrimarySpellThang: -> if @lastSelectedThang spellThang = _.find @spell.thangs, (spellThang) => spellThang.thang.id is @lastSelectedThang.id return spellThang if spellThang for thangID, spellThang of @spell.thangs continue unless spellThang.thang.exists return spellThang # Just do the first one else afterRender: -> super() return unless @options.showTopDivider # Don't repeat Thang avatars when not changed from previous entry return @$el.hide() unless spellThang = @getPrimarySpellThang() @$el.show() @avatar?.destroy() @avatar = new ThangAvatarView thang: spellThang.thang, includeName: false, supermodel: @supermodel @$el.prepend @avatar.el # Before rendering, so render can use parent for popover @avatar.render() @avatar.setSharedThangs _.size @spell.thangs @$el.addClass 'shows-top-divider' if @options.showTopDivider setSelected: (selected, @lastSelectedThang) -> @avatar?.setSelected selected onClick: (e) -> spellThang = @getPrimarySpellThang() Backbone.Mediator.publish "level-select-sprite", thangID: spellThang.thang.id, spellName: @spell.name onMouseEnterAvatar: (e) -> return unless @controlsEnabled and _.size(@spell.thangs) > 1 @showThangs() onMouseLeaveAvatar: (e) -> return unless @controlsEnabled and _.size(@spell.thangs) > 1 @hideThangsTimeout = _.delay @hideThangs, 100 showThangs: -> clearTimeout @hideThangsTimeout if @hideThangsTimeout return if @thangsView spellThang = @getPrimarySpellThang() return unless spellThang @thangsView = new SpellListEntryThangsView thangs: (spellThang.thang for thangID, spellThang of @spell.thangs), thang: spellTHang.thang, spell: @spell, supermodel: @supermodel @thangsView.render() @$el.append @thangsView.el @thangsView.$el.mouseenter (e) => @onMouseEnterAvatar() @thangsView.$el.mouseleave (e) => @onMouseLeaveAvatar() hideThangs: => return unless @thangsView @thangsView.off 'mouseenter mouseleave' @thangsView.$el.remove() @thangsView.destroy() @thangsView = null onProblemsUpdated: (e) -> return unless e.spell is @spell @$el.toggleClass "user-code-problem", e.problems.length onDisableControls: (e) -> @toggleControls e, false onEnableControls: (e) -> @toggleControls e, true toggleControls: (e, enabled) -> return if e.controls and not ('editor' in e.controls) return if enabled is @controlsEnabled @controlsEnabled = enabled disabled = not enabled # Should refactor the disabling list so we can target the spell list separately? # Should not call it 'editor' any more? @$el.toggleClass('disabled', disabled).find('*').prop('disabled', disabled) onNewWorld: (e) -> @lastSelectedThang = e.world.thangMap[@lastSelectedThang.id] if @lastSelectedThang destroy: -> @avatar?.destroy() super()
true
# TODO: This still needs a way to send problem states to its Thang View = require 'views/kinds/CocoView' ThangAvatarView = require 'views/play/level/thang_avatar_view' SpellListEntryThangsView = require 'views/play/level/tome/spell_list_entry_thangs_view' template = require 'templates/play/level/tome/spell_list_entry' module.exports = class SpellListEntryView extends View tagName: 'div' #'li' className: 'spell-list-entry-view' template: template controlsEnabled: true subscriptions: 'tome:problems-updated': "onProblemsUpdated" 'level-disable-controls': 'onDisableControls' 'level-enable-controls': 'onEnableControls' 'god:new-world-created': 'onNewWorld' events: 'click': 'onClick' 'mouseenter .thang-avatar-view': 'onMouseEnterAvatar' 'mouseleave .thang-avatar-view': 'onMouseLeaveAvatar' constructor: (options) -> super options @spell = options.spell @showTopDivider = options.showTopDivider getRenderData: (context={}) -> context = super context context.spell = @spell context.parameters = (@spell.parameters or []).join ', ' context.thangNames = (thangID for thangID, spellThang of @spell.thangs when spellThang.thang.exists).join(', ') # + ", PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, You, PI:NAME:<NAME>END_PI" context.showTopDivider = @showTopDivider context getPrimarySpellThang: -> if @lastSelectedThang spellThang = _.find @spell.thangs, (spellThang) => spellThang.thang.id is @lastSelectedThang.id return spellThang if spellThang for thangID, spellThang of @spell.thangs continue unless spellThang.thang.exists return spellThang # Just do the first one else afterRender: -> super() return unless @options.showTopDivider # Don't repeat Thang avatars when not changed from previous entry return @$el.hide() unless spellThang = @getPrimarySpellThang() @$el.show() @avatar?.destroy() @avatar = new ThangAvatarView thang: spellThang.thang, includeName: false, supermodel: @supermodel @$el.prepend @avatar.el # Before rendering, so render can use parent for popover @avatar.render() @avatar.setSharedThangs _.size @spell.thangs @$el.addClass 'shows-top-divider' if @options.showTopDivider setSelected: (selected, @lastSelectedThang) -> @avatar?.setSelected selected onClick: (e) -> spellThang = @getPrimarySpellThang() Backbone.Mediator.publish "level-select-sprite", thangID: spellThang.thang.id, spellName: @spell.name onMouseEnterAvatar: (e) -> return unless @controlsEnabled and _.size(@spell.thangs) > 1 @showThangs() onMouseLeaveAvatar: (e) -> return unless @controlsEnabled and _.size(@spell.thangs) > 1 @hideThangsTimeout = _.delay @hideThangs, 100 showThangs: -> clearTimeout @hideThangsTimeout if @hideThangsTimeout return if @thangsView spellThang = @getPrimarySpellThang() return unless spellThang @thangsView = new SpellListEntryThangsView thangs: (spellThang.thang for thangID, spellThang of @spell.thangs), thang: spellTHang.thang, spell: @spell, supermodel: @supermodel @thangsView.render() @$el.append @thangsView.el @thangsView.$el.mouseenter (e) => @onMouseEnterAvatar() @thangsView.$el.mouseleave (e) => @onMouseLeaveAvatar() hideThangs: => return unless @thangsView @thangsView.off 'mouseenter mouseleave' @thangsView.$el.remove() @thangsView.destroy() @thangsView = null onProblemsUpdated: (e) -> return unless e.spell is @spell @$el.toggleClass "user-code-problem", e.problems.length onDisableControls: (e) -> @toggleControls e, false onEnableControls: (e) -> @toggleControls e, true toggleControls: (e, enabled) -> return if e.controls and not ('editor' in e.controls) return if enabled is @controlsEnabled @controlsEnabled = enabled disabled = not enabled # Should refactor the disabling list so we can target the spell list separately? # Should not call it 'editor' any more? @$el.toggleClass('disabled', disabled).find('*').prop('disabled', disabled) onNewWorld: (e) -> @lastSelectedThang = e.world.thangMap[@lastSelectedThang.id] if @lastSelectedThang destroy: -> @avatar?.destroy() super()
[ { "context": " \n # Approximate angle calculation courtesy of Jordan Clist\n # http://www.jaycodesign.co.nz/js/using-googl", "end": 2901, "score": 0.9560808539390564, "start": 2889, "tag": "NAME", "value": "Jordan Clist" } ]
web/js/views/map_location_marker.coffee
reitti/reittiopas
3
define ['jquery', 'hbs!template/map_location_marker', "async!http://maps.googleapis.com/maps/api/js?sensor=true#{window.gmapsKey}"], ($, template) -> WIDTH = 150 HEIGHT = 20 class MapLocationMarker extends google.maps.OverlayView constructor: ({@leg, @location, @name, @anchor, @originOrDestination}) -> @setMap(@leg.map) onAdd: -> @div = $(template(anchor: @anchor, content: @name))[0] @getPanes().floatPane.appendChild(@div) $('.streetview-icon', @div).on 'click', @onStreetViewClicked $(@div).on 'click', @onClicked @_checkStreetViewAvailability() onRemove: -> @div.parentNode.removeChild(@div) @div = null draw: -> {x, y} = @getProjection().fromLatLngToDivPixel(@location) # TODO: There's something fishy with these magic offsets here. switch @anchor when 'top' x -= WIDTH / 2 + 2 y -= (HEIGHT + 10) + 3 when 'bottom' x -= WIDTH / 2 + 3 y -= 1 when 'left' x -= (WIDTH + 10) + 3 y -= HEIGHT / 2 + 2 when 'right' y -= HEIGHT / 2 + 2 x -= 2 @div.style.left = "#{x}px" @div.style.top = "#{y}px" onStreetViewClicked: => @leg.map.getStreetView().setVisible(true) @leg.map.getStreetView().setPosition(@location) @leg.map.getStreetView().setPov(heading: @heading, pitch: 0, zoom: 0) onClicked: => Reitti.Router.navigateToRoutes _.extend(@leg.routeParams, legIndex: @leg.index, originOrDestination: @originOrDestination) false onRoutesChanged: (routes, routeParams) => if @leg.isSelectedIn(routes, routeParams) and routeParams.originOrDestination is @originOrDestination if @leg.map.getStreetView().getVisible() @onStreetViewClicked() @markerAnchor: (latLng, latLngs) -> if @_isNorthMost(latLng, latLngs) 'top' else if @_isSouthMost(latLng, latLngs) 'bottom' else if @_isEastMost(latLng, latLngs) 'left' else 'right' @_isNorthMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lat() > latLng.lat() true @_isSouthMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lat() < latLng.lat() true @_isEastMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lng() < latLng.lng() true _checkStreetViewAvailability: () -> new google.maps.StreetViewService().getPanoramaByLocation @location, 30, (panoramaData, streetviewStatus) => if streetviewStatus is 'OK' @heading = @_computeAngle(panoramaData.location.latLng) $('.streetview-icon', @div).show() # Approximate angle calculation courtesy of Jordan Clist # http://www.jaycodesign.co.nz/js/using-google-maps-to-show-a-streetview-of-a-house-based-on-an-address/ _computeAngle: (availableLatLng) -> DEGREE_PER_RADIAN = 57.2957795 RADIAN_PER_DEGREE = 0.017453 dlat = @location.lat() - availableLatLng.lat() dlng = @location.lng() - availableLatLng.lng() yaw = Math.atan2(dlng * Math.cos(@location.lat() * RADIAN_PER_DEGREE), dlat) * DEGREE_PER_RADIAN @_wrapAngle(yaw) _wrapAngle: (angle) -> if angle >= 360 angle -= 360 else if angle < 0 angle += 360 angle
156963
define ['jquery', 'hbs!template/map_location_marker', "async!http://maps.googleapis.com/maps/api/js?sensor=true#{window.gmapsKey}"], ($, template) -> WIDTH = 150 HEIGHT = 20 class MapLocationMarker extends google.maps.OverlayView constructor: ({@leg, @location, @name, @anchor, @originOrDestination}) -> @setMap(@leg.map) onAdd: -> @div = $(template(anchor: @anchor, content: @name))[0] @getPanes().floatPane.appendChild(@div) $('.streetview-icon', @div).on 'click', @onStreetViewClicked $(@div).on 'click', @onClicked @_checkStreetViewAvailability() onRemove: -> @div.parentNode.removeChild(@div) @div = null draw: -> {x, y} = @getProjection().fromLatLngToDivPixel(@location) # TODO: There's something fishy with these magic offsets here. switch @anchor when 'top' x -= WIDTH / 2 + 2 y -= (HEIGHT + 10) + 3 when 'bottom' x -= WIDTH / 2 + 3 y -= 1 when 'left' x -= (WIDTH + 10) + 3 y -= HEIGHT / 2 + 2 when 'right' y -= HEIGHT / 2 + 2 x -= 2 @div.style.left = "#{x}px" @div.style.top = "#{y}px" onStreetViewClicked: => @leg.map.getStreetView().setVisible(true) @leg.map.getStreetView().setPosition(@location) @leg.map.getStreetView().setPov(heading: @heading, pitch: 0, zoom: 0) onClicked: => Reitti.Router.navigateToRoutes _.extend(@leg.routeParams, legIndex: @leg.index, originOrDestination: @originOrDestination) false onRoutesChanged: (routes, routeParams) => if @leg.isSelectedIn(routes, routeParams) and routeParams.originOrDestination is @originOrDestination if @leg.map.getStreetView().getVisible() @onStreetViewClicked() @markerAnchor: (latLng, latLngs) -> if @_isNorthMost(latLng, latLngs) 'top' else if @_isSouthMost(latLng, latLngs) 'bottom' else if @_isEastMost(latLng, latLngs) 'left' else 'right' @_isNorthMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lat() > latLng.lat() true @_isSouthMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lat() < latLng.lat() true @_isEastMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lng() < latLng.lng() true _checkStreetViewAvailability: () -> new google.maps.StreetViewService().getPanoramaByLocation @location, 30, (panoramaData, streetviewStatus) => if streetviewStatus is 'OK' @heading = @_computeAngle(panoramaData.location.latLng) $('.streetview-icon', @div).show() # Approximate angle calculation courtesy of <NAME> # http://www.jaycodesign.co.nz/js/using-google-maps-to-show-a-streetview-of-a-house-based-on-an-address/ _computeAngle: (availableLatLng) -> DEGREE_PER_RADIAN = 57.2957795 RADIAN_PER_DEGREE = 0.017453 dlat = @location.lat() - availableLatLng.lat() dlng = @location.lng() - availableLatLng.lng() yaw = Math.atan2(dlng * Math.cos(@location.lat() * RADIAN_PER_DEGREE), dlat) * DEGREE_PER_RADIAN @_wrapAngle(yaw) _wrapAngle: (angle) -> if angle >= 360 angle -= 360 else if angle < 0 angle += 360 angle
true
define ['jquery', 'hbs!template/map_location_marker', "async!http://maps.googleapis.com/maps/api/js?sensor=true#{window.gmapsKey}"], ($, template) -> WIDTH = 150 HEIGHT = 20 class MapLocationMarker extends google.maps.OverlayView constructor: ({@leg, @location, @name, @anchor, @originOrDestination}) -> @setMap(@leg.map) onAdd: -> @div = $(template(anchor: @anchor, content: @name))[0] @getPanes().floatPane.appendChild(@div) $('.streetview-icon', @div).on 'click', @onStreetViewClicked $(@div).on 'click', @onClicked @_checkStreetViewAvailability() onRemove: -> @div.parentNode.removeChild(@div) @div = null draw: -> {x, y} = @getProjection().fromLatLngToDivPixel(@location) # TODO: There's something fishy with these magic offsets here. switch @anchor when 'top' x -= WIDTH / 2 + 2 y -= (HEIGHT + 10) + 3 when 'bottom' x -= WIDTH / 2 + 3 y -= 1 when 'left' x -= (WIDTH + 10) + 3 y -= HEIGHT / 2 + 2 when 'right' y -= HEIGHT / 2 + 2 x -= 2 @div.style.left = "#{x}px" @div.style.top = "#{y}px" onStreetViewClicked: => @leg.map.getStreetView().setVisible(true) @leg.map.getStreetView().setPosition(@location) @leg.map.getStreetView().setPov(heading: @heading, pitch: 0, zoom: 0) onClicked: => Reitti.Router.navigateToRoutes _.extend(@leg.routeParams, legIndex: @leg.index, originOrDestination: @originOrDestination) false onRoutesChanged: (routes, routeParams) => if @leg.isSelectedIn(routes, routeParams) and routeParams.originOrDestination is @originOrDestination if @leg.map.getStreetView().getVisible() @onStreetViewClicked() @markerAnchor: (latLng, latLngs) -> if @_isNorthMost(latLng, latLngs) 'top' else if @_isSouthMost(latLng, latLngs) 'bottom' else if @_isEastMost(latLng, latLngs) 'left' else 'right' @_isNorthMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lat() > latLng.lat() true @_isSouthMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lat() < latLng.lat() true @_isEastMost: (latLng, latLngs) -> for i in [0...latLngs.getLength()] return false if latLngs.getAt(i).lng() < latLng.lng() true _checkStreetViewAvailability: () -> new google.maps.StreetViewService().getPanoramaByLocation @location, 30, (panoramaData, streetviewStatus) => if streetviewStatus is 'OK' @heading = @_computeAngle(panoramaData.location.latLng) $('.streetview-icon', @div).show() # Approximate angle calculation courtesy of PI:NAME:<NAME>END_PI # http://www.jaycodesign.co.nz/js/using-google-maps-to-show-a-streetview-of-a-house-based-on-an-address/ _computeAngle: (availableLatLng) -> DEGREE_PER_RADIAN = 57.2957795 RADIAN_PER_DEGREE = 0.017453 dlat = @location.lat() - availableLatLng.lat() dlng = @location.lng() - availableLatLng.lng() yaw = Math.atan2(dlng * Math.cos(@location.lat() * RADIAN_PER_DEGREE), dlat) * DEGREE_PER_RADIAN @_wrapAngle(yaw) _wrapAngle: (angle) -> if angle >= 360 angle -= 360 else if angle < 0 angle += 360 angle
[ { "context": "elpers to test EventGenerator interface.\n# @author Toru Nagashima\n###\n'use strict'\n\n### global describe, it ###\n\n#-", "end": 87, "score": 0.9998633861541748, "start": 73, "tag": "NAME", "value": "Toru Nagashima" } ]
src/tools/internal-testers/event-generator-tester.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Helpers to test EventGenerator interface. # @author Toru Nagashima ### 'use strict' ### global describe, it ### #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' #------------------------------------------------------------------------------ # Public Interface #------------------------------------------------------------------------------ module.exports = ###* # Overrideable `describe` function to test. # @param {string} text - A description. # @param {Function} method - A test logic. # @returns {any} The returned value with the test logic. ### describe: if typeof describe is 'function' describe ### istanbul ignore next ### else (text, method) -> method.apply @ ###* # Overrideable `it` function to test. # @param {string} text - A description. # @param {Function} method - A test logic. # @returns {any} The returned value with the test logic. ### it: if typeof it is 'function' it ### istanbul ignore next ### else (text, method) -> method.apply @ ###* # Does some tests to check a given object implements the EventGenerator interface. # @param {Object} instance - An object to check. # @returns {void} ### testEventGeneratorInterface: (instance) -> @describe 'should implement EventGenerator interface', => @it 'should have `emitter` property.', -> assert.strictEqual typeof instance.emitter, 'object' assert.strictEqual typeof instance.emitter.emit, 'function' @it 'should have `enterNode` property.', -> assert.strictEqual typeof instance.enterNode, 'function' @it 'should have `leaveNode` property.', -> assert.strictEqual typeof instance.leaveNode, 'function'
2197
###* # @fileoverview Helpers to test EventGenerator interface. # @author <NAME> ### 'use strict' ### global describe, it ### #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' #------------------------------------------------------------------------------ # Public Interface #------------------------------------------------------------------------------ module.exports = ###* # Overrideable `describe` function to test. # @param {string} text - A description. # @param {Function} method - A test logic. # @returns {any} The returned value with the test logic. ### describe: if typeof describe is 'function' describe ### istanbul ignore next ### else (text, method) -> method.apply @ ###* # Overrideable `it` function to test. # @param {string} text - A description. # @param {Function} method - A test logic. # @returns {any} The returned value with the test logic. ### it: if typeof it is 'function' it ### istanbul ignore next ### else (text, method) -> method.apply @ ###* # Does some tests to check a given object implements the EventGenerator interface. # @param {Object} instance - An object to check. # @returns {void} ### testEventGeneratorInterface: (instance) -> @describe 'should implement EventGenerator interface', => @it 'should have `emitter` property.', -> assert.strictEqual typeof instance.emitter, 'object' assert.strictEqual typeof instance.emitter.emit, 'function' @it 'should have `enterNode` property.', -> assert.strictEqual typeof instance.enterNode, 'function' @it 'should have `leaveNode` property.', -> assert.strictEqual typeof instance.leaveNode, 'function'
true
###* # @fileoverview Helpers to test EventGenerator interface. # @author PI:NAME:<NAME>END_PI ### 'use strict' ### global describe, it ### #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ assert = require 'assert' #------------------------------------------------------------------------------ # Public Interface #------------------------------------------------------------------------------ module.exports = ###* # Overrideable `describe` function to test. # @param {string} text - A description. # @param {Function} method - A test logic. # @returns {any} The returned value with the test logic. ### describe: if typeof describe is 'function' describe ### istanbul ignore next ### else (text, method) -> method.apply @ ###* # Overrideable `it` function to test. # @param {string} text - A description. # @param {Function} method - A test logic. # @returns {any} The returned value with the test logic. ### it: if typeof it is 'function' it ### istanbul ignore next ### else (text, method) -> method.apply @ ###* # Does some tests to check a given object implements the EventGenerator interface. # @param {Object} instance - An object to check. # @returns {void} ### testEventGeneratorInterface: (instance) -> @describe 'should implement EventGenerator interface', => @it 'should have `emitter` property.', -> assert.strictEqual typeof instance.emitter, 'object' assert.strictEqual typeof instance.emitter.emit, 'function' @it 'should have `enterNode` property.', -> assert.strictEqual typeof instance.enterNode, 'function' @it 'should have `leaveNode` property.', -> assert.strictEqual typeof instance.leaveNode, 'function'
[ { "context": "k, i in @props.details\n subtask._key ?= Math.random()\n <div key={subtask._key} className=\"", "end": 678, "score": 0.6027948260307312, "start": 667, "tag": "KEY", "value": "Math.random" } ]
app/classifier/tasks/drawing-task-details-editor.cjsx
camallen/Panoptes-Front-End
0
React = require 'react' AutoSave = require '../../components/auto-save' module.exports = React.createClass displayName: 'DrawingTaskDetailsEditor' getDefaultProps: -> workflow: null task: null details: null toolIndex: NaN toolPath: '' onClose: null render: -> GenericTaskEditor = require './generic-editor' # Work around circular dependency. <div className="drawing-task-details-editor"> <div className="sub-tasks"> {if @props.details.length is 0 <span className="form-help">No sub-tasks defined for this tool</span> else for subtask, i in @props.details subtask._key ?= Math.random() <div key={subtask._key} className="drawing-task-details-editor-subtask-wrapper"> <GenericTaskEditor workflow={@props.workflow} task={subtask} taskPrefix="#{@props.toolPath}.details.#{i}" isSubtask={true} onChange={@handleSubtaskChange.bind this, i} onDelete={@handleSubtaskDelete.bind this, i} /> <AutoSave resource={@props.workflow}> <button type="button" className="subtask-delete" aria-label="Remove subtask" title="Remove subtask" onClick={@handleSubtaskDelete.bind this, i}>&times;</button> </AutoSave> </div>} </div> <div className="commands columns-container"> <button type="button" className="standard-button" onClick={@props.onClose}>Close</button> <button type="button" className="major-button" onClick={@handleAddTask}>Add task</button> </div> </div> handleAddTask: -> SingleChoiceTask = require './single' @props.task.tools[@props.toolIndex].details.push SingleChoiceTask.getDefaultTask() @props.workflow.update 'tasks' @props.workflow.save() handleSubtaskChange: (subtaskIndex, path, value) -> console?.log 'Handling subtask change', arguments... taskKey = (key for key, description of @props.workflow.tasks when description is @props.task)[0] changes = {} changes["#{@props.toolPath}.details.#{subtaskIndex}.#{path}"] = value @props.workflow.update(changes).save() console?.log changes, @props.workflow handleSubtaskDelete: (subtaskIndex) -> @props.task.tools[@props.toolIndex].details.splice subtaskIndex, 1 @props.workflow.update('tasks').save()
74091
React = require 'react' AutoSave = require '../../components/auto-save' module.exports = React.createClass displayName: 'DrawingTaskDetailsEditor' getDefaultProps: -> workflow: null task: null details: null toolIndex: NaN toolPath: '' onClose: null render: -> GenericTaskEditor = require './generic-editor' # Work around circular dependency. <div className="drawing-task-details-editor"> <div className="sub-tasks"> {if @props.details.length is 0 <span className="form-help">No sub-tasks defined for this tool</span> else for subtask, i in @props.details subtask._key ?= <KEY>() <div key={subtask._key} className="drawing-task-details-editor-subtask-wrapper"> <GenericTaskEditor workflow={@props.workflow} task={subtask} taskPrefix="#{@props.toolPath}.details.#{i}" isSubtask={true} onChange={@handleSubtaskChange.bind this, i} onDelete={@handleSubtaskDelete.bind this, i} /> <AutoSave resource={@props.workflow}> <button type="button" className="subtask-delete" aria-label="Remove subtask" title="Remove subtask" onClick={@handleSubtaskDelete.bind this, i}>&times;</button> </AutoSave> </div>} </div> <div className="commands columns-container"> <button type="button" className="standard-button" onClick={@props.onClose}>Close</button> <button type="button" className="major-button" onClick={@handleAddTask}>Add task</button> </div> </div> handleAddTask: -> SingleChoiceTask = require './single' @props.task.tools[@props.toolIndex].details.push SingleChoiceTask.getDefaultTask() @props.workflow.update 'tasks' @props.workflow.save() handleSubtaskChange: (subtaskIndex, path, value) -> console?.log 'Handling subtask change', arguments... taskKey = (key for key, description of @props.workflow.tasks when description is @props.task)[0] changes = {} changes["#{@props.toolPath}.details.#{subtaskIndex}.#{path}"] = value @props.workflow.update(changes).save() console?.log changes, @props.workflow handleSubtaskDelete: (subtaskIndex) -> @props.task.tools[@props.toolIndex].details.splice subtaskIndex, 1 @props.workflow.update('tasks').save()
true
React = require 'react' AutoSave = require '../../components/auto-save' module.exports = React.createClass displayName: 'DrawingTaskDetailsEditor' getDefaultProps: -> workflow: null task: null details: null toolIndex: NaN toolPath: '' onClose: null render: -> GenericTaskEditor = require './generic-editor' # Work around circular dependency. <div className="drawing-task-details-editor"> <div className="sub-tasks"> {if @props.details.length is 0 <span className="form-help">No sub-tasks defined for this tool</span> else for subtask, i in @props.details subtask._key ?= PI:KEY:<KEY>END_PI() <div key={subtask._key} className="drawing-task-details-editor-subtask-wrapper"> <GenericTaskEditor workflow={@props.workflow} task={subtask} taskPrefix="#{@props.toolPath}.details.#{i}" isSubtask={true} onChange={@handleSubtaskChange.bind this, i} onDelete={@handleSubtaskDelete.bind this, i} /> <AutoSave resource={@props.workflow}> <button type="button" className="subtask-delete" aria-label="Remove subtask" title="Remove subtask" onClick={@handleSubtaskDelete.bind this, i}>&times;</button> </AutoSave> </div>} </div> <div className="commands columns-container"> <button type="button" className="standard-button" onClick={@props.onClose}>Close</button> <button type="button" className="major-button" onClick={@handleAddTask}>Add task</button> </div> </div> handleAddTask: -> SingleChoiceTask = require './single' @props.task.tools[@props.toolIndex].details.push SingleChoiceTask.getDefaultTask() @props.workflow.update 'tasks' @props.workflow.save() handleSubtaskChange: (subtaskIndex, path, value) -> console?.log 'Handling subtask change', arguments... taskKey = (key for key, description of @props.workflow.tasks when description is @props.task)[0] changes = {} changes["#{@props.toolPath}.details.#{subtaskIndex}.#{path}"] = value @props.workflow.update(changes).save() console?.log changes, @props.workflow handleSubtaskDelete: (subtaskIndex) -> @props.task.tools[@props.toolIndex].details.splice subtaskIndex, 1 @props.workflow.update('tasks').save()
[ { "context": "bar\"})\n obj = xhrs.parseHeaders({\"x-token\": \"1234\"}, str)\n expect(obj).to.deep.eq({\n \"x", "end": 1413, "score": 0.8588877320289612, "start": 1409, "tag": "KEY", "value": "1234" }, { "context": " expect(obj).to.deep.eq({\n \"x-token\": \"1234\"\n \"content-type\": \"application/json\"\n ", "end": 1477, "score": 0.94356769323349, "start": 1473, "tag": "KEY", "value": "1234" } ]
packages/server/test/unit/xhrs_spec.coffee
rwwiv/cypress
3
require("../spec_helper") xhrs = require("#{root}lib/controllers/xhrs") describe "lib/controllers/xhr", -> describe "#parseContentType", -> it "returns application/json", -> str = JSON.stringify({foo: "bar"}) expect(xhrs.parseContentType(str)).to.eq("application/json") it "returns text/html", -> str = """ <html> <body>foobarbaz</body> </html> """ expect(xhrs.parseContentType(str)).to.eq("text/html") it "returns text/plain", -> str = "foobar<p>baz" expect(xhrs.parseContentType(str)).to.eq("text/plain") it "returns text/plain by default", -> expect(xhrs.parseContentType()).to.eq("text/plain") describe "#parseHeaders", -> it "returns object literal on undefined", -> obj = xhrs.parseHeaders(undefined) expect(obj).to.deep.eq({ "content-type": "text/plain" }) it "uses passed in content-type", -> obj = xhrs.parseHeaders({"content-type": "application/json"}, "foo") expect(obj).to.deep.eq({ "content-type": "application/json" }) it "uses response if content-type is omitted", -> obj = xhrs.parseHeaders({}, "<html>foo</html>") expect(obj).to.deep.eq({ "content-type": "text/html" }) it "sets content-type to application/json", -> str = JSON.stringify({foo: "bar"}) obj = xhrs.parseHeaders({"x-token": "1234"}, str) expect(obj).to.deep.eq({ "x-token": "1234" "content-type": "application/json" })
46087
require("../spec_helper") xhrs = require("#{root}lib/controllers/xhrs") describe "lib/controllers/xhr", -> describe "#parseContentType", -> it "returns application/json", -> str = JSON.stringify({foo: "bar"}) expect(xhrs.parseContentType(str)).to.eq("application/json") it "returns text/html", -> str = """ <html> <body>foobarbaz</body> </html> """ expect(xhrs.parseContentType(str)).to.eq("text/html") it "returns text/plain", -> str = "foobar<p>baz" expect(xhrs.parseContentType(str)).to.eq("text/plain") it "returns text/plain by default", -> expect(xhrs.parseContentType()).to.eq("text/plain") describe "#parseHeaders", -> it "returns object literal on undefined", -> obj = xhrs.parseHeaders(undefined) expect(obj).to.deep.eq({ "content-type": "text/plain" }) it "uses passed in content-type", -> obj = xhrs.parseHeaders({"content-type": "application/json"}, "foo") expect(obj).to.deep.eq({ "content-type": "application/json" }) it "uses response if content-type is omitted", -> obj = xhrs.parseHeaders({}, "<html>foo</html>") expect(obj).to.deep.eq({ "content-type": "text/html" }) it "sets content-type to application/json", -> str = JSON.stringify({foo: "bar"}) obj = xhrs.parseHeaders({"x-token": "<KEY>"}, str) expect(obj).to.deep.eq({ "x-token": "<KEY>" "content-type": "application/json" })
true
require("../spec_helper") xhrs = require("#{root}lib/controllers/xhrs") describe "lib/controllers/xhr", -> describe "#parseContentType", -> it "returns application/json", -> str = JSON.stringify({foo: "bar"}) expect(xhrs.parseContentType(str)).to.eq("application/json") it "returns text/html", -> str = """ <html> <body>foobarbaz</body> </html> """ expect(xhrs.parseContentType(str)).to.eq("text/html") it "returns text/plain", -> str = "foobar<p>baz" expect(xhrs.parseContentType(str)).to.eq("text/plain") it "returns text/plain by default", -> expect(xhrs.parseContentType()).to.eq("text/plain") describe "#parseHeaders", -> it "returns object literal on undefined", -> obj = xhrs.parseHeaders(undefined) expect(obj).to.deep.eq({ "content-type": "text/plain" }) it "uses passed in content-type", -> obj = xhrs.parseHeaders({"content-type": "application/json"}, "foo") expect(obj).to.deep.eq({ "content-type": "application/json" }) it "uses response if content-type is omitted", -> obj = xhrs.parseHeaders({}, "<html>foo</html>") expect(obj).to.deep.eq({ "content-type": "text/html" }) it "sets content-type to application/json", -> str = JSON.stringify({foo: "bar"}) obj = xhrs.parseHeaders({"x-token": "PI:KEY:<KEY>END_PI"}, str) expect(obj).to.deep.eq({ "x-token": "PI:KEY:<KEY>END_PI" "content-type": "application/json" })
[ { "context": "b>10</sub>\"}\n \"ozone\": {\"limit\": 120, \"name\": \"Otsoni\"}\n \"particulateslt2.5um\": {\"limit\": 25, \"name\"", "end": 144, "score": 0.9988473057746887, "start": 138, "tag": "NAME", "value": "Otsoni" }, { "context": ">\"}\n \"sulphurdioxide\": {\"limit\": 350, \"name\": \"Rikkidioksidi\"}\n \"nitrogendioxide\": {\"limit\": 200, \"name\": \"", "end": 275, "score": 0.9974499344825745, "start": 262, "tag": "NAME", "value": "Rikkidioksidi" }, { "context": "\"}\n \"nitrogendioxide\": {\"limit\": 200, \"name\": \"Typpidioksidi\"}\n\n data_timeout = null\n\n elem = jq \".outdoor-a", "end": 338, "score": 0.9980362057685852, "start": 325, "tag": "NAME", "value": "Typpidioksidi" } ]
homedisplay/info_air_quality/static/js/outdoor_quality.coffee
ojarva/home-info-display
1
OutdoorQuality = -> type_data = "particulateslt10um": {"limit": 50, "name": "PM<sub>10</sub>"} "ozone": {"limit": 120, "name": "Otsoni"} "particulateslt2.5um": {"limit": 25, "name": "PM<sub>2.5</sub>"} "sulphurdioxide": {"limit": 350, "name": "Rikkidioksidi"} "nitrogendioxide": {"limit": 200, "name": "Typpidioksidi"} data_timeout = null elem = jq ".outdoor-air-quality-content" clearData = -> elem.children().remove() if data_timeout? data_timeout = clearTimeout data_timeout data_timeout = setTimeout clearData, 90 * 60 * 1000 fetchData = -> jq.get "/homecontroller/air_quality/get/outdoor/latest", (data) -> receivedData(data) receivedData = (message) -> clearData() max_percent = 0 for own key, data of message value = data.value if key of type_data limit = type_data[key].limit name = type_data[key].name icon_class = "" if value > limit icon = "times" icon_class = "error-message" else if value > limit * .75 icon = "times" icon_class = "warning-message" else if value > limit * .5 icon = "check" else icon = "check" icon_class = "success-message" percent_of_limit = value / limit max_percent = Math.max(percent_of_limit, max_percent) elem.append """<span class="air-quality-item"> <span class="type">#{name}</span> <span class="value">#{value}</span> <span class="unit">&mu;g/m<sup>3</sup></span> <span class="status"><i class="fa fa-#{icon} #{icon_class}"></i></span> </span>""" return ws_generic.register "outside_air_quality", receivedData ge_refresh.register "outside_air_quality", fetchData fetchData() @receivedData = receivedData @fetchData = fetchData return @ jq => @outdoor_quality = new OutdoorQuality()
213779
OutdoorQuality = -> type_data = "particulateslt10um": {"limit": 50, "name": "PM<sub>10</sub>"} "ozone": {"limit": 120, "name": "<NAME>"} "particulateslt2.5um": {"limit": 25, "name": "PM<sub>2.5</sub>"} "sulphurdioxide": {"limit": 350, "name": "<NAME>"} "nitrogendioxide": {"limit": 200, "name": "<NAME>"} data_timeout = null elem = jq ".outdoor-air-quality-content" clearData = -> elem.children().remove() if data_timeout? data_timeout = clearTimeout data_timeout data_timeout = setTimeout clearData, 90 * 60 * 1000 fetchData = -> jq.get "/homecontroller/air_quality/get/outdoor/latest", (data) -> receivedData(data) receivedData = (message) -> clearData() max_percent = 0 for own key, data of message value = data.value if key of type_data limit = type_data[key].limit name = type_data[key].name icon_class = "" if value > limit icon = "times" icon_class = "error-message" else if value > limit * .75 icon = "times" icon_class = "warning-message" else if value > limit * .5 icon = "check" else icon = "check" icon_class = "success-message" percent_of_limit = value / limit max_percent = Math.max(percent_of_limit, max_percent) elem.append """<span class="air-quality-item"> <span class="type">#{name}</span> <span class="value">#{value}</span> <span class="unit">&mu;g/m<sup>3</sup></span> <span class="status"><i class="fa fa-#{icon} #{icon_class}"></i></span> </span>""" return ws_generic.register "outside_air_quality", receivedData ge_refresh.register "outside_air_quality", fetchData fetchData() @receivedData = receivedData @fetchData = fetchData return @ jq => @outdoor_quality = new OutdoorQuality()
true
OutdoorQuality = -> type_data = "particulateslt10um": {"limit": 50, "name": "PM<sub>10</sub>"} "ozone": {"limit": 120, "name": "PI:NAME:<NAME>END_PI"} "particulateslt2.5um": {"limit": 25, "name": "PM<sub>2.5</sub>"} "sulphurdioxide": {"limit": 350, "name": "PI:NAME:<NAME>END_PI"} "nitrogendioxide": {"limit": 200, "name": "PI:NAME:<NAME>END_PI"} data_timeout = null elem = jq ".outdoor-air-quality-content" clearData = -> elem.children().remove() if data_timeout? data_timeout = clearTimeout data_timeout data_timeout = setTimeout clearData, 90 * 60 * 1000 fetchData = -> jq.get "/homecontroller/air_quality/get/outdoor/latest", (data) -> receivedData(data) receivedData = (message) -> clearData() max_percent = 0 for own key, data of message value = data.value if key of type_data limit = type_data[key].limit name = type_data[key].name icon_class = "" if value > limit icon = "times" icon_class = "error-message" else if value > limit * .75 icon = "times" icon_class = "warning-message" else if value > limit * .5 icon = "check" else icon = "check" icon_class = "success-message" percent_of_limit = value / limit max_percent = Math.max(percent_of_limit, max_percent) elem.append """<span class="air-quality-item"> <span class="type">#{name}</span> <span class="value">#{value}</span> <span class="unit">&mu;g/m<sup>3</sup></span> <span class="status"><i class="fa fa-#{icon} #{icon_class}"></i></span> </span>""" return ws_generic.register "outside_air_quality", receivedData ge_refresh.register "outside_air_quality", fetchData fetchData() @receivedData = receivedData @fetchData = fetchData return @ jq => @outdoor_quality = new OutdoorQuality()
[ { "context": " CONFIGS.database\n user: CONFIGS.user\n password: CONFIGS.password\n port: CONFIGS.port\n\nconnection.connect (error) ", "end": 333, "score": 0.999045193195343, "start": 317, "tag": "PASSWORD", "value": "CONFIGS.password" } ]
backend/database-controller.coffee
kashesandr/test-app
0
fs = require "fs" winston = require "winston" path = require "path" mysql = require 'mysql' Q = require 'q' CONFIGS = JSON.parse(fs.readFileSync(path.join __dirname, 'configs.json'), 'utf8').mysql connection = mysql.createConnection host: CONFIGS.host database: CONFIGS.database user: CONFIGS.user password: CONFIGS.password port: CONFIGS.port connection.connect (error) -> if error winston.error "Connection refused to mysql: #{error.stack}" winston.error error else winston.info "Connection successful to mysql: id is #{connection.threadId}" queryDeferred = (sql, values) -> deferred = Q.defer() connection.query { sql: sql values: values }, (error, result) -> if error or !result winston.error "DB-CONTROLLER: error when processing a query (#{sql}): #{error}" return deferred.reject error deferred.resolve result deferred.promise user = findOne: (obj) -> deferred = Q.defer() key = null value = null for k, v of obj key = k value = v sql = "SELECT * FROM users where #{key} = ? LIMIT 1" values = [value] queryDeferred(sql, values) .then (users) -> if users?.length? is 0 return deferred.reject 'No users found.' deferred.resolve users[0] .catch (error) -> deferred.reject error deferred.promise findAll: -> sql = "SELECT * FROM users" values = [] queryDeferred sql, values addUser: (user) -> sql = """ INSERT INTO users (`username`, `password`, `firstname`, `lastname`, `street`, `zip`, `location`) VALUES (?, ?, ?, ?, ?, ?, ?) """ values = [ user.username user.password user.firstname user.lastname user.street || '' user.zip || '' user.location || '' ] queryDeferred sql, values updateUser: (user) -> id = user.id callback(throw new Error "Error updating user, no id specified") if !id sql = """ UPDATE users SET username=?, password=?, firstname=?, lastname=?, street=?, zip=?, location=? WHERE id=#{id} """ values = [ user.username user.password user.firstname user.lastname user.street || '' user.zip || '' user.location || '' ] queryDeferred sql, values deleteUser: (userId) -> sql = "DELETE FROM users where id = ?" values = [userId] queryDeferred sql, values checkUser: (username) -> sql = "SELECT username FROM users WHERE username = ?" values = [username] queryDeferred sql, values module.exports = { user }
67228
fs = require "fs" winston = require "winston" path = require "path" mysql = require 'mysql' Q = require 'q' CONFIGS = JSON.parse(fs.readFileSync(path.join __dirname, 'configs.json'), 'utf8').mysql connection = mysql.createConnection host: CONFIGS.host database: CONFIGS.database user: CONFIGS.user password: <PASSWORD> port: CONFIGS.port connection.connect (error) -> if error winston.error "Connection refused to mysql: #{error.stack}" winston.error error else winston.info "Connection successful to mysql: id is #{connection.threadId}" queryDeferred = (sql, values) -> deferred = Q.defer() connection.query { sql: sql values: values }, (error, result) -> if error or !result winston.error "DB-CONTROLLER: error when processing a query (#{sql}): #{error}" return deferred.reject error deferred.resolve result deferred.promise user = findOne: (obj) -> deferred = Q.defer() key = null value = null for k, v of obj key = k value = v sql = "SELECT * FROM users where #{key} = ? LIMIT 1" values = [value] queryDeferred(sql, values) .then (users) -> if users?.length? is 0 return deferred.reject 'No users found.' deferred.resolve users[0] .catch (error) -> deferred.reject error deferred.promise findAll: -> sql = "SELECT * FROM users" values = [] queryDeferred sql, values addUser: (user) -> sql = """ INSERT INTO users (`username`, `password`, `firstname`, `lastname`, `street`, `zip`, `location`) VALUES (?, ?, ?, ?, ?, ?, ?) """ values = [ user.username user.password user.firstname user.lastname user.street || '' user.zip || '' user.location || '' ] queryDeferred sql, values updateUser: (user) -> id = user.id callback(throw new Error "Error updating user, no id specified") if !id sql = """ UPDATE users SET username=?, password=?, firstname=?, lastname=?, street=?, zip=?, location=? WHERE id=#{id} """ values = [ user.username user.password user.firstname user.lastname user.street || '' user.zip || '' user.location || '' ] queryDeferred sql, values deleteUser: (userId) -> sql = "DELETE FROM users where id = ?" values = [userId] queryDeferred sql, values checkUser: (username) -> sql = "SELECT username FROM users WHERE username = ?" values = [username] queryDeferred sql, values module.exports = { user }
true
fs = require "fs" winston = require "winston" path = require "path" mysql = require 'mysql' Q = require 'q' CONFIGS = JSON.parse(fs.readFileSync(path.join __dirname, 'configs.json'), 'utf8').mysql connection = mysql.createConnection host: CONFIGS.host database: CONFIGS.database user: CONFIGS.user password: PI:PASSWORD:<PASSWORD>END_PI port: CONFIGS.port connection.connect (error) -> if error winston.error "Connection refused to mysql: #{error.stack}" winston.error error else winston.info "Connection successful to mysql: id is #{connection.threadId}" queryDeferred = (sql, values) -> deferred = Q.defer() connection.query { sql: sql values: values }, (error, result) -> if error or !result winston.error "DB-CONTROLLER: error when processing a query (#{sql}): #{error}" return deferred.reject error deferred.resolve result deferred.promise user = findOne: (obj) -> deferred = Q.defer() key = null value = null for k, v of obj key = k value = v sql = "SELECT * FROM users where #{key} = ? LIMIT 1" values = [value] queryDeferred(sql, values) .then (users) -> if users?.length? is 0 return deferred.reject 'No users found.' deferred.resolve users[0] .catch (error) -> deferred.reject error deferred.promise findAll: -> sql = "SELECT * FROM users" values = [] queryDeferred sql, values addUser: (user) -> sql = """ INSERT INTO users (`username`, `password`, `firstname`, `lastname`, `street`, `zip`, `location`) VALUES (?, ?, ?, ?, ?, ?, ?) """ values = [ user.username user.password user.firstname user.lastname user.street || '' user.zip || '' user.location || '' ] queryDeferred sql, values updateUser: (user) -> id = user.id callback(throw new Error "Error updating user, no id specified") if !id sql = """ UPDATE users SET username=?, password=?, firstname=?, lastname=?, street=?, zip=?, location=? WHERE id=#{id} """ values = [ user.username user.password user.firstname user.lastname user.street || '' user.zip || '' user.location || '' ] queryDeferred sql, values deleteUser: (userId) -> sql = "DELETE FROM users where id = ?" values = [userId] queryDeferred sql, values checkUser: (username) -> sql = "SELECT username FROM users WHERE username = ?" values = [username] queryDeferred sql, values module.exports = { user }
[ { "context": "# By Frank Leenaars\n# University of Twente - Department of Instructio", "end": 19, "score": 0.9998514652252197, "start": 5, "tag": "NAME", "value": "Frank Leenaars" } ]
activities/Gears.activity/lib/gearsketch/src/gearsketch_main.coffee
sarthakagr104/Sugarizer
4
# By Frank Leenaars # University of Twente - Department of Instructional Technology # Licensed under the MIT license "use strict" # TODO: # - support IE9? # - use "for element, i in ..." where appropriate # - chained comparisons: 1 < x < 100 # - improve gear, chain & momentum icons # - disallow chains crossing gears' axes? (if gear on higher level) # - allow gears to overlap other gears' axes when the larger gear is on a higher level? # - figure out why drawing with RAF is slower than drawing without RAF on iPad # imports Point = window.gearsketch.Point ArcSegment = window.gearsketch.ArcSegment LineSegment = window.gearsketch.LineSegment Util = window.gearsketch.Util Gear = window.gearsketch.model.Gear Chain = window.gearsketch.model.Chain Board = window.gearsketch.model.Board # -- constants -- FPS = 60 MIN_GEAR_TEETH = 8 MIN_MOMENTUM = 0.2 # --------------------------- # -------- GearSketch ------- # --------------------------- class GearSketch # -- imported constants -- MODULE = Util.MODULE AXIS_RADIUS = Util.AXIS_RADIUS BUTTON_INFO = [ ["gearButton", "GearIcon.png"] ["chainButton", "ChainIcon.png"] ["momentumButton", "MomentumIcon.png"] ["playButton", "PlayIcon.png"] ["clearButton", "ClearIcon.png"] ["cloudButton", "CloudIcon.png"] ["helpButton", "HelpIcon.png"] ] MovementAction = PEN_DOWN: "penDown" PEN_UP: "penUp" PEN_TAP: "penTap" MovementType = STRAIGHT: "straight" CIRCLE: "circle" LEFT_HALF_CIRCLE: "leftHalfCircle" RIGHT_HALF_CIRCLE: "rightHalfCircle" buttons: {} loadedButtons: 0 areButtonsLoaded: false selectedButton: BUTTON_INFO[0][0] gearImages: {} isPenDown: false stroke: [] offset: new Point() message: "" messageColor: "black" # usage demo pointerLocation: new Point() currentDemoMovement: 0 movementCompletion: 0 restTimer: 0 # Passing false to showButtons will hide them, unless the demo is # playing. This comes handy when adding controls outside the canvas. constructor: (showButtons = true) -> @loadButtons() @showButtons = showButtons @loadDemoPointer() @loadBoard() @canvas = document.getElementById("gearsketch_canvas") @canvasOffsetX = @canvas.getBoundingClientRect().left @canvasOffsetY = @canvas.getBoundingClientRect().top @isDemoPlaying = false @updateCanvasSize() @addCanvasListeners() @lastUpdateTime = new Date().getTime() #@updateAndDraw() @updateAndDrawNoRAF() buttonLoaded: -> @loadedButtons++ if @loadedButtons is BUTTON_INFO.length @areButtonsLoaded = true loadButtons: -> x = y = 20 for [name, file] in BUTTON_INFO button = new Image() button.name = name button.onload = => @buttonLoaded() button.src = "img/" + file button.location = new Point(x, y) button.padding = 3 @buttons[name] = button x += 80 loadDemoPointer: -> image = new Image() image.onload = => @pointerImage = image image.src = "img/hand.png" loadBoard: -> @board = if parent.location.hash.length > 1 try hash = parent.location.hash.substr(1) boardJSON = Util.sendGetRequest("boards/#{hash}.txt") Board.fromObject(JSON.parse(boardJSON)) catch error @displayMessage("Error: could not load board", "red", 2000) new Board() else new Board() @addGearImage(gear) for id, gear of @board.getGears() displayMessage: (message, color = "black", time = 0) -> @message = message @messageColor = color if time > 0 setTimeout((=> @clearMessage()), time) clearMessage: -> @message = "" selectButton: (buttonName) -> @selectedButton = buttonName shouldShowButtons: -> return @showButtons or @isDemoPlaying # Input callback methods addCanvasListeners: -> canvasEventHandler = Hammer(@canvas, {drag_min_distance: 1}) canvasEventHandler.on("touch", ((e) => @forwardPenDownEvent.call(this, e))) canvasEventHandler.on("drag", ((e) => @forwardPenMoveEvent.call(this, e))) canvasEventHandler.on("release", ((e) => @forwardPenUpEvent.call(this, e))) forwardPenDownEvent: (event) -> event.gesture.preventDefault() if @isDemoPlaying @stopDemo() else x = event.gesture.center.pageX - @canvasOffsetX y = event.gesture.center.pageY - @canvasOffsetY @handlePenDown(x, y) forwardPenMoveEvent: (event) -> event.gesture.preventDefault() unless @isDemoPlaying x = event.gesture.center.pageX - @canvasOffsetX y = event.gesture.center.pageY - @canvasOffsetY @handlePenMove(x, y) forwardPenUpEvent: (event) -> unless @isDemoPlaying @handlePenUp() handlePenDown: (x, y) -> point = new Point(x, y) if @isPenDown # pen released outside of canvas @handlePenUp() else button = @getButtonAt(x, y) if button if button.name is "clearButton" # remove hash from url and clear board parent.location.hash = "" @board.clear() else if button.name is "cloudButton" @uploadBoard() else if button.name is "helpButton" @playDemo() else @selectButton(button.name) else if @selectedButton is "gearButton" @selectedGear = @board.getTopLevelGearAt(point) if @selectedGear? @offset = point.minus(@selectedGear.location) else if !@board.getGearAt(point)? # don't create stroke if lower level gear selected @stroke.push(point) @isPenDown = true else if @selectedButton is "chainButton" @stroke.push(point) @isPenDown = true else if @selectedButton is "momentumButton" @selectedGear = @board.getGearAt(point) if @selectedGear @selectedGear.momentum = 0 @selectedGearMomentum = @calculateMomentumFromCoords(@selectedGear, x, y) @isPenDown = true handlePenMove: (x, y) -> point = new Point(x, y) if @isPenDown if @selectedButton is "gearButton" if @selectedGear goalLocation = point.minus(@offset) canPlaceGear = @board.placeGear(@selectedGear, goalLocation) if canPlaceGear @goalLocationGear = null else @goalLocationGear = new Gear(goalLocation, @selectedGear.rotation, @selectedGear.numberOfTeeth, @selectedGear.id) else if @stroke.length > 0 @stroke.push(point) else if @selectedButton is "chainButton" @stroke.push(point) else if @selectedButton is "momentumButton" if @selectedGear @selectedGearMomentum = @calculateMomentumFromCoords(@selectedGear, x, y) handlePenUp: -> if @isPenDown if @selectedButton is "gearButton" unless (@selectedGear? or @stroke.length is 0) @processGearStroke() else if @selectedButton is "chainButton" @processChainStroke() else if @selectedButton is "momentumButton" if @selectedGear if Math.abs(@selectedGearMomentum) > MIN_MOMENTUM @selectedGear.momentum = @selectedGearMomentum else @selectedGear.momentum = 0 @selectedGearMomentum = 0 @selectedGear = null @goalLocationGear = null @isPenDown = false isButtonAt: (x, y, button) -> x > button.location.x and x < button.location.x + button.width + 2 * button.padding and y > button.location.y and y < button.location.y + button.height + 2 * button.padding getButtonAt: (x, y) -> if not @shouldShowButtons() return null for own buttonName, button of @buttons if @isButtonAt(x, y, button) return button null normalizeStroke: (stroke) -> MIN_POINT_DISTANCE = 10 normalizedStroke = [] if stroke.length > 0 [p1, strokeTail...] = stroke normalizedStroke.push(p1) for p2 in strokeTail if p1.distance(p2) > MIN_POINT_DISTANCE normalizedStroke.push(p2) p1 = p2 normalizedStroke createGearFromStroke: (stroke) -> numberOfPoints = stroke.length if numberOfPoints > 0 sumX = 0 sumY = 0 minX = Number.MAX_VALUE maxX = Number.MIN_VALUE minY = Number.MAX_VALUE maxY = Number.MIN_VALUE for p in stroke sumX += p.x sumY += p.y minX = Math.min(minX, p.x) maxX = Math.max(maxX, p.x) minY = Math.min(minY, p.y) maxY = Math.max(maxY, p.y) width = maxX - minX height = maxY - minY t = Math.floor(0.5 * (width + height) / MODULE) # find area, based on http://stackoverflow.com/questions/451426 # /how-do-i-calculate-the-surface-area-of-a-2d-polygon doubleArea = 0 for i in [0...numberOfPoints] j = (i + 1) % numberOfPoints doubleArea += stroke[i].x * stroke[j].y doubleArea -= stroke[i].y * stroke[j].x # create a new gear if the stroke is sufficiently circle-like and large enough area = Math.abs(doubleArea) / 2 radius = 0.25 * ((maxX - minX) + (maxY - minY)) idealTrueAreaRatio = (Math.PI * Math.pow(radius, 2)) / area if idealTrueAreaRatio > 0.80 and idealTrueAreaRatio < 1.20 and t > MIN_GEAR_TEETH x = sumX / numberOfPoints y = sumY / numberOfPoints return new Gear(new Point(x, y), 0, t) null removeStrokedGears: (stroke) -> for own id, gear of @board.getTopLevelGears() if Util.pointPathDistance(gear.location, stroke, false) < gear.innerRadius @board.removeGear(gear) processGearStroke: -> normalizedStroke = @normalizeStroke(@stroke) gear = @createGearFromStroke(normalizedStroke) if gear? isGearAdded = @board.addGear(gear) if isGearAdded and !(gear.numberOfTeeth of @gearImages) @addGearImage(gear) else @removeStrokedGears(normalizedStroke) @stroke = [] gearImageLoaded: (numberOfTeeth, image) -> @gearImages[numberOfTeeth] = image addGearImage: (gear) -> # draw gear on temporary canvas gearCanvas = document.createElement("canvas") size = 2 * (gear.outerRadius + MODULE) # slightly larger than gear diameter gearCanvas.height = size gearCanvas.width = size ctx = gearCanvas.getContext("2d") gearCopy = new Gear(new Point(0.5 * size, 0.5 * size), 0, gear.numberOfTeeth, gear.id) @drawGear(ctx, gearCopy) # convert canvas to png image = new Image() image.onload = => @gearImageLoaded(gear.numberOfTeeth, image) image.src = gearCanvas.toDataURL("image/png") removeStrokedChains: (stroke) -> for own id, chain of @board.getChains() if chain.intersectsPath(stroke) @board.removeChain(chain) processChainStroke: -> normalizedStroke = @normalizeStroke(@stroke) @stroke = [] gearsInChain = Util.findGearsInsidePolygon(normalizedStroke, @board.getGears()) if normalizedStroke.length >= 3 and gearsInChain.length > 0 chain = new Chain(normalizedStroke) @board.addChain(chain) else if normalizedStroke.length >= 2 @removeStrokedChains(normalizedStroke) calculateMomentumFromCoords: (gear, x, y) -> angle = Math.atan2(y - gear.location.y, x - gear.location.x) angleFromTop = angle + 0.5 * Math.PI if angleFromTop < Math.PI angleFromTop else angleFromTop - 2 * Math.PI # -- updating -- updateAndDraw: => setTimeout((=> requestAnimationFrame(@updateAndDraw) @update() @draw() ), 1000 / FPS) updateAndDrawNoRAF: => @update() @draw() setTimeout((=> @updateAndDrawNoRAF()), 1000 / FPS) update: => updateTime = new Date().getTime() delta = updateTime - @lastUpdateTime if @selectedButton is "playButton" @board.rotateAllTurningObjects(delta) if @isDemoPlaying @updateDemo(delta) @lastUpdateTime = updateTime # -- rendering -- drawGear: (ctx, gear, color = "black") -> {x, y} = gear.location rotation = gear.rotation numberOfTeeth = gear.numberOfTeeth gearImage = @gearImages[gear.numberOfTeeth] if color is "black" and gearImage? # use predrawn image instead of drawing it again gearImage = @gearImages[gear.numberOfTeeth] ctx.save() ctx.translate(x, y) ctx.rotate(rotation) ctx.drawImage(gearImage, -0.5 * gearImage.width, -0.5 * gearImage.height) ctx.restore() return # draw teeth angleStep = 2 * Math.PI / numberOfTeeth innerPoints = [] outerPoints = [] for i in [0...numberOfTeeth] for r in [0...4] if r is 0 or r is 3 innerPoints.push(Point.polar((i + 0.25 * r) * angleStep, gear.innerRadius)) else outerPoints.push(Point.polar((i + 0.25 * r) * angleStep, gear.outerRadius)) ctx.save() if color is "black" hue = Math.floor(Math.random()*360) ctx.fillStyle = "hsla(" + hue + ", 85%, 60%, 0.8)" else ctx.fillStyle = "hsla(0, 0%, 90%, 0.2)" ctx.strokeStyle = color ctx.lineWidth = 2 ctx.translate(x, y) ctx.rotate(rotation) ctx.beginPath() ctx.moveTo(gear.innerRadius, 0) for i in [0...numberOfTeeth * 2] if i % 2 is 0 ctx.lineTo(innerPoints[i].x, innerPoints[i].y) ctx.lineTo(outerPoints[i].x, outerPoints[i].y) else ctx.lineTo(outerPoints[i].x, outerPoints[i].y) ctx.lineTo(innerPoints[i].x, innerPoints[i].y) ctx.closePath() ctx.fill() ctx.stroke() # draw axis ctx.beginPath() ctx.moveTo(AXIS_RADIUS, 0) ctx.arc(0, 0, AXIS_RADIUS, 0, 2 * Math.PI, true) ctx.closePath() ctx.stroke() # draw rotation indicator line ctx.beginPath() ctx.moveTo(AXIS_RADIUS, 0) ctx.lineTo(gear.innerRadius, 0) ctx.closePath() ctx.stroke() ctx.restore() drawButton: (ctx, button) -> {x, y} = button.location padding = button.padding ctx.save() ctx.translate(x, y) ctx.beginPath() # draw a round rectangle radius = 10 width = button.width + 2 * padding height = button.height + 2 * padding ctx.moveTo(radius, 0) ctx.lineTo(width - radius, 0) ctx.quadraticCurveTo(width, 0, width, radius) ctx.lineTo(width, height - radius) ctx.quadraticCurveTo(width, height, width - radius, height) ctx.lineTo(radius, height) ctx.quadraticCurveTo(0, height, 0, height - radius); ctx.lineTo(0, radius) ctx.quadraticCurveTo(0, 0, radius, 0); if button.name is @selectedButton ctx.fillStyle = "rgba(50, 150, 255, 0.8)" else ctx.fillStyle = "rgba(255, 255, 255, 0.8)" ctx.fill() ctx.lineWidth = 1 ctx.strokeStyle = "black" ctx.stroke() ctx.drawImage(button, padding, padding) ctx.restore() drawMomentum: (ctx, gear, momentum, color = "red") -> pitchRadius = gear.pitchRadius top = new Point(gear.location.x, gear.location.y - pitchRadius) ctx.save() ctx.lineWidth = 5 ctx.lineCap = "round" ctx.strokeStyle = color ctx.translate(top.x, top.y) # draw arc ctx.beginPath() ctx.arc(0, pitchRadius, pitchRadius, -0.5 * Math.PI, momentum - 0.5 * Math.PI, momentum < 0) ctx.stroke() # draw arrow head length = 15 angle = 0.2 * Math.PI headX = -Math.cos(momentum + 0.5 * Math.PI) * pitchRadius headY = pitchRadius - Math.sin(momentum + 0.5 * Math.PI) * pitchRadius head = new Point(headX, headY) sign = Util.sign(momentum) p1 = head.minus(Point.polar(momentum + angle, sign * length)) ctx.beginPath() ctx.moveTo(headX, headY) ctx.lineTo(p1.x, p1.y) ctx.stroke() p2 = head.minus(Point.polar(momentum - angle, sign * length)) ctx.beginPath() ctx.moveTo(headX, headY) ctx.lineTo(p2.x, p2.y) ctx.stroke() ctx.restore() drawChain: (ctx, chain) -> ctx.save() ctx.lineWidth = Chain.WIDTH ctx.lineCap = "round" ctx.strokeStyle = "rgb(0, 0, 255)" ctx.moveTo(chain.segments[0].start.x, chain.segments[0].start.y) for segment in chain.segments if segment instanceof ArcSegment isCounterClockwise = (segment.direction is Util.Direction.COUNTER_CLOCKWISE) ctx.beginPath() ctx.arc(segment.center.x, segment.center.y, segment.radius, segment.startAngle, segment.endAngle, isCounterClockwise) ctx.stroke() else ctx.beginPath() ctx.moveTo(segment.start.x, segment.start.y) ctx.lineTo(segment.end.x, segment.end.y) ctx.stroke() ctx.fillStyle = "white" for point in chain.findPointsOnChain(25) ctx.beginPath() ctx.arc(point.x, point.y, 3, 0, 2 * Math.PI, true) ctx.fill() ctx.restore() drawDemoPointer: (ctx, location) -> ctx.drawImage(@pointerImage, location.x - 0.5 * @pointerImage.width, location.y) draw: -> if @canvas.getContext? @updateCanvasSize() ctx = @canvas.getContext("2d") ctx.clearRect(0, 0, @canvas.width, @canvas.height) # draw gears sortedGears = @board.getGearsSortedByGroupAndLevel() arrowsToDraw = [] for i in [0...sortedGears.length] gear = sortedGears[i] momentum = gear.momentum if gear is @selectedGear and @goalLocationGear @drawGear(ctx, gear, "grey") if momentum arrowsToDraw.push([gear, momentum, "grey"]) else @drawGear(ctx, gear) if momentum arrowsToDraw.push([gear, momentum, "red"]) # draw chains and arrows when all the gears in current group on current level are drawn shouldDrawChainsAndArrows = (i is sortedGears.length - 1) or (@board.getLevelScore(gear) isnt @board.getLevelScore(sortedGears[i + 1])) if shouldDrawChainsAndArrows for chain in @board.getChainsInGroupOnLevel(gear.group, gear.level) @drawChain(ctx, chain) for arrow in arrowsToDraw @drawMomentum(ctx, arrow[0], arrow[1], arrow[2]) arrowsToDraw = [] # draw goalLocationGear if @goalLocationGear @drawGear(ctx, @goalLocationGear, "red") # draw selected gear momentum if @selectedGear? and @selectedGearMomentum @drawMomentum(ctx, @selectedGear, @selectedGearMomentum) # draw stroke if @stroke.length > 0 ctx.save() if @selectedButton is "gearButton" ctx.strokeStyle = "black" ctx.lineWidth = 2 else # chain stroke ctx.strokeStyle = "blue" ctx.lineWidth = 4 ctx.beginPath() ctx.moveTo(@stroke[0].x, @stroke[0].y) for i in [1...@stroke.length] ctx.lineTo(@stroke[i].x, @stroke[i].y) ctx.stroke() ctx.restore() # draw buttons if @areButtonsLoaded and @shouldShowButtons() for own buttonName of @buttons @drawButton(ctx, @buttons[buttonName]) # draw message if @message.length > 0 ctx.save() ctx.fillStyle = @messageColor ctx.font = "bold 20px Arial" ctx.fillText(@message, 20, 120) ctx.restore() # draw demo text and pointer if @isDemoPlaying and @pointerImage @drawDemoPointer(ctx, @pointerLocation) updateCanvasSize: () -> @canvas.width = @canvas.parentElement.getBoundingClientRect().width @canvas.height = @canvas.parentElement.getBoundingClientRect().height @buttons["clearButton"].location.x = Math.max(@canvas.width - 260, @buttons["playButton"].location.x + 80) @buttons["cloudButton"].location.x = @buttons["clearButton"].location.x + 80 @buttons["helpButton"].location.x = @buttons["cloudButton"].location.x + 80 # -- usage demo -- loadDemoMovements: -> @demoMovements = [ from: @getButtonCenter("helpButton") to: @getButtonCenter("gearButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 2000 , to: new Point(300, 200) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 100 duration: 1500 , to: new Point(500, 200) type: MovementType.STRAIGHT duration: 1000 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 40 duration: 1000 , to: new Point(500, 240) type: MovementType.STRAIGHT duration: 500 , to: new Point(300, 300) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(100, 180) type: MovementType.STRAIGHT duration: 1000 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 90 duration: 1000 , to: new Point(100, 260) type: MovementType.STRAIGHT duration: 500 , to: new Point(180, 260) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(550, 220) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 80 duration: 1000 , to: @getButtonCenter("chainButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(280, 150) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN type: MovementType.LEFT_HALF_CIRCLE radius: 140 duration: 1500 pause: 0 , to: new Point(600, 400) type: MovementType.STRAIGHT duration: 1000 pause: 0 , type: MovementType.RIGHT_HALF_CIRCLE radius: 110 duration: 1000 pause: 0 , to: new Point(280, 150) atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("momentumButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(185, 180) type: MovementType.STRAIGHT duration: 1500 , to: new Point(150, 190) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("playButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: @getButtonCenter("chainButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 3000 , to: new Point(425, 250) type: MovementType.STRAIGHT duration: 1000 , to: new Point(525, 150) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("gearButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(20, 250) type: MovementType.STRAIGHT duration: 1000 , to: new Point(650, 300) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(425, 200) type: MovementType.STRAIGHT duration: 1000 , to: new Point(200, 400) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 ] getButtonCenter: (buttonName) -> button = @buttons[buttonName] buttonCorner = new Point(button.location.x, button.location.y) buttonCorner.plus(new Point(0.5 * button.width + button.padding, 0.5 * button.height + button.padding)) updateDemo: (delta) -> # check if resting or if last movement completed if @restTimer > 0 @restTimer = Math.max(@restTimer - delta, 0) return else if @currentDemoMovement is @demoMovements.length @stopDemo() return # advance movement movement = @demoMovements[@currentDemoMovement] if @movementCompletion is 0 movement.from ?= @pointerLocation movement.pause ?= 500 @pointerLocation = movement.from.clone() if movement.atStart is MovementAction.PEN_DOWN @handlePenDown(@pointerLocation.x, @pointerLocation.y) if @movementCompletion < 1 @movementCompletion = Math.min(1, @movementCompletion + delta / movement.duration) @updatePointerLocation(movement, @movementCompletion) @handlePenMove(@pointerLocation.x, @pointerLocation.y) if @movementCompletion is 1 if movement.atEnd is MovementAction.PEN_TAP @handlePenDown(@pointerLocation.x, @pointerLocation.y) @handlePenUp() else if movement.atEnd is MovementAction.PEN_UP @handlePenUp() @restTimer = movement.pause @movementCompletion = 0 @currentDemoMovement++ updatePointerLocation: (movement, movementCompletion) -> if movement.type is MovementType.STRAIGHT delta = movement.to.minus(movement.from) @pointerLocation = movement.from.plus(delta.times(movementCompletion)) else if movement.type is MovementType.CIRCLE center = new Point(movement.from.x , movement.from.y + movement.radius) @pointerLocation = center.plus(Point.polar(Math.PI - (movementCompletion - 0.25) * 2 * Math.PI, movement.radius)) else if movement.type is MovementType.LEFT_HALF_CIRCLE center = new Point(movement.from.x , movement.from.y + movement.radius) angle = 1.5 * Math.PI - movementCompletion * Math.PI @pointerLocation = center.plus(Point.polar(angle, movement.radius)) else if movement.type is MovementType.RIGHT_HALF_CIRCLE center = new Point(movement.from.x , movement.from.y - movement.radius) angle = 0.5 * Math.PI - movementCompletion * Math.PI @pointerLocation = center.plus(Point.polar(angle, movement.radius)) playDemo: -> @loadDemoMovements() # load these on each play in case canvas size changed @boardBackup = @board.clone() @board.clear() @currentDemoMovement = 0 @movementCompletion = 0 @isDemoPlaying = true @displayMessage("click anywhere to stop the demo") stopDemo: -> @isDemoPlaying = false @restTimer = 0 @stroke = [] @selectedGear = null @selectedIcon = "gearIcon" @board.restoreAfterDemo(@boardBackup) @clearMessage() boardUploaded: (event) -> parent.location.hash = event.target.responseText.trim() @displayMessage("Board saved. Share it by copying the text in your address bar.", "black", 4000) uploadBoard: -> boardJSON = JSON.stringify(@board) Util.sendPostRequest(boardJSON, "upload_board.php", ((event) => @boardUploaded(event))) window.gearsketch.GearSketch = GearSketch
52087
# By <NAME> # University of Twente - Department of Instructional Technology # Licensed under the MIT license "use strict" # TODO: # - support IE9? # - use "for element, i in ..." where appropriate # - chained comparisons: 1 < x < 100 # - improve gear, chain & momentum icons # - disallow chains crossing gears' axes? (if gear on higher level) # - allow gears to overlap other gears' axes when the larger gear is on a higher level? # - figure out why drawing with RAF is slower than drawing without RAF on iPad # imports Point = window.gearsketch.Point ArcSegment = window.gearsketch.ArcSegment LineSegment = window.gearsketch.LineSegment Util = window.gearsketch.Util Gear = window.gearsketch.model.Gear Chain = window.gearsketch.model.Chain Board = window.gearsketch.model.Board # -- constants -- FPS = 60 MIN_GEAR_TEETH = 8 MIN_MOMENTUM = 0.2 # --------------------------- # -------- GearSketch ------- # --------------------------- class GearSketch # -- imported constants -- MODULE = Util.MODULE AXIS_RADIUS = Util.AXIS_RADIUS BUTTON_INFO = [ ["gearButton", "GearIcon.png"] ["chainButton", "ChainIcon.png"] ["momentumButton", "MomentumIcon.png"] ["playButton", "PlayIcon.png"] ["clearButton", "ClearIcon.png"] ["cloudButton", "CloudIcon.png"] ["helpButton", "HelpIcon.png"] ] MovementAction = PEN_DOWN: "penDown" PEN_UP: "penUp" PEN_TAP: "penTap" MovementType = STRAIGHT: "straight" CIRCLE: "circle" LEFT_HALF_CIRCLE: "leftHalfCircle" RIGHT_HALF_CIRCLE: "rightHalfCircle" buttons: {} loadedButtons: 0 areButtonsLoaded: false selectedButton: BUTTON_INFO[0][0] gearImages: {} isPenDown: false stroke: [] offset: new Point() message: "" messageColor: "black" # usage demo pointerLocation: new Point() currentDemoMovement: 0 movementCompletion: 0 restTimer: 0 # Passing false to showButtons will hide them, unless the demo is # playing. This comes handy when adding controls outside the canvas. constructor: (showButtons = true) -> @loadButtons() @showButtons = showButtons @loadDemoPointer() @loadBoard() @canvas = document.getElementById("gearsketch_canvas") @canvasOffsetX = @canvas.getBoundingClientRect().left @canvasOffsetY = @canvas.getBoundingClientRect().top @isDemoPlaying = false @updateCanvasSize() @addCanvasListeners() @lastUpdateTime = new Date().getTime() #@updateAndDraw() @updateAndDrawNoRAF() buttonLoaded: -> @loadedButtons++ if @loadedButtons is BUTTON_INFO.length @areButtonsLoaded = true loadButtons: -> x = y = 20 for [name, file] in BUTTON_INFO button = new Image() button.name = name button.onload = => @buttonLoaded() button.src = "img/" + file button.location = new Point(x, y) button.padding = 3 @buttons[name] = button x += 80 loadDemoPointer: -> image = new Image() image.onload = => @pointerImage = image image.src = "img/hand.png" loadBoard: -> @board = if parent.location.hash.length > 1 try hash = parent.location.hash.substr(1) boardJSON = Util.sendGetRequest("boards/#{hash}.txt") Board.fromObject(JSON.parse(boardJSON)) catch error @displayMessage("Error: could not load board", "red", 2000) new Board() else new Board() @addGearImage(gear) for id, gear of @board.getGears() displayMessage: (message, color = "black", time = 0) -> @message = message @messageColor = color if time > 0 setTimeout((=> @clearMessage()), time) clearMessage: -> @message = "" selectButton: (buttonName) -> @selectedButton = buttonName shouldShowButtons: -> return @showButtons or @isDemoPlaying # Input callback methods addCanvasListeners: -> canvasEventHandler = Hammer(@canvas, {drag_min_distance: 1}) canvasEventHandler.on("touch", ((e) => @forwardPenDownEvent.call(this, e))) canvasEventHandler.on("drag", ((e) => @forwardPenMoveEvent.call(this, e))) canvasEventHandler.on("release", ((e) => @forwardPenUpEvent.call(this, e))) forwardPenDownEvent: (event) -> event.gesture.preventDefault() if @isDemoPlaying @stopDemo() else x = event.gesture.center.pageX - @canvasOffsetX y = event.gesture.center.pageY - @canvasOffsetY @handlePenDown(x, y) forwardPenMoveEvent: (event) -> event.gesture.preventDefault() unless @isDemoPlaying x = event.gesture.center.pageX - @canvasOffsetX y = event.gesture.center.pageY - @canvasOffsetY @handlePenMove(x, y) forwardPenUpEvent: (event) -> unless @isDemoPlaying @handlePenUp() handlePenDown: (x, y) -> point = new Point(x, y) if @isPenDown # pen released outside of canvas @handlePenUp() else button = @getButtonAt(x, y) if button if button.name is "clearButton" # remove hash from url and clear board parent.location.hash = "" @board.clear() else if button.name is "cloudButton" @uploadBoard() else if button.name is "helpButton" @playDemo() else @selectButton(button.name) else if @selectedButton is "gearButton" @selectedGear = @board.getTopLevelGearAt(point) if @selectedGear? @offset = point.minus(@selectedGear.location) else if !@board.getGearAt(point)? # don't create stroke if lower level gear selected @stroke.push(point) @isPenDown = true else if @selectedButton is "chainButton" @stroke.push(point) @isPenDown = true else if @selectedButton is "momentumButton" @selectedGear = @board.getGearAt(point) if @selectedGear @selectedGear.momentum = 0 @selectedGearMomentum = @calculateMomentumFromCoords(@selectedGear, x, y) @isPenDown = true handlePenMove: (x, y) -> point = new Point(x, y) if @isPenDown if @selectedButton is "gearButton" if @selectedGear goalLocation = point.minus(@offset) canPlaceGear = @board.placeGear(@selectedGear, goalLocation) if canPlaceGear @goalLocationGear = null else @goalLocationGear = new Gear(goalLocation, @selectedGear.rotation, @selectedGear.numberOfTeeth, @selectedGear.id) else if @stroke.length > 0 @stroke.push(point) else if @selectedButton is "chainButton" @stroke.push(point) else if @selectedButton is "momentumButton" if @selectedGear @selectedGearMomentum = @calculateMomentumFromCoords(@selectedGear, x, y) handlePenUp: -> if @isPenDown if @selectedButton is "gearButton" unless (@selectedGear? or @stroke.length is 0) @processGearStroke() else if @selectedButton is "chainButton" @processChainStroke() else if @selectedButton is "momentumButton" if @selectedGear if Math.abs(@selectedGearMomentum) > MIN_MOMENTUM @selectedGear.momentum = @selectedGearMomentum else @selectedGear.momentum = 0 @selectedGearMomentum = 0 @selectedGear = null @goalLocationGear = null @isPenDown = false isButtonAt: (x, y, button) -> x > button.location.x and x < button.location.x + button.width + 2 * button.padding and y > button.location.y and y < button.location.y + button.height + 2 * button.padding getButtonAt: (x, y) -> if not @shouldShowButtons() return null for own buttonName, button of @buttons if @isButtonAt(x, y, button) return button null normalizeStroke: (stroke) -> MIN_POINT_DISTANCE = 10 normalizedStroke = [] if stroke.length > 0 [p1, strokeTail...] = stroke normalizedStroke.push(p1) for p2 in strokeTail if p1.distance(p2) > MIN_POINT_DISTANCE normalizedStroke.push(p2) p1 = p2 normalizedStroke createGearFromStroke: (stroke) -> numberOfPoints = stroke.length if numberOfPoints > 0 sumX = 0 sumY = 0 minX = Number.MAX_VALUE maxX = Number.MIN_VALUE minY = Number.MAX_VALUE maxY = Number.MIN_VALUE for p in stroke sumX += p.x sumY += p.y minX = Math.min(minX, p.x) maxX = Math.max(maxX, p.x) minY = Math.min(minY, p.y) maxY = Math.max(maxY, p.y) width = maxX - minX height = maxY - minY t = Math.floor(0.5 * (width + height) / MODULE) # find area, based on http://stackoverflow.com/questions/451426 # /how-do-i-calculate-the-surface-area-of-a-2d-polygon doubleArea = 0 for i in [0...numberOfPoints] j = (i + 1) % numberOfPoints doubleArea += stroke[i].x * stroke[j].y doubleArea -= stroke[i].y * stroke[j].x # create a new gear if the stroke is sufficiently circle-like and large enough area = Math.abs(doubleArea) / 2 radius = 0.25 * ((maxX - minX) + (maxY - minY)) idealTrueAreaRatio = (Math.PI * Math.pow(radius, 2)) / area if idealTrueAreaRatio > 0.80 and idealTrueAreaRatio < 1.20 and t > MIN_GEAR_TEETH x = sumX / numberOfPoints y = sumY / numberOfPoints return new Gear(new Point(x, y), 0, t) null removeStrokedGears: (stroke) -> for own id, gear of @board.getTopLevelGears() if Util.pointPathDistance(gear.location, stroke, false) < gear.innerRadius @board.removeGear(gear) processGearStroke: -> normalizedStroke = @normalizeStroke(@stroke) gear = @createGearFromStroke(normalizedStroke) if gear? isGearAdded = @board.addGear(gear) if isGearAdded and !(gear.numberOfTeeth of @gearImages) @addGearImage(gear) else @removeStrokedGears(normalizedStroke) @stroke = [] gearImageLoaded: (numberOfTeeth, image) -> @gearImages[numberOfTeeth] = image addGearImage: (gear) -> # draw gear on temporary canvas gearCanvas = document.createElement("canvas") size = 2 * (gear.outerRadius + MODULE) # slightly larger than gear diameter gearCanvas.height = size gearCanvas.width = size ctx = gearCanvas.getContext("2d") gearCopy = new Gear(new Point(0.5 * size, 0.5 * size), 0, gear.numberOfTeeth, gear.id) @drawGear(ctx, gearCopy) # convert canvas to png image = new Image() image.onload = => @gearImageLoaded(gear.numberOfTeeth, image) image.src = gearCanvas.toDataURL("image/png") removeStrokedChains: (stroke) -> for own id, chain of @board.getChains() if chain.intersectsPath(stroke) @board.removeChain(chain) processChainStroke: -> normalizedStroke = @normalizeStroke(@stroke) @stroke = [] gearsInChain = Util.findGearsInsidePolygon(normalizedStroke, @board.getGears()) if normalizedStroke.length >= 3 and gearsInChain.length > 0 chain = new Chain(normalizedStroke) @board.addChain(chain) else if normalizedStroke.length >= 2 @removeStrokedChains(normalizedStroke) calculateMomentumFromCoords: (gear, x, y) -> angle = Math.atan2(y - gear.location.y, x - gear.location.x) angleFromTop = angle + 0.5 * Math.PI if angleFromTop < Math.PI angleFromTop else angleFromTop - 2 * Math.PI # -- updating -- updateAndDraw: => setTimeout((=> requestAnimationFrame(@updateAndDraw) @update() @draw() ), 1000 / FPS) updateAndDrawNoRAF: => @update() @draw() setTimeout((=> @updateAndDrawNoRAF()), 1000 / FPS) update: => updateTime = new Date().getTime() delta = updateTime - @lastUpdateTime if @selectedButton is "playButton" @board.rotateAllTurningObjects(delta) if @isDemoPlaying @updateDemo(delta) @lastUpdateTime = updateTime # -- rendering -- drawGear: (ctx, gear, color = "black") -> {x, y} = gear.location rotation = gear.rotation numberOfTeeth = gear.numberOfTeeth gearImage = @gearImages[gear.numberOfTeeth] if color is "black" and gearImage? # use predrawn image instead of drawing it again gearImage = @gearImages[gear.numberOfTeeth] ctx.save() ctx.translate(x, y) ctx.rotate(rotation) ctx.drawImage(gearImage, -0.5 * gearImage.width, -0.5 * gearImage.height) ctx.restore() return # draw teeth angleStep = 2 * Math.PI / numberOfTeeth innerPoints = [] outerPoints = [] for i in [0...numberOfTeeth] for r in [0...4] if r is 0 or r is 3 innerPoints.push(Point.polar((i + 0.25 * r) * angleStep, gear.innerRadius)) else outerPoints.push(Point.polar((i + 0.25 * r) * angleStep, gear.outerRadius)) ctx.save() if color is "black" hue = Math.floor(Math.random()*360) ctx.fillStyle = "hsla(" + hue + ", 85%, 60%, 0.8)" else ctx.fillStyle = "hsla(0, 0%, 90%, 0.2)" ctx.strokeStyle = color ctx.lineWidth = 2 ctx.translate(x, y) ctx.rotate(rotation) ctx.beginPath() ctx.moveTo(gear.innerRadius, 0) for i in [0...numberOfTeeth * 2] if i % 2 is 0 ctx.lineTo(innerPoints[i].x, innerPoints[i].y) ctx.lineTo(outerPoints[i].x, outerPoints[i].y) else ctx.lineTo(outerPoints[i].x, outerPoints[i].y) ctx.lineTo(innerPoints[i].x, innerPoints[i].y) ctx.closePath() ctx.fill() ctx.stroke() # draw axis ctx.beginPath() ctx.moveTo(AXIS_RADIUS, 0) ctx.arc(0, 0, AXIS_RADIUS, 0, 2 * Math.PI, true) ctx.closePath() ctx.stroke() # draw rotation indicator line ctx.beginPath() ctx.moveTo(AXIS_RADIUS, 0) ctx.lineTo(gear.innerRadius, 0) ctx.closePath() ctx.stroke() ctx.restore() drawButton: (ctx, button) -> {x, y} = button.location padding = button.padding ctx.save() ctx.translate(x, y) ctx.beginPath() # draw a round rectangle radius = 10 width = button.width + 2 * padding height = button.height + 2 * padding ctx.moveTo(radius, 0) ctx.lineTo(width - radius, 0) ctx.quadraticCurveTo(width, 0, width, radius) ctx.lineTo(width, height - radius) ctx.quadraticCurveTo(width, height, width - radius, height) ctx.lineTo(radius, height) ctx.quadraticCurveTo(0, height, 0, height - radius); ctx.lineTo(0, radius) ctx.quadraticCurveTo(0, 0, radius, 0); if button.name is @selectedButton ctx.fillStyle = "rgba(50, 150, 255, 0.8)" else ctx.fillStyle = "rgba(255, 255, 255, 0.8)" ctx.fill() ctx.lineWidth = 1 ctx.strokeStyle = "black" ctx.stroke() ctx.drawImage(button, padding, padding) ctx.restore() drawMomentum: (ctx, gear, momentum, color = "red") -> pitchRadius = gear.pitchRadius top = new Point(gear.location.x, gear.location.y - pitchRadius) ctx.save() ctx.lineWidth = 5 ctx.lineCap = "round" ctx.strokeStyle = color ctx.translate(top.x, top.y) # draw arc ctx.beginPath() ctx.arc(0, pitchRadius, pitchRadius, -0.5 * Math.PI, momentum - 0.5 * Math.PI, momentum < 0) ctx.stroke() # draw arrow head length = 15 angle = 0.2 * Math.PI headX = -Math.cos(momentum + 0.5 * Math.PI) * pitchRadius headY = pitchRadius - Math.sin(momentum + 0.5 * Math.PI) * pitchRadius head = new Point(headX, headY) sign = Util.sign(momentum) p1 = head.minus(Point.polar(momentum + angle, sign * length)) ctx.beginPath() ctx.moveTo(headX, headY) ctx.lineTo(p1.x, p1.y) ctx.stroke() p2 = head.minus(Point.polar(momentum - angle, sign * length)) ctx.beginPath() ctx.moveTo(headX, headY) ctx.lineTo(p2.x, p2.y) ctx.stroke() ctx.restore() drawChain: (ctx, chain) -> ctx.save() ctx.lineWidth = Chain.WIDTH ctx.lineCap = "round" ctx.strokeStyle = "rgb(0, 0, 255)" ctx.moveTo(chain.segments[0].start.x, chain.segments[0].start.y) for segment in chain.segments if segment instanceof ArcSegment isCounterClockwise = (segment.direction is Util.Direction.COUNTER_CLOCKWISE) ctx.beginPath() ctx.arc(segment.center.x, segment.center.y, segment.radius, segment.startAngle, segment.endAngle, isCounterClockwise) ctx.stroke() else ctx.beginPath() ctx.moveTo(segment.start.x, segment.start.y) ctx.lineTo(segment.end.x, segment.end.y) ctx.stroke() ctx.fillStyle = "white" for point in chain.findPointsOnChain(25) ctx.beginPath() ctx.arc(point.x, point.y, 3, 0, 2 * Math.PI, true) ctx.fill() ctx.restore() drawDemoPointer: (ctx, location) -> ctx.drawImage(@pointerImage, location.x - 0.5 * @pointerImage.width, location.y) draw: -> if @canvas.getContext? @updateCanvasSize() ctx = @canvas.getContext("2d") ctx.clearRect(0, 0, @canvas.width, @canvas.height) # draw gears sortedGears = @board.getGearsSortedByGroupAndLevel() arrowsToDraw = [] for i in [0...sortedGears.length] gear = sortedGears[i] momentum = gear.momentum if gear is @selectedGear and @goalLocationGear @drawGear(ctx, gear, "grey") if momentum arrowsToDraw.push([gear, momentum, "grey"]) else @drawGear(ctx, gear) if momentum arrowsToDraw.push([gear, momentum, "red"]) # draw chains and arrows when all the gears in current group on current level are drawn shouldDrawChainsAndArrows = (i is sortedGears.length - 1) or (@board.getLevelScore(gear) isnt @board.getLevelScore(sortedGears[i + 1])) if shouldDrawChainsAndArrows for chain in @board.getChainsInGroupOnLevel(gear.group, gear.level) @drawChain(ctx, chain) for arrow in arrowsToDraw @drawMomentum(ctx, arrow[0], arrow[1], arrow[2]) arrowsToDraw = [] # draw goalLocationGear if @goalLocationGear @drawGear(ctx, @goalLocationGear, "red") # draw selected gear momentum if @selectedGear? and @selectedGearMomentum @drawMomentum(ctx, @selectedGear, @selectedGearMomentum) # draw stroke if @stroke.length > 0 ctx.save() if @selectedButton is "gearButton" ctx.strokeStyle = "black" ctx.lineWidth = 2 else # chain stroke ctx.strokeStyle = "blue" ctx.lineWidth = 4 ctx.beginPath() ctx.moveTo(@stroke[0].x, @stroke[0].y) for i in [1...@stroke.length] ctx.lineTo(@stroke[i].x, @stroke[i].y) ctx.stroke() ctx.restore() # draw buttons if @areButtonsLoaded and @shouldShowButtons() for own buttonName of @buttons @drawButton(ctx, @buttons[buttonName]) # draw message if @message.length > 0 ctx.save() ctx.fillStyle = @messageColor ctx.font = "bold 20px Arial" ctx.fillText(@message, 20, 120) ctx.restore() # draw demo text and pointer if @isDemoPlaying and @pointerImage @drawDemoPointer(ctx, @pointerLocation) updateCanvasSize: () -> @canvas.width = @canvas.parentElement.getBoundingClientRect().width @canvas.height = @canvas.parentElement.getBoundingClientRect().height @buttons["clearButton"].location.x = Math.max(@canvas.width - 260, @buttons["playButton"].location.x + 80) @buttons["cloudButton"].location.x = @buttons["clearButton"].location.x + 80 @buttons["helpButton"].location.x = @buttons["cloudButton"].location.x + 80 # -- usage demo -- loadDemoMovements: -> @demoMovements = [ from: @getButtonCenter("helpButton") to: @getButtonCenter("gearButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 2000 , to: new Point(300, 200) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 100 duration: 1500 , to: new Point(500, 200) type: MovementType.STRAIGHT duration: 1000 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 40 duration: 1000 , to: new Point(500, 240) type: MovementType.STRAIGHT duration: 500 , to: new Point(300, 300) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(100, 180) type: MovementType.STRAIGHT duration: 1000 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 90 duration: 1000 , to: new Point(100, 260) type: MovementType.STRAIGHT duration: 500 , to: new Point(180, 260) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(550, 220) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 80 duration: 1000 , to: @getButtonCenter("chainButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(280, 150) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN type: MovementType.LEFT_HALF_CIRCLE radius: 140 duration: 1500 pause: 0 , to: new Point(600, 400) type: MovementType.STRAIGHT duration: 1000 pause: 0 , type: MovementType.RIGHT_HALF_CIRCLE radius: 110 duration: 1000 pause: 0 , to: new Point(280, 150) atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("momentumButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(185, 180) type: MovementType.STRAIGHT duration: 1500 , to: new Point(150, 190) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("playButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: @getButtonCenter("chainButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 3000 , to: new Point(425, 250) type: MovementType.STRAIGHT duration: 1000 , to: new Point(525, 150) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("gearButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(20, 250) type: MovementType.STRAIGHT duration: 1000 , to: new Point(650, 300) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(425, 200) type: MovementType.STRAIGHT duration: 1000 , to: new Point(200, 400) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 ] getButtonCenter: (buttonName) -> button = @buttons[buttonName] buttonCorner = new Point(button.location.x, button.location.y) buttonCorner.plus(new Point(0.5 * button.width + button.padding, 0.5 * button.height + button.padding)) updateDemo: (delta) -> # check if resting or if last movement completed if @restTimer > 0 @restTimer = Math.max(@restTimer - delta, 0) return else if @currentDemoMovement is @demoMovements.length @stopDemo() return # advance movement movement = @demoMovements[@currentDemoMovement] if @movementCompletion is 0 movement.from ?= @pointerLocation movement.pause ?= 500 @pointerLocation = movement.from.clone() if movement.atStart is MovementAction.PEN_DOWN @handlePenDown(@pointerLocation.x, @pointerLocation.y) if @movementCompletion < 1 @movementCompletion = Math.min(1, @movementCompletion + delta / movement.duration) @updatePointerLocation(movement, @movementCompletion) @handlePenMove(@pointerLocation.x, @pointerLocation.y) if @movementCompletion is 1 if movement.atEnd is MovementAction.PEN_TAP @handlePenDown(@pointerLocation.x, @pointerLocation.y) @handlePenUp() else if movement.atEnd is MovementAction.PEN_UP @handlePenUp() @restTimer = movement.pause @movementCompletion = 0 @currentDemoMovement++ updatePointerLocation: (movement, movementCompletion) -> if movement.type is MovementType.STRAIGHT delta = movement.to.minus(movement.from) @pointerLocation = movement.from.plus(delta.times(movementCompletion)) else if movement.type is MovementType.CIRCLE center = new Point(movement.from.x , movement.from.y + movement.radius) @pointerLocation = center.plus(Point.polar(Math.PI - (movementCompletion - 0.25) * 2 * Math.PI, movement.radius)) else if movement.type is MovementType.LEFT_HALF_CIRCLE center = new Point(movement.from.x , movement.from.y + movement.radius) angle = 1.5 * Math.PI - movementCompletion * Math.PI @pointerLocation = center.plus(Point.polar(angle, movement.radius)) else if movement.type is MovementType.RIGHT_HALF_CIRCLE center = new Point(movement.from.x , movement.from.y - movement.radius) angle = 0.5 * Math.PI - movementCompletion * Math.PI @pointerLocation = center.plus(Point.polar(angle, movement.radius)) playDemo: -> @loadDemoMovements() # load these on each play in case canvas size changed @boardBackup = @board.clone() @board.clear() @currentDemoMovement = 0 @movementCompletion = 0 @isDemoPlaying = true @displayMessage("click anywhere to stop the demo") stopDemo: -> @isDemoPlaying = false @restTimer = 0 @stroke = [] @selectedGear = null @selectedIcon = "gearIcon" @board.restoreAfterDemo(@boardBackup) @clearMessage() boardUploaded: (event) -> parent.location.hash = event.target.responseText.trim() @displayMessage("Board saved. Share it by copying the text in your address bar.", "black", 4000) uploadBoard: -> boardJSON = JSON.stringify(@board) Util.sendPostRequest(boardJSON, "upload_board.php", ((event) => @boardUploaded(event))) window.gearsketch.GearSketch = GearSketch
true
# By PI:NAME:<NAME>END_PI # University of Twente - Department of Instructional Technology # Licensed under the MIT license "use strict" # TODO: # - support IE9? # - use "for element, i in ..." where appropriate # - chained comparisons: 1 < x < 100 # - improve gear, chain & momentum icons # - disallow chains crossing gears' axes? (if gear on higher level) # - allow gears to overlap other gears' axes when the larger gear is on a higher level? # - figure out why drawing with RAF is slower than drawing without RAF on iPad # imports Point = window.gearsketch.Point ArcSegment = window.gearsketch.ArcSegment LineSegment = window.gearsketch.LineSegment Util = window.gearsketch.Util Gear = window.gearsketch.model.Gear Chain = window.gearsketch.model.Chain Board = window.gearsketch.model.Board # -- constants -- FPS = 60 MIN_GEAR_TEETH = 8 MIN_MOMENTUM = 0.2 # --------------------------- # -------- GearSketch ------- # --------------------------- class GearSketch # -- imported constants -- MODULE = Util.MODULE AXIS_RADIUS = Util.AXIS_RADIUS BUTTON_INFO = [ ["gearButton", "GearIcon.png"] ["chainButton", "ChainIcon.png"] ["momentumButton", "MomentumIcon.png"] ["playButton", "PlayIcon.png"] ["clearButton", "ClearIcon.png"] ["cloudButton", "CloudIcon.png"] ["helpButton", "HelpIcon.png"] ] MovementAction = PEN_DOWN: "penDown" PEN_UP: "penUp" PEN_TAP: "penTap" MovementType = STRAIGHT: "straight" CIRCLE: "circle" LEFT_HALF_CIRCLE: "leftHalfCircle" RIGHT_HALF_CIRCLE: "rightHalfCircle" buttons: {} loadedButtons: 0 areButtonsLoaded: false selectedButton: BUTTON_INFO[0][0] gearImages: {} isPenDown: false stroke: [] offset: new Point() message: "" messageColor: "black" # usage demo pointerLocation: new Point() currentDemoMovement: 0 movementCompletion: 0 restTimer: 0 # Passing false to showButtons will hide them, unless the demo is # playing. This comes handy when adding controls outside the canvas. constructor: (showButtons = true) -> @loadButtons() @showButtons = showButtons @loadDemoPointer() @loadBoard() @canvas = document.getElementById("gearsketch_canvas") @canvasOffsetX = @canvas.getBoundingClientRect().left @canvasOffsetY = @canvas.getBoundingClientRect().top @isDemoPlaying = false @updateCanvasSize() @addCanvasListeners() @lastUpdateTime = new Date().getTime() #@updateAndDraw() @updateAndDrawNoRAF() buttonLoaded: -> @loadedButtons++ if @loadedButtons is BUTTON_INFO.length @areButtonsLoaded = true loadButtons: -> x = y = 20 for [name, file] in BUTTON_INFO button = new Image() button.name = name button.onload = => @buttonLoaded() button.src = "img/" + file button.location = new Point(x, y) button.padding = 3 @buttons[name] = button x += 80 loadDemoPointer: -> image = new Image() image.onload = => @pointerImage = image image.src = "img/hand.png" loadBoard: -> @board = if parent.location.hash.length > 1 try hash = parent.location.hash.substr(1) boardJSON = Util.sendGetRequest("boards/#{hash}.txt") Board.fromObject(JSON.parse(boardJSON)) catch error @displayMessage("Error: could not load board", "red", 2000) new Board() else new Board() @addGearImage(gear) for id, gear of @board.getGears() displayMessage: (message, color = "black", time = 0) -> @message = message @messageColor = color if time > 0 setTimeout((=> @clearMessage()), time) clearMessage: -> @message = "" selectButton: (buttonName) -> @selectedButton = buttonName shouldShowButtons: -> return @showButtons or @isDemoPlaying # Input callback methods addCanvasListeners: -> canvasEventHandler = Hammer(@canvas, {drag_min_distance: 1}) canvasEventHandler.on("touch", ((e) => @forwardPenDownEvent.call(this, e))) canvasEventHandler.on("drag", ((e) => @forwardPenMoveEvent.call(this, e))) canvasEventHandler.on("release", ((e) => @forwardPenUpEvent.call(this, e))) forwardPenDownEvent: (event) -> event.gesture.preventDefault() if @isDemoPlaying @stopDemo() else x = event.gesture.center.pageX - @canvasOffsetX y = event.gesture.center.pageY - @canvasOffsetY @handlePenDown(x, y) forwardPenMoveEvent: (event) -> event.gesture.preventDefault() unless @isDemoPlaying x = event.gesture.center.pageX - @canvasOffsetX y = event.gesture.center.pageY - @canvasOffsetY @handlePenMove(x, y) forwardPenUpEvent: (event) -> unless @isDemoPlaying @handlePenUp() handlePenDown: (x, y) -> point = new Point(x, y) if @isPenDown # pen released outside of canvas @handlePenUp() else button = @getButtonAt(x, y) if button if button.name is "clearButton" # remove hash from url and clear board parent.location.hash = "" @board.clear() else if button.name is "cloudButton" @uploadBoard() else if button.name is "helpButton" @playDemo() else @selectButton(button.name) else if @selectedButton is "gearButton" @selectedGear = @board.getTopLevelGearAt(point) if @selectedGear? @offset = point.minus(@selectedGear.location) else if !@board.getGearAt(point)? # don't create stroke if lower level gear selected @stroke.push(point) @isPenDown = true else if @selectedButton is "chainButton" @stroke.push(point) @isPenDown = true else if @selectedButton is "momentumButton" @selectedGear = @board.getGearAt(point) if @selectedGear @selectedGear.momentum = 0 @selectedGearMomentum = @calculateMomentumFromCoords(@selectedGear, x, y) @isPenDown = true handlePenMove: (x, y) -> point = new Point(x, y) if @isPenDown if @selectedButton is "gearButton" if @selectedGear goalLocation = point.minus(@offset) canPlaceGear = @board.placeGear(@selectedGear, goalLocation) if canPlaceGear @goalLocationGear = null else @goalLocationGear = new Gear(goalLocation, @selectedGear.rotation, @selectedGear.numberOfTeeth, @selectedGear.id) else if @stroke.length > 0 @stroke.push(point) else if @selectedButton is "chainButton" @stroke.push(point) else if @selectedButton is "momentumButton" if @selectedGear @selectedGearMomentum = @calculateMomentumFromCoords(@selectedGear, x, y) handlePenUp: -> if @isPenDown if @selectedButton is "gearButton" unless (@selectedGear? or @stroke.length is 0) @processGearStroke() else if @selectedButton is "chainButton" @processChainStroke() else if @selectedButton is "momentumButton" if @selectedGear if Math.abs(@selectedGearMomentum) > MIN_MOMENTUM @selectedGear.momentum = @selectedGearMomentum else @selectedGear.momentum = 0 @selectedGearMomentum = 0 @selectedGear = null @goalLocationGear = null @isPenDown = false isButtonAt: (x, y, button) -> x > button.location.x and x < button.location.x + button.width + 2 * button.padding and y > button.location.y and y < button.location.y + button.height + 2 * button.padding getButtonAt: (x, y) -> if not @shouldShowButtons() return null for own buttonName, button of @buttons if @isButtonAt(x, y, button) return button null normalizeStroke: (stroke) -> MIN_POINT_DISTANCE = 10 normalizedStroke = [] if stroke.length > 0 [p1, strokeTail...] = stroke normalizedStroke.push(p1) for p2 in strokeTail if p1.distance(p2) > MIN_POINT_DISTANCE normalizedStroke.push(p2) p1 = p2 normalizedStroke createGearFromStroke: (stroke) -> numberOfPoints = stroke.length if numberOfPoints > 0 sumX = 0 sumY = 0 minX = Number.MAX_VALUE maxX = Number.MIN_VALUE minY = Number.MAX_VALUE maxY = Number.MIN_VALUE for p in stroke sumX += p.x sumY += p.y minX = Math.min(minX, p.x) maxX = Math.max(maxX, p.x) minY = Math.min(minY, p.y) maxY = Math.max(maxY, p.y) width = maxX - minX height = maxY - minY t = Math.floor(0.5 * (width + height) / MODULE) # find area, based on http://stackoverflow.com/questions/451426 # /how-do-i-calculate-the-surface-area-of-a-2d-polygon doubleArea = 0 for i in [0...numberOfPoints] j = (i + 1) % numberOfPoints doubleArea += stroke[i].x * stroke[j].y doubleArea -= stroke[i].y * stroke[j].x # create a new gear if the stroke is sufficiently circle-like and large enough area = Math.abs(doubleArea) / 2 radius = 0.25 * ((maxX - minX) + (maxY - minY)) idealTrueAreaRatio = (Math.PI * Math.pow(radius, 2)) / area if idealTrueAreaRatio > 0.80 and idealTrueAreaRatio < 1.20 and t > MIN_GEAR_TEETH x = sumX / numberOfPoints y = sumY / numberOfPoints return new Gear(new Point(x, y), 0, t) null removeStrokedGears: (stroke) -> for own id, gear of @board.getTopLevelGears() if Util.pointPathDistance(gear.location, stroke, false) < gear.innerRadius @board.removeGear(gear) processGearStroke: -> normalizedStroke = @normalizeStroke(@stroke) gear = @createGearFromStroke(normalizedStroke) if gear? isGearAdded = @board.addGear(gear) if isGearAdded and !(gear.numberOfTeeth of @gearImages) @addGearImage(gear) else @removeStrokedGears(normalizedStroke) @stroke = [] gearImageLoaded: (numberOfTeeth, image) -> @gearImages[numberOfTeeth] = image addGearImage: (gear) -> # draw gear on temporary canvas gearCanvas = document.createElement("canvas") size = 2 * (gear.outerRadius + MODULE) # slightly larger than gear diameter gearCanvas.height = size gearCanvas.width = size ctx = gearCanvas.getContext("2d") gearCopy = new Gear(new Point(0.5 * size, 0.5 * size), 0, gear.numberOfTeeth, gear.id) @drawGear(ctx, gearCopy) # convert canvas to png image = new Image() image.onload = => @gearImageLoaded(gear.numberOfTeeth, image) image.src = gearCanvas.toDataURL("image/png") removeStrokedChains: (stroke) -> for own id, chain of @board.getChains() if chain.intersectsPath(stroke) @board.removeChain(chain) processChainStroke: -> normalizedStroke = @normalizeStroke(@stroke) @stroke = [] gearsInChain = Util.findGearsInsidePolygon(normalizedStroke, @board.getGears()) if normalizedStroke.length >= 3 and gearsInChain.length > 0 chain = new Chain(normalizedStroke) @board.addChain(chain) else if normalizedStroke.length >= 2 @removeStrokedChains(normalizedStroke) calculateMomentumFromCoords: (gear, x, y) -> angle = Math.atan2(y - gear.location.y, x - gear.location.x) angleFromTop = angle + 0.5 * Math.PI if angleFromTop < Math.PI angleFromTop else angleFromTop - 2 * Math.PI # -- updating -- updateAndDraw: => setTimeout((=> requestAnimationFrame(@updateAndDraw) @update() @draw() ), 1000 / FPS) updateAndDrawNoRAF: => @update() @draw() setTimeout((=> @updateAndDrawNoRAF()), 1000 / FPS) update: => updateTime = new Date().getTime() delta = updateTime - @lastUpdateTime if @selectedButton is "playButton" @board.rotateAllTurningObjects(delta) if @isDemoPlaying @updateDemo(delta) @lastUpdateTime = updateTime # -- rendering -- drawGear: (ctx, gear, color = "black") -> {x, y} = gear.location rotation = gear.rotation numberOfTeeth = gear.numberOfTeeth gearImage = @gearImages[gear.numberOfTeeth] if color is "black" and gearImage? # use predrawn image instead of drawing it again gearImage = @gearImages[gear.numberOfTeeth] ctx.save() ctx.translate(x, y) ctx.rotate(rotation) ctx.drawImage(gearImage, -0.5 * gearImage.width, -0.5 * gearImage.height) ctx.restore() return # draw teeth angleStep = 2 * Math.PI / numberOfTeeth innerPoints = [] outerPoints = [] for i in [0...numberOfTeeth] for r in [0...4] if r is 0 or r is 3 innerPoints.push(Point.polar((i + 0.25 * r) * angleStep, gear.innerRadius)) else outerPoints.push(Point.polar((i + 0.25 * r) * angleStep, gear.outerRadius)) ctx.save() if color is "black" hue = Math.floor(Math.random()*360) ctx.fillStyle = "hsla(" + hue + ", 85%, 60%, 0.8)" else ctx.fillStyle = "hsla(0, 0%, 90%, 0.2)" ctx.strokeStyle = color ctx.lineWidth = 2 ctx.translate(x, y) ctx.rotate(rotation) ctx.beginPath() ctx.moveTo(gear.innerRadius, 0) for i in [0...numberOfTeeth * 2] if i % 2 is 0 ctx.lineTo(innerPoints[i].x, innerPoints[i].y) ctx.lineTo(outerPoints[i].x, outerPoints[i].y) else ctx.lineTo(outerPoints[i].x, outerPoints[i].y) ctx.lineTo(innerPoints[i].x, innerPoints[i].y) ctx.closePath() ctx.fill() ctx.stroke() # draw axis ctx.beginPath() ctx.moveTo(AXIS_RADIUS, 0) ctx.arc(0, 0, AXIS_RADIUS, 0, 2 * Math.PI, true) ctx.closePath() ctx.stroke() # draw rotation indicator line ctx.beginPath() ctx.moveTo(AXIS_RADIUS, 0) ctx.lineTo(gear.innerRadius, 0) ctx.closePath() ctx.stroke() ctx.restore() drawButton: (ctx, button) -> {x, y} = button.location padding = button.padding ctx.save() ctx.translate(x, y) ctx.beginPath() # draw a round rectangle radius = 10 width = button.width + 2 * padding height = button.height + 2 * padding ctx.moveTo(radius, 0) ctx.lineTo(width - radius, 0) ctx.quadraticCurveTo(width, 0, width, radius) ctx.lineTo(width, height - radius) ctx.quadraticCurveTo(width, height, width - radius, height) ctx.lineTo(radius, height) ctx.quadraticCurveTo(0, height, 0, height - radius); ctx.lineTo(0, radius) ctx.quadraticCurveTo(0, 0, radius, 0); if button.name is @selectedButton ctx.fillStyle = "rgba(50, 150, 255, 0.8)" else ctx.fillStyle = "rgba(255, 255, 255, 0.8)" ctx.fill() ctx.lineWidth = 1 ctx.strokeStyle = "black" ctx.stroke() ctx.drawImage(button, padding, padding) ctx.restore() drawMomentum: (ctx, gear, momentum, color = "red") -> pitchRadius = gear.pitchRadius top = new Point(gear.location.x, gear.location.y - pitchRadius) ctx.save() ctx.lineWidth = 5 ctx.lineCap = "round" ctx.strokeStyle = color ctx.translate(top.x, top.y) # draw arc ctx.beginPath() ctx.arc(0, pitchRadius, pitchRadius, -0.5 * Math.PI, momentum - 0.5 * Math.PI, momentum < 0) ctx.stroke() # draw arrow head length = 15 angle = 0.2 * Math.PI headX = -Math.cos(momentum + 0.5 * Math.PI) * pitchRadius headY = pitchRadius - Math.sin(momentum + 0.5 * Math.PI) * pitchRadius head = new Point(headX, headY) sign = Util.sign(momentum) p1 = head.minus(Point.polar(momentum + angle, sign * length)) ctx.beginPath() ctx.moveTo(headX, headY) ctx.lineTo(p1.x, p1.y) ctx.stroke() p2 = head.minus(Point.polar(momentum - angle, sign * length)) ctx.beginPath() ctx.moveTo(headX, headY) ctx.lineTo(p2.x, p2.y) ctx.stroke() ctx.restore() drawChain: (ctx, chain) -> ctx.save() ctx.lineWidth = Chain.WIDTH ctx.lineCap = "round" ctx.strokeStyle = "rgb(0, 0, 255)" ctx.moveTo(chain.segments[0].start.x, chain.segments[0].start.y) for segment in chain.segments if segment instanceof ArcSegment isCounterClockwise = (segment.direction is Util.Direction.COUNTER_CLOCKWISE) ctx.beginPath() ctx.arc(segment.center.x, segment.center.y, segment.radius, segment.startAngle, segment.endAngle, isCounterClockwise) ctx.stroke() else ctx.beginPath() ctx.moveTo(segment.start.x, segment.start.y) ctx.lineTo(segment.end.x, segment.end.y) ctx.stroke() ctx.fillStyle = "white" for point in chain.findPointsOnChain(25) ctx.beginPath() ctx.arc(point.x, point.y, 3, 0, 2 * Math.PI, true) ctx.fill() ctx.restore() drawDemoPointer: (ctx, location) -> ctx.drawImage(@pointerImage, location.x - 0.5 * @pointerImage.width, location.y) draw: -> if @canvas.getContext? @updateCanvasSize() ctx = @canvas.getContext("2d") ctx.clearRect(0, 0, @canvas.width, @canvas.height) # draw gears sortedGears = @board.getGearsSortedByGroupAndLevel() arrowsToDraw = [] for i in [0...sortedGears.length] gear = sortedGears[i] momentum = gear.momentum if gear is @selectedGear and @goalLocationGear @drawGear(ctx, gear, "grey") if momentum arrowsToDraw.push([gear, momentum, "grey"]) else @drawGear(ctx, gear) if momentum arrowsToDraw.push([gear, momentum, "red"]) # draw chains and arrows when all the gears in current group on current level are drawn shouldDrawChainsAndArrows = (i is sortedGears.length - 1) or (@board.getLevelScore(gear) isnt @board.getLevelScore(sortedGears[i + 1])) if shouldDrawChainsAndArrows for chain in @board.getChainsInGroupOnLevel(gear.group, gear.level) @drawChain(ctx, chain) for arrow in arrowsToDraw @drawMomentum(ctx, arrow[0], arrow[1], arrow[2]) arrowsToDraw = [] # draw goalLocationGear if @goalLocationGear @drawGear(ctx, @goalLocationGear, "red") # draw selected gear momentum if @selectedGear? and @selectedGearMomentum @drawMomentum(ctx, @selectedGear, @selectedGearMomentum) # draw stroke if @stroke.length > 0 ctx.save() if @selectedButton is "gearButton" ctx.strokeStyle = "black" ctx.lineWidth = 2 else # chain stroke ctx.strokeStyle = "blue" ctx.lineWidth = 4 ctx.beginPath() ctx.moveTo(@stroke[0].x, @stroke[0].y) for i in [1...@stroke.length] ctx.lineTo(@stroke[i].x, @stroke[i].y) ctx.stroke() ctx.restore() # draw buttons if @areButtonsLoaded and @shouldShowButtons() for own buttonName of @buttons @drawButton(ctx, @buttons[buttonName]) # draw message if @message.length > 0 ctx.save() ctx.fillStyle = @messageColor ctx.font = "bold 20px Arial" ctx.fillText(@message, 20, 120) ctx.restore() # draw demo text and pointer if @isDemoPlaying and @pointerImage @drawDemoPointer(ctx, @pointerLocation) updateCanvasSize: () -> @canvas.width = @canvas.parentElement.getBoundingClientRect().width @canvas.height = @canvas.parentElement.getBoundingClientRect().height @buttons["clearButton"].location.x = Math.max(@canvas.width - 260, @buttons["playButton"].location.x + 80) @buttons["cloudButton"].location.x = @buttons["clearButton"].location.x + 80 @buttons["helpButton"].location.x = @buttons["cloudButton"].location.x + 80 # -- usage demo -- loadDemoMovements: -> @demoMovements = [ from: @getButtonCenter("helpButton") to: @getButtonCenter("gearButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 2000 , to: new Point(300, 200) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 100 duration: 1500 , to: new Point(500, 200) type: MovementType.STRAIGHT duration: 1000 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 40 duration: 1000 , to: new Point(500, 240) type: MovementType.STRAIGHT duration: 500 , to: new Point(300, 300) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(100, 180) type: MovementType.STRAIGHT duration: 1000 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 90 duration: 1000 , to: new Point(100, 260) type: MovementType.STRAIGHT duration: 500 , to: new Point(180, 260) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(550, 220) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.CIRCLE radius: 80 duration: 1000 , to: @getButtonCenter("chainButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(280, 150) type: MovementType.STRAIGHT duration: 1500 , atStart: MovementAction.PEN_DOWN type: MovementType.LEFT_HALF_CIRCLE radius: 140 duration: 1500 pause: 0 , to: new Point(600, 400) type: MovementType.STRAIGHT duration: 1000 pause: 0 , type: MovementType.RIGHT_HALF_CIRCLE radius: 110 duration: 1000 pause: 0 , to: new Point(280, 150) atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("momentumButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(185, 180) type: MovementType.STRAIGHT duration: 1500 , to: new Point(150, 190) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("playButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: @getButtonCenter("chainButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 3000 , to: new Point(425, 250) type: MovementType.STRAIGHT duration: 1000 , to: new Point(525, 150) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1000 , to: @getButtonCenter("gearButton") atEnd: MovementAction.PEN_TAP type: MovementType.STRAIGHT duration: 1500 , to: new Point(20, 250) type: MovementType.STRAIGHT duration: 1000 , to: new Point(650, 300) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 , to: new Point(425, 200) type: MovementType.STRAIGHT duration: 1000 , to: new Point(200, 400) atStart: MovementAction.PEN_DOWN atEnd: MovementAction.PEN_UP type: MovementType.STRAIGHT duration: 1500 ] getButtonCenter: (buttonName) -> button = @buttons[buttonName] buttonCorner = new Point(button.location.x, button.location.y) buttonCorner.plus(new Point(0.5 * button.width + button.padding, 0.5 * button.height + button.padding)) updateDemo: (delta) -> # check if resting or if last movement completed if @restTimer > 0 @restTimer = Math.max(@restTimer - delta, 0) return else if @currentDemoMovement is @demoMovements.length @stopDemo() return # advance movement movement = @demoMovements[@currentDemoMovement] if @movementCompletion is 0 movement.from ?= @pointerLocation movement.pause ?= 500 @pointerLocation = movement.from.clone() if movement.atStart is MovementAction.PEN_DOWN @handlePenDown(@pointerLocation.x, @pointerLocation.y) if @movementCompletion < 1 @movementCompletion = Math.min(1, @movementCompletion + delta / movement.duration) @updatePointerLocation(movement, @movementCompletion) @handlePenMove(@pointerLocation.x, @pointerLocation.y) if @movementCompletion is 1 if movement.atEnd is MovementAction.PEN_TAP @handlePenDown(@pointerLocation.x, @pointerLocation.y) @handlePenUp() else if movement.atEnd is MovementAction.PEN_UP @handlePenUp() @restTimer = movement.pause @movementCompletion = 0 @currentDemoMovement++ updatePointerLocation: (movement, movementCompletion) -> if movement.type is MovementType.STRAIGHT delta = movement.to.minus(movement.from) @pointerLocation = movement.from.plus(delta.times(movementCompletion)) else if movement.type is MovementType.CIRCLE center = new Point(movement.from.x , movement.from.y + movement.radius) @pointerLocation = center.plus(Point.polar(Math.PI - (movementCompletion - 0.25) * 2 * Math.PI, movement.radius)) else if movement.type is MovementType.LEFT_HALF_CIRCLE center = new Point(movement.from.x , movement.from.y + movement.radius) angle = 1.5 * Math.PI - movementCompletion * Math.PI @pointerLocation = center.plus(Point.polar(angle, movement.radius)) else if movement.type is MovementType.RIGHT_HALF_CIRCLE center = new Point(movement.from.x , movement.from.y - movement.radius) angle = 0.5 * Math.PI - movementCompletion * Math.PI @pointerLocation = center.plus(Point.polar(angle, movement.radius)) playDemo: -> @loadDemoMovements() # load these on each play in case canvas size changed @boardBackup = @board.clone() @board.clear() @currentDemoMovement = 0 @movementCompletion = 0 @isDemoPlaying = true @displayMessage("click anywhere to stop the demo") stopDemo: -> @isDemoPlaying = false @restTimer = 0 @stroke = [] @selectedGear = null @selectedIcon = "gearIcon" @board.restoreAfterDemo(@boardBackup) @clearMessage() boardUploaded: (event) -> parent.location.hash = event.target.responseText.trim() @displayMessage("Board saved. Share it by copying the text in your address bar.", "black", 4000) uploadBoard: -> boardJSON = JSON.stringify(@board) Util.sendPostRequest(boardJSON, "upload_board.php", ((event) => @boardUploaded(event))) window.gearsketch.GearSketch = GearSketch
[ { "context": "AND TRUST COMPANY'\n assert.equal b.city, 'N. QUINCY'\n assert.equal b.state, 'MA' \n ", "end": 1562, "score": 0.5757278203964233, "start": 1562, "tag": "NAME", "value": "" } ]
test/index.coffee
freewil/node-fedach
1
assert = require 'assert' {readFile} = require 'fs' fedach = require '../' describe 'fedach', -> describe 'download', -> it 'should download the data securely', (done) -> fedach.download (err, data) -> assert.ifError err assert.ok data done() describe 'parse', -> it 'should parse all the data', (done) -> readFile __dirname + '/FedACHdir.txt', 'utf8', (err, data) -> results = fedach.parse data assert.ok results assert.equal results.length, 100 a = results[0] assert.equal a.routing, '011000015' assert.equal a.office, 'O' assert.equal a.frb, '011000015' assert.equal a.type, '0' assert.equal a.date, '020802' assert.equal a.newRouting, '000000000' assert.equal a.customer, 'FEDERAL RESERVE BANK' assert.equal a.address, '1000 PEACHTREE ST N.E.' assert.equal a.city, 'ATLANTA' assert.equal a.state, 'GA' assert.equal a.zip, '30309' assert.equal a.zipExt, '4470' assert.equal a.zipFull, '30309-4470' assert.equal a.phoneArea, '866' assert.equal a.phonePrefix, '234' assert.equal a.phoneSuffix, '5681' assert.equal a.phoneFull, '8662345681' assert.equal a.status, '1' assert.equal a.dataView, '1' assert.equal a.filter, ' ' b = results[1] assert.equal b.routing, '011000028' assert.equal b.customer, 'STATE STREET BANK AND TRUST COMPANY' assert.equal b.city, 'N. QUINCY' assert.equal b.state, 'MA' done()
12880
assert = require 'assert' {readFile} = require 'fs' fedach = require '../' describe 'fedach', -> describe 'download', -> it 'should download the data securely', (done) -> fedach.download (err, data) -> assert.ifError err assert.ok data done() describe 'parse', -> it 'should parse all the data', (done) -> readFile __dirname + '/FedACHdir.txt', 'utf8', (err, data) -> results = fedach.parse data assert.ok results assert.equal results.length, 100 a = results[0] assert.equal a.routing, '011000015' assert.equal a.office, 'O' assert.equal a.frb, '011000015' assert.equal a.type, '0' assert.equal a.date, '020802' assert.equal a.newRouting, '000000000' assert.equal a.customer, 'FEDERAL RESERVE BANK' assert.equal a.address, '1000 PEACHTREE ST N.E.' assert.equal a.city, 'ATLANTA' assert.equal a.state, 'GA' assert.equal a.zip, '30309' assert.equal a.zipExt, '4470' assert.equal a.zipFull, '30309-4470' assert.equal a.phoneArea, '866' assert.equal a.phonePrefix, '234' assert.equal a.phoneSuffix, '5681' assert.equal a.phoneFull, '8662345681' assert.equal a.status, '1' assert.equal a.dataView, '1' assert.equal a.filter, ' ' b = results[1] assert.equal b.routing, '011000028' assert.equal b.customer, 'STATE STREET BANK AND TRUST COMPANY' assert.equal b.city, 'N<NAME>. QUINCY' assert.equal b.state, 'MA' done()
true
assert = require 'assert' {readFile} = require 'fs' fedach = require '../' describe 'fedach', -> describe 'download', -> it 'should download the data securely', (done) -> fedach.download (err, data) -> assert.ifError err assert.ok data done() describe 'parse', -> it 'should parse all the data', (done) -> readFile __dirname + '/FedACHdir.txt', 'utf8', (err, data) -> results = fedach.parse data assert.ok results assert.equal results.length, 100 a = results[0] assert.equal a.routing, '011000015' assert.equal a.office, 'O' assert.equal a.frb, '011000015' assert.equal a.type, '0' assert.equal a.date, '020802' assert.equal a.newRouting, '000000000' assert.equal a.customer, 'FEDERAL RESERVE BANK' assert.equal a.address, '1000 PEACHTREE ST N.E.' assert.equal a.city, 'ATLANTA' assert.equal a.state, 'GA' assert.equal a.zip, '30309' assert.equal a.zipExt, '4470' assert.equal a.zipFull, '30309-4470' assert.equal a.phoneArea, '866' assert.equal a.phonePrefix, '234' assert.equal a.phoneSuffix, '5681' assert.equal a.phoneFull, '8662345681' assert.equal a.status, '1' assert.equal a.dataView, '1' assert.equal a.filter, ' ' b = results[1] assert.equal b.routing, '011000028' assert.equal b.customer, 'STATE STREET BANK AND TRUST COMPANY' assert.equal b.city, 'NPI:NAME:<NAME>END_PI. QUINCY' assert.equal b.state, 'MA' done()
[ { "context": "other tasks that need to be throttled.\n * @author Jesús Carrera [@jesucarr](https://twitter.com/jesucarr) - [fron", "end": 404, "score": 0.999890148639679, "start": 391, "tag": "NAME", "value": "Jesús Carrera" }, { "context": "at need to be throttled.\n * @author Jesús Carrera [@jesucarr](https://twitter.com/jesucarr) - [frontendmatters", "end": 415, "score": 0.9996575117111206, "start": 405, "tag": "USERNAME", "value": "[@jesucarr" }, { "context": "hor Jesús Carrera [@jesucarr](https://twitter.com/jesucarr) - [frontendmatters.com](http://frontendmatters.c", "end": 445, "score": 0.9995637536048889, "start": 437, "tag": "USERNAME", "value": "jesucarr" }, { "context": "isClient] - The [Redis client](https://github.com/mranney/node_redis#rediscreateclient) to save the bucket.", "end": 2918, "score": 0.9955518841743469, "start": 2911, "tag": "USERNAME", "value": "mranney" }, { "context": "- [Redis client configuration](https://github.com/mranney/node_redis#rediscreateclient) to create the Redis", "end": 3080, "score": 0.9971649646759033, "start": 3073, "tag": "USERNAME", "value": "mranney" }, { "context": "e [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient).\n * @param {String", "end": 3391, "score": 0.9826011061668396, "start": 3384, "tag": "USERNAME", "value": "mranney" }, { "context": "m {String} [options.redis.redisClientConfig.host='127.0.0.1'] - The connection host for the Redis client. See", "end": 3491, "score": 0.999736487865448, "start": 3482, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "e [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient)\n * @param {String}", "end": 3597, "score": 0.9980676770210266, "start": 3590, "tag": "USERNAME", "value": "mranney" }, { "context": "e [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient)\n * @param {String}", "end": 3803, "score": 0.9919636845588684, "start": 3796, "tag": "USERNAME", "value": "mranney" }, { "context": "e [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient)\n *\n * This option", "end": 3991, "score": 0.9963141083717346, "start": 3984, "tag": "USERNAME", "value": "mranney" }, { "context": "000,\n * options: {\n * auth_pass: 'mypass'\n * }\n * }\n * }\n * });\n * ```\n ", "end": 6416, "score": 0.9993518590927124, "start": 6410, "tag": "PASSWORD", "value": "mypass" }, { "context": " 6379\n @redis.redisClientConfig.host ?= '127.0.0.1'\n @redis.redisClientConfig.options ?= {}", "end": 8172, "score": 0.9997583031654358, "start": 8163, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": " * @external Promise\n * @see https://github.com/petkaantonov/bluebird\n###\n###*\n * @external redisClient\n * @", "end": 19357, "score": 0.9996263384819031, "start": 19345, "tag": "USERNAME", "value": "petkaantonov" }, { "context": "@external redisClient\n * @see https://github.com/mranney/node_redis#rediscreateclient\n###\n###*\n * @extern", "end": 19437, "score": 0.9996824860572815, "start": 19430, "tag": "USERNAME", "value": "mranney" }, { "context": "rnal redisClientCofig\n * @see https://github.com/mranney/node_redis#rediscreateclient\n###\n", "end": 19542, "score": 0.9997102618217468, "start": 19535, "tag": "USERNAME", "value": "mranney" } ]
src/tokenbucket.coffee
jesucarr/tokenbucket
24
'use strict' Promise = require 'bluebird' redis = require 'redis' ###* * @module tokenbucket * @desc A flexible rate limiter configurable with different variations of the [Token Bucket algorithm](http://en.wikipedia.org/wiki/Token_bucket), with hierarchy support, and optional persistence in Redis. Useful for limiting API requests, or other tasks that need to be throttled. * @author Jesús Carrera [@jesucarr](https://twitter.com/jesucarr) - [frontendmatters.com](http://frontendmatters.com) * * **Installation** * ``` * npm install tokenbucket * ``` * * @example * Require the library * ```javascript * var TokenBucket = require('tokenbucket'); * ``` * Create a new tokenbucket instance. See below for possible options. * ```javascript * var tokenBucket = new TokenBucket(); * ``` ### ###* * @class * @alias module:tokenbucket * @classdesc The class that the module exports and that instantiate a new token bucket with the given options. * * @param {Object} [options] - The options object * @param {Number} [options.size=1] - Maximum number of tokens to hold in the bucket. Also known as the burst size. * @param {Number} [options.tokensToAddPerInterval=1] - Number of tokens to add to the bucket in one interval. * @param {Number|String} [options.interval=1000] - The time passing between adding tokens, in milliseconds or as one of the following strings: 'second', 'minute', 'hour', day'. * @param {Number} [options.lastFill] - The timestamp of the last time when tokens where added to the bucket (last interval). * @param {Number} [options.tokensLeft=size] - By default it will initialize full of tokens, but you can set here the number of tokens you want to initialize it with. * @param {Boolean} [options.spread=false] - By default it will wait the interval, and then add all the tokensToAddPerInterval at once. If you set this to true, it will insert fractions of tokens at any given time, spreading the token addition along the interval. * @param {Number|String} [options.maxWait] - The maximum time that we would wait for enough tokens to be added, in milliseconds or as one of the following strings: 'second', 'minute', 'hour', day'. If any of the parents in the hierarchy has `maxWait`, we will use the smallest value. * @param {TokenBucket} [options.parentBucket] - A token bucket that will act as the parent of this bucket. Tokens removed in the children, will also be removed in the parent, and if the parent reach its limit, the children will get limited too. * @param {Object} [options.redis] - Options object for Redis * @param {String} options.redis.bucketName - The name of the bucket to reference it in Redis. This is the only required field to set Redis persistance. The `bucketName` for each bucket **must be unique**. * @param {external:redisClient} [options.redis.redisClient] - The [Redis client](https://github.com/mranney/node_redis#rediscreateclient) to save the bucket. * @param {Object} [options.redis.redisClientConfig] - [Redis client configuration](https://github.com/mranney/node_redis#rediscreateclient) to create the Redis client and save the bucket. If the `redisClient` option is set, this option will be ignored. * @param {Number} [options.redis.redisClientConfig.port=6379] - The connection port for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient). * @param {String} [options.redis.redisClientConfig.host='127.0.0.1'] - The connection host for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * @param {String} [options.redis.redisClientConfig.unixSocket] - The connection unix socket for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * @param {String} [options.redis.redisClientConfig.options] - The options for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * * This options will be properties of the class instances. The properties `tokensLeft` and `lastFill` will get updated when we add/remove tokens. * * @example * * A filled token bucket that can hold 100 tokens, and it will add 30 tokens every minute (all at once). * ```javascript * var tokenBucket = new TokenBucket({ * size: 100, * tokensToAddPerInterval: 30, * interval: 'minute' * }); * ``` * An empty token bucket that can hold 1 token (default), and it will add 1 token (default) every 500ms, spreading the token addition along the interval (so after 250ms it will have 0.5 tokens). * ```javascript * var tokenBucket = new TokenBucket({ * tokensLeft: 0, * interval: 500, * spread: true * }); * ``` * A token bucket limited to 15 requests every 15 minutes, with a parent bucket limited to 1000 requests every 24 hours. The maximum time that we are willing to wait for enough tokens to be added is one hour. * ```javascript * var parentTokenBucket = new TokenBucket({ * size: 1000, * interval: 'day' * }); * var tokenBucket = new TokenBucket({ * size: 15, * tokensToAddPerInterval: 15, * interval: 'minute', * maxWait: 'hour', * parentBucket: parentBucket * }); * ``` * A token bucket limited to 15 requests every 15 minutes, with a parent bucket limited to 1000 requests every 24 hours. The maximum time that we are willing to wait for enough tokens to be added is 5 minutes. * ```javascript * var parentTokenBucket = new TokenBucket({ * size: 1000, * interval: 'day' * maxWait: 1000 * 60 * 5, * }); * var tokenBucket = new TokenBucket({ * size: 15, * tokensToAddPerInterval: 15, * interval: 'minute', * parentBucket: parentBucket * }); * ``` * A token bucket with Redis persistance setting the redis client. * ```javascript * redis = require('redis'); * redisClient = redis.redisClient(); * var tokenBucket = new TokenBucket({ * redis: { * bucketName: 'myBucket', * redisClient: redisClient * } * }); * ``` * A token bucket with Redis persistance setting the redis configuration. * ```javascript * var tokenBucket = new TokenBucket({ * redis: { * bucketName: 'myBucket', * redisClientConfig: { * host: 'myhost', * port: 1000, * options: { * auth_pass: 'mypass' * } * } * } * }); * ``` * Note that setting both `redisClient` or `redisClientConfig`, the redis client will be exposed at `tokenBucket.redis.redisClient`. * This means you can watch for redis events, or execute redis client functions. * For example if we want to close the redis connection we can execute `tokenBucket.redis.redisClient.quit()`. ### class TokenBucket # Private members errors = noRedisOptions: 'Redis options missing.' notEnoughSize: (tokensToRemove, size) -> 'Requested tokens (' + tokensToRemove + ') exceed bucket size (' + size + ')' noInfinityRemoval: 'Not possible to remove infinite tokens.' exceedsMaxWait: 'It will exceed maximum waiting time' # Add new tokens to the bucket if possible. addTokens = -> now = +new Date() timeSinceLastFill = Math.max(now - @lastFill, 0) if timeSinceLastFill tokensSinceLastFill = timeSinceLastFill * (@tokensToAddPerInterval / @interval) else tokensSinceLastFill = 0 if @spread or (timeSinceLastFill >= @interval) @lastFill = now @tokensLeft = Math.min(@tokensLeft + tokensSinceLastFill, @size) constructor: (config) -> {@size, @tokensToAddPerInterval, @interval, @tokensLeft, @lastFill, @spread, @redis, @parentBucket, @maxWait} = config if config if @redis? and @redis.bucketName? if @redis.redisClient? delete @redis.redisClientConfig else @redis.redisClientConfig ?= {} if @redis.redisClientConfig.unixSocket? @redis.redisClient = redis.createClient @redis.redisClientConfig.unixSocket, @redis.redisClientConfig.options else @redis.redisClientConfig.port ?= 6379 @redis.redisClientConfig.host ?= '127.0.0.1' @redis.redisClientConfig.options ?= {} @redis.redisClient = redis.createClient @redis.redisClientConfig.port, @redis.redisClientConfig.host, @redis.redisClientConfig.options else delete @redis if @size != Number.POSITIVE_INFINITY then @size ?= 1 @tokensLeft ?= @size @tokensToAddPerInterval ?= 1 if !@interval? @interval = 1000 else if typeof @interval == 'string' switch @interval when 'second' then @interval = 1000 when 'minute' then @interval = 1000 * 60 when 'hour' then @interval = 1000 * 60 * 60 when 'day' then @interval = 1000 * 60 * 60 * 24 if typeof @maxWait == 'string' switch @maxWait when 'second' then @maxWait = 1000 when 'minute' then @maxWait = 1000 * 60 when 'hour' then @maxWait = 1000 * 60 * 60 when 'day' then @maxWait = 1000 * 60 * 60 * 24 @lastFill ?= +new Date() # Public API ###* * @desc Remove the requested number of tokens. If the bucket (and any parent buckets) contains enough tokens this will happen immediately. Otherwise, it will wait to get enough tokens. * @param {Number} tokensToRemove - The number of tokens to remove. * @returns {external:Promise} * @fulfil {Number} - The remaining tokens number, taking into account the parent if it has it. * @reject {Error} - Operational errors will be returned with the following `name` property, so they can be handled accordingly: * * `'NotEnoughSize'` - The requested tokens are greater than the bucket size. * * `'NoInfinityRemoval'` - It is not possible to remove infinite tokens, because even if the bucket has infinite size, the `tokensLeft` would be indeterminant. * * `'ExceedsMaxWait'` - The time we need to wait to be able to remove the tokens requested exceed the time set in `maxWait` configuration (parent or child). * * . * @example * We have some code that uses 3 API requests, so we would need to remove 3 tokens from our rate limiter bucket. * If we had to wait more than the specified `maxWait` to get enough tokens, we would handle that in certain way. * ```javascript * tokenBucket.removeTokens(3).then(function(remainingTokens) { * console.log('10 tokens removed, ' + remainingTokens + 'tokens left'); * // make triple API call * }).catch(function (err) { * console.log(err) * if (err.name === 'ExceedsMaxWait') { * // do something to handle this specific error * } * }); * ``` ### removeTokens: (tokensToRemove) => resolver = Promise.pending() tokensToRemove ||= 1 # Make sure the bucket can hold the requested number of tokens if tokensToRemove > @size error = new Error(errors.notEnoughSize tokensToRemove, @size) Object.defineProperty error, 'name', {value: 'NotEnoughSize'} resolver.reject error return resolver.promise # Not possible to remove infitine tokens because even if the bucket has infinite size, the tokensLeft would be indeterminant if tokensToRemove == Number.POSITIVE_INFINITY error = new Error errors.noInfinityRemoval Object.defineProperty error, 'name', {value: 'NoInfinityRemoval'} resolver.reject error return resolver.promise # Add new tokens into this bucket if necessary addTokens.call(@) # Calculates the waiting time necessary to get enough tokens for the specified bucket calculateWaitInterval = (bucket) -> tokensNeeded = tokensToRemove - bucket.tokensLeft timeSinceLastFill = Math.max(+new Date() - bucket.lastFill, 0) if bucket.spread timePerToken = bucket.interval / bucket.tokensToAddPerInterval waitInterval = Math.ceil(tokensNeeded * timePerToken - timeSinceLastFill) else # waitInterval = @interval - timeSinceLastFill intervalsNeeded = tokensNeeded / bucket.tokensToAddPerInterval waitInterval = Math.ceil(intervalsNeeded * bucket.interval - timeSinceLastFill) Math.max(waitInterval, 0) # Calculate the wait time to get enough tokens taking into account the parents bucketWaitInterval = calculateWaitInterval(@) hierarchyWaitInterval = bucketWaitInterval if @maxWait? then hierarchyMaxWait = @maxWait parentBucket = @parentBucket while parentBucket? hierarchyWaitInterval += calculateWaitInterval(parentBucket) if parentBucket.maxWait? if hierarchyMaxWait? hierarchyMaxWait = Math.min(parentBucket.maxWait, hierarchyMaxWait) else hierarchyMaxWait = parentBucket.maxWait parentBucket = parentBucket.parentBucket # If we need to wait longer than maxWait, reject with the right error if hierarchyMaxWait? and (hierarchyWaitInterval > hierarchyMaxWait) error = new Error errors.exceedsMaxWait Object.defineProperty error, 'name', {value: 'ExceedsMaxWait'} resolver.reject error return resolver.promise # Times out to get enough tokens wait = => waitResolver = Promise.pending() setTimeout -> waitResolver.resolve(true) , bucketWaitInterval waitResolver.promise # If we don't have enough tokens in this bucket, wait to get them if tokensToRemove > @tokensLeft return wait().then => @removeTokens tokensToRemove else if @parentBucket # Remove the requested tokens from the parent bucket first parentLastFill = @parentBucket.lastFill return @parentBucket.removeTokens tokensToRemove .then => # Add tokens after the wait for the parent addTokens.call(@) # Check that we still have enough tokens in this bucket, if not, reset removal from parent, wait for tokens, and start over if tokensToRemove > @tokensLeft @parentBucket.tokensLeft += tokensToRemove @parentBucket.lastFill = parentLastFill return wait().then => @removeTokens tokensToRemove else # Tokens were removed from the parent bucket, now remove them from this bucket and return @tokensLeft -= tokensToRemove return Math.min @tokensLeft, @parentBucket.tokensLeft else # Remove the requested tokens from this bucket and resolve @tokensLeft -= tokensToRemove resolver.resolve(@tokensLeft) resolver.promise ###* * @desc Attempt to remove the requested number of tokens and return inmediately. * @param {Number} tokensToRemove - The number of tokens to remove. * @returns {Boolean} If it could remove the tokens inmediately it will return `true`, if not possible or needs to wait, it will return `false`. * * @example * ```javascript * if (tokenBucket.removeTokensSync(50)) { * // the tokens were removed * } else { * // the tokens were not removed * } * ``` ### removeTokensSync: (tokensToRemove) => tokensToRemove ||= 1 # Add new tokens into this bucket if necessary addTokens.call(@) # Make sure the bucket can hold the requested number of tokens if tokensToRemove > @size then return false # If we don't have enough tokens in this bucket, return false if tokensToRemove > @tokensLeft then return false # Try to remove the requested tokens from the parent bucket if @parentBucket and !@parentBucket.removeTokensSync tokensToRemove then return false # Remove the requested tokens from this bucket and return @tokensLeft -= tokensToRemove true ###* * @desc Saves the bucket lastFill and tokensLeft to Redis. If it has any parents with `redis` options, they will get saved too. * * @returns {external:Promise} * @fulfil {true} * @reject {Error} - If we call this function and we didn't set the redis options, the error will have `'NoRedisOptions'` as the `name` property, so it can be handled specifically. * If there is an error with Redis it will be rejected with the error returned by Redis. * @example * We have a worker process that uses 1 API requests, so we would need to remove 1 token (default) from our rate limiter bucket. * If we had to wait more than the specified `maxWait` to get enough tokens, we would end the worker process. * We are saving the bucket state in Redis, so we first load from Redis, and before exiting we save the updated bucket state. * Note that if it had parent buckets with Redis options set, they would get saved too. * ```javascript * tokenBucket.loadSaved().then(function () { * // now the bucket has the state it had last time we saved it * return tokenBucket.removeTokens().then(function() { * // make API call * }); * }).catch(function (err) { * if (err.name === 'ExceedsMaxWait') { * tokenBucket.save().then(function () { * process.kill(process.pid, 'SIGKILL'); * }).catch(function (err) { * if (err.name == 'NoRedisOptions') { * // do something to handle this specific error * } * }); * } * }); * ``` ### save: => resolver = Promise.pending() if !@redis error = new Error errors.noRedisOptions Object.defineProperty error, 'name', {value: 'NoRedisOptions'} resolver.reject error else set = => @redis.redisClient.mset 'tokenbucket:' + @redis.bucketName + ':lastFill', @lastFill, 'tokenbucket:' + @redis.bucketName + ':tokensLeft', @tokensLeft, (err, reply) -> if err resolver.reject new Error err else resolver.resolve(true) if @parentBucket and @parentBucket.redis? return @parentBucket.save().then set else set() resolver.promise ###* * @desc Loads the bucket lastFill and tokensLeft as it was saved in Redis. If it has any parents with `redis` options, they will get loaded too. * @returns {external:Promise} * @fulfil {true} * @reject {Error} - If we call this function and we didn't set the redis options, the error will have `'NoRedisOptions'` as the `name` property, so it can be handled specifically. * If there is an error with Redis it will be rejected with the error returned by Redis. * @example @lang off * See {@link module:tokenbucket#save} ### loadSaved: => resolver = Promise.pending() if !@redis error = new Error errors.noRedisOptions Object.defineProperty error, 'name', {value: 'NoRedisOptions'} resolver.reject error else get = => @redis.redisClient.mget 'tokenbucket:' + @redis.bucketName + ':lastFill', 'tokenbucket:' + @redis.bucketName + ':tokensLeft', (err, reply) => if err resolver.reject new Error err else @lastFill = +reply[0] if reply[0] @tokensLeft = +reply[1] if reply[1] resolver.resolve(true) if @parentBucket and @parentBucket.redis? return @parentBucket.loadSaved().then get else get() resolver.promise module.exports = TokenBucket ###* * @external Promise * @see https://github.com/petkaantonov/bluebird ### ###* * @external redisClient * @see https://github.com/mranney/node_redis#rediscreateclient ### ###* * @external redisClientCofig * @see https://github.com/mranney/node_redis#rediscreateclient ###
206849
'use strict' Promise = require 'bluebird' redis = require 'redis' ###* * @module tokenbucket * @desc A flexible rate limiter configurable with different variations of the [Token Bucket algorithm](http://en.wikipedia.org/wiki/Token_bucket), with hierarchy support, and optional persistence in Redis. Useful for limiting API requests, or other tasks that need to be throttled. * @author <NAME> [@jesucarr](https://twitter.com/jesucarr) - [frontendmatters.com](http://frontendmatters.com) * * **Installation** * ``` * npm install tokenbucket * ``` * * @example * Require the library * ```javascript * var TokenBucket = require('tokenbucket'); * ``` * Create a new tokenbucket instance. See below for possible options. * ```javascript * var tokenBucket = new TokenBucket(); * ``` ### ###* * @class * @alias module:tokenbucket * @classdesc The class that the module exports and that instantiate a new token bucket with the given options. * * @param {Object} [options] - The options object * @param {Number} [options.size=1] - Maximum number of tokens to hold in the bucket. Also known as the burst size. * @param {Number} [options.tokensToAddPerInterval=1] - Number of tokens to add to the bucket in one interval. * @param {Number|String} [options.interval=1000] - The time passing between adding tokens, in milliseconds or as one of the following strings: 'second', 'minute', 'hour', day'. * @param {Number} [options.lastFill] - The timestamp of the last time when tokens where added to the bucket (last interval). * @param {Number} [options.tokensLeft=size] - By default it will initialize full of tokens, but you can set here the number of tokens you want to initialize it with. * @param {Boolean} [options.spread=false] - By default it will wait the interval, and then add all the tokensToAddPerInterval at once. If you set this to true, it will insert fractions of tokens at any given time, spreading the token addition along the interval. * @param {Number|String} [options.maxWait] - The maximum time that we would wait for enough tokens to be added, in milliseconds or as one of the following strings: 'second', 'minute', 'hour', day'. If any of the parents in the hierarchy has `maxWait`, we will use the smallest value. * @param {TokenBucket} [options.parentBucket] - A token bucket that will act as the parent of this bucket. Tokens removed in the children, will also be removed in the parent, and if the parent reach its limit, the children will get limited too. * @param {Object} [options.redis] - Options object for Redis * @param {String} options.redis.bucketName - The name of the bucket to reference it in Redis. This is the only required field to set Redis persistance. The `bucketName` for each bucket **must be unique**. * @param {external:redisClient} [options.redis.redisClient] - The [Redis client](https://github.com/mranney/node_redis#rediscreateclient) to save the bucket. * @param {Object} [options.redis.redisClientConfig] - [Redis client configuration](https://github.com/mranney/node_redis#rediscreateclient) to create the Redis client and save the bucket. If the `redisClient` option is set, this option will be ignored. * @param {Number} [options.redis.redisClientConfig.port=6379] - The connection port for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient). * @param {String} [options.redis.redisClientConfig.host='127.0.0.1'] - The connection host for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * @param {String} [options.redis.redisClientConfig.unixSocket] - The connection unix socket for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * @param {String} [options.redis.redisClientConfig.options] - The options for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * * This options will be properties of the class instances. The properties `tokensLeft` and `lastFill` will get updated when we add/remove tokens. * * @example * * A filled token bucket that can hold 100 tokens, and it will add 30 tokens every minute (all at once). * ```javascript * var tokenBucket = new TokenBucket({ * size: 100, * tokensToAddPerInterval: 30, * interval: 'minute' * }); * ``` * An empty token bucket that can hold 1 token (default), and it will add 1 token (default) every 500ms, spreading the token addition along the interval (so after 250ms it will have 0.5 tokens). * ```javascript * var tokenBucket = new TokenBucket({ * tokensLeft: 0, * interval: 500, * spread: true * }); * ``` * A token bucket limited to 15 requests every 15 minutes, with a parent bucket limited to 1000 requests every 24 hours. The maximum time that we are willing to wait for enough tokens to be added is one hour. * ```javascript * var parentTokenBucket = new TokenBucket({ * size: 1000, * interval: 'day' * }); * var tokenBucket = new TokenBucket({ * size: 15, * tokensToAddPerInterval: 15, * interval: 'minute', * maxWait: 'hour', * parentBucket: parentBucket * }); * ``` * A token bucket limited to 15 requests every 15 minutes, with a parent bucket limited to 1000 requests every 24 hours. The maximum time that we are willing to wait for enough tokens to be added is 5 minutes. * ```javascript * var parentTokenBucket = new TokenBucket({ * size: 1000, * interval: 'day' * maxWait: 1000 * 60 * 5, * }); * var tokenBucket = new TokenBucket({ * size: 15, * tokensToAddPerInterval: 15, * interval: 'minute', * parentBucket: parentBucket * }); * ``` * A token bucket with Redis persistance setting the redis client. * ```javascript * redis = require('redis'); * redisClient = redis.redisClient(); * var tokenBucket = new TokenBucket({ * redis: { * bucketName: 'myBucket', * redisClient: redisClient * } * }); * ``` * A token bucket with Redis persistance setting the redis configuration. * ```javascript * var tokenBucket = new TokenBucket({ * redis: { * bucketName: 'myBucket', * redisClientConfig: { * host: 'myhost', * port: 1000, * options: { * auth_pass: '<PASSWORD>' * } * } * } * }); * ``` * Note that setting both `redisClient` or `redisClientConfig`, the redis client will be exposed at `tokenBucket.redis.redisClient`. * This means you can watch for redis events, or execute redis client functions. * For example if we want to close the redis connection we can execute `tokenBucket.redis.redisClient.quit()`. ### class TokenBucket # Private members errors = noRedisOptions: 'Redis options missing.' notEnoughSize: (tokensToRemove, size) -> 'Requested tokens (' + tokensToRemove + ') exceed bucket size (' + size + ')' noInfinityRemoval: 'Not possible to remove infinite tokens.' exceedsMaxWait: 'It will exceed maximum waiting time' # Add new tokens to the bucket if possible. addTokens = -> now = +new Date() timeSinceLastFill = Math.max(now - @lastFill, 0) if timeSinceLastFill tokensSinceLastFill = timeSinceLastFill * (@tokensToAddPerInterval / @interval) else tokensSinceLastFill = 0 if @spread or (timeSinceLastFill >= @interval) @lastFill = now @tokensLeft = Math.min(@tokensLeft + tokensSinceLastFill, @size) constructor: (config) -> {@size, @tokensToAddPerInterval, @interval, @tokensLeft, @lastFill, @spread, @redis, @parentBucket, @maxWait} = config if config if @redis? and @redis.bucketName? if @redis.redisClient? delete @redis.redisClientConfig else @redis.redisClientConfig ?= {} if @redis.redisClientConfig.unixSocket? @redis.redisClient = redis.createClient @redis.redisClientConfig.unixSocket, @redis.redisClientConfig.options else @redis.redisClientConfig.port ?= 6379 @redis.redisClientConfig.host ?= '127.0.0.1' @redis.redisClientConfig.options ?= {} @redis.redisClient = redis.createClient @redis.redisClientConfig.port, @redis.redisClientConfig.host, @redis.redisClientConfig.options else delete @redis if @size != Number.POSITIVE_INFINITY then @size ?= 1 @tokensLeft ?= @size @tokensToAddPerInterval ?= 1 if !@interval? @interval = 1000 else if typeof @interval == 'string' switch @interval when 'second' then @interval = 1000 when 'minute' then @interval = 1000 * 60 when 'hour' then @interval = 1000 * 60 * 60 when 'day' then @interval = 1000 * 60 * 60 * 24 if typeof @maxWait == 'string' switch @maxWait when 'second' then @maxWait = 1000 when 'minute' then @maxWait = 1000 * 60 when 'hour' then @maxWait = 1000 * 60 * 60 when 'day' then @maxWait = 1000 * 60 * 60 * 24 @lastFill ?= +new Date() # Public API ###* * @desc Remove the requested number of tokens. If the bucket (and any parent buckets) contains enough tokens this will happen immediately. Otherwise, it will wait to get enough tokens. * @param {Number} tokensToRemove - The number of tokens to remove. * @returns {external:Promise} * @fulfil {Number} - The remaining tokens number, taking into account the parent if it has it. * @reject {Error} - Operational errors will be returned with the following `name` property, so they can be handled accordingly: * * `'NotEnoughSize'` - The requested tokens are greater than the bucket size. * * `'NoInfinityRemoval'` - It is not possible to remove infinite tokens, because even if the bucket has infinite size, the `tokensLeft` would be indeterminant. * * `'ExceedsMaxWait'` - The time we need to wait to be able to remove the tokens requested exceed the time set in `maxWait` configuration (parent or child). * * . * @example * We have some code that uses 3 API requests, so we would need to remove 3 tokens from our rate limiter bucket. * If we had to wait more than the specified `maxWait` to get enough tokens, we would handle that in certain way. * ```javascript * tokenBucket.removeTokens(3).then(function(remainingTokens) { * console.log('10 tokens removed, ' + remainingTokens + 'tokens left'); * // make triple API call * }).catch(function (err) { * console.log(err) * if (err.name === 'ExceedsMaxWait') { * // do something to handle this specific error * } * }); * ``` ### removeTokens: (tokensToRemove) => resolver = Promise.pending() tokensToRemove ||= 1 # Make sure the bucket can hold the requested number of tokens if tokensToRemove > @size error = new Error(errors.notEnoughSize tokensToRemove, @size) Object.defineProperty error, 'name', {value: 'NotEnoughSize'} resolver.reject error return resolver.promise # Not possible to remove infitine tokens because even if the bucket has infinite size, the tokensLeft would be indeterminant if tokensToRemove == Number.POSITIVE_INFINITY error = new Error errors.noInfinityRemoval Object.defineProperty error, 'name', {value: 'NoInfinityRemoval'} resolver.reject error return resolver.promise # Add new tokens into this bucket if necessary addTokens.call(@) # Calculates the waiting time necessary to get enough tokens for the specified bucket calculateWaitInterval = (bucket) -> tokensNeeded = tokensToRemove - bucket.tokensLeft timeSinceLastFill = Math.max(+new Date() - bucket.lastFill, 0) if bucket.spread timePerToken = bucket.interval / bucket.tokensToAddPerInterval waitInterval = Math.ceil(tokensNeeded * timePerToken - timeSinceLastFill) else # waitInterval = @interval - timeSinceLastFill intervalsNeeded = tokensNeeded / bucket.tokensToAddPerInterval waitInterval = Math.ceil(intervalsNeeded * bucket.interval - timeSinceLastFill) Math.max(waitInterval, 0) # Calculate the wait time to get enough tokens taking into account the parents bucketWaitInterval = calculateWaitInterval(@) hierarchyWaitInterval = bucketWaitInterval if @maxWait? then hierarchyMaxWait = @maxWait parentBucket = @parentBucket while parentBucket? hierarchyWaitInterval += calculateWaitInterval(parentBucket) if parentBucket.maxWait? if hierarchyMaxWait? hierarchyMaxWait = Math.min(parentBucket.maxWait, hierarchyMaxWait) else hierarchyMaxWait = parentBucket.maxWait parentBucket = parentBucket.parentBucket # If we need to wait longer than maxWait, reject with the right error if hierarchyMaxWait? and (hierarchyWaitInterval > hierarchyMaxWait) error = new Error errors.exceedsMaxWait Object.defineProperty error, 'name', {value: 'ExceedsMaxWait'} resolver.reject error return resolver.promise # Times out to get enough tokens wait = => waitResolver = Promise.pending() setTimeout -> waitResolver.resolve(true) , bucketWaitInterval waitResolver.promise # If we don't have enough tokens in this bucket, wait to get them if tokensToRemove > @tokensLeft return wait().then => @removeTokens tokensToRemove else if @parentBucket # Remove the requested tokens from the parent bucket first parentLastFill = @parentBucket.lastFill return @parentBucket.removeTokens tokensToRemove .then => # Add tokens after the wait for the parent addTokens.call(@) # Check that we still have enough tokens in this bucket, if not, reset removal from parent, wait for tokens, and start over if tokensToRemove > @tokensLeft @parentBucket.tokensLeft += tokensToRemove @parentBucket.lastFill = parentLastFill return wait().then => @removeTokens tokensToRemove else # Tokens were removed from the parent bucket, now remove them from this bucket and return @tokensLeft -= tokensToRemove return Math.min @tokensLeft, @parentBucket.tokensLeft else # Remove the requested tokens from this bucket and resolve @tokensLeft -= tokensToRemove resolver.resolve(@tokensLeft) resolver.promise ###* * @desc Attempt to remove the requested number of tokens and return inmediately. * @param {Number} tokensToRemove - The number of tokens to remove. * @returns {Boolean} If it could remove the tokens inmediately it will return `true`, if not possible or needs to wait, it will return `false`. * * @example * ```javascript * if (tokenBucket.removeTokensSync(50)) { * // the tokens were removed * } else { * // the tokens were not removed * } * ``` ### removeTokensSync: (tokensToRemove) => tokensToRemove ||= 1 # Add new tokens into this bucket if necessary addTokens.call(@) # Make sure the bucket can hold the requested number of tokens if tokensToRemove > @size then return false # If we don't have enough tokens in this bucket, return false if tokensToRemove > @tokensLeft then return false # Try to remove the requested tokens from the parent bucket if @parentBucket and !@parentBucket.removeTokensSync tokensToRemove then return false # Remove the requested tokens from this bucket and return @tokensLeft -= tokensToRemove true ###* * @desc Saves the bucket lastFill and tokensLeft to Redis. If it has any parents with `redis` options, they will get saved too. * * @returns {external:Promise} * @fulfil {true} * @reject {Error} - If we call this function and we didn't set the redis options, the error will have `'NoRedisOptions'` as the `name` property, so it can be handled specifically. * If there is an error with Redis it will be rejected with the error returned by Redis. * @example * We have a worker process that uses 1 API requests, so we would need to remove 1 token (default) from our rate limiter bucket. * If we had to wait more than the specified `maxWait` to get enough tokens, we would end the worker process. * We are saving the bucket state in Redis, so we first load from Redis, and before exiting we save the updated bucket state. * Note that if it had parent buckets with Redis options set, they would get saved too. * ```javascript * tokenBucket.loadSaved().then(function () { * // now the bucket has the state it had last time we saved it * return tokenBucket.removeTokens().then(function() { * // make API call * }); * }).catch(function (err) { * if (err.name === 'ExceedsMaxWait') { * tokenBucket.save().then(function () { * process.kill(process.pid, 'SIGKILL'); * }).catch(function (err) { * if (err.name == 'NoRedisOptions') { * // do something to handle this specific error * } * }); * } * }); * ``` ### save: => resolver = Promise.pending() if !@redis error = new Error errors.noRedisOptions Object.defineProperty error, 'name', {value: 'NoRedisOptions'} resolver.reject error else set = => @redis.redisClient.mset 'tokenbucket:' + @redis.bucketName + ':lastFill', @lastFill, 'tokenbucket:' + @redis.bucketName + ':tokensLeft', @tokensLeft, (err, reply) -> if err resolver.reject new Error err else resolver.resolve(true) if @parentBucket and @parentBucket.redis? return @parentBucket.save().then set else set() resolver.promise ###* * @desc Loads the bucket lastFill and tokensLeft as it was saved in Redis. If it has any parents with `redis` options, they will get loaded too. * @returns {external:Promise} * @fulfil {true} * @reject {Error} - If we call this function and we didn't set the redis options, the error will have `'NoRedisOptions'` as the `name` property, so it can be handled specifically. * If there is an error with Redis it will be rejected with the error returned by Redis. * @example @lang off * See {@link module:tokenbucket#save} ### loadSaved: => resolver = Promise.pending() if !@redis error = new Error errors.noRedisOptions Object.defineProperty error, 'name', {value: 'NoRedisOptions'} resolver.reject error else get = => @redis.redisClient.mget 'tokenbucket:' + @redis.bucketName + ':lastFill', 'tokenbucket:' + @redis.bucketName + ':tokensLeft', (err, reply) => if err resolver.reject new Error err else @lastFill = +reply[0] if reply[0] @tokensLeft = +reply[1] if reply[1] resolver.resolve(true) if @parentBucket and @parentBucket.redis? return @parentBucket.loadSaved().then get else get() resolver.promise module.exports = TokenBucket ###* * @external Promise * @see https://github.com/petkaantonov/bluebird ### ###* * @external redisClient * @see https://github.com/mranney/node_redis#rediscreateclient ### ###* * @external redisClientCofig * @see https://github.com/mranney/node_redis#rediscreateclient ###
true
'use strict' Promise = require 'bluebird' redis = require 'redis' ###* * @module tokenbucket * @desc A flexible rate limiter configurable with different variations of the [Token Bucket algorithm](http://en.wikipedia.org/wiki/Token_bucket), with hierarchy support, and optional persistence in Redis. Useful for limiting API requests, or other tasks that need to be throttled. * @author PI:NAME:<NAME>END_PI [@jesucarr](https://twitter.com/jesucarr) - [frontendmatters.com](http://frontendmatters.com) * * **Installation** * ``` * npm install tokenbucket * ``` * * @example * Require the library * ```javascript * var TokenBucket = require('tokenbucket'); * ``` * Create a new tokenbucket instance. See below for possible options. * ```javascript * var tokenBucket = new TokenBucket(); * ``` ### ###* * @class * @alias module:tokenbucket * @classdesc The class that the module exports and that instantiate a new token bucket with the given options. * * @param {Object} [options] - The options object * @param {Number} [options.size=1] - Maximum number of tokens to hold in the bucket. Also known as the burst size. * @param {Number} [options.tokensToAddPerInterval=1] - Number of tokens to add to the bucket in one interval. * @param {Number|String} [options.interval=1000] - The time passing between adding tokens, in milliseconds or as one of the following strings: 'second', 'minute', 'hour', day'. * @param {Number} [options.lastFill] - The timestamp of the last time when tokens where added to the bucket (last interval). * @param {Number} [options.tokensLeft=size] - By default it will initialize full of tokens, but you can set here the number of tokens you want to initialize it with. * @param {Boolean} [options.spread=false] - By default it will wait the interval, and then add all the tokensToAddPerInterval at once. If you set this to true, it will insert fractions of tokens at any given time, spreading the token addition along the interval. * @param {Number|String} [options.maxWait] - The maximum time that we would wait for enough tokens to be added, in milliseconds or as one of the following strings: 'second', 'minute', 'hour', day'. If any of the parents in the hierarchy has `maxWait`, we will use the smallest value. * @param {TokenBucket} [options.parentBucket] - A token bucket that will act as the parent of this bucket. Tokens removed in the children, will also be removed in the parent, and if the parent reach its limit, the children will get limited too. * @param {Object} [options.redis] - Options object for Redis * @param {String} options.redis.bucketName - The name of the bucket to reference it in Redis. This is the only required field to set Redis persistance. The `bucketName` for each bucket **must be unique**. * @param {external:redisClient} [options.redis.redisClient] - The [Redis client](https://github.com/mranney/node_redis#rediscreateclient) to save the bucket. * @param {Object} [options.redis.redisClientConfig] - [Redis client configuration](https://github.com/mranney/node_redis#rediscreateclient) to create the Redis client and save the bucket. If the `redisClient` option is set, this option will be ignored. * @param {Number} [options.redis.redisClientConfig.port=6379] - The connection port for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient). * @param {String} [options.redis.redisClientConfig.host='127.0.0.1'] - The connection host for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * @param {String} [options.redis.redisClientConfig.unixSocket] - The connection unix socket for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * @param {String} [options.redis.redisClientConfig.options] - The options for the Redis client. See [configuration instructions](https://github.com/mranney/node_redis#rediscreateclient) * * This options will be properties of the class instances. The properties `tokensLeft` and `lastFill` will get updated when we add/remove tokens. * * @example * * A filled token bucket that can hold 100 tokens, and it will add 30 tokens every minute (all at once). * ```javascript * var tokenBucket = new TokenBucket({ * size: 100, * tokensToAddPerInterval: 30, * interval: 'minute' * }); * ``` * An empty token bucket that can hold 1 token (default), and it will add 1 token (default) every 500ms, spreading the token addition along the interval (so after 250ms it will have 0.5 tokens). * ```javascript * var tokenBucket = new TokenBucket({ * tokensLeft: 0, * interval: 500, * spread: true * }); * ``` * A token bucket limited to 15 requests every 15 minutes, with a parent bucket limited to 1000 requests every 24 hours. The maximum time that we are willing to wait for enough tokens to be added is one hour. * ```javascript * var parentTokenBucket = new TokenBucket({ * size: 1000, * interval: 'day' * }); * var tokenBucket = new TokenBucket({ * size: 15, * tokensToAddPerInterval: 15, * interval: 'minute', * maxWait: 'hour', * parentBucket: parentBucket * }); * ``` * A token bucket limited to 15 requests every 15 minutes, with a parent bucket limited to 1000 requests every 24 hours. The maximum time that we are willing to wait for enough tokens to be added is 5 minutes. * ```javascript * var parentTokenBucket = new TokenBucket({ * size: 1000, * interval: 'day' * maxWait: 1000 * 60 * 5, * }); * var tokenBucket = new TokenBucket({ * size: 15, * tokensToAddPerInterval: 15, * interval: 'minute', * parentBucket: parentBucket * }); * ``` * A token bucket with Redis persistance setting the redis client. * ```javascript * redis = require('redis'); * redisClient = redis.redisClient(); * var tokenBucket = new TokenBucket({ * redis: { * bucketName: 'myBucket', * redisClient: redisClient * } * }); * ``` * A token bucket with Redis persistance setting the redis configuration. * ```javascript * var tokenBucket = new TokenBucket({ * redis: { * bucketName: 'myBucket', * redisClientConfig: { * host: 'myhost', * port: 1000, * options: { * auth_pass: 'PI:PASSWORD:<PASSWORD>END_PI' * } * } * } * }); * ``` * Note that setting both `redisClient` or `redisClientConfig`, the redis client will be exposed at `tokenBucket.redis.redisClient`. * This means you can watch for redis events, or execute redis client functions. * For example if we want to close the redis connection we can execute `tokenBucket.redis.redisClient.quit()`. ### class TokenBucket # Private members errors = noRedisOptions: 'Redis options missing.' notEnoughSize: (tokensToRemove, size) -> 'Requested tokens (' + tokensToRemove + ') exceed bucket size (' + size + ')' noInfinityRemoval: 'Not possible to remove infinite tokens.' exceedsMaxWait: 'It will exceed maximum waiting time' # Add new tokens to the bucket if possible. addTokens = -> now = +new Date() timeSinceLastFill = Math.max(now - @lastFill, 0) if timeSinceLastFill tokensSinceLastFill = timeSinceLastFill * (@tokensToAddPerInterval / @interval) else tokensSinceLastFill = 0 if @spread or (timeSinceLastFill >= @interval) @lastFill = now @tokensLeft = Math.min(@tokensLeft + tokensSinceLastFill, @size) constructor: (config) -> {@size, @tokensToAddPerInterval, @interval, @tokensLeft, @lastFill, @spread, @redis, @parentBucket, @maxWait} = config if config if @redis? and @redis.bucketName? if @redis.redisClient? delete @redis.redisClientConfig else @redis.redisClientConfig ?= {} if @redis.redisClientConfig.unixSocket? @redis.redisClient = redis.createClient @redis.redisClientConfig.unixSocket, @redis.redisClientConfig.options else @redis.redisClientConfig.port ?= 6379 @redis.redisClientConfig.host ?= '127.0.0.1' @redis.redisClientConfig.options ?= {} @redis.redisClient = redis.createClient @redis.redisClientConfig.port, @redis.redisClientConfig.host, @redis.redisClientConfig.options else delete @redis if @size != Number.POSITIVE_INFINITY then @size ?= 1 @tokensLeft ?= @size @tokensToAddPerInterval ?= 1 if !@interval? @interval = 1000 else if typeof @interval == 'string' switch @interval when 'second' then @interval = 1000 when 'minute' then @interval = 1000 * 60 when 'hour' then @interval = 1000 * 60 * 60 when 'day' then @interval = 1000 * 60 * 60 * 24 if typeof @maxWait == 'string' switch @maxWait when 'second' then @maxWait = 1000 when 'minute' then @maxWait = 1000 * 60 when 'hour' then @maxWait = 1000 * 60 * 60 when 'day' then @maxWait = 1000 * 60 * 60 * 24 @lastFill ?= +new Date() # Public API ###* * @desc Remove the requested number of tokens. If the bucket (and any parent buckets) contains enough tokens this will happen immediately. Otherwise, it will wait to get enough tokens. * @param {Number} tokensToRemove - The number of tokens to remove. * @returns {external:Promise} * @fulfil {Number} - The remaining tokens number, taking into account the parent if it has it. * @reject {Error} - Operational errors will be returned with the following `name` property, so they can be handled accordingly: * * `'NotEnoughSize'` - The requested tokens are greater than the bucket size. * * `'NoInfinityRemoval'` - It is not possible to remove infinite tokens, because even if the bucket has infinite size, the `tokensLeft` would be indeterminant. * * `'ExceedsMaxWait'` - The time we need to wait to be able to remove the tokens requested exceed the time set in `maxWait` configuration (parent or child). * * . * @example * We have some code that uses 3 API requests, so we would need to remove 3 tokens from our rate limiter bucket. * If we had to wait more than the specified `maxWait` to get enough tokens, we would handle that in certain way. * ```javascript * tokenBucket.removeTokens(3).then(function(remainingTokens) { * console.log('10 tokens removed, ' + remainingTokens + 'tokens left'); * // make triple API call * }).catch(function (err) { * console.log(err) * if (err.name === 'ExceedsMaxWait') { * // do something to handle this specific error * } * }); * ``` ### removeTokens: (tokensToRemove) => resolver = Promise.pending() tokensToRemove ||= 1 # Make sure the bucket can hold the requested number of tokens if tokensToRemove > @size error = new Error(errors.notEnoughSize tokensToRemove, @size) Object.defineProperty error, 'name', {value: 'NotEnoughSize'} resolver.reject error return resolver.promise # Not possible to remove infitine tokens because even if the bucket has infinite size, the tokensLeft would be indeterminant if tokensToRemove == Number.POSITIVE_INFINITY error = new Error errors.noInfinityRemoval Object.defineProperty error, 'name', {value: 'NoInfinityRemoval'} resolver.reject error return resolver.promise # Add new tokens into this bucket if necessary addTokens.call(@) # Calculates the waiting time necessary to get enough tokens for the specified bucket calculateWaitInterval = (bucket) -> tokensNeeded = tokensToRemove - bucket.tokensLeft timeSinceLastFill = Math.max(+new Date() - bucket.lastFill, 0) if bucket.spread timePerToken = bucket.interval / bucket.tokensToAddPerInterval waitInterval = Math.ceil(tokensNeeded * timePerToken - timeSinceLastFill) else # waitInterval = @interval - timeSinceLastFill intervalsNeeded = tokensNeeded / bucket.tokensToAddPerInterval waitInterval = Math.ceil(intervalsNeeded * bucket.interval - timeSinceLastFill) Math.max(waitInterval, 0) # Calculate the wait time to get enough tokens taking into account the parents bucketWaitInterval = calculateWaitInterval(@) hierarchyWaitInterval = bucketWaitInterval if @maxWait? then hierarchyMaxWait = @maxWait parentBucket = @parentBucket while parentBucket? hierarchyWaitInterval += calculateWaitInterval(parentBucket) if parentBucket.maxWait? if hierarchyMaxWait? hierarchyMaxWait = Math.min(parentBucket.maxWait, hierarchyMaxWait) else hierarchyMaxWait = parentBucket.maxWait parentBucket = parentBucket.parentBucket # If we need to wait longer than maxWait, reject with the right error if hierarchyMaxWait? and (hierarchyWaitInterval > hierarchyMaxWait) error = new Error errors.exceedsMaxWait Object.defineProperty error, 'name', {value: 'ExceedsMaxWait'} resolver.reject error return resolver.promise # Times out to get enough tokens wait = => waitResolver = Promise.pending() setTimeout -> waitResolver.resolve(true) , bucketWaitInterval waitResolver.promise # If we don't have enough tokens in this bucket, wait to get them if tokensToRemove > @tokensLeft return wait().then => @removeTokens tokensToRemove else if @parentBucket # Remove the requested tokens from the parent bucket first parentLastFill = @parentBucket.lastFill return @parentBucket.removeTokens tokensToRemove .then => # Add tokens after the wait for the parent addTokens.call(@) # Check that we still have enough tokens in this bucket, if not, reset removal from parent, wait for tokens, and start over if tokensToRemove > @tokensLeft @parentBucket.tokensLeft += tokensToRemove @parentBucket.lastFill = parentLastFill return wait().then => @removeTokens tokensToRemove else # Tokens were removed from the parent bucket, now remove them from this bucket and return @tokensLeft -= tokensToRemove return Math.min @tokensLeft, @parentBucket.tokensLeft else # Remove the requested tokens from this bucket and resolve @tokensLeft -= tokensToRemove resolver.resolve(@tokensLeft) resolver.promise ###* * @desc Attempt to remove the requested number of tokens and return inmediately. * @param {Number} tokensToRemove - The number of tokens to remove. * @returns {Boolean} If it could remove the tokens inmediately it will return `true`, if not possible or needs to wait, it will return `false`. * * @example * ```javascript * if (tokenBucket.removeTokensSync(50)) { * // the tokens were removed * } else { * // the tokens were not removed * } * ``` ### removeTokensSync: (tokensToRemove) => tokensToRemove ||= 1 # Add new tokens into this bucket if necessary addTokens.call(@) # Make sure the bucket can hold the requested number of tokens if tokensToRemove > @size then return false # If we don't have enough tokens in this bucket, return false if tokensToRemove > @tokensLeft then return false # Try to remove the requested tokens from the parent bucket if @parentBucket and !@parentBucket.removeTokensSync tokensToRemove then return false # Remove the requested tokens from this bucket and return @tokensLeft -= tokensToRemove true ###* * @desc Saves the bucket lastFill and tokensLeft to Redis. If it has any parents with `redis` options, they will get saved too. * * @returns {external:Promise} * @fulfil {true} * @reject {Error} - If we call this function and we didn't set the redis options, the error will have `'NoRedisOptions'` as the `name` property, so it can be handled specifically. * If there is an error with Redis it will be rejected with the error returned by Redis. * @example * We have a worker process that uses 1 API requests, so we would need to remove 1 token (default) from our rate limiter bucket. * If we had to wait more than the specified `maxWait` to get enough tokens, we would end the worker process. * We are saving the bucket state in Redis, so we first load from Redis, and before exiting we save the updated bucket state. * Note that if it had parent buckets with Redis options set, they would get saved too. * ```javascript * tokenBucket.loadSaved().then(function () { * // now the bucket has the state it had last time we saved it * return tokenBucket.removeTokens().then(function() { * // make API call * }); * }).catch(function (err) { * if (err.name === 'ExceedsMaxWait') { * tokenBucket.save().then(function () { * process.kill(process.pid, 'SIGKILL'); * }).catch(function (err) { * if (err.name == 'NoRedisOptions') { * // do something to handle this specific error * } * }); * } * }); * ``` ### save: => resolver = Promise.pending() if !@redis error = new Error errors.noRedisOptions Object.defineProperty error, 'name', {value: 'NoRedisOptions'} resolver.reject error else set = => @redis.redisClient.mset 'tokenbucket:' + @redis.bucketName + ':lastFill', @lastFill, 'tokenbucket:' + @redis.bucketName + ':tokensLeft', @tokensLeft, (err, reply) -> if err resolver.reject new Error err else resolver.resolve(true) if @parentBucket and @parentBucket.redis? return @parentBucket.save().then set else set() resolver.promise ###* * @desc Loads the bucket lastFill and tokensLeft as it was saved in Redis. If it has any parents with `redis` options, they will get loaded too. * @returns {external:Promise} * @fulfil {true} * @reject {Error} - If we call this function and we didn't set the redis options, the error will have `'NoRedisOptions'` as the `name` property, so it can be handled specifically. * If there is an error with Redis it will be rejected with the error returned by Redis. * @example @lang off * See {@link module:tokenbucket#save} ### loadSaved: => resolver = Promise.pending() if !@redis error = new Error errors.noRedisOptions Object.defineProperty error, 'name', {value: 'NoRedisOptions'} resolver.reject error else get = => @redis.redisClient.mget 'tokenbucket:' + @redis.bucketName + ':lastFill', 'tokenbucket:' + @redis.bucketName + ':tokensLeft', (err, reply) => if err resolver.reject new Error err else @lastFill = +reply[0] if reply[0] @tokensLeft = +reply[1] if reply[1] resolver.resolve(true) if @parentBucket and @parentBucket.redis? return @parentBucket.loadSaved().then get else get() resolver.promise module.exports = TokenBucket ###* * @external Promise * @see https://github.com/petkaantonov/bluebird ### ###* * @external redisClient * @see https://github.com/mranney/node_redis#rediscreateclient ### ###* * @external redisClientCofig * @see https://github.com/mranney/node_redis#rediscreateclient ###
[ { "context": ")\n @game.setOpponent(new Debater(@game, true, 'SMITH', 31, 6, 'COACH'))\n @game.opponentElem.show()\n", "end": 359, "score": 0.9968681931495667, "start": 354, "tag": "NAME", "value": "SMITH" }, { "context": "low Debate!\n My name is SMITH! People call me SMITH! This world\n ", "end": 638, "score": 0.9995042681694031, "start": 633, "tag": "NAME", "value": "SMITH" }, { "context": " My name is SMITH! People call me SMITH! This world\n is inhabi", "end": 660, "score": 0.999317467212677, "start": 655, "tag": "NAME", "value": "SMITH" } ]
src/js/screens/oak.coffee
nagn/Battle-Resolution
0
$ = require './../lib/jquery.js' Screen = require './../screen.coffee' Debater = require './../debater.coffee' Player = require './../debaters/player.coffee' Async = require './../lib/async.js' module.exports = class Oak extends Screen constructor: (@game) -> super @game load: () -> super() @game.setOpponent(new Debater(@game, true, 'SMITH', 31, 6, 'COACH')) @game.opponentElem.show() @game.console.show() Async.waterfall [ (cb) => @game.pause 1000, cb (cb) => @game.opponent.say 'Hello there! Welcome to the world of Barlow Debate! My name is SMITH! People call me SMITH! This world is inhabited by creatures called DEBATERS! For some people, DEBATERS are pets. Others use them for fights. Myself... I teach DEBATERS as a profession. Tell me, would YOU like to join the Barlow Debate Team?', cb (cb) => @game.dialog.menu 'Would you like to join Barlow Debate?', ['YES', true], ['NO', false], cb (result, cb) => if(result is yes) @game.opponent.say 'Great! First, however, you\'ll need to get these permission slips signed... I can help you fill them out. First, are you a DEBATER or are you a GIRL?', cb if(result is no) @game.opponent.say 'Oh. Well... Goodbye then!\n(YOU LOSE)', (err) => cb('LOST GAME') @game.prev() (cb) => @game.dialog.menu 'Are you a BOY or a GIRL?', ['BOY', 1], ['GIRL', 2], #['I don\'t conform to the gender binary', 3], cb (result, cb) => player = new Player(@game, 'PLAYER', if result is 2 then 'girl' else 'boy') resp = (if result is 3 then '... Okay. That\'s great, but I couldn\'t find a gender-neutral character picture, so I\'m going to have to draw you as a guy. Sorrypleasedontsue.' else '') + 'Next question, what is your name?' @game.setPlayer player @game.opponent.say resp, cb (cb) => @game.dialog.menu 'What is your name?', ['PLAYER ONE', 'PLAYER ONE'], ['PLAYER TWO', 'PLAYER TWO'], ['RED', 'RED'], ['FUSCHIA', 'FUSCHIA'], ['RANDY', 'RANDY'], ['ME', 'ME'], ['RANDOM', 'RANDOM'], ['NONE OF THESE', 'NONE OF THESE ARE MY NAME'], cb (name, cb) => @game.player.setName(name) @game.opponent.say 'Right! So your name is ' + name + '. Listen ' + name + ' normally, I\'d teach you how to debate before sending you off to face CDA judges, but we just don\'t have time. You see, we\'ve got a bit of an emergency on our hands. Earlier this year, my old co-coach EVAN STREAMS moved to China to teach debate there. And, like everyone in China, while there he became a COMMUNIST. Well, now he\'s back, and he\'s begun convincing all of my old debaters to join him under the COMMUNIST FLAG. That means you\'re all I have left. Please ' + name + ' I need you to head out and out-debate EVAN, convincing him to become a God-fearing CAPITALIST. You\'re the only hope I have left. Will you help me?', cb (cb) => @game.dialog.menu 'Will you help stop the COMMUNIST EVAN STREAMS and restore a love of CAPITALISM to the debate team?', ['YES', true], ['NO', false], cb (result, cb) => if(result is yes) @game.opponent.say 'Excellent! You\'ll have to head out now and face all of the debaters EVAN has turned into COMMUNISTS. Once you\'ve defeated all of them, you\'ll face EVAN himself. But, before you go, I can teach you ONE TECHNIQUE. What would you like to learn?', cb if(result is no) @game.opponent.say 'Oh. Well... Goodbye then!\n(YOU LOSE)', (err) => cb('LOST GAME') @game.prev() (cb) => @game.dialog.arrMenu 'Choose a technique to learn:', @game.availableMoves, cb (move, cb) => @game.removeMove(move.name) @game.player.addMove(move) @game.opponent.say move.name + '? I can definitely explain that... (one hour later)... THERE! All set! Now it\'s off to debate. You\'ll begin in the novice league, so you\'re sure to get some cupcakes at first, but as you win (in the name of CAPITALISM) your opponents will get more difficult. You\'ll learn more techniques over time. Just pay attention to your opponents. Your end-goal, of course, is EVAN STREAMS. You must out-debate him. You must convince that COMMUNIST that the AMERICAN WAY is best. Good luck ' + @game.player.name + '.', cb (cb) => @game.next() ] unload: () -> super()
214194
$ = require './../lib/jquery.js' Screen = require './../screen.coffee' Debater = require './../debater.coffee' Player = require './../debaters/player.coffee' Async = require './../lib/async.js' module.exports = class Oak extends Screen constructor: (@game) -> super @game load: () -> super() @game.setOpponent(new Debater(@game, true, '<NAME>', 31, 6, 'COACH')) @game.opponentElem.show() @game.console.show() Async.waterfall [ (cb) => @game.pause 1000, cb (cb) => @game.opponent.say 'Hello there! Welcome to the world of Barlow Debate! My name is <NAME>! People call me <NAME>! This world is inhabited by creatures called DEBATERS! For some people, DEBATERS are pets. Others use them for fights. Myself... I teach DEBATERS as a profession. Tell me, would YOU like to join the Barlow Debate Team?', cb (cb) => @game.dialog.menu 'Would you like to join Barlow Debate?', ['YES', true], ['NO', false], cb (result, cb) => if(result is yes) @game.opponent.say 'Great! First, however, you\'ll need to get these permission slips signed... I can help you fill them out. First, are you a DEBATER or are you a GIRL?', cb if(result is no) @game.opponent.say 'Oh. Well... Goodbye then!\n(YOU LOSE)', (err) => cb('LOST GAME') @game.prev() (cb) => @game.dialog.menu 'Are you a BOY or a GIRL?', ['BOY', 1], ['GIRL', 2], #['I don\'t conform to the gender binary', 3], cb (result, cb) => player = new Player(@game, 'PLAYER', if result is 2 then 'girl' else 'boy') resp = (if result is 3 then '... Okay. That\'s great, but I couldn\'t find a gender-neutral character picture, so I\'m going to have to draw you as a guy. Sorrypleasedontsue.' else '') + 'Next question, what is your name?' @game.setPlayer player @game.opponent.say resp, cb (cb) => @game.dialog.menu 'What is your name?', ['PLAYER ONE', 'PLAYER ONE'], ['PLAYER TWO', 'PLAYER TWO'], ['RED', 'RED'], ['FUSCHIA', 'FUSCHIA'], ['RANDY', 'RANDY'], ['ME', 'ME'], ['RANDOM', 'RANDOM'], ['NONE OF THESE', 'NONE OF THESE ARE MY NAME'], cb (name, cb) => @game.player.setName(name) @game.opponent.say 'Right! So your name is ' + name + '. Listen ' + name + ' normally, I\'d teach you how to debate before sending you off to face CDA judges, but we just don\'t have time. You see, we\'ve got a bit of an emergency on our hands. Earlier this year, my old co-coach EVAN STREAMS moved to China to teach debate there. And, like everyone in China, while there he became a COMMUNIST. Well, now he\'s back, and he\'s begun convincing all of my old debaters to join him under the COMMUNIST FLAG. That means you\'re all I have left. Please ' + name + ' I need you to head out and out-debate EVAN, convincing him to become a God-fearing CAPITALIST. You\'re the only hope I have left. Will you help me?', cb (cb) => @game.dialog.menu 'Will you help stop the COMMUNIST EVAN STREAMS and restore a love of CAPITALISM to the debate team?', ['YES', true], ['NO', false], cb (result, cb) => if(result is yes) @game.opponent.say 'Excellent! You\'ll have to head out now and face all of the debaters EVAN has turned into COMMUNISTS. Once you\'ve defeated all of them, you\'ll face EVAN himself. But, before you go, I can teach you ONE TECHNIQUE. What would you like to learn?', cb if(result is no) @game.opponent.say 'Oh. Well... Goodbye then!\n(YOU LOSE)', (err) => cb('LOST GAME') @game.prev() (cb) => @game.dialog.arrMenu 'Choose a technique to learn:', @game.availableMoves, cb (move, cb) => @game.removeMove(move.name) @game.player.addMove(move) @game.opponent.say move.name + '? I can definitely explain that... (one hour later)... THERE! All set! Now it\'s off to debate. You\'ll begin in the novice league, so you\'re sure to get some cupcakes at first, but as you win (in the name of CAPITALISM) your opponents will get more difficult. You\'ll learn more techniques over time. Just pay attention to your opponents. Your end-goal, of course, is EVAN STREAMS. You must out-debate him. You must convince that COMMUNIST that the AMERICAN WAY is best. Good luck ' + @game.player.name + '.', cb (cb) => @game.next() ] unload: () -> super()
true
$ = require './../lib/jquery.js' Screen = require './../screen.coffee' Debater = require './../debater.coffee' Player = require './../debaters/player.coffee' Async = require './../lib/async.js' module.exports = class Oak extends Screen constructor: (@game) -> super @game load: () -> super() @game.setOpponent(new Debater(@game, true, 'PI:NAME:<NAME>END_PI', 31, 6, 'COACH')) @game.opponentElem.show() @game.console.show() Async.waterfall [ (cb) => @game.pause 1000, cb (cb) => @game.opponent.say 'Hello there! Welcome to the world of Barlow Debate! My name is PI:NAME:<NAME>END_PI! People call me PI:NAME:<NAME>END_PI! This world is inhabited by creatures called DEBATERS! For some people, DEBATERS are pets. Others use them for fights. Myself... I teach DEBATERS as a profession. Tell me, would YOU like to join the Barlow Debate Team?', cb (cb) => @game.dialog.menu 'Would you like to join Barlow Debate?', ['YES', true], ['NO', false], cb (result, cb) => if(result is yes) @game.opponent.say 'Great! First, however, you\'ll need to get these permission slips signed... I can help you fill them out. First, are you a DEBATER or are you a GIRL?', cb if(result is no) @game.opponent.say 'Oh. Well... Goodbye then!\n(YOU LOSE)', (err) => cb('LOST GAME') @game.prev() (cb) => @game.dialog.menu 'Are you a BOY or a GIRL?', ['BOY', 1], ['GIRL', 2], #['I don\'t conform to the gender binary', 3], cb (result, cb) => player = new Player(@game, 'PLAYER', if result is 2 then 'girl' else 'boy') resp = (if result is 3 then '... Okay. That\'s great, but I couldn\'t find a gender-neutral character picture, so I\'m going to have to draw you as a guy. Sorrypleasedontsue.' else '') + 'Next question, what is your name?' @game.setPlayer player @game.opponent.say resp, cb (cb) => @game.dialog.menu 'What is your name?', ['PLAYER ONE', 'PLAYER ONE'], ['PLAYER TWO', 'PLAYER TWO'], ['RED', 'RED'], ['FUSCHIA', 'FUSCHIA'], ['RANDY', 'RANDY'], ['ME', 'ME'], ['RANDOM', 'RANDOM'], ['NONE OF THESE', 'NONE OF THESE ARE MY NAME'], cb (name, cb) => @game.player.setName(name) @game.opponent.say 'Right! So your name is ' + name + '. Listen ' + name + ' normally, I\'d teach you how to debate before sending you off to face CDA judges, but we just don\'t have time. You see, we\'ve got a bit of an emergency on our hands. Earlier this year, my old co-coach EVAN STREAMS moved to China to teach debate there. And, like everyone in China, while there he became a COMMUNIST. Well, now he\'s back, and he\'s begun convincing all of my old debaters to join him under the COMMUNIST FLAG. That means you\'re all I have left. Please ' + name + ' I need you to head out and out-debate EVAN, convincing him to become a God-fearing CAPITALIST. You\'re the only hope I have left. Will you help me?', cb (cb) => @game.dialog.menu 'Will you help stop the COMMUNIST EVAN STREAMS and restore a love of CAPITALISM to the debate team?', ['YES', true], ['NO', false], cb (result, cb) => if(result is yes) @game.opponent.say 'Excellent! You\'ll have to head out now and face all of the debaters EVAN has turned into COMMUNISTS. Once you\'ve defeated all of them, you\'ll face EVAN himself. But, before you go, I can teach you ONE TECHNIQUE. What would you like to learn?', cb if(result is no) @game.opponent.say 'Oh. Well... Goodbye then!\n(YOU LOSE)', (err) => cb('LOST GAME') @game.prev() (cb) => @game.dialog.arrMenu 'Choose a technique to learn:', @game.availableMoves, cb (move, cb) => @game.removeMove(move.name) @game.player.addMove(move) @game.opponent.say move.name + '? I can definitely explain that... (one hour later)... THERE! All set! Now it\'s off to debate. You\'ll begin in the novice league, so you\'re sure to get some cupcakes at first, but as you win (in the name of CAPITALISM) your opponents will get more difficult. You\'ll learn more techniques over time. Just pay attention to your opponents. Your end-goal, of course, is EVAN STREAMS. You must out-debate him. You must convince that COMMUNIST that the AMERICAN WAY is best. Good luck ' + @game.player.name + '.', cb (cb) => @game.next() ] unload: () -> super()
[ { "context": " (8).should.equal gridC.height\n '127.0.0.1'.should.equal gridC.host\n port.should.eq", "end": 1594, "score": 0.9997630715370178, "start": 1585, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "sys/size', 8, 8\n client.send '/sys/host', '127.0.0.1'\n client.send '/sys/port', port\n cl", "end": 1897, "score": 0.9997131824493408, "start": 1888, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "ittle Mocha Reference ========\nhttps://github.com/visionmedia/should.js\nhttps://github.com/visionmedia/mocha\n\nM", "end": 2169, "score": 0.9993683099746704, "start": 2158, "tag": "USERNAME", "value": "visionmedia" }, { "context": "thub.com/visionmedia/should.js\nhttps://github.com/visionmedia/mocha\n\nMocha hooks:\n before ()-> # before descri", "end": 2210, "score": 0.9992998838424683, "start": 2199, "tag": "USERNAME", "value": "visionmedia" }, { "context": "\n 'foo bar baz'.should.include('foo')\n { name: 'TJ', pet: tobi }.user.should.include({ pet: tobi, na", "end": 3148, "score": 0.5946540236473083, "start": 3146, "tag": "NAME", "value": "TJ" }, { "context": "t: tobi }.user.should.include({ pet: tobi, name: 'TJ' })\n { foo: 'bar', baz: 'raz' }.should.have.key", "end": 3204, "score": 0.5760142207145691, "start": 3203, "tag": "NAME", "value": "T" }, { "context": ".should.be.a('object').and.have.property('name', 'tj')\n###\n", "end": 3454, "score": 0.8698847889900208, "start": 3452, "tag": "NAME", "value": "tj" } ]
src/test/grid-test.coffee
CharlesHolbrow/monode
13
'use strict' should = require 'should' osc = require 'node-osc' makeGrid = require '../lib/grid' grid = null DEVICE_PORT= 9009 # create a new grid at every descrive at current indentation level before -> grid = makeGrid(DEVICE_PORT) after -> grid.close() describe 'makeGrid', -> describe 'width', -> it 'should be be null when first created', -> should.strictEqual grid.width, null it 'should throw an error on assignment', -> error = 'No Error' # Is there a better way? try grid.width = 5 catch err then error = err error.should.be.an.instanceOf(Error) it 'should emit "listening" and listen for "size"', (done)-> @timeout(200) gridB = makeGrid(DEVICE_PORT + 1) gridB.on 'listening', (port)-> # pretend we are serialosc, and we are sending a size client = new osc.Client 'localhost', port client.send '/sys/size', 8, 16 setTimeout -> (8).should.equal(gridB.width) (16).should.equal(gridB.height) gridB.close() done() , 10 describe 'ready event', -> it 'should emit "ready" only once all 6 sys ' + 'messages have been received', (done)-> @timeout(200) gridC = makeGrid(DEVICE_PORT + 3, 'monome 64') gridC.on 'listening', (port)-> client = new osc.Client 'localhost', port error = new Error 'grid triggered ready too soon' gridC.on 'ready', -> 'm9999999'.should.equal gridC.id (8).should.equal gridC.width (8).should.equal gridC.height '127.0.0.1'.should.equal gridC.host port.should.equal gridC.port '/testprefix'.should.equal gridC.prefix (0).should.equal gridC.rotation done(error) client.send '/sys/id', 'm9999999' client.send '/sys/size', 8, 8 client.send '/sys/host', '127.0.0.1' client.send '/sys/port', port client.send '/sys/prefix', '/testprefix' setTimeout => client.send '/sys/rotation', 0 error = null , 20 ### ======== A Handy Little Mocha Reference ======== https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: 'TJ', pet: tobi }.user.should.include({ pet: tobi, name: 'TJ' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', 'tj') ###
118312
'use strict' should = require 'should' osc = require 'node-osc' makeGrid = require '../lib/grid' grid = null DEVICE_PORT= 9009 # create a new grid at every descrive at current indentation level before -> grid = makeGrid(DEVICE_PORT) after -> grid.close() describe 'makeGrid', -> describe 'width', -> it 'should be be null when first created', -> should.strictEqual grid.width, null it 'should throw an error on assignment', -> error = 'No Error' # Is there a better way? try grid.width = 5 catch err then error = err error.should.be.an.instanceOf(Error) it 'should emit "listening" and listen for "size"', (done)-> @timeout(200) gridB = makeGrid(DEVICE_PORT + 1) gridB.on 'listening', (port)-> # pretend we are serialosc, and we are sending a size client = new osc.Client 'localhost', port client.send '/sys/size', 8, 16 setTimeout -> (8).should.equal(gridB.width) (16).should.equal(gridB.height) gridB.close() done() , 10 describe 'ready event', -> it 'should emit "ready" only once all 6 sys ' + 'messages have been received', (done)-> @timeout(200) gridC = makeGrid(DEVICE_PORT + 3, 'monome 64') gridC.on 'listening', (port)-> client = new osc.Client 'localhost', port error = new Error 'grid triggered ready too soon' gridC.on 'ready', -> 'm9999999'.should.equal gridC.id (8).should.equal gridC.width (8).should.equal gridC.height '127.0.0.1'.should.equal gridC.host port.should.equal gridC.port '/testprefix'.should.equal gridC.prefix (0).should.equal gridC.rotation done(error) client.send '/sys/id', 'm9999999' client.send '/sys/size', 8, 8 client.send '/sys/host', '127.0.0.1' client.send '/sys/port', port client.send '/sys/prefix', '/testprefix' setTimeout => client.send '/sys/rotation', 0 error = null , 20 ### ======== A Handy Little Mocha Reference ======== https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: '<NAME>', pet: tobi }.user.should.include({ pet: tobi, name: '<NAME>J' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', '<NAME>') ###
true
'use strict' should = require 'should' osc = require 'node-osc' makeGrid = require '../lib/grid' grid = null DEVICE_PORT= 9009 # create a new grid at every descrive at current indentation level before -> grid = makeGrid(DEVICE_PORT) after -> grid.close() describe 'makeGrid', -> describe 'width', -> it 'should be be null when first created', -> should.strictEqual grid.width, null it 'should throw an error on assignment', -> error = 'No Error' # Is there a better way? try grid.width = 5 catch err then error = err error.should.be.an.instanceOf(Error) it 'should emit "listening" and listen for "size"', (done)-> @timeout(200) gridB = makeGrid(DEVICE_PORT + 1) gridB.on 'listening', (port)-> # pretend we are serialosc, and we are sending a size client = new osc.Client 'localhost', port client.send '/sys/size', 8, 16 setTimeout -> (8).should.equal(gridB.width) (16).should.equal(gridB.height) gridB.close() done() , 10 describe 'ready event', -> it 'should emit "ready" only once all 6 sys ' + 'messages have been received', (done)-> @timeout(200) gridC = makeGrid(DEVICE_PORT + 3, 'monome 64') gridC.on 'listening', (port)-> client = new osc.Client 'localhost', port error = new Error 'grid triggered ready too soon' gridC.on 'ready', -> 'm9999999'.should.equal gridC.id (8).should.equal gridC.width (8).should.equal gridC.height '127.0.0.1'.should.equal gridC.host port.should.equal gridC.port '/testprefix'.should.equal gridC.prefix (0).should.equal gridC.rotation done(error) client.send '/sys/id', 'm9999999' client.send '/sys/size', 8, 8 client.send '/sys/host', '127.0.0.1' client.send '/sys/port', port client.send '/sys/prefix', '/testprefix' setTimeout => client.send '/sys/rotation', 0 error = null , 20 ### ======== A Handy Little Mocha Reference ======== https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: 'PI:NAME:<NAME>END_PI', pet: tobi }.user.should.include({ pet: tobi, name: 'PI:NAME:<NAME>END_PIJ' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', 'PI:NAME:<NAME>END_PI') ###
[ { "context": " @_events = {}\n @headerFields = [\n key: '_roomId'\n type: 'selector'\n ]\n @footerFields =", "end": 1846, "score": 0.879968523979187, "start": 1838, "tag": "KEY", "value": "'_roomId" } ]
src/service.coffee
jianliaoim/talk-services
40
path = require 'path' fs = require 'fs' Promise = require 'bluebird' _ = require 'lodash' glob = require 'glob' request = require 'request' marked = require 'marked' util = require './util' requestAsync = Promise.promisify request _getManual = -> return @_manual if @_manual? self = this name = @name fileNames = glob.sync "#{__dirname}/../manuals/#{name}*.md" _getContent = (fileName) -> baseName = path.basename fileName lang = baseName[(name.length + 1)..-4] content = fs.readFileSync(fileName, encoding: 'UTF-8') content = content.replace /\((.*?images.*?)\)/ig, (m, uri) -> '(' + util.static uri + ')' [lang, marked(content)] if fileNames.length is 0 @_manual = false else if fileNames.length is 1 @_manual = _getContent(fileNames[0])[1] else @_manual = _.zipObject fileNames.map _getContent _getFields = -> [].concat @headerFields, @_fields, @footerFields _httpPost = (url, payload) -> requestAsync method: 'POST' url: url headers: 'User-Agent': util.getUserAgent() json: true timeout: 5000 body: payload .then (res) -> unless res.statusCode >= 200 and res.statusCode < 300 throw new Error("Bad request #{res.statusCode}") res.body class Service # Shown as title title: '' # Shown in the integration list summary: '' # Shown in the integration configuation page description: '' # Shown as integration icon and default avatarUrl of message creator iconUrl: '' # Template of settings page template: '' # Whether if the service displayed in web/android/ios isHidden: false isCustomized: false showRobot: false constructor: (@name) -> register: -> @title = @name @_fields = [] # Open api @_apis = {} # Handler on events @_events = {} @headerFields = [ key: '_roomId' type: 'selector' ] @footerFields = [ key: 'title' type: 'text' , key: 'description' type: 'text' , key: 'iconUrl' type: 'file' ] Object.defineProperty this, 'fields', get: _getFields, set: (@_fields) -> @_fields Object.defineProperty this, 'manual', get: _getManual # Register open apis # The route of api will be `POST services/:integration_name/:api_name` registerApi: (name, fn) -> @_apis[name] = fn registerEvents: (events) -> self = this if toString.call(events) is '[object Array]' events.forEach (event) -> self.registerEvent event else if toString.call(events) is '[object Object]' Object.keys(events).forEach (event) -> handler = events[event] self.registerEvent event, handler else throw new Error('Events are invalid') ###* * Get url of apis from services, group by service name * @param {String} apiName - Api name * @return {String} url - The complete api url ### getApiUrl: (apiName) -> util.getApiUrl @name, apiName receiveApi: (name, req, res) -> self = this Promise.resolve() .then -> unless toString.call(self._apis[name]) is '[object Function]' throw new Error('Api function is not defined') self._apis[name].call self, req, res registerEvent: (event, handler) -> self = this unless toString.call(handler) is '[object Function]' throw new Error('Event handler is undefined') @_events[event] = handler receiveEvent: (event, req, res) -> unless toString.call(@_events[event]) is '[object Function]' return Promise.resolve() self = this Promise.resolve().then -> self._events[event].call self, req, res toJSON: -> name: @name template: @template title: @title summary: @summary description: @description iconUrl: @iconUrl fields: @fields manual: @manual isCustomized: @isCustomized showRobot: @showRobot toObject: @::toJSON # ========================== Define build-in functions ========================== ###* * Send message to talk users * @param {Object} message * @return {Promise} MessageModel ### sendMessage: (message) -> # @todo Implement this function ###* * Post data to the thrid part services * @param {String} URL * @param {Object} Payload * @param {Object} Options * @return {Promise} Response body ### httpPost: (url, payload, options = {}) -> tryTimes = 0 retryTimes = options.retryTimes or 0 interval = options.interval or 1000 return _httpPost url, payload if retryTimes < 1 _tryPost = -> _httpPost url, payload .catch (err) -> tryTimes += 1 throw err if tryTimes > retryTimes Promise.delay interval .then -> interval *= 3 _tryPost() _tryPost() # ========================== Define build-in functions finish ========================== module.exports = Service
116988
path = require 'path' fs = require 'fs' Promise = require 'bluebird' _ = require 'lodash' glob = require 'glob' request = require 'request' marked = require 'marked' util = require './util' requestAsync = Promise.promisify request _getManual = -> return @_manual if @_manual? self = this name = @name fileNames = glob.sync "#{__dirname}/../manuals/#{name}*.md" _getContent = (fileName) -> baseName = path.basename fileName lang = baseName[(name.length + 1)..-4] content = fs.readFileSync(fileName, encoding: 'UTF-8') content = content.replace /\((.*?images.*?)\)/ig, (m, uri) -> '(' + util.static uri + ')' [lang, marked(content)] if fileNames.length is 0 @_manual = false else if fileNames.length is 1 @_manual = _getContent(fileNames[0])[1] else @_manual = _.zipObject fileNames.map _getContent _getFields = -> [].concat @headerFields, @_fields, @footerFields _httpPost = (url, payload) -> requestAsync method: 'POST' url: url headers: 'User-Agent': util.getUserAgent() json: true timeout: 5000 body: payload .then (res) -> unless res.statusCode >= 200 and res.statusCode < 300 throw new Error("Bad request #{res.statusCode}") res.body class Service # Shown as title title: '' # Shown in the integration list summary: '' # Shown in the integration configuation page description: '' # Shown as integration icon and default avatarUrl of message creator iconUrl: '' # Template of settings page template: '' # Whether if the service displayed in web/android/ios isHidden: false isCustomized: false showRobot: false constructor: (@name) -> register: -> @title = @name @_fields = [] # Open api @_apis = {} # Handler on events @_events = {} @headerFields = [ key: <KEY>' type: 'selector' ] @footerFields = [ key: 'title' type: 'text' , key: 'description' type: 'text' , key: 'iconUrl' type: 'file' ] Object.defineProperty this, 'fields', get: _getFields, set: (@_fields) -> @_fields Object.defineProperty this, 'manual', get: _getManual # Register open apis # The route of api will be `POST services/:integration_name/:api_name` registerApi: (name, fn) -> @_apis[name] = fn registerEvents: (events) -> self = this if toString.call(events) is '[object Array]' events.forEach (event) -> self.registerEvent event else if toString.call(events) is '[object Object]' Object.keys(events).forEach (event) -> handler = events[event] self.registerEvent event, handler else throw new Error('Events are invalid') ###* * Get url of apis from services, group by service name * @param {String} apiName - Api name * @return {String} url - The complete api url ### getApiUrl: (apiName) -> util.getApiUrl @name, apiName receiveApi: (name, req, res) -> self = this Promise.resolve() .then -> unless toString.call(self._apis[name]) is '[object Function]' throw new Error('Api function is not defined') self._apis[name].call self, req, res registerEvent: (event, handler) -> self = this unless toString.call(handler) is '[object Function]' throw new Error('Event handler is undefined') @_events[event] = handler receiveEvent: (event, req, res) -> unless toString.call(@_events[event]) is '[object Function]' return Promise.resolve() self = this Promise.resolve().then -> self._events[event].call self, req, res toJSON: -> name: @name template: @template title: @title summary: @summary description: @description iconUrl: @iconUrl fields: @fields manual: @manual isCustomized: @isCustomized showRobot: @showRobot toObject: @::toJSON # ========================== Define build-in functions ========================== ###* * Send message to talk users * @param {Object} message * @return {Promise} MessageModel ### sendMessage: (message) -> # @todo Implement this function ###* * Post data to the thrid part services * @param {String} URL * @param {Object} Payload * @param {Object} Options * @return {Promise} Response body ### httpPost: (url, payload, options = {}) -> tryTimes = 0 retryTimes = options.retryTimes or 0 interval = options.interval or 1000 return _httpPost url, payload if retryTimes < 1 _tryPost = -> _httpPost url, payload .catch (err) -> tryTimes += 1 throw err if tryTimes > retryTimes Promise.delay interval .then -> interval *= 3 _tryPost() _tryPost() # ========================== Define build-in functions finish ========================== module.exports = Service
true
path = require 'path' fs = require 'fs' Promise = require 'bluebird' _ = require 'lodash' glob = require 'glob' request = require 'request' marked = require 'marked' util = require './util' requestAsync = Promise.promisify request _getManual = -> return @_manual if @_manual? self = this name = @name fileNames = glob.sync "#{__dirname}/../manuals/#{name}*.md" _getContent = (fileName) -> baseName = path.basename fileName lang = baseName[(name.length + 1)..-4] content = fs.readFileSync(fileName, encoding: 'UTF-8') content = content.replace /\((.*?images.*?)\)/ig, (m, uri) -> '(' + util.static uri + ')' [lang, marked(content)] if fileNames.length is 0 @_manual = false else if fileNames.length is 1 @_manual = _getContent(fileNames[0])[1] else @_manual = _.zipObject fileNames.map _getContent _getFields = -> [].concat @headerFields, @_fields, @footerFields _httpPost = (url, payload) -> requestAsync method: 'POST' url: url headers: 'User-Agent': util.getUserAgent() json: true timeout: 5000 body: payload .then (res) -> unless res.statusCode >= 200 and res.statusCode < 300 throw new Error("Bad request #{res.statusCode}") res.body class Service # Shown as title title: '' # Shown in the integration list summary: '' # Shown in the integration configuation page description: '' # Shown as integration icon and default avatarUrl of message creator iconUrl: '' # Template of settings page template: '' # Whether if the service displayed in web/android/ios isHidden: false isCustomized: false showRobot: false constructor: (@name) -> register: -> @title = @name @_fields = [] # Open api @_apis = {} # Handler on events @_events = {} @headerFields = [ key: PI:KEY:<KEY>END_PI' type: 'selector' ] @footerFields = [ key: 'title' type: 'text' , key: 'description' type: 'text' , key: 'iconUrl' type: 'file' ] Object.defineProperty this, 'fields', get: _getFields, set: (@_fields) -> @_fields Object.defineProperty this, 'manual', get: _getManual # Register open apis # The route of api will be `POST services/:integration_name/:api_name` registerApi: (name, fn) -> @_apis[name] = fn registerEvents: (events) -> self = this if toString.call(events) is '[object Array]' events.forEach (event) -> self.registerEvent event else if toString.call(events) is '[object Object]' Object.keys(events).forEach (event) -> handler = events[event] self.registerEvent event, handler else throw new Error('Events are invalid') ###* * Get url of apis from services, group by service name * @param {String} apiName - Api name * @return {String} url - The complete api url ### getApiUrl: (apiName) -> util.getApiUrl @name, apiName receiveApi: (name, req, res) -> self = this Promise.resolve() .then -> unless toString.call(self._apis[name]) is '[object Function]' throw new Error('Api function is not defined') self._apis[name].call self, req, res registerEvent: (event, handler) -> self = this unless toString.call(handler) is '[object Function]' throw new Error('Event handler is undefined') @_events[event] = handler receiveEvent: (event, req, res) -> unless toString.call(@_events[event]) is '[object Function]' return Promise.resolve() self = this Promise.resolve().then -> self._events[event].call self, req, res toJSON: -> name: @name template: @template title: @title summary: @summary description: @description iconUrl: @iconUrl fields: @fields manual: @manual isCustomized: @isCustomized showRobot: @showRobot toObject: @::toJSON # ========================== Define build-in functions ========================== ###* * Send message to talk users * @param {Object} message * @return {Promise} MessageModel ### sendMessage: (message) -> # @todo Implement this function ###* * Post data to the thrid part services * @param {String} URL * @param {Object} Payload * @param {Object} Options * @return {Promise} Response body ### httpPost: (url, payload, options = {}) -> tryTimes = 0 retryTimes = options.retryTimes or 0 interval = options.interval or 1000 return _httpPost url, payload if retryTimes < 1 _tryPost = -> _httpPost url, payload .catch (err) -> tryTimes += 1 throw err if tryTimes > retryTimes Promise.delay interval .then -> interval *= 3 _tryPost() _tryPost() # ========================== Define build-in functions finish ========================== module.exports = Service
[ { "context": "###\n# Copyright 2014, 2015, 2016 Simon Lydell\n# X11 (“MIT”) Licensed. (See LICENSE.)\n###\n\nasser", "end": 45, "score": 0.999847412109375, "start": 33, "tag": "NAME", "value": "Simon Lydell" } ]
test/index.coffee
lydell/n-ary-huffman
10
### # Copyright 2014, 2015, 2016 Simon Lydell # X11 (“MIT”) Licensed. (See LICENSE.) ### assert = require("assert") huffman = require("../index.coffee") verifyCode = (item, code)-> assert code == item.expected, """code: "#{code}", item: #{JSON.stringify(item)}""" testCodes = (alphabet, elements)-> tree = huffman.createTree(elements, alphabet.length) # Make sure that the `children` array always is a copy. assert.notEqual tree.children, elements tree.assignCodeWords alphabet, verifyCode suite "codes", -> suite "binary", -> test "one element", -> testCodes "01", [ {value: "a", weight: 4, expected: "0"} ] test "two elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "0"} {value: "b", weight: 3, expected: "1"} ] test "three elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "00"} {value: "b", weight: 3, expected: "01"} {value: "c", weight: 6, expected: "1"} ] test "four elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} {value: "c", weight: 6, expected: "01"} {value: "d", weight: 8, expected: "1"} ] test "ternary", -> testCodes "ABC", [ {value: "a", weight: 4, expected: "BA"} {value: "b", weight: 3, expected: "BB"} {value: "c", weight: 6, expected: "C"} {value: "d", weight: 8, expected: "A"} ] test "longer alphabet than list", -> # Higher weight, earlier letter. testCodes "ABCDEF", [ {value: "a", weight: 4, expected: "C"} {value: "b", weight: 3, expected: "D"} {value: "c", weight: 6, expected: "B"} {value: "d", weight: 8, expected: "A"} ] test "equal weights", -> testCodes "01", [ {value: "a", weight: 1, expected: "10"} {value: "b", weight: 1, expected: "11"} {value: "c", weight: 1, expected: "000"} {value: "d", weight: 1, expected: "001"} {value: "e", weight: 1, expected: "010"} {value: "f", weight: 1, expected: "011"} ] test "preserve “original order”", -> testCodes "abcdefgh", [ {value: "a", weight: 1, expected: "a"} {value: "b", weight: 1, expected: "b"} {value: "c", weight: 1, expected: "c"} {value: "d", weight: 1, expected: "d"} {value: "e", weight: 1, expected: "e"} {value: "f", weight: 1, expected: "f"} ] test "“unusual” weights", -> testCodes "01", [ {value: "a", weight: -4, expected: "111"} {value: "b", weight: 0, expected: "110"} {value: "c", weight: 18.3, expected: "0"} {value: "d", weight: 9, expected: "10"} ] test "QWERTY home row", -> testCodes "fjdksla;", [ {value: "a", weight: 4, expected: "kl"} {value: "b", weight: 1201, expected: "f"} {value: "c", weight: 254.56, expected: "a"} {value: "d", weight: 202, expected: ";"} {value: "e", weight: 578, expected: "j"} {value: "f", weight: 104, expected: "kj"} {value: "g", weight: 48.5, expected: "kd"} {value: "h", weight: 198, expected: "kf"} {value: "i", weight: 18, expected: "ks"} {value: "j", weight: 286, expected: "s"} {value: "k", weight: 463, expected: "d"} {value: "l", weight: 32, expected: "kk"} {value: "m", weight: 271, expected: "l"} ] test "alphabet as array", -> testCodes ["0", "1"], [ {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} {value: "c", weight: 6, expected: "01"} {value: "d", weight: 8, expected: "1"} ] test "mixing trees", -> subTree = huffman.createTree([ {value: "sub-a", weight: 4, expected: "ABA"} {value: "sub-b", weight: 3, expected: "ABB"} {value: "sub-c", weight: 6, expected: "AC"} {value: "sub-d", weight: 8, expected: "AA"} ], 3) tree = huffman.createTree([ {value: "a", weight: 4, expected: "BB"} {value: "b", weight: 3, expected: "BC"} {value: "c", weight: 6, expected: "BA"} {value: "d", weight: 8, expected: "C"} subTree ], 3) tree.assignCodeWords "ABC", verifyCode test "custom prefix", -> tree = huffman.createTree([ {value: "a", weight: 4, expected: "pBA"} {value: "b", weight: 3, expected: "pBB"} {value: "c", weight: 6, expected: "pC"} {value: "d", weight: 8, expected: "pA"} ], 3) tree.assignCodeWords "ABC", verifyCode, "p" test "already sorted", -> elements = [ {value: "d", weight: 8, expected: "1"} {value: "c", weight: 6, expected: "01"} {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} ] elements.slice = -> assert false, "expected the elements not to be copied" tree = huffman.createTree(elements, 2, sorted: yes) tree.assignCodeWords "01", verifyCode suite "createTree", -> test "empty list", -> elements = [] tree = huffman.createTree(elements, 2) assert.equal tree.weight, 0 assert.equal tree.children.length, 0 assert.notEqual tree.children, elements tree.assignCodeWords "01", -> assert false, "Expected callback not to run" test "prevent infinite recursion", -> assert.throws (-> huffman.createTree([], 0)), RangeError assert.throws (-> huffman.createTree([], 1)), RangeError test "returns BranchPoint", -> assert huffman.createTree([], 2) instanceof huffman.BranchPoint assert huffman.createTree([ {weight: 1} {weight: 2} ], 2) instanceof huffman.BranchPoint test "preserve sort order", -> elements = [{weight: 3}, {weight: 1}, {weight: 2}] tree = huffman.createTree(elements, 3) assert.deepEqual tree.children, [{weight: 1}, {weight: 2}, {weight: 3}] assert.deepEqual elements, [{weight: 3}, {weight: 1}, {weight: 2}]
10040
### # Copyright 2014, 2015, 2016 <NAME> # X11 (“MIT”) Licensed. (See LICENSE.) ### assert = require("assert") huffman = require("../index.coffee") verifyCode = (item, code)-> assert code == item.expected, """code: "#{code}", item: #{JSON.stringify(item)}""" testCodes = (alphabet, elements)-> tree = huffman.createTree(elements, alphabet.length) # Make sure that the `children` array always is a copy. assert.notEqual tree.children, elements tree.assignCodeWords alphabet, verifyCode suite "codes", -> suite "binary", -> test "one element", -> testCodes "01", [ {value: "a", weight: 4, expected: "0"} ] test "two elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "0"} {value: "b", weight: 3, expected: "1"} ] test "three elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "00"} {value: "b", weight: 3, expected: "01"} {value: "c", weight: 6, expected: "1"} ] test "four elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} {value: "c", weight: 6, expected: "01"} {value: "d", weight: 8, expected: "1"} ] test "ternary", -> testCodes "ABC", [ {value: "a", weight: 4, expected: "BA"} {value: "b", weight: 3, expected: "BB"} {value: "c", weight: 6, expected: "C"} {value: "d", weight: 8, expected: "A"} ] test "longer alphabet than list", -> # Higher weight, earlier letter. testCodes "ABCDEF", [ {value: "a", weight: 4, expected: "C"} {value: "b", weight: 3, expected: "D"} {value: "c", weight: 6, expected: "B"} {value: "d", weight: 8, expected: "A"} ] test "equal weights", -> testCodes "01", [ {value: "a", weight: 1, expected: "10"} {value: "b", weight: 1, expected: "11"} {value: "c", weight: 1, expected: "000"} {value: "d", weight: 1, expected: "001"} {value: "e", weight: 1, expected: "010"} {value: "f", weight: 1, expected: "011"} ] test "preserve “original order”", -> testCodes "abcdefgh", [ {value: "a", weight: 1, expected: "a"} {value: "b", weight: 1, expected: "b"} {value: "c", weight: 1, expected: "c"} {value: "d", weight: 1, expected: "d"} {value: "e", weight: 1, expected: "e"} {value: "f", weight: 1, expected: "f"} ] test "“unusual” weights", -> testCodes "01", [ {value: "a", weight: -4, expected: "111"} {value: "b", weight: 0, expected: "110"} {value: "c", weight: 18.3, expected: "0"} {value: "d", weight: 9, expected: "10"} ] test "QWERTY home row", -> testCodes "fjdksla;", [ {value: "a", weight: 4, expected: "kl"} {value: "b", weight: 1201, expected: "f"} {value: "c", weight: 254.56, expected: "a"} {value: "d", weight: 202, expected: ";"} {value: "e", weight: 578, expected: "j"} {value: "f", weight: 104, expected: "kj"} {value: "g", weight: 48.5, expected: "kd"} {value: "h", weight: 198, expected: "kf"} {value: "i", weight: 18, expected: "ks"} {value: "j", weight: 286, expected: "s"} {value: "k", weight: 463, expected: "d"} {value: "l", weight: 32, expected: "kk"} {value: "m", weight: 271, expected: "l"} ] test "alphabet as array", -> testCodes ["0", "1"], [ {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} {value: "c", weight: 6, expected: "01"} {value: "d", weight: 8, expected: "1"} ] test "mixing trees", -> subTree = huffman.createTree([ {value: "sub-a", weight: 4, expected: "ABA"} {value: "sub-b", weight: 3, expected: "ABB"} {value: "sub-c", weight: 6, expected: "AC"} {value: "sub-d", weight: 8, expected: "AA"} ], 3) tree = huffman.createTree([ {value: "a", weight: 4, expected: "BB"} {value: "b", weight: 3, expected: "BC"} {value: "c", weight: 6, expected: "BA"} {value: "d", weight: 8, expected: "C"} subTree ], 3) tree.assignCodeWords "ABC", verifyCode test "custom prefix", -> tree = huffman.createTree([ {value: "a", weight: 4, expected: "pBA"} {value: "b", weight: 3, expected: "pBB"} {value: "c", weight: 6, expected: "pC"} {value: "d", weight: 8, expected: "pA"} ], 3) tree.assignCodeWords "ABC", verifyCode, "p" test "already sorted", -> elements = [ {value: "d", weight: 8, expected: "1"} {value: "c", weight: 6, expected: "01"} {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} ] elements.slice = -> assert false, "expected the elements not to be copied" tree = huffman.createTree(elements, 2, sorted: yes) tree.assignCodeWords "01", verifyCode suite "createTree", -> test "empty list", -> elements = [] tree = huffman.createTree(elements, 2) assert.equal tree.weight, 0 assert.equal tree.children.length, 0 assert.notEqual tree.children, elements tree.assignCodeWords "01", -> assert false, "Expected callback not to run" test "prevent infinite recursion", -> assert.throws (-> huffman.createTree([], 0)), RangeError assert.throws (-> huffman.createTree([], 1)), RangeError test "returns BranchPoint", -> assert huffman.createTree([], 2) instanceof huffman.BranchPoint assert huffman.createTree([ {weight: 1} {weight: 2} ], 2) instanceof huffman.BranchPoint test "preserve sort order", -> elements = [{weight: 3}, {weight: 1}, {weight: 2}] tree = huffman.createTree(elements, 3) assert.deepEqual tree.children, [{weight: 1}, {weight: 2}, {weight: 3}] assert.deepEqual elements, [{weight: 3}, {weight: 1}, {weight: 2}]
true
### # Copyright 2014, 2015, 2016 PI:NAME:<NAME>END_PI # X11 (“MIT”) Licensed. (See LICENSE.) ### assert = require("assert") huffman = require("../index.coffee") verifyCode = (item, code)-> assert code == item.expected, """code: "#{code}", item: #{JSON.stringify(item)}""" testCodes = (alphabet, elements)-> tree = huffman.createTree(elements, alphabet.length) # Make sure that the `children` array always is a copy. assert.notEqual tree.children, elements tree.assignCodeWords alphabet, verifyCode suite "codes", -> suite "binary", -> test "one element", -> testCodes "01", [ {value: "a", weight: 4, expected: "0"} ] test "two elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "0"} {value: "b", weight: 3, expected: "1"} ] test "three elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "00"} {value: "b", weight: 3, expected: "01"} {value: "c", weight: 6, expected: "1"} ] test "four elements", -> testCodes "01", [ {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} {value: "c", weight: 6, expected: "01"} {value: "d", weight: 8, expected: "1"} ] test "ternary", -> testCodes "ABC", [ {value: "a", weight: 4, expected: "BA"} {value: "b", weight: 3, expected: "BB"} {value: "c", weight: 6, expected: "C"} {value: "d", weight: 8, expected: "A"} ] test "longer alphabet than list", -> # Higher weight, earlier letter. testCodes "ABCDEF", [ {value: "a", weight: 4, expected: "C"} {value: "b", weight: 3, expected: "D"} {value: "c", weight: 6, expected: "B"} {value: "d", weight: 8, expected: "A"} ] test "equal weights", -> testCodes "01", [ {value: "a", weight: 1, expected: "10"} {value: "b", weight: 1, expected: "11"} {value: "c", weight: 1, expected: "000"} {value: "d", weight: 1, expected: "001"} {value: "e", weight: 1, expected: "010"} {value: "f", weight: 1, expected: "011"} ] test "preserve “original order”", -> testCodes "abcdefgh", [ {value: "a", weight: 1, expected: "a"} {value: "b", weight: 1, expected: "b"} {value: "c", weight: 1, expected: "c"} {value: "d", weight: 1, expected: "d"} {value: "e", weight: 1, expected: "e"} {value: "f", weight: 1, expected: "f"} ] test "“unusual” weights", -> testCodes "01", [ {value: "a", weight: -4, expected: "111"} {value: "b", weight: 0, expected: "110"} {value: "c", weight: 18.3, expected: "0"} {value: "d", weight: 9, expected: "10"} ] test "QWERTY home row", -> testCodes "fjdksla;", [ {value: "a", weight: 4, expected: "kl"} {value: "b", weight: 1201, expected: "f"} {value: "c", weight: 254.56, expected: "a"} {value: "d", weight: 202, expected: ";"} {value: "e", weight: 578, expected: "j"} {value: "f", weight: 104, expected: "kj"} {value: "g", weight: 48.5, expected: "kd"} {value: "h", weight: 198, expected: "kf"} {value: "i", weight: 18, expected: "ks"} {value: "j", weight: 286, expected: "s"} {value: "k", weight: 463, expected: "d"} {value: "l", weight: 32, expected: "kk"} {value: "m", weight: 271, expected: "l"} ] test "alphabet as array", -> testCodes ["0", "1"], [ {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} {value: "c", weight: 6, expected: "01"} {value: "d", weight: 8, expected: "1"} ] test "mixing trees", -> subTree = huffman.createTree([ {value: "sub-a", weight: 4, expected: "ABA"} {value: "sub-b", weight: 3, expected: "ABB"} {value: "sub-c", weight: 6, expected: "AC"} {value: "sub-d", weight: 8, expected: "AA"} ], 3) tree = huffman.createTree([ {value: "a", weight: 4, expected: "BB"} {value: "b", weight: 3, expected: "BC"} {value: "c", weight: 6, expected: "BA"} {value: "d", weight: 8, expected: "C"} subTree ], 3) tree.assignCodeWords "ABC", verifyCode test "custom prefix", -> tree = huffman.createTree([ {value: "a", weight: 4, expected: "pBA"} {value: "b", weight: 3, expected: "pBB"} {value: "c", weight: 6, expected: "pC"} {value: "d", weight: 8, expected: "pA"} ], 3) tree.assignCodeWords "ABC", verifyCode, "p" test "already sorted", -> elements = [ {value: "d", weight: 8, expected: "1"} {value: "c", weight: 6, expected: "01"} {value: "a", weight: 4, expected: "000"} {value: "b", weight: 3, expected: "001"} ] elements.slice = -> assert false, "expected the elements not to be copied" tree = huffman.createTree(elements, 2, sorted: yes) tree.assignCodeWords "01", verifyCode suite "createTree", -> test "empty list", -> elements = [] tree = huffman.createTree(elements, 2) assert.equal tree.weight, 0 assert.equal tree.children.length, 0 assert.notEqual tree.children, elements tree.assignCodeWords "01", -> assert false, "Expected callback not to run" test "prevent infinite recursion", -> assert.throws (-> huffman.createTree([], 0)), RangeError assert.throws (-> huffman.createTree([], 1)), RangeError test "returns BranchPoint", -> assert huffman.createTree([], 2) instanceof huffman.BranchPoint assert huffman.createTree([ {weight: 1} {weight: 2} ], 2) instanceof huffman.BranchPoint test "preserve sort order", -> elements = [{weight: 3}, {weight: 1}, {weight: 2}] tree = huffman.createTree(elements, 3) assert.deepEqual tree.children, [{weight: 1}, {weight: 2}, {weight: 3}] assert.deepEqual elements, [{weight: 3}, {weight: 1}, {weight: 2}]
[ { "context": "###\n Copyright (c) 2014 clowwindy\n \n Permission is hereby granted, free of charge,", "end": 34, "score": 0.9996866583824158, "start": 25, "tag": "USERNAME", "value": "clowwindy" }, { "context": "ce = source\n @_method = method\n @_password = password\n @_IVSent = false\n @_IVBytesReceived = 0\n ", "end": 2742, "score": 0.9991834759712219, "start": 2734, "tag": "PASSWORD", "value": "password" } ]
src/encrypt.coffee
masdude/ShadowSPDY
0
### Copyright (c) 2014 clowwindy 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. ### # table encryption is not supported now crypto = require("crypto") tls = require("tls") util = require("util") stream = require('stream') int32Max = Math.pow(2, 32) bytes_to_key_results = {} EVP_BytesToKey = (password, key_len, iv_len) -> password = to_buffer password if bytes_to_key_results[password] return bytes_to_key_results[password] m = [] i = 0 count = 0 while count < key_len + iv_len md5 = crypto.createHash('md5') data = password if i > 0 data = Buffer.concat([m[i - 1], password]) md5.update(data) d = to_buffer md5.digest() m.push(d) count += d.length i += 1 ms = Buffer.concat(m) key = ms.slice(0, key_len) iv = ms.slice(key_len, key_len + iv_len) bytes_to_key_results[password] = [key, iv] return [key, iv] to_buffer = (input) -> if input.copy? return input else return new Buffer(input, 'binary') method_supported = 'aes-128-cfb': [16, 16] 'aes-192-cfb': [24, 16] 'aes-256-cfb': [32, 16] 'bf-cfb': [16, 8] 'camellia-128-cfb': [16, 16] 'camellia-192-cfb': [24, 16] 'camellia-256-cfb': [32, 16] 'cast5-cfb': [16, 8] 'des-cfb': [8, 8] 'idea-cfb': [16, 8] 'rc2-cfb': [16, 8] 'rc4': [16, 0] 'seed-cfb': [16, 16] getCipherLen = (method) -> method = method.toLowerCase() m = method_supported[method] return m class ShadowStream extends stream.Duplex constructor: (source, method, password) -> super() if method not of method_supported throw new Error("method #{method} not supported") method = method.toLowerCase() @_source = source @_method = method @_password = password @_IVSent = false @_IVBytesReceived = 0 m = getCipherLen(method) [@_key, iv_] = EVP_BytesToKey password, m[0], m[1] @_sendIV = crypto.randomBytes m[1] @_cipher = crypto.createCipheriv method, @_key, @_sendIV @_receiveIV = new Buffer(m[1]) @_IVBytesToReceive = m[1] @timeout = source.timeout self = this source.on 'connect', -> self.emit 'connect' source.on 'end', -> self.push null source.on 'readable', -> self.read(0) source.on 'error', (err) -> self.emit 'error', err source.on 'timeout', -> self.emit 'timeout' source.on 'close', (hadError) -> self.emit 'close', hadError _read: (bytes) -> chunk = @_source.read() if chunk == null return @push('') if chunk.length == 0 return @push(chunk) decipherStart = 0 if @_IVBytesReceived < @_IVBytesToReceive # copy IV from chunk into @_receiveIV # the data left starts from decipherStart decipherStart = chunk.copy @_receiveIV, @_IVBytesReceived @_IVBytesReceived += decipherStart if @_IVBytesReceived < @_IVBytesToReceive return if not @_decipher? @_decipher = crypto.createDecipheriv @_method, @_key, @_receiveIV if decipherStart > 0 cipher = chunk.slice decipherStart else cipher = chunk if cipher.length > 0 plain = @_decipher.update cipher @push plain _write: (chunk, encoding, callback) -> if chunk instanceof String chunk = new Buffer(chunk, encoding) try cipher = @_cipher.update chunk if not @_IVSent @_IVSent = true cipher = Buffer.concat [@_sendIV, cipher] @_source.write cipher catch e return callback(e) callback() end: (data) -> if data? and data.length > 0 data = @_cipher.update data if not @_IVSent @_IVSent = true data = Buffer.concat [@_sendIV, data] @_source.end cipher else @_source.end destroy: -> @_source.destroy() setTimeout: (timeout) -> @_source.setTimeout(timeout) exports.ShadowStream = ShadowStream
1564
### Copyright (c) 2014 clowwindy 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. ### # table encryption is not supported now crypto = require("crypto") tls = require("tls") util = require("util") stream = require('stream') int32Max = Math.pow(2, 32) bytes_to_key_results = {} EVP_BytesToKey = (password, key_len, iv_len) -> password = to_buffer password if bytes_to_key_results[password] return bytes_to_key_results[password] m = [] i = 0 count = 0 while count < key_len + iv_len md5 = crypto.createHash('md5') data = password if i > 0 data = Buffer.concat([m[i - 1], password]) md5.update(data) d = to_buffer md5.digest() m.push(d) count += d.length i += 1 ms = Buffer.concat(m) key = ms.slice(0, key_len) iv = ms.slice(key_len, key_len + iv_len) bytes_to_key_results[password] = [key, iv] return [key, iv] to_buffer = (input) -> if input.copy? return input else return new Buffer(input, 'binary') method_supported = 'aes-128-cfb': [16, 16] 'aes-192-cfb': [24, 16] 'aes-256-cfb': [32, 16] 'bf-cfb': [16, 8] 'camellia-128-cfb': [16, 16] 'camellia-192-cfb': [24, 16] 'camellia-256-cfb': [32, 16] 'cast5-cfb': [16, 8] 'des-cfb': [8, 8] 'idea-cfb': [16, 8] 'rc2-cfb': [16, 8] 'rc4': [16, 0] 'seed-cfb': [16, 16] getCipherLen = (method) -> method = method.toLowerCase() m = method_supported[method] return m class ShadowStream extends stream.Duplex constructor: (source, method, password) -> super() if method not of method_supported throw new Error("method #{method} not supported") method = method.toLowerCase() @_source = source @_method = method @_password = <PASSWORD> @_IVSent = false @_IVBytesReceived = 0 m = getCipherLen(method) [@_key, iv_] = EVP_BytesToKey password, m[0], m[1] @_sendIV = crypto.randomBytes m[1] @_cipher = crypto.createCipheriv method, @_key, @_sendIV @_receiveIV = new Buffer(m[1]) @_IVBytesToReceive = m[1] @timeout = source.timeout self = this source.on 'connect', -> self.emit 'connect' source.on 'end', -> self.push null source.on 'readable', -> self.read(0) source.on 'error', (err) -> self.emit 'error', err source.on 'timeout', -> self.emit 'timeout' source.on 'close', (hadError) -> self.emit 'close', hadError _read: (bytes) -> chunk = @_source.read() if chunk == null return @push('') if chunk.length == 0 return @push(chunk) decipherStart = 0 if @_IVBytesReceived < @_IVBytesToReceive # copy IV from chunk into @_receiveIV # the data left starts from decipherStart decipherStart = chunk.copy @_receiveIV, @_IVBytesReceived @_IVBytesReceived += decipherStart if @_IVBytesReceived < @_IVBytesToReceive return if not @_decipher? @_decipher = crypto.createDecipheriv @_method, @_key, @_receiveIV if decipherStart > 0 cipher = chunk.slice decipherStart else cipher = chunk if cipher.length > 0 plain = @_decipher.update cipher @push plain _write: (chunk, encoding, callback) -> if chunk instanceof String chunk = new Buffer(chunk, encoding) try cipher = @_cipher.update chunk if not @_IVSent @_IVSent = true cipher = Buffer.concat [@_sendIV, cipher] @_source.write cipher catch e return callback(e) callback() end: (data) -> if data? and data.length > 0 data = @_cipher.update data if not @_IVSent @_IVSent = true data = Buffer.concat [@_sendIV, data] @_source.end cipher else @_source.end destroy: -> @_source.destroy() setTimeout: (timeout) -> @_source.setTimeout(timeout) exports.ShadowStream = ShadowStream
true
### Copyright (c) 2014 clowwindy 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. ### # table encryption is not supported now crypto = require("crypto") tls = require("tls") util = require("util") stream = require('stream') int32Max = Math.pow(2, 32) bytes_to_key_results = {} EVP_BytesToKey = (password, key_len, iv_len) -> password = to_buffer password if bytes_to_key_results[password] return bytes_to_key_results[password] m = [] i = 0 count = 0 while count < key_len + iv_len md5 = crypto.createHash('md5') data = password if i > 0 data = Buffer.concat([m[i - 1], password]) md5.update(data) d = to_buffer md5.digest() m.push(d) count += d.length i += 1 ms = Buffer.concat(m) key = ms.slice(0, key_len) iv = ms.slice(key_len, key_len + iv_len) bytes_to_key_results[password] = [key, iv] return [key, iv] to_buffer = (input) -> if input.copy? return input else return new Buffer(input, 'binary') method_supported = 'aes-128-cfb': [16, 16] 'aes-192-cfb': [24, 16] 'aes-256-cfb': [32, 16] 'bf-cfb': [16, 8] 'camellia-128-cfb': [16, 16] 'camellia-192-cfb': [24, 16] 'camellia-256-cfb': [32, 16] 'cast5-cfb': [16, 8] 'des-cfb': [8, 8] 'idea-cfb': [16, 8] 'rc2-cfb': [16, 8] 'rc4': [16, 0] 'seed-cfb': [16, 16] getCipherLen = (method) -> method = method.toLowerCase() m = method_supported[method] return m class ShadowStream extends stream.Duplex constructor: (source, method, password) -> super() if method not of method_supported throw new Error("method #{method} not supported") method = method.toLowerCase() @_source = source @_method = method @_password = PI:PASSWORD:<PASSWORD>END_PI @_IVSent = false @_IVBytesReceived = 0 m = getCipherLen(method) [@_key, iv_] = EVP_BytesToKey password, m[0], m[1] @_sendIV = crypto.randomBytes m[1] @_cipher = crypto.createCipheriv method, @_key, @_sendIV @_receiveIV = new Buffer(m[1]) @_IVBytesToReceive = m[1] @timeout = source.timeout self = this source.on 'connect', -> self.emit 'connect' source.on 'end', -> self.push null source.on 'readable', -> self.read(0) source.on 'error', (err) -> self.emit 'error', err source.on 'timeout', -> self.emit 'timeout' source.on 'close', (hadError) -> self.emit 'close', hadError _read: (bytes) -> chunk = @_source.read() if chunk == null return @push('') if chunk.length == 0 return @push(chunk) decipherStart = 0 if @_IVBytesReceived < @_IVBytesToReceive # copy IV from chunk into @_receiveIV # the data left starts from decipherStart decipherStart = chunk.copy @_receiveIV, @_IVBytesReceived @_IVBytesReceived += decipherStart if @_IVBytesReceived < @_IVBytesToReceive return if not @_decipher? @_decipher = crypto.createDecipheriv @_method, @_key, @_receiveIV if decipherStart > 0 cipher = chunk.slice decipherStart else cipher = chunk if cipher.length > 0 plain = @_decipher.update cipher @push plain _write: (chunk, encoding, callback) -> if chunk instanceof String chunk = new Buffer(chunk, encoding) try cipher = @_cipher.update chunk if not @_IVSent @_IVSent = true cipher = Buffer.concat [@_sendIV, cipher] @_source.write cipher catch e return callback(e) callback() end: (data) -> if data? and data.length > 0 data = @_cipher.update data if not @_IVSent @_IVSent = true data = Buffer.concat [@_sendIV, data] @_source.end cipher else @_source.end destroy: -> @_source.destroy() setTimeout: (timeout) -> @_source.setTimeout(timeout) exports.ShadowStream = ShadowStream
[ { "context": "eate'\n\n username = req.body.username\n password = req.body.password\n new_user = models.User.build({username})\n new_", "end": 632, "score": 0.9982565641403198, "start": 615, "tag": "PASSWORD", "value": "req.body.password" }, { "context": "_password = req.body.old_password\n new_password = req.body.new_password\n\n fail = () ->\n req.flash 'errors', {msg: 'Fa", "end": 2831, "score": 0.9544124603271484, "start": 2810, "tag": "PASSWORD", "value": "req.body.new_password" } ]
src/controllers/user_controller.coffee
dwetterau/quill-firebase
1
passport = require 'passport' models = require '../models' exports.get_user_create = (req, res) -> res.render 'user/create_account', title: 'Create Account' exports.post_user_create = (req, res) -> req.assert('username', 'Username must be at least 3 characters long.').len(3) req.assert('password', 'Password must be at least 4 characters long.').len(4) req.assert('confirm_password', 'Passwords do not match.').equals(req.body.password) errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect '/user/create' username = req.body.username password = req.body.password new_user = models.User.build({username}) new_user.hash_and_set_password password, (err) -> if err? req.flash 'errors', {msg: "Unable to create account at this time"} return res.redirect '/user/create' else new_user.save().success () -> req.logIn new_user, (err) -> req.flash 'success', {msg: 'Your account has been created!'} if err? req.flash 'info', {msg: "Could not automatically log you in at this time."} res.redirect '/' .failure () -> req.flash 'errors', {msg: 'Username already in use!'} res.redirect '/user/create' exports.get_user_login = (req, res) -> redirect = req.param('r') res.render 'user/login', { title: 'Login' redirect } exports.post_user_login = (req, res, next) -> req.assert('username', 'Username is not valid.').notEmpty() req.assert('password', 'Password cannot be blank.').notEmpty() redirect = req.param('redirect') redirect_string = if redirect then '?r=' + encodeURIComponent(redirect) else '' redirect_url = decodeURIComponent(redirect) errors = req.validationErrors() if errors? req.flash 'errors', errors return res.redirect '/user/login' + redirect_string passport.authenticate('local', (err, user, info) -> if err? return next(err) if not user req.flash 'errors', {msg: info.message} return res.redirect '/user/login' + redirect_string req.logIn user, (err) -> if err? return next err req.flash 'success', {msg: "Login successful!"} res.redirect redirect_url || '/' )(req, res, next) exports.get_user_logout = (req, res) -> req.logout() res.redirect '/' exports.post_change_password = (req, res) -> req.assert('old_password', 'Password must be at least 4 characters long.').len(4) req.assert('new_password', 'Password must be at least 4 characters long.').len(4) req.assert('confirm_password', 'Passwords do not match.').equals(req.body.new_password) errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect '/user/password' old_password = req.body.old_password new_password = req.body.new_password fail = () -> req.flash 'errors', {msg: 'Failed to update password.'} return res.redirect '/user/password' models.User.find(req.user.id).success (user) -> user.compare_password old_password, (err, is_match) -> if not is_match or err req.flash 'errors', {msg: 'Current password incorrect.'} return fail(); user.hash_and_set_password new_password, (err) -> if err? return fail() user.save().success () -> req.flash 'success', {msg: 'Password changed!'} res.redirect '/user/password' .failure fail .failure fail exports.get_change_password = (req, res) -> res.render 'user/change_password', { user: req.user, title: 'Change Password' }
105021
passport = require 'passport' models = require '../models' exports.get_user_create = (req, res) -> res.render 'user/create_account', title: 'Create Account' exports.post_user_create = (req, res) -> req.assert('username', 'Username must be at least 3 characters long.').len(3) req.assert('password', 'Password must be at least 4 characters long.').len(4) req.assert('confirm_password', 'Passwords do not match.').equals(req.body.password) errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect '/user/create' username = req.body.username password = <PASSWORD> new_user = models.User.build({username}) new_user.hash_and_set_password password, (err) -> if err? req.flash 'errors', {msg: "Unable to create account at this time"} return res.redirect '/user/create' else new_user.save().success () -> req.logIn new_user, (err) -> req.flash 'success', {msg: 'Your account has been created!'} if err? req.flash 'info', {msg: "Could not automatically log you in at this time."} res.redirect '/' .failure () -> req.flash 'errors', {msg: 'Username already in use!'} res.redirect '/user/create' exports.get_user_login = (req, res) -> redirect = req.param('r') res.render 'user/login', { title: 'Login' redirect } exports.post_user_login = (req, res, next) -> req.assert('username', 'Username is not valid.').notEmpty() req.assert('password', 'Password cannot be blank.').notEmpty() redirect = req.param('redirect') redirect_string = if redirect then '?r=' + encodeURIComponent(redirect) else '' redirect_url = decodeURIComponent(redirect) errors = req.validationErrors() if errors? req.flash 'errors', errors return res.redirect '/user/login' + redirect_string passport.authenticate('local', (err, user, info) -> if err? return next(err) if not user req.flash 'errors', {msg: info.message} return res.redirect '/user/login' + redirect_string req.logIn user, (err) -> if err? return next err req.flash 'success', {msg: "Login successful!"} res.redirect redirect_url || '/' )(req, res, next) exports.get_user_logout = (req, res) -> req.logout() res.redirect '/' exports.post_change_password = (req, res) -> req.assert('old_password', 'Password must be at least 4 characters long.').len(4) req.assert('new_password', 'Password must be at least 4 characters long.').len(4) req.assert('confirm_password', 'Passwords do not match.').equals(req.body.new_password) errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect '/user/password' old_password = req.body.old_password new_password = <PASSWORD> fail = () -> req.flash 'errors', {msg: 'Failed to update password.'} return res.redirect '/user/password' models.User.find(req.user.id).success (user) -> user.compare_password old_password, (err, is_match) -> if not is_match or err req.flash 'errors', {msg: 'Current password incorrect.'} return fail(); user.hash_and_set_password new_password, (err) -> if err? return fail() user.save().success () -> req.flash 'success', {msg: 'Password changed!'} res.redirect '/user/password' .failure fail .failure fail exports.get_change_password = (req, res) -> res.render 'user/change_password', { user: req.user, title: 'Change Password' }
true
passport = require 'passport' models = require '../models' exports.get_user_create = (req, res) -> res.render 'user/create_account', title: 'Create Account' exports.post_user_create = (req, res) -> req.assert('username', 'Username must be at least 3 characters long.').len(3) req.assert('password', 'Password must be at least 4 characters long.').len(4) req.assert('confirm_password', 'Passwords do not match.').equals(req.body.password) errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect '/user/create' username = req.body.username password = PI:PASSWORD:<PASSWORD>END_PI new_user = models.User.build({username}) new_user.hash_and_set_password password, (err) -> if err? req.flash 'errors', {msg: "Unable to create account at this time"} return res.redirect '/user/create' else new_user.save().success () -> req.logIn new_user, (err) -> req.flash 'success', {msg: 'Your account has been created!'} if err? req.flash 'info', {msg: "Could not automatically log you in at this time."} res.redirect '/' .failure () -> req.flash 'errors', {msg: 'Username already in use!'} res.redirect '/user/create' exports.get_user_login = (req, res) -> redirect = req.param('r') res.render 'user/login', { title: 'Login' redirect } exports.post_user_login = (req, res, next) -> req.assert('username', 'Username is not valid.').notEmpty() req.assert('password', 'Password cannot be blank.').notEmpty() redirect = req.param('redirect') redirect_string = if redirect then '?r=' + encodeURIComponent(redirect) else '' redirect_url = decodeURIComponent(redirect) errors = req.validationErrors() if errors? req.flash 'errors', errors return res.redirect '/user/login' + redirect_string passport.authenticate('local', (err, user, info) -> if err? return next(err) if not user req.flash 'errors', {msg: info.message} return res.redirect '/user/login' + redirect_string req.logIn user, (err) -> if err? return next err req.flash 'success', {msg: "Login successful!"} res.redirect redirect_url || '/' )(req, res, next) exports.get_user_logout = (req, res) -> req.logout() res.redirect '/' exports.post_change_password = (req, res) -> req.assert('old_password', 'Password must be at least 4 characters long.').len(4) req.assert('new_password', 'Password must be at least 4 characters long.').len(4) req.assert('confirm_password', 'Passwords do not match.').equals(req.body.new_password) errors = req.validationErrors() if errors req.flash 'errors', errors return res.redirect '/user/password' old_password = req.body.old_password new_password = PI:PASSWORD:<PASSWORD>END_PI fail = () -> req.flash 'errors', {msg: 'Failed to update password.'} return res.redirect '/user/password' models.User.find(req.user.id).success (user) -> user.compare_password old_password, (err, is_match) -> if not is_match or err req.flash 'errors', {msg: 'Current password incorrect.'} return fail(); user.hash_and_set_password new_password, (err) -> if err? return fail() user.save().success () -> req.flash 'success', {msg: 'Password changed!'} res.redirect '/user/password' .failure fail .failure fail exports.get_change_password = (req, res) -> res.render 'user/change_password', { user: req.user, title: 'Change Password' }
[ { "context": "ual: 'notUnique'\n\n data =\n firstName : 'Fatih'\n lastName : 'Acet'\n age : 2", "end": 583, "score": 0.9997152090072632, "start": 578, "tag": "NAME", "value": "Fatih" }, { "context": "\n firstName : 'Fatih'\n lastName : 'Acet'\n age : 27\n isMarried : yes\n ", "end": 610, "score": 0.9997812509536743, "start": 606, "tag": "NAME", "value": "Acet" }, { "context": ": 27\n isMarried : yes\n email : 'acetfatih@gmail.com'\n userId : '123ab678'\n uniqueKey ", "end": 699, "score": 0.9999302625656128, "start": 680, "tag": "EMAIL", "value": "acetfatih@gmail.com" }, { "context": "a =\n userId : '123456'\n username : 'fatihacet'\n pageIds : [ 34, 42, 70 ]\n meta ", "end": 1260, "score": 0.9996776580810547, "start": 1251, "tag": "USERNAME", "value": "fatihacet" }, { "context": "y', ->\n expect(store.get('firstName')).toBe 'Fatih'\n expect(store.get('lastName')).toBe 'Acet'\n", "end": 2349, "score": 0.9997934103012085, "start": 2344, "tag": "NAME", "value": "Fatih" }, { "context": "'Fatih'\n expect(store.get('lastName')).toBe 'Acet'\n expect(store.get('isMarried')).toBeTruthy(", "end": 2397, "score": 0.9997023940086365, "start": 2393, "tag": "NAME", "value": "Acet" }, { "context": "ect(failed).toBe 1\n\n store.set 'firstName', 'Fatih Acet'\n expect(passed).toBe 1\n\n store.set 'ag", "end": 3250, "score": 0.9996860027313232, "start": 3240, "tag": "NAME", "value": "Fatih Acet" }, { "context": "Truthy()\n expect(store.get('firstName')).toBe 'Fatih'\n\n store.clear()\n\n expect(store.getKeys().l", "end": 3871, "score": 0.9995465874671936, "start": 3866, "tag": "NAME", "value": "Fatih" }, { "context": "id', ->\n expect(store.validate 'firstName', 'acet').toBeTruthy()\n expect(store.validate 'lastN", "end": 4770, "score": 0.669132649898529, "start": 4766, "tag": "NAME", "value": "acet" }, { "context": "Truthy()\n expect(store.validate 'lastName', 'Fatih').toBeTruthy()\n expect(store.validate 'email", "end": 4832, "score": 0.9995003342628479, "start": 4827, "tag": "NAME", "value": "Fatih" }, { "context": "oBeTruthy()\n expect(store.validate 'email', 'fatih@fatihacet.com').toBeTruthy()\n expect(store.validate 'age',", "end": 4905, "score": 0.9999246597290039, "start": 4886, "tag": "EMAIL", "value": "fatih@fatihacet.com" }, { "context": "toBeFalsy()\n expect(store.validate 'email', 'fatih@fatihacet').toBeFalsy()\n expect(store.validate 'email'", "end": 6144, "score": 0.9989196062088013, "start": 6129, "tag": "EMAIL", "value": "fatih@fatihacet" }, { "context": " validateOnInitialize: no\n data = name: 'Acetz'\n store = new spark.core.Store options, da", "end": 7058, "score": 0.9993178248405457, "start": 7053, "tag": "NAME", "value": "Acetz" }, { "context": "ect(failed).toBe 1\n\n store2.set 'username', 'fatih'\n expect(passed).toBe 1\n\n store2.set 'i", "end": 7493, "score": 0.9996265172958374, "start": 7488, "tag": "USERNAME", "value": "fatih" }, { "context": "toBe '123456'\n expect(snapshot.username).toBe 'fatihacet'\n expect(snapshot.pageIds.length).toBe 3\n e", "end": 8468, "score": 0.999669075012207, "start": 8459, "tag": "USERNAME", "value": "fatihacet" } ]
src/tests/core/test_store.coffee
dashersw/spark
1
goog = goog or goog = require: -> goog.require 'spark.core.Store' describe 'spark.core.Store', -> store = null store2 = null beforeEach -> # Store created for validations. options = validations : firstName : required: yes, maxLength: 32, minLength: 2, alphabetic: yes lastName : required: yes, maxLength: 32, minLength: 2, alphabetic: yes age : numeric : yes email : email : yes userId : length : 8 uniqueKey : equal : 'unique', notEqual: 'notUnique' data = firstName : 'Fatih' lastName : 'Acet' age : 27 isMarried : yes email : 'acetfatih@gmail.com' userId : '123ab678' uniqueKey : 'unique' store = new spark.core.Store options, data # Another store created to validate data type validations. storeOptions = validations : userId : dataType: 'string' username : dataType: 'string' pageIds : dataType: 'array' meta : dataType: 'object' isOnline : dataType: 'boolean' likeCount : dataType: 'number' fetch : dataType: 'function' storeData = userId : '123456' username : 'fatihacet' pageIds : [ 34, 42, 70 ] meta : { registedAt: 1420323019571 } isOnline : yes likeCount : 22 fetch : -> return 'fetched user data...' store2 = new spark.core.Store storeOptions, storeData describe 'constructor', -> it 'should extends spark.core.Object', -> expect(store instanceof spark.core.Object).toBeTruthy() it 'should have default options', -> s = new spark.core.Store null, null expect(s.getOptions()).toBeDefined() expect(s.map_).toBeDefined() if goog.debug it 'should create a goog.structs.Map with given data', -> if goog.structs?.Map expect(store.map_ instanceof goog.structs.Map).toBeTruthy() it 'should throw error when initial validation failed', -> error = new Error "Failed to validate store data, name: null" expect( -> new spark.core.Store { validations: name: required: yes }, name: null ).toThrow error describe 'get', -> it 'should return the value of a given key', -> expect(store.get('firstName')).toBe 'Fatih' expect(store.get('lastName')).toBe 'Acet' expect(store.get('isMarried')).toBeTruthy() expect(store.get('age')).toBe 27 it 'should return undefined for a non exists key', -> expect(store.get('realName')).not.toBeDefined() expect(store.get('realName')).toBeUndefined() describe 'set', -> it 'should set a key with value', -> store.set 'hasCar', no expect(store.get('hasCar')).toBeDefined() expect(store.get('hasCar')).toBeFalsy() it 'should not set a key without a value', -> store.set 'isDoctor' expect(store.get('isDoctor')).not.toBeDefined() it 'should validate the value', -> passed = 0 failed = 0 store.on 'PropertySet', -> ++passed store.on 'PropertyRejected', -> ++failed store.set 'email', 'acet' expect(failed).toBe 1 store.set 'firstName', 'Fatih Acet' expect(passed).toBe 1 store.set 'age', 'acet' expect(failed).toBe 2 store.set 'userId', '10ak10ak' expect(passed).toBe 2 store.set 'isMarried', yes expect(passed).toBe 3 it 'should remove a key from store', -> keysLength = store.getKeys().length expect(store.has('age')).toBeTruthy() store.unset('age') expect(store.has('age')).toBeFalsy() expect(store.getKeys().length + 1 is keysLength).toBeTruthy() it 'should remove all keys from store', -> expect(store.getKeys().length > 3).toBeTruthy() expect(store.get('firstName')).toBe 'Fatih' store.clear() expect(store.getKeys().length is 0).toBeTruthy() expect(store.get('firstName')).not.toBeDefined() it 'should return true if store has the given key', -> expect(store.has('firstName')).toBeTruthy() expect(store.has('lastName')).toBeTruthy() expect(store.has('hasCar')).toBeFalsy() it 'should return all keys', -> keys = store.getKeys() expect(keys.length > 3).toBeTruthy() expect(keys.indexOf('firstName') > -1).toBeTruthy() expect(keys.indexOf('isDoctor') is -1).toBeTruthy() it 'should return all values', -> values = store.getValues() expect(values.length > 3).toBeTruthy() expect(values.indexOf('Fatih') > -1).toBeTruthy() expect(values.indexOf('32') is -1).toBeTruthy() describe 'validate', -> it 'should return true when the given data is valid', -> expect(store.validate 'firstName', 'acet').toBeTruthy() expect(store.validate 'lastName', 'Fatih').toBeTruthy() expect(store.validate 'email', 'fatih@fatihacet.com').toBeTruthy() expect(store.validate 'age', 29).toBeTruthy() expect(store.validate 'age', '12').toBeTruthy() expect(store.validate 'userId', '911ef212').toBeTruthy() expect(store.validate 'uniqueKey', 'unique').toBeTruthy() it 'should return false when the given data is invalid', -> expect(store.validate 'firstName', '').toBeFalsy() expect(store.validate 'firstName', 'f').toBeFalsy() expect(store.validate 'firstName', 'f4t1h4c3t').toBeFalsy() expect(store.validate 'firstName', 'thisisverylongfirstnameitshouldnotvalid').toBeFalsy() expect(store.validate 'firstName', 23).toBeFalsy() expect(store.validate 'lastName', '').toBeFalsy() expect(store.validate 'lastName', 'a').toBeFalsy() expect(store.validate 'lastName', 'thisisverylonglastnameitshouldnotvalid').toBeFalsy() expect(store.validate 'lastName', 42).toBeFalsy() expect(store.validate 'age', '').toBeFalsy() expect(store.validate 'age', {}).toBeFalsy() expect(store.validate 'age', 'fatih').toBeFalsy() expect(store.validate 'email', '12').toBeFalsy() expect(store.validate 'email', 'fatih').toBeFalsy() expect(store.validate 'email', 'fatih@fatihacet').toBeFalsy() expect(store.validate 'email', '').toBeFalsy() expect(store.validate 'userId', '12').toBeFalsy() expect(store.validate 'userId', 'fatih').toBeFalsy() expect(store.validate 'userId', 123123123123).toBeFalsy() expect(store.validate 'userId', '').toBeFalsy() expect(store.validate 'uniqueKey', 'notUnique').toBeFalsy() expect(store.validate 'uniqueKey', 'notValid').toBeFalsy() it 'should assume the value is valid if there is not validation rule for it', -> expect(store.validate 'notExistKey', 'itdoesnotmatter').toBeTruthy() it 'should validate all', -> expect(store.validateAll()).toBeTruthy() it 'should throw error when no validator found', -> error = new Error 'Validation type foo does not exist.' options = validations: name: foo: yes validateOnInitialize: no data = name: 'Acetz' store = new spark.core.Store options, data expect( -> store.validate('name', 'fatih')).toThrow error it 'should validate data types', -> passed = 0 failed = 0 expect(store2.validateAll()).toBeTruthy() store2.on 'PropertySet', -> ++passed store2.on 'PropertyRejected', -> ++failed store2.set 'userId', 5423091 expect(failed).toBe 1 store2.set 'username', 'fatih' expect(passed).toBe 1 store2.set 'isOnline', 'yes' expect(failed).toBe 2 store2.set 'isOnline', no expect(passed).toBe 2 message = store2.get('fetch')() expect(message).toBe 'fetched user data...' store2.set 'fetch', 'it must be a function to pass' expect(failed).toBe 3 store2.set 'fetch', -> expect(passed).toBe 3 store2.set 'meta', -> expect(failed).toBe 4 store2.set 'meta', { a: 1, b: 2 } expect(passed).toBe 4 store2.set 'pageIds', { a: 1 } expect(failed).toBe 5 store2.set 'pageIds', [ 1, 2, 3 ] expect(passed).toBe 5 store2.set 'likeCount', 'ok' expect(failed).toBe 6 store2.set 'likeCount', store.get('likeCount') + 1 expect(passed).toBe 6 it 'should return all the data as an object', -> snapshot = store2.toObject() expect(snapshot.userId).toBe '123456' expect(snapshot.username).toBe 'fatihacet' expect(snapshot.pageIds.length).toBe 3 expect(snapshot.meta.registedAt).toBe 1420323019571 expect(snapshot.isOnline).toBe yes expect(snapshot.likeCount).toBe 22
100589
goog = goog or goog = require: -> goog.require 'spark.core.Store' describe 'spark.core.Store', -> store = null store2 = null beforeEach -> # Store created for validations. options = validations : firstName : required: yes, maxLength: 32, minLength: 2, alphabetic: yes lastName : required: yes, maxLength: 32, minLength: 2, alphabetic: yes age : numeric : yes email : email : yes userId : length : 8 uniqueKey : equal : 'unique', notEqual: 'notUnique' data = firstName : '<NAME>' lastName : '<NAME>' age : 27 isMarried : yes email : '<EMAIL>' userId : '123ab678' uniqueKey : 'unique' store = new spark.core.Store options, data # Another store created to validate data type validations. storeOptions = validations : userId : dataType: 'string' username : dataType: 'string' pageIds : dataType: 'array' meta : dataType: 'object' isOnline : dataType: 'boolean' likeCount : dataType: 'number' fetch : dataType: 'function' storeData = userId : '123456' username : 'fatihacet' pageIds : [ 34, 42, 70 ] meta : { registedAt: 1420323019571 } isOnline : yes likeCount : 22 fetch : -> return 'fetched user data...' store2 = new spark.core.Store storeOptions, storeData describe 'constructor', -> it 'should extends spark.core.Object', -> expect(store instanceof spark.core.Object).toBeTruthy() it 'should have default options', -> s = new spark.core.Store null, null expect(s.getOptions()).toBeDefined() expect(s.map_).toBeDefined() if goog.debug it 'should create a goog.structs.Map with given data', -> if goog.structs?.Map expect(store.map_ instanceof goog.structs.Map).toBeTruthy() it 'should throw error when initial validation failed', -> error = new Error "Failed to validate store data, name: null" expect( -> new spark.core.Store { validations: name: required: yes }, name: null ).toThrow error describe 'get', -> it 'should return the value of a given key', -> expect(store.get('firstName')).toBe '<NAME>' expect(store.get('lastName')).toBe '<NAME>' expect(store.get('isMarried')).toBeTruthy() expect(store.get('age')).toBe 27 it 'should return undefined for a non exists key', -> expect(store.get('realName')).not.toBeDefined() expect(store.get('realName')).toBeUndefined() describe 'set', -> it 'should set a key with value', -> store.set 'hasCar', no expect(store.get('hasCar')).toBeDefined() expect(store.get('hasCar')).toBeFalsy() it 'should not set a key without a value', -> store.set 'isDoctor' expect(store.get('isDoctor')).not.toBeDefined() it 'should validate the value', -> passed = 0 failed = 0 store.on 'PropertySet', -> ++passed store.on 'PropertyRejected', -> ++failed store.set 'email', 'acet' expect(failed).toBe 1 store.set 'firstName', '<NAME>' expect(passed).toBe 1 store.set 'age', 'acet' expect(failed).toBe 2 store.set 'userId', '10ak10ak' expect(passed).toBe 2 store.set 'isMarried', yes expect(passed).toBe 3 it 'should remove a key from store', -> keysLength = store.getKeys().length expect(store.has('age')).toBeTruthy() store.unset('age') expect(store.has('age')).toBeFalsy() expect(store.getKeys().length + 1 is keysLength).toBeTruthy() it 'should remove all keys from store', -> expect(store.getKeys().length > 3).toBeTruthy() expect(store.get('firstName')).toBe '<NAME>' store.clear() expect(store.getKeys().length is 0).toBeTruthy() expect(store.get('firstName')).not.toBeDefined() it 'should return true if store has the given key', -> expect(store.has('firstName')).toBeTruthy() expect(store.has('lastName')).toBeTruthy() expect(store.has('hasCar')).toBeFalsy() it 'should return all keys', -> keys = store.getKeys() expect(keys.length > 3).toBeTruthy() expect(keys.indexOf('firstName') > -1).toBeTruthy() expect(keys.indexOf('isDoctor') is -1).toBeTruthy() it 'should return all values', -> values = store.getValues() expect(values.length > 3).toBeTruthy() expect(values.indexOf('Fatih') > -1).toBeTruthy() expect(values.indexOf('32') is -1).toBeTruthy() describe 'validate', -> it 'should return true when the given data is valid', -> expect(store.validate 'firstName', '<NAME>').toBeTruthy() expect(store.validate 'lastName', '<NAME>').toBeTruthy() expect(store.validate 'email', '<EMAIL>').toBeTruthy() expect(store.validate 'age', 29).toBeTruthy() expect(store.validate 'age', '12').toBeTruthy() expect(store.validate 'userId', '911ef212').toBeTruthy() expect(store.validate 'uniqueKey', 'unique').toBeTruthy() it 'should return false when the given data is invalid', -> expect(store.validate 'firstName', '').toBeFalsy() expect(store.validate 'firstName', 'f').toBeFalsy() expect(store.validate 'firstName', 'f4t1h4c3t').toBeFalsy() expect(store.validate 'firstName', 'thisisverylongfirstnameitshouldnotvalid').toBeFalsy() expect(store.validate 'firstName', 23).toBeFalsy() expect(store.validate 'lastName', '').toBeFalsy() expect(store.validate 'lastName', 'a').toBeFalsy() expect(store.validate 'lastName', 'thisisverylonglastnameitshouldnotvalid').toBeFalsy() expect(store.validate 'lastName', 42).toBeFalsy() expect(store.validate 'age', '').toBeFalsy() expect(store.validate 'age', {}).toBeFalsy() expect(store.validate 'age', 'fatih').toBeFalsy() expect(store.validate 'email', '12').toBeFalsy() expect(store.validate 'email', 'fatih').toBeFalsy() expect(store.validate 'email', '<EMAIL>').toBeFalsy() expect(store.validate 'email', '').toBeFalsy() expect(store.validate 'userId', '12').toBeFalsy() expect(store.validate 'userId', 'fatih').toBeFalsy() expect(store.validate 'userId', 123123123123).toBeFalsy() expect(store.validate 'userId', '').toBeFalsy() expect(store.validate 'uniqueKey', 'notUnique').toBeFalsy() expect(store.validate 'uniqueKey', 'notValid').toBeFalsy() it 'should assume the value is valid if there is not validation rule for it', -> expect(store.validate 'notExistKey', 'itdoesnotmatter').toBeTruthy() it 'should validate all', -> expect(store.validateAll()).toBeTruthy() it 'should throw error when no validator found', -> error = new Error 'Validation type foo does not exist.' options = validations: name: foo: yes validateOnInitialize: no data = name: '<NAME>' store = new spark.core.Store options, data expect( -> store.validate('name', 'fatih')).toThrow error it 'should validate data types', -> passed = 0 failed = 0 expect(store2.validateAll()).toBeTruthy() store2.on 'PropertySet', -> ++passed store2.on 'PropertyRejected', -> ++failed store2.set 'userId', 5423091 expect(failed).toBe 1 store2.set 'username', 'fatih' expect(passed).toBe 1 store2.set 'isOnline', 'yes' expect(failed).toBe 2 store2.set 'isOnline', no expect(passed).toBe 2 message = store2.get('fetch')() expect(message).toBe 'fetched user data...' store2.set 'fetch', 'it must be a function to pass' expect(failed).toBe 3 store2.set 'fetch', -> expect(passed).toBe 3 store2.set 'meta', -> expect(failed).toBe 4 store2.set 'meta', { a: 1, b: 2 } expect(passed).toBe 4 store2.set 'pageIds', { a: 1 } expect(failed).toBe 5 store2.set 'pageIds', [ 1, 2, 3 ] expect(passed).toBe 5 store2.set 'likeCount', 'ok' expect(failed).toBe 6 store2.set 'likeCount', store.get('likeCount') + 1 expect(passed).toBe 6 it 'should return all the data as an object', -> snapshot = store2.toObject() expect(snapshot.userId).toBe '123456' expect(snapshot.username).toBe 'fatihacet' expect(snapshot.pageIds.length).toBe 3 expect(snapshot.meta.registedAt).toBe 1420323019571 expect(snapshot.isOnline).toBe yes expect(snapshot.likeCount).toBe 22
true
goog = goog or goog = require: -> goog.require 'spark.core.Store' describe 'spark.core.Store', -> store = null store2 = null beforeEach -> # Store created for validations. options = validations : firstName : required: yes, maxLength: 32, minLength: 2, alphabetic: yes lastName : required: yes, maxLength: 32, minLength: 2, alphabetic: yes age : numeric : yes email : email : yes userId : length : 8 uniqueKey : equal : 'unique', notEqual: 'notUnique' data = firstName : 'PI:NAME:<NAME>END_PI' lastName : 'PI:NAME:<NAME>END_PI' age : 27 isMarried : yes email : 'PI:EMAIL:<EMAIL>END_PI' userId : '123ab678' uniqueKey : 'unique' store = new spark.core.Store options, data # Another store created to validate data type validations. storeOptions = validations : userId : dataType: 'string' username : dataType: 'string' pageIds : dataType: 'array' meta : dataType: 'object' isOnline : dataType: 'boolean' likeCount : dataType: 'number' fetch : dataType: 'function' storeData = userId : '123456' username : 'fatihacet' pageIds : [ 34, 42, 70 ] meta : { registedAt: 1420323019571 } isOnline : yes likeCount : 22 fetch : -> return 'fetched user data...' store2 = new spark.core.Store storeOptions, storeData describe 'constructor', -> it 'should extends spark.core.Object', -> expect(store instanceof spark.core.Object).toBeTruthy() it 'should have default options', -> s = new spark.core.Store null, null expect(s.getOptions()).toBeDefined() expect(s.map_).toBeDefined() if goog.debug it 'should create a goog.structs.Map with given data', -> if goog.structs?.Map expect(store.map_ instanceof goog.structs.Map).toBeTruthy() it 'should throw error when initial validation failed', -> error = new Error "Failed to validate store data, name: null" expect( -> new spark.core.Store { validations: name: required: yes }, name: null ).toThrow error describe 'get', -> it 'should return the value of a given key', -> expect(store.get('firstName')).toBe 'PI:NAME:<NAME>END_PI' expect(store.get('lastName')).toBe 'PI:NAME:<NAME>END_PI' expect(store.get('isMarried')).toBeTruthy() expect(store.get('age')).toBe 27 it 'should return undefined for a non exists key', -> expect(store.get('realName')).not.toBeDefined() expect(store.get('realName')).toBeUndefined() describe 'set', -> it 'should set a key with value', -> store.set 'hasCar', no expect(store.get('hasCar')).toBeDefined() expect(store.get('hasCar')).toBeFalsy() it 'should not set a key without a value', -> store.set 'isDoctor' expect(store.get('isDoctor')).not.toBeDefined() it 'should validate the value', -> passed = 0 failed = 0 store.on 'PropertySet', -> ++passed store.on 'PropertyRejected', -> ++failed store.set 'email', 'acet' expect(failed).toBe 1 store.set 'firstName', 'PI:NAME:<NAME>END_PI' expect(passed).toBe 1 store.set 'age', 'acet' expect(failed).toBe 2 store.set 'userId', '10ak10ak' expect(passed).toBe 2 store.set 'isMarried', yes expect(passed).toBe 3 it 'should remove a key from store', -> keysLength = store.getKeys().length expect(store.has('age')).toBeTruthy() store.unset('age') expect(store.has('age')).toBeFalsy() expect(store.getKeys().length + 1 is keysLength).toBeTruthy() it 'should remove all keys from store', -> expect(store.getKeys().length > 3).toBeTruthy() expect(store.get('firstName')).toBe 'PI:NAME:<NAME>END_PI' store.clear() expect(store.getKeys().length is 0).toBeTruthy() expect(store.get('firstName')).not.toBeDefined() it 'should return true if store has the given key', -> expect(store.has('firstName')).toBeTruthy() expect(store.has('lastName')).toBeTruthy() expect(store.has('hasCar')).toBeFalsy() it 'should return all keys', -> keys = store.getKeys() expect(keys.length > 3).toBeTruthy() expect(keys.indexOf('firstName') > -1).toBeTruthy() expect(keys.indexOf('isDoctor') is -1).toBeTruthy() it 'should return all values', -> values = store.getValues() expect(values.length > 3).toBeTruthy() expect(values.indexOf('Fatih') > -1).toBeTruthy() expect(values.indexOf('32') is -1).toBeTruthy() describe 'validate', -> it 'should return true when the given data is valid', -> expect(store.validate 'firstName', 'PI:NAME:<NAME>END_PI').toBeTruthy() expect(store.validate 'lastName', 'PI:NAME:<NAME>END_PI').toBeTruthy() expect(store.validate 'email', 'PI:EMAIL:<EMAIL>END_PI').toBeTruthy() expect(store.validate 'age', 29).toBeTruthy() expect(store.validate 'age', '12').toBeTruthy() expect(store.validate 'userId', '911ef212').toBeTruthy() expect(store.validate 'uniqueKey', 'unique').toBeTruthy() it 'should return false when the given data is invalid', -> expect(store.validate 'firstName', '').toBeFalsy() expect(store.validate 'firstName', 'f').toBeFalsy() expect(store.validate 'firstName', 'f4t1h4c3t').toBeFalsy() expect(store.validate 'firstName', 'thisisverylongfirstnameitshouldnotvalid').toBeFalsy() expect(store.validate 'firstName', 23).toBeFalsy() expect(store.validate 'lastName', '').toBeFalsy() expect(store.validate 'lastName', 'a').toBeFalsy() expect(store.validate 'lastName', 'thisisverylonglastnameitshouldnotvalid').toBeFalsy() expect(store.validate 'lastName', 42).toBeFalsy() expect(store.validate 'age', '').toBeFalsy() expect(store.validate 'age', {}).toBeFalsy() expect(store.validate 'age', 'fatih').toBeFalsy() expect(store.validate 'email', '12').toBeFalsy() expect(store.validate 'email', 'fatih').toBeFalsy() expect(store.validate 'email', 'PI:EMAIL:<EMAIL>END_PI').toBeFalsy() expect(store.validate 'email', '').toBeFalsy() expect(store.validate 'userId', '12').toBeFalsy() expect(store.validate 'userId', 'fatih').toBeFalsy() expect(store.validate 'userId', 123123123123).toBeFalsy() expect(store.validate 'userId', '').toBeFalsy() expect(store.validate 'uniqueKey', 'notUnique').toBeFalsy() expect(store.validate 'uniqueKey', 'notValid').toBeFalsy() it 'should assume the value is valid if there is not validation rule for it', -> expect(store.validate 'notExistKey', 'itdoesnotmatter').toBeTruthy() it 'should validate all', -> expect(store.validateAll()).toBeTruthy() it 'should throw error when no validator found', -> error = new Error 'Validation type foo does not exist.' options = validations: name: foo: yes validateOnInitialize: no data = name: 'PI:NAME:<NAME>END_PI' store = new spark.core.Store options, data expect( -> store.validate('name', 'fatih')).toThrow error it 'should validate data types', -> passed = 0 failed = 0 expect(store2.validateAll()).toBeTruthy() store2.on 'PropertySet', -> ++passed store2.on 'PropertyRejected', -> ++failed store2.set 'userId', 5423091 expect(failed).toBe 1 store2.set 'username', 'fatih' expect(passed).toBe 1 store2.set 'isOnline', 'yes' expect(failed).toBe 2 store2.set 'isOnline', no expect(passed).toBe 2 message = store2.get('fetch')() expect(message).toBe 'fetched user data...' store2.set 'fetch', 'it must be a function to pass' expect(failed).toBe 3 store2.set 'fetch', -> expect(passed).toBe 3 store2.set 'meta', -> expect(failed).toBe 4 store2.set 'meta', { a: 1, b: 2 } expect(passed).toBe 4 store2.set 'pageIds', { a: 1 } expect(failed).toBe 5 store2.set 'pageIds', [ 1, 2, 3 ] expect(passed).toBe 5 store2.set 'likeCount', 'ok' expect(failed).toBe 6 store2.set 'likeCount', store.get('likeCount') + 1 expect(passed).toBe 6 it 'should return all the data as an object', -> snapshot = store2.toObject() expect(snapshot.userId).toBe '123456' expect(snapshot.username).toBe 'fatihacet' expect(snapshot.pageIds.length).toBe 3 expect(snapshot.meta.registedAt).toBe 1420323019571 expect(snapshot.isOnline).toBe yes expect(snapshot.likeCount).toBe 22
[ { "context": "nts to context', 1, ->\n context = Batman\n foo: Batman\n baz: Batman\n qux: \"filtered!\"\n ba", "end": 13309, "score": 0.6892099976539612, "start": 13303, "tag": "NAME", "value": "Batman" } ]
tests/batman/view/filter_parsing_test.coffee
nickjs/batman.js
3
helpers = window.viewHelpers QUnit.module "Batman.View filter value and parameter parsing", setup: -> Batman.Filters['test'] = @spy = createSpy().whichReturns("testValue") teardown: -> delete Batman.Filters.test asyncTest "should parse one segment keypaths as values", -> helpers.render '<div data-bind="foo | test"></div>', Batman(foo: "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths that begin with numbers", -> helpers.render '<div data-bind="404_title | test"></div>', Batman("404_title": "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths that begin with numbers and hyphens", -> helpers.render '<div data-bind="404-title | test"></div>', Batman("404-title": "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo"></div>', Batman(foo: "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should not pass arguments implicitly to the named filter", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz | test"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ['testValue'] QUnit.start() asyncTest "should parse many segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test qux.foo, 2, qux.bar, 3, qux.baz"></div>', Batman(qux: Batman(foo: "a", bar: "b", baz: "c")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse many segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo.bar"></div>', Batman(foo: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse many segment keypaths that begin with numbers", -> helpers.render '<div data-bind="404_title.bar | test"></div>', Batman("404_title": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse many segment keypaths that begin with numbers and hyphens", -> helpers.render '<div data-bind="404-title.bar | test"></div>', Batman("404-title": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse many segment keypaths as values", -> helpers.render '<div data-bind="foo.bar | test"></div>', Batman(foo: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse keypaths containing true as arguments", -> helpers.render '<div data-bind="1 | test true.bar"></div>', Batman("true": Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test truesay.bar"></div>', Batman(truesay: Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing false as arguments", -> helpers.render '<div data-bind="1 | test false.bar"></div>', Batman("false": Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test falsified.bar"></div>', Batman(falsified: Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should not parse true or false as a keypath", -> helpers.render '<div data-bind="1 | test true"></div>', Batman("true": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, true] helpers.render '<div data-bind="1 | test false"></div>', Batman(truesay: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, false] QUnit.start() asyncTest "should parse single quoted strings as arguments", -> helpers.render '<div data-bind="1 | test \'foo\'"></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "foo"] QUnit.start() asyncTest "should parse double quoted strings as arguments", -> helpers.render '<div data-bind=\'1 | test "foo"\'></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "foo"] QUnit.start() asyncTest "should parse strings with more than 3 commas as arguments", -> helpers.render '<div data-bind="1 | test \'a,b,c,d,e,f\'"></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a,b,c,d,e,f"] QUnit.start() asyncTest 'should pass undefined for absent arguments', 2, -> Batman.Filters['test'] = (a, b, binding) -> equal a, 'foo' strictEqual b, undefined node = helpers.render '<div data-bind="foo | test"></div>', foo: 'foo' , (node) -> QUnit.start() asyncTest 'should render chained filters', 1, -> node = helpers.render '<div data-bind="foo | upcase | downcase"></div>', foo: 'foo' , (node) -> equal node.html(), "foo" QUnit.start() asyncTest 'should render chained filters with arguments', 1, -> node = helpers.render '<div data-bind="foo | prepend \'(\' | append \')\' | append"></div>', foo: 'foo' , (node) -> equal node.html(), "(foo)" QUnit.start() asyncTest 'should update bindings with the filtered value if they change', 1, -> context = Batman foo: 'bar' helpers.render '<div data-bind="foo | upcase"></div>', context, (node, view) -> view.set('foo', 'baz') equal node.html(), 'BAZ' QUnit.start() asyncTest 'should allow filtering on attributes', 2, -> helpers.render '<div data-addclass-works="bar | first" data-bind-attr="foo | upcase "></div>', foo: "bar" bar: [true] , (node) -> ok node.hasClass('works') equal node.attr('attr'), 'BAR' QUnit.start() asyncTest 'should allow filtering on simple values', 1, -> helpers.render '<div data-bind="\'foo\' | upcase"></div>', {}, (node) -> equal node.html(), 'FOO' QUnit.start() asyncTest 'should allow filtering on objects and arrays', 2, -> helpers.render '<div data-bind="[1,2,3] | join \' \'"></div>', {}, (node) -> equal node.html(), '1 2 3' Batman.Filters.dummyObjectFilter = (value, key) -> value[key] helpers.render '<div data-bind="{\'foo\': \'bar\', \'baz\': 4} | dummyObjectFilter \'foo\'"></div>', {}, (node) -> equal node.html(), 'bar' delete Batman.Filters.dummyObjectFilter QUnit.start() asyncTest 'should allow keypaths as arguments to filters', 1, -> helpers.render '<div data-bind="foo | join bar"></div>', foo: [1,2,3] bar: ':' , (node) -> equal node.html(), '1:2:3' QUnit.start() asyncTest 'should allow many keypaths as arguments to filters', 1, -> Batman.Filters.joining = (sep, values..., binding) -> values.join(sep) helpers.render '<div data-bind="foo | joining bar, baz, qux"></div>', foo: ' ' bar: 'a' baz: 'b' qux: 'c' , (node) -> delete Batman.Filters.joining equal node.html(), 'a b c' QUnit.start() asyncTest 'should allow a mix of keypaths and simple values as arguments to filters', 2, -> Batman.Filters.joining = (sep, values..., binding) -> values.join(sep) context = Batman foo: ' ' bar: 'a' baz: 'b' qux: 'c' helpers.render '<div data-bind="foo | joining \'a\', baz, \'c\'"></div>', context, (node) -> equal node.html(), 'a b c' helpers.render '<div data-bind="foo | joining bar, \'b\', qux"></div>', context, (node) -> delete Batman.Filters.joining equal node.html(), 'a b c' QUnit.start() asyncTest 'should allow argument values which are simple objects', 2, -> context = foo: 'foo' bar: baz: "qux" Batman.Filters.test = (val, arg) -> equal val, 'foo' deepEqual arg, {baz: "qux"} helpers.render '<div data-bind="foo | test bar"></div>', context, -> delete Batman.Filters.test QUnit.start() asyncTest 'should allow argument values which are in the context of simple objects', 2, -> context = foo: 'foo' bar: baz: "qux" Batman.Filters.test = (val, arg) -> equal val, 'foo' equal arg, "qux" helpers.render '<div data-bind="foo | test bar.baz"></div>', context, -> delete Batman.Filters.test QUnit.start() asyncTest 'should update bindings when argument keypaths change', 2, -> context = Batman foo: [1,2,3] bar: '' helpers.render '<div data-bind="foo | join bar"></div>', context, (node, view) -> equal node.html(), '123' view.set('bar', "-") equal node.html(), '1-2-3' QUnit.start() asyncTest 'should update bindings when argument keypaths change in the middle of the keypath', 2, -> context = Batman foo: Batman bar: '.' array: [1,2,3] helpers.render '<div data-bind="array | join foo.bar"></div>', context, (node, view) -> equal node.html(), '1.2.3' view.set('foo', Batman(bar: '-')) equal node.html(), '1-2-3' QUnit.start() asyncTest 'should update bindings when argument keypaths change context', 2, -> context = foo: '.' array: [1,2,3], html: '' closer = closer: true html: '<div data-bind="array | join foo"></div>' outerView = new Batman.View(context) innerView = new Batman.View(closer) helpers.render '', context, (node, view) -> view.subviews.add(innerView) innerNode = innerView.get('node') equal(innerNode.children[0].innerHTML, '1.2.3') innerView.set('foo', '-') equal(innerNode.children[0].innerHTML, '1-2-3') QUnit.start() test 'it should update the data object if value bindings aren\'t filtered', 3, -> getSpy = createSpy().whichReturns("abcabcabc") setSpy = createSpy().whichReturns("defdefdef") class TestView extends Batman.View @accessor 'one', set: setSpy get: getSpy view = new TestView(html: '<textarea data-bind="one"></textarea>') node = view.get('node') view.initializeBindings() node.children[0].innerHTML = 'defdefdef' helpers.triggerChange(node.children[0]) equal node.children[0].innerHTML, 'defdefdef' ok getSpy.called ok setSpy.called asyncTest 'it shouldn\'t update the data object if value bindings are filtered', 3, -> # Try it with a filter context = new Batman.Object one: "abcabcabcabcabc" context.accessor "one", get: getSpy = createSpy().whichReturns("abcabcabc") set: setSpy = createSpy().whichReturns("defdefdef") context.accessor { get: defaultGetSpy = createSpy() set: defaultSetSpy = createSpy() } helpers.render '<textarea data-bind="one | truncate 5"></textarea>', context, (node) -> node.val('defdefdefdef') helpers.triggerChange(node.get(0)) equal node.val(), 'defdefdefdef' ok !setSpy.called ok !defaultSetSpy.called QUnit.start() asyncTest 'should allow filtered keypaths as arguments to context', 1, -> context = Batman foo: Batman baz: Batman qux: "filtered!" bar: 'baz' helpers.render '<div data-context-corge="foo | get bar"><div id="test" data-bind="corge.qux"></div></div>', context, (node) -> equal $("#test", node).html(), 'filtered!' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to context and filters to be performed in the context', 2, -> context = Batman foo: Batman baz: new Batman.Set([{foo: 'bar'}, {foo: 'baz'}]) qux: new Batman.Set([{foo: '1'}, {foo: '2'}]) bar: 'baz' helpers.render '<div data-context-corge="foo | get bar"><div id="test" data-bind="corge | map \'foo\' | join \', \'"></div></div>', context, (node, view) -> helpers.splitAndSortedEquals $("#test", node).html(), 'bar, baz', ', ' view.set('bar', 'qux') helpers.splitAndSortedEquals $("#test", node).html(), '1, 2', ', ' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to formfor', 1, -> class SingletonDooDad extends Batman.Object someKey: 'foobar' @classAccessor 'instance', get: (key) -> unless @_instance @_instance = new SingletonDooDad @_instance context = Batman klass: SingletonDooDad source = '<form data-formfor-obj="klass | get \'instance\'"><span id="test" data-bind="obj.someKey"></span></form>' helpers.render source, context, (node) -> equal $("#test", node).html(), 'foobar' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to event', 1, -> context = Batman foo: Batman baz: spy = createSpy() bar: 'baz' helpers.render '<button id="test" data-event-click="foo | get bar"></button>', context, (node) -> helpers.triggerClick(node[0]) ok spy.called QUnit.start() asyncTest 'should allow filtered keypaths as arguments to foreach', 3, -> context = Batman foo: Batman baz: [Batman(key: 1), Batman(key: 2), Batman(key: 3)] bar: 'baz' helpers.render '<div><span class="tracking" data-foreach-number="foo | get bar" data-bind="number.key"></span></div>', context, (node) -> tracker = {'1': false, '2': false, '3': false} $(".tracking", node).each (i, x) -> tracker[$(x).html()] = true ok tracker['1'] ok tracker['2'] ok tracker['3'] QUnit.start() asyncTest 'should bind to things under window only when the keypath specifies it', 2, -> Batman.container.foo = "bar" helpers.render '<div data-bind="foo"></div>', {}, (node) -> equal node.html(), "" helpers.render '<div data-bind="window.foo"></div>', {}, (node) -> equal node.html(), "bar" QUnit.start() asyncTest 'withArguments passes arguments to specified function and returns result', 2, -> context = foo: spy = createSpy() helpers.render '<a data-event-click="foo | withArguments 2">', context, (node) -> helpers.triggerClick(node[0]) ok spy.called equal spy.lastCallArguments[0], 2 QUnit.start() asyncTest 'Pass arguments to accessor with Batman.TerminalAccessible', -> context = Batman test: new class extends Batman.Object @accessor 'accessible', -> new Batman.TerminalAccessible (x) -> x + 1 helpers.render '<div data-bind="test.accessible[1]"></div>', context, (node) -> equal node[0].innerHTML, "2" QUnit.start() asyncTest 'withArguments with Batman.TerminalAccessible', -> context = Batman test: new class extends Batman.Object @accessor 'accessible', -> new Batman.TerminalAccessible (x) -> x + 1 helpers.render '<div data-bind="test.accessible | withArguments 1"></div>', context, (node) -> equal node[0].innerHTML, "2" QUnit.start() asyncTest 'toggle filter returns a function to toggle the value', 2, -> context = foo: Batman(bar: true) helpers.render '<a data-event-click="foo.bar | toggle">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), false helpers.triggerClick(node[0]) equal context.foo.get('bar'), true QUnit.start() asyncTest 'increment filter returns a function to increment the value', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | increment">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 1 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 2 QUnit.start() asyncTest 'increment filter accepts other change values', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | increment 3">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 3 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 6 QUnit.start() asyncTest 'decrement filter returns a function to increment the value', 2, -> context = foo: Batman(bar: 10) helpers.render '<a data-event-click="foo.bar | decrement">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 9 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 8 QUnit.start() asyncTest 'decrement filter accepts other change values', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | decrement 3">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), -3 helpers.triggerClick(node[0]) equal context.foo.get('bar'), -6 QUnit.start()
156003
helpers = window.viewHelpers QUnit.module "Batman.View filter value and parameter parsing", setup: -> Batman.Filters['test'] = @spy = createSpy().whichReturns("testValue") teardown: -> delete Batman.Filters.test asyncTest "should parse one segment keypaths as values", -> helpers.render '<div data-bind="foo | test"></div>', Batman(foo: "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths that begin with numbers", -> helpers.render '<div data-bind="404_title | test"></div>', Batman("404_title": "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths that begin with numbers and hyphens", -> helpers.render '<div data-bind="404-title | test"></div>', Batman("404-title": "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo"></div>', Batman(foo: "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should not pass arguments implicitly to the named filter", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz | test"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ['testValue'] QUnit.start() asyncTest "should parse many segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test qux.foo, 2, qux.bar, 3, qux.baz"></div>', Batman(qux: Batman(foo: "a", bar: "b", baz: "c")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse many segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo.bar"></div>', Batman(foo: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse many segment keypaths that begin with numbers", -> helpers.render '<div data-bind="404_title.bar | test"></div>', Batman("404_title": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse many segment keypaths that begin with numbers and hyphens", -> helpers.render '<div data-bind="404-title.bar | test"></div>', Batman("404-title": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse many segment keypaths as values", -> helpers.render '<div data-bind="foo.bar | test"></div>', Batman(foo: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse keypaths containing true as arguments", -> helpers.render '<div data-bind="1 | test true.bar"></div>', Batman("true": Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test truesay.bar"></div>', Batman(truesay: Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing false as arguments", -> helpers.render '<div data-bind="1 | test false.bar"></div>', Batman("false": Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test falsified.bar"></div>', Batman(falsified: Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should not parse true or false as a keypath", -> helpers.render '<div data-bind="1 | test true"></div>', Batman("true": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, true] helpers.render '<div data-bind="1 | test false"></div>', Batman(truesay: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, false] QUnit.start() asyncTest "should parse single quoted strings as arguments", -> helpers.render '<div data-bind="1 | test \'foo\'"></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "foo"] QUnit.start() asyncTest "should parse double quoted strings as arguments", -> helpers.render '<div data-bind=\'1 | test "foo"\'></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "foo"] QUnit.start() asyncTest "should parse strings with more than 3 commas as arguments", -> helpers.render '<div data-bind="1 | test \'a,b,c,d,e,f\'"></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a,b,c,d,e,f"] QUnit.start() asyncTest 'should pass undefined for absent arguments', 2, -> Batman.Filters['test'] = (a, b, binding) -> equal a, 'foo' strictEqual b, undefined node = helpers.render '<div data-bind="foo | test"></div>', foo: 'foo' , (node) -> QUnit.start() asyncTest 'should render chained filters', 1, -> node = helpers.render '<div data-bind="foo | upcase | downcase"></div>', foo: 'foo' , (node) -> equal node.html(), "foo" QUnit.start() asyncTest 'should render chained filters with arguments', 1, -> node = helpers.render '<div data-bind="foo | prepend \'(\' | append \')\' | append"></div>', foo: 'foo' , (node) -> equal node.html(), "(foo)" QUnit.start() asyncTest 'should update bindings with the filtered value if they change', 1, -> context = Batman foo: 'bar' helpers.render '<div data-bind="foo | upcase"></div>', context, (node, view) -> view.set('foo', 'baz') equal node.html(), 'BAZ' QUnit.start() asyncTest 'should allow filtering on attributes', 2, -> helpers.render '<div data-addclass-works="bar | first" data-bind-attr="foo | upcase "></div>', foo: "bar" bar: [true] , (node) -> ok node.hasClass('works') equal node.attr('attr'), 'BAR' QUnit.start() asyncTest 'should allow filtering on simple values', 1, -> helpers.render '<div data-bind="\'foo\' | upcase"></div>', {}, (node) -> equal node.html(), 'FOO' QUnit.start() asyncTest 'should allow filtering on objects and arrays', 2, -> helpers.render '<div data-bind="[1,2,3] | join \' \'"></div>', {}, (node) -> equal node.html(), '1 2 3' Batman.Filters.dummyObjectFilter = (value, key) -> value[key] helpers.render '<div data-bind="{\'foo\': \'bar\', \'baz\': 4} | dummyObjectFilter \'foo\'"></div>', {}, (node) -> equal node.html(), 'bar' delete Batman.Filters.dummyObjectFilter QUnit.start() asyncTest 'should allow keypaths as arguments to filters', 1, -> helpers.render '<div data-bind="foo | join bar"></div>', foo: [1,2,3] bar: ':' , (node) -> equal node.html(), '1:2:3' QUnit.start() asyncTest 'should allow many keypaths as arguments to filters', 1, -> Batman.Filters.joining = (sep, values..., binding) -> values.join(sep) helpers.render '<div data-bind="foo | joining bar, baz, qux"></div>', foo: ' ' bar: 'a' baz: 'b' qux: 'c' , (node) -> delete Batman.Filters.joining equal node.html(), 'a b c' QUnit.start() asyncTest 'should allow a mix of keypaths and simple values as arguments to filters', 2, -> Batman.Filters.joining = (sep, values..., binding) -> values.join(sep) context = Batman foo: ' ' bar: 'a' baz: 'b' qux: 'c' helpers.render '<div data-bind="foo | joining \'a\', baz, \'c\'"></div>', context, (node) -> equal node.html(), 'a b c' helpers.render '<div data-bind="foo | joining bar, \'b\', qux"></div>', context, (node) -> delete Batman.Filters.joining equal node.html(), 'a b c' QUnit.start() asyncTest 'should allow argument values which are simple objects', 2, -> context = foo: 'foo' bar: baz: "qux" Batman.Filters.test = (val, arg) -> equal val, 'foo' deepEqual arg, {baz: "qux"} helpers.render '<div data-bind="foo | test bar"></div>', context, -> delete Batman.Filters.test QUnit.start() asyncTest 'should allow argument values which are in the context of simple objects', 2, -> context = foo: 'foo' bar: baz: "qux" Batman.Filters.test = (val, arg) -> equal val, 'foo' equal arg, "qux" helpers.render '<div data-bind="foo | test bar.baz"></div>', context, -> delete Batman.Filters.test QUnit.start() asyncTest 'should update bindings when argument keypaths change', 2, -> context = Batman foo: [1,2,3] bar: '' helpers.render '<div data-bind="foo | join bar"></div>', context, (node, view) -> equal node.html(), '123' view.set('bar', "-") equal node.html(), '1-2-3' QUnit.start() asyncTest 'should update bindings when argument keypaths change in the middle of the keypath', 2, -> context = Batman foo: Batman bar: '.' array: [1,2,3] helpers.render '<div data-bind="array | join foo.bar"></div>', context, (node, view) -> equal node.html(), '1.2.3' view.set('foo', Batman(bar: '-')) equal node.html(), '1-2-3' QUnit.start() asyncTest 'should update bindings when argument keypaths change context', 2, -> context = foo: '.' array: [1,2,3], html: '' closer = closer: true html: '<div data-bind="array | join foo"></div>' outerView = new Batman.View(context) innerView = new Batman.View(closer) helpers.render '', context, (node, view) -> view.subviews.add(innerView) innerNode = innerView.get('node') equal(innerNode.children[0].innerHTML, '1.2.3') innerView.set('foo', '-') equal(innerNode.children[0].innerHTML, '1-2-3') QUnit.start() test 'it should update the data object if value bindings aren\'t filtered', 3, -> getSpy = createSpy().whichReturns("abcabcabc") setSpy = createSpy().whichReturns("defdefdef") class TestView extends Batman.View @accessor 'one', set: setSpy get: getSpy view = new TestView(html: '<textarea data-bind="one"></textarea>') node = view.get('node') view.initializeBindings() node.children[0].innerHTML = 'defdefdef' helpers.triggerChange(node.children[0]) equal node.children[0].innerHTML, 'defdefdef' ok getSpy.called ok setSpy.called asyncTest 'it shouldn\'t update the data object if value bindings are filtered', 3, -> # Try it with a filter context = new Batman.Object one: "abcabcabcabcabc" context.accessor "one", get: getSpy = createSpy().whichReturns("abcabcabc") set: setSpy = createSpy().whichReturns("defdefdef") context.accessor { get: defaultGetSpy = createSpy() set: defaultSetSpy = createSpy() } helpers.render '<textarea data-bind="one | truncate 5"></textarea>', context, (node) -> node.val('defdefdefdef') helpers.triggerChange(node.get(0)) equal node.val(), 'defdefdefdef' ok !setSpy.called ok !defaultSetSpy.called QUnit.start() asyncTest 'should allow filtered keypaths as arguments to context', 1, -> context = Batman foo: <NAME> baz: Batman qux: "filtered!" bar: 'baz' helpers.render '<div data-context-corge="foo | get bar"><div id="test" data-bind="corge.qux"></div></div>', context, (node) -> equal $("#test", node).html(), 'filtered!' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to context and filters to be performed in the context', 2, -> context = Batman foo: Batman baz: new Batman.Set([{foo: 'bar'}, {foo: 'baz'}]) qux: new Batman.Set([{foo: '1'}, {foo: '2'}]) bar: 'baz' helpers.render '<div data-context-corge="foo | get bar"><div id="test" data-bind="corge | map \'foo\' | join \', \'"></div></div>', context, (node, view) -> helpers.splitAndSortedEquals $("#test", node).html(), 'bar, baz', ', ' view.set('bar', 'qux') helpers.splitAndSortedEquals $("#test", node).html(), '1, 2', ', ' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to formfor', 1, -> class SingletonDooDad extends Batman.Object someKey: 'foobar' @classAccessor 'instance', get: (key) -> unless @_instance @_instance = new SingletonDooDad @_instance context = Batman klass: SingletonDooDad source = '<form data-formfor-obj="klass | get \'instance\'"><span id="test" data-bind="obj.someKey"></span></form>' helpers.render source, context, (node) -> equal $("#test", node).html(), 'foobar' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to event', 1, -> context = Batman foo: Batman baz: spy = createSpy() bar: 'baz' helpers.render '<button id="test" data-event-click="foo | get bar"></button>', context, (node) -> helpers.triggerClick(node[0]) ok spy.called QUnit.start() asyncTest 'should allow filtered keypaths as arguments to foreach', 3, -> context = Batman foo: Batman baz: [Batman(key: 1), Batman(key: 2), Batman(key: 3)] bar: 'baz' helpers.render '<div><span class="tracking" data-foreach-number="foo | get bar" data-bind="number.key"></span></div>', context, (node) -> tracker = {'1': false, '2': false, '3': false} $(".tracking", node).each (i, x) -> tracker[$(x).html()] = true ok tracker['1'] ok tracker['2'] ok tracker['3'] QUnit.start() asyncTest 'should bind to things under window only when the keypath specifies it', 2, -> Batman.container.foo = "bar" helpers.render '<div data-bind="foo"></div>', {}, (node) -> equal node.html(), "" helpers.render '<div data-bind="window.foo"></div>', {}, (node) -> equal node.html(), "bar" QUnit.start() asyncTest 'withArguments passes arguments to specified function and returns result', 2, -> context = foo: spy = createSpy() helpers.render '<a data-event-click="foo | withArguments 2">', context, (node) -> helpers.triggerClick(node[0]) ok spy.called equal spy.lastCallArguments[0], 2 QUnit.start() asyncTest 'Pass arguments to accessor with Batman.TerminalAccessible', -> context = Batman test: new class extends Batman.Object @accessor 'accessible', -> new Batman.TerminalAccessible (x) -> x + 1 helpers.render '<div data-bind="test.accessible[1]"></div>', context, (node) -> equal node[0].innerHTML, "2" QUnit.start() asyncTest 'withArguments with Batman.TerminalAccessible', -> context = Batman test: new class extends Batman.Object @accessor 'accessible', -> new Batman.TerminalAccessible (x) -> x + 1 helpers.render '<div data-bind="test.accessible | withArguments 1"></div>', context, (node) -> equal node[0].innerHTML, "2" QUnit.start() asyncTest 'toggle filter returns a function to toggle the value', 2, -> context = foo: Batman(bar: true) helpers.render '<a data-event-click="foo.bar | toggle">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), false helpers.triggerClick(node[0]) equal context.foo.get('bar'), true QUnit.start() asyncTest 'increment filter returns a function to increment the value', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | increment">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 1 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 2 QUnit.start() asyncTest 'increment filter accepts other change values', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | increment 3">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 3 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 6 QUnit.start() asyncTest 'decrement filter returns a function to increment the value', 2, -> context = foo: Batman(bar: 10) helpers.render '<a data-event-click="foo.bar | decrement">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 9 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 8 QUnit.start() asyncTest 'decrement filter accepts other change values', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | decrement 3">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), -3 helpers.triggerClick(node[0]) equal context.foo.get('bar'), -6 QUnit.start()
true
helpers = window.viewHelpers QUnit.module "Batman.View filter value and parameter parsing", setup: -> Batman.Filters['test'] = @spy = createSpy().whichReturns("testValue") teardown: -> delete Batman.Filters.test asyncTest "should parse one segment keypaths as values", -> helpers.render '<div data-bind="foo | test"></div>', Batman(foo: "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths that begin with numbers", -> helpers.render '<div data-bind="404_title | test"></div>', Batman("404_title": "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths that begin with numbers and hyphens", -> helpers.render '<div data-bind="404-title | test"></div>', Batman("404-title": "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo"></div>', Batman(foo: "bar"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "bar"] QUnit.start() asyncTest "should parse one segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should not pass arguments implicitly to the named filter", -> helpers.render '<div data-bind="1 | test foo, 2, bar, 3, baz | test"></div>', Batman(foo: "a", bar: "b", baz: "c"), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ['testValue'] QUnit.start() asyncTest "should parse many segment keypaths as arguments anywhere in the list of arguments", -> helpers.render '<div data-bind="1 | test qux.foo, 2, qux.bar, 3, qux.baz"></div>', Batman(qux: Batman(foo: "a", bar: "b", baz: "c")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a", 2, "b", 3, "c"] QUnit.start() asyncTest "should parse many segment keypaths as arguments", -> helpers.render '<div data-bind="1 | test foo.bar"></div>', Batman(foo: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse many segment keypaths that begin with numbers", -> helpers.render '<div data-bind="404_title.bar | test"></div>', Batman("404_title": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse many segment keypaths that begin with numbers and hyphens", -> helpers.render '<div data-bind="404-title.bar | test"></div>', Batman("404-title": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse many segment keypaths as values", -> helpers.render '<div data-bind="foo.bar | test"></div>', Batman(foo: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, ["baz"] QUnit.start() asyncTest "should parse keypaths containing true as arguments", -> helpers.render '<div data-bind="1 | test true.bar"></div>', Batman("true": Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test truesay.bar"></div>', Batman(truesay: Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should parse keypaths containing false as arguments", -> helpers.render '<div data-bind="1 | test false.bar"></div>', Batman("false": Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] helpers.render '<div data-bind="1 | test falsified.bar"></div>', Batman(falsified: Batman(bar: "baz")), (node) => ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "baz"] QUnit.start() asyncTest "should not parse true or false as a keypath", -> helpers.render '<div data-bind="1 | test true"></div>', Batman("true": Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, true] helpers.render '<div data-bind="1 | test false"></div>', Batman(truesay: Batman(bar: "baz")), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, false] QUnit.start() asyncTest "should parse single quoted strings as arguments", -> helpers.render '<div data-bind="1 | test \'foo\'"></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "foo"] QUnit.start() asyncTest "should parse double quoted strings as arguments", -> helpers.render '<div data-bind=\'1 | test "foo"\'></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "foo"] QUnit.start() asyncTest "should parse strings with more than 3 commas as arguments", -> helpers.render '<div data-bind="1 | test \'a,b,c,d,e,f\'"></div>', Batman(), (node) => equal node.html(), "testValue" ok @spy.lastCallArguments.pop() instanceof Batman.DOM.AbstractBinding deepEqual @spy.lastCallArguments, [1, "a,b,c,d,e,f"] QUnit.start() asyncTest 'should pass undefined for absent arguments', 2, -> Batman.Filters['test'] = (a, b, binding) -> equal a, 'foo' strictEqual b, undefined node = helpers.render '<div data-bind="foo | test"></div>', foo: 'foo' , (node) -> QUnit.start() asyncTest 'should render chained filters', 1, -> node = helpers.render '<div data-bind="foo | upcase | downcase"></div>', foo: 'foo' , (node) -> equal node.html(), "foo" QUnit.start() asyncTest 'should render chained filters with arguments', 1, -> node = helpers.render '<div data-bind="foo | prepend \'(\' | append \')\' | append"></div>', foo: 'foo' , (node) -> equal node.html(), "(foo)" QUnit.start() asyncTest 'should update bindings with the filtered value if they change', 1, -> context = Batman foo: 'bar' helpers.render '<div data-bind="foo | upcase"></div>', context, (node, view) -> view.set('foo', 'baz') equal node.html(), 'BAZ' QUnit.start() asyncTest 'should allow filtering on attributes', 2, -> helpers.render '<div data-addclass-works="bar | first" data-bind-attr="foo | upcase "></div>', foo: "bar" bar: [true] , (node) -> ok node.hasClass('works') equal node.attr('attr'), 'BAR' QUnit.start() asyncTest 'should allow filtering on simple values', 1, -> helpers.render '<div data-bind="\'foo\' | upcase"></div>', {}, (node) -> equal node.html(), 'FOO' QUnit.start() asyncTest 'should allow filtering on objects and arrays', 2, -> helpers.render '<div data-bind="[1,2,3] | join \' \'"></div>', {}, (node) -> equal node.html(), '1 2 3' Batman.Filters.dummyObjectFilter = (value, key) -> value[key] helpers.render '<div data-bind="{\'foo\': \'bar\', \'baz\': 4} | dummyObjectFilter \'foo\'"></div>', {}, (node) -> equal node.html(), 'bar' delete Batman.Filters.dummyObjectFilter QUnit.start() asyncTest 'should allow keypaths as arguments to filters', 1, -> helpers.render '<div data-bind="foo | join bar"></div>', foo: [1,2,3] bar: ':' , (node) -> equal node.html(), '1:2:3' QUnit.start() asyncTest 'should allow many keypaths as arguments to filters', 1, -> Batman.Filters.joining = (sep, values..., binding) -> values.join(sep) helpers.render '<div data-bind="foo | joining bar, baz, qux"></div>', foo: ' ' bar: 'a' baz: 'b' qux: 'c' , (node) -> delete Batman.Filters.joining equal node.html(), 'a b c' QUnit.start() asyncTest 'should allow a mix of keypaths and simple values as arguments to filters', 2, -> Batman.Filters.joining = (sep, values..., binding) -> values.join(sep) context = Batman foo: ' ' bar: 'a' baz: 'b' qux: 'c' helpers.render '<div data-bind="foo | joining \'a\', baz, \'c\'"></div>', context, (node) -> equal node.html(), 'a b c' helpers.render '<div data-bind="foo | joining bar, \'b\', qux"></div>', context, (node) -> delete Batman.Filters.joining equal node.html(), 'a b c' QUnit.start() asyncTest 'should allow argument values which are simple objects', 2, -> context = foo: 'foo' bar: baz: "qux" Batman.Filters.test = (val, arg) -> equal val, 'foo' deepEqual arg, {baz: "qux"} helpers.render '<div data-bind="foo | test bar"></div>', context, -> delete Batman.Filters.test QUnit.start() asyncTest 'should allow argument values which are in the context of simple objects', 2, -> context = foo: 'foo' bar: baz: "qux" Batman.Filters.test = (val, arg) -> equal val, 'foo' equal arg, "qux" helpers.render '<div data-bind="foo | test bar.baz"></div>', context, -> delete Batman.Filters.test QUnit.start() asyncTest 'should update bindings when argument keypaths change', 2, -> context = Batman foo: [1,2,3] bar: '' helpers.render '<div data-bind="foo | join bar"></div>', context, (node, view) -> equal node.html(), '123' view.set('bar', "-") equal node.html(), '1-2-3' QUnit.start() asyncTest 'should update bindings when argument keypaths change in the middle of the keypath', 2, -> context = Batman foo: Batman bar: '.' array: [1,2,3] helpers.render '<div data-bind="array | join foo.bar"></div>', context, (node, view) -> equal node.html(), '1.2.3' view.set('foo', Batman(bar: '-')) equal node.html(), '1-2-3' QUnit.start() asyncTest 'should update bindings when argument keypaths change context', 2, -> context = foo: '.' array: [1,2,3], html: '' closer = closer: true html: '<div data-bind="array | join foo"></div>' outerView = new Batman.View(context) innerView = new Batman.View(closer) helpers.render '', context, (node, view) -> view.subviews.add(innerView) innerNode = innerView.get('node') equal(innerNode.children[0].innerHTML, '1.2.3') innerView.set('foo', '-') equal(innerNode.children[0].innerHTML, '1-2-3') QUnit.start() test 'it should update the data object if value bindings aren\'t filtered', 3, -> getSpy = createSpy().whichReturns("abcabcabc") setSpy = createSpy().whichReturns("defdefdef") class TestView extends Batman.View @accessor 'one', set: setSpy get: getSpy view = new TestView(html: '<textarea data-bind="one"></textarea>') node = view.get('node') view.initializeBindings() node.children[0].innerHTML = 'defdefdef' helpers.triggerChange(node.children[0]) equal node.children[0].innerHTML, 'defdefdef' ok getSpy.called ok setSpy.called asyncTest 'it shouldn\'t update the data object if value bindings are filtered', 3, -> # Try it with a filter context = new Batman.Object one: "abcabcabcabcabc" context.accessor "one", get: getSpy = createSpy().whichReturns("abcabcabc") set: setSpy = createSpy().whichReturns("defdefdef") context.accessor { get: defaultGetSpy = createSpy() set: defaultSetSpy = createSpy() } helpers.render '<textarea data-bind="one | truncate 5"></textarea>', context, (node) -> node.val('defdefdefdef') helpers.triggerChange(node.get(0)) equal node.val(), 'defdefdefdef' ok !setSpy.called ok !defaultSetSpy.called QUnit.start() asyncTest 'should allow filtered keypaths as arguments to context', 1, -> context = Batman foo: PI:NAME:<NAME>END_PI baz: Batman qux: "filtered!" bar: 'baz' helpers.render '<div data-context-corge="foo | get bar"><div id="test" data-bind="corge.qux"></div></div>', context, (node) -> equal $("#test", node).html(), 'filtered!' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to context and filters to be performed in the context', 2, -> context = Batman foo: Batman baz: new Batman.Set([{foo: 'bar'}, {foo: 'baz'}]) qux: new Batman.Set([{foo: '1'}, {foo: '2'}]) bar: 'baz' helpers.render '<div data-context-corge="foo | get bar"><div id="test" data-bind="corge | map \'foo\' | join \', \'"></div></div>', context, (node, view) -> helpers.splitAndSortedEquals $("#test", node).html(), 'bar, baz', ', ' view.set('bar', 'qux') helpers.splitAndSortedEquals $("#test", node).html(), '1, 2', ', ' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to formfor', 1, -> class SingletonDooDad extends Batman.Object someKey: 'foobar' @classAccessor 'instance', get: (key) -> unless @_instance @_instance = new SingletonDooDad @_instance context = Batman klass: SingletonDooDad source = '<form data-formfor-obj="klass | get \'instance\'"><span id="test" data-bind="obj.someKey"></span></form>' helpers.render source, context, (node) -> equal $("#test", node).html(), 'foobar' QUnit.start() asyncTest 'should allow filtered keypaths as arguments to event', 1, -> context = Batman foo: Batman baz: spy = createSpy() bar: 'baz' helpers.render '<button id="test" data-event-click="foo | get bar"></button>', context, (node) -> helpers.triggerClick(node[0]) ok spy.called QUnit.start() asyncTest 'should allow filtered keypaths as arguments to foreach', 3, -> context = Batman foo: Batman baz: [Batman(key: 1), Batman(key: 2), Batman(key: 3)] bar: 'baz' helpers.render '<div><span class="tracking" data-foreach-number="foo | get bar" data-bind="number.key"></span></div>', context, (node) -> tracker = {'1': false, '2': false, '3': false} $(".tracking", node).each (i, x) -> tracker[$(x).html()] = true ok tracker['1'] ok tracker['2'] ok tracker['3'] QUnit.start() asyncTest 'should bind to things under window only when the keypath specifies it', 2, -> Batman.container.foo = "bar" helpers.render '<div data-bind="foo"></div>', {}, (node) -> equal node.html(), "" helpers.render '<div data-bind="window.foo"></div>', {}, (node) -> equal node.html(), "bar" QUnit.start() asyncTest 'withArguments passes arguments to specified function and returns result', 2, -> context = foo: spy = createSpy() helpers.render '<a data-event-click="foo | withArguments 2">', context, (node) -> helpers.triggerClick(node[0]) ok spy.called equal spy.lastCallArguments[0], 2 QUnit.start() asyncTest 'Pass arguments to accessor with Batman.TerminalAccessible', -> context = Batman test: new class extends Batman.Object @accessor 'accessible', -> new Batman.TerminalAccessible (x) -> x + 1 helpers.render '<div data-bind="test.accessible[1]"></div>', context, (node) -> equal node[0].innerHTML, "2" QUnit.start() asyncTest 'withArguments with Batman.TerminalAccessible', -> context = Batman test: new class extends Batman.Object @accessor 'accessible', -> new Batman.TerminalAccessible (x) -> x + 1 helpers.render '<div data-bind="test.accessible | withArguments 1"></div>', context, (node) -> equal node[0].innerHTML, "2" QUnit.start() asyncTest 'toggle filter returns a function to toggle the value', 2, -> context = foo: Batman(bar: true) helpers.render '<a data-event-click="foo.bar | toggle">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), false helpers.triggerClick(node[0]) equal context.foo.get('bar'), true QUnit.start() asyncTest 'increment filter returns a function to increment the value', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | increment">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 1 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 2 QUnit.start() asyncTest 'increment filter accepts other change values', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | increment 3">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 3 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 6 QUnit.start() asyncTest 'decrement filter returns a function to increment the value', 2, -> context = foo: Batman(bar: 10) helpers.render '<a data-event-click="foo.bar | decrement">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), 9 helpers.triggerClick(node[0]) equal context.foo.get('bar'), 8 QUnit.start() asyncTest 'decrement filter accepts other change values', 2, -> context = foo: Batman() helpers.render '<a data-event-click="foo.bar | decrement 3">', context, (node) -> helpers.triggerClick(node[0]) equal context.foo.get('bar'), -3 helpers.triggerClick(node[0]) equal context.foo.get('bar'), -6 QUnit.start()
[ { "context": "rror'\n process.env.FOURSQUARE_CLIENT_ID='foobar1'\n process.env.FOURSQUARE_CLIENT_SECRET='foobar", "end": 441, "score": 0.521101713180542, "start": 440, "tag": "USERNAME", "value": "1" }, { "context": "oobar1'\n process.env.FOURSQUARE_CLIENT_SECRET='foobar2'\n process.env.HUBOT_DEFAULT_LATITUDE=36.151417", "end": 492, "score": 0.9961543679237366, "start": 485, "tag": "KEY", "value": "foobar2" }, { "context": "6.1514179,-86.8262359',\n client_id: 'foobar1',\n client_secret: 'foobar2'\n v: '20", "end": 1305, "score": 0.8713105916976929, "start": 1304, "tag": "USERNAME", "value": "1" }, { "context": " client_id: 'foobar1',\n client_secret: 'foobar2'\n v: '20140806'\n )\n .replyWithFi", "end": 1339, "score": 0.9979245066642761, "start": 1332, "tag": "KEY", "value": "foobar2" }, { "context": "on')\n\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot lunch')\n setTimeout(() ->\n try\n", "end": 1499, "score": 0.6979427933692932, "start": 1494, "tag": "USERNAME", "value": "alice" }, { "context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot lunch']\n [\n 'hubot'", "end": 1609, "score": 0.8963363766670227, "start": 1604, "tag": "USERNAME", "value": "alice" }, { "context": "e) ->\n selfRoom = @room\n selfRoom.user.say('alice', '@hubot lunch')\n setTimeout(() ->\n try\n", "end": 2202, "score": 0.5915020704269409, "start": 2197, "tag": "USERNAME", "value": "alice" }, { "context": " expect(selfRoom.messages).to.eql [\n ['alice', '@hubot lunch']\n ['hubot', 'Ensure tha", "end": 2312, "score": 0.8104862570762634, "start": 2307, "tag": "USERNAME", "value": "alice" } ]
test/foursquare-lunch-test.coffee
stephenyeargin/hubot-foursquare-lunch
0
Helper = require('hubot-test-helper') chai = require 'chai' nock = require 'nock' expect = chai.expect helper = new Helper [ '../src/foursquare-lunch.coffee' ] # Alter time as test runs originalDateNow = Date.now mockDateNow = () -> return Date.parse('Tue Mar 30 2018 14:10:00 GMT-0500 (CDT)') describe 'hubot-foursquare-lunch', -> beforeEach -> process.env.HUBOT_LOG_LEVEL='error' process.env.FOURSQUARE_CLIENT_ID='foobar1' process.env.FOURSQUARE_CLIENT_SECRET='foobar2' process.env.HUBOT_DEFAULT_LATITUDE=36.1514179 process.env.HUBOT_DEFAULT_LONGITUDE=-86.8262359 Date.now = mockDateNow nock.disableNetConnect() @room = helper.createRoom() afterEach -> delete process.env.HUBOT_LOG_LEVEL delete process.env.FOURSQUARE_CLIENT_ID delete process.env.FOURSQUARE_CLIENT_SECRET delete process.env.HUBOT_DEFAULT_LATITUDE delete process.env.HUBOT_DEFAULT_LONGITUDE Date.now = originalDateNow nock.cleanAll() @room.destroy() # hubot lunch it 'responds with a lunch location', (done) -> nock('https://api.foursquare.com') .get('/v2/venues/explore') .query( price: '1,2,3', openNow: true, query: 'lunch', radius: 1600, ll: '36.1514179,-86.8262359', client_id: 'foobar1', client_secret: 'foobar2' v: '20140806' ) .replyWithFile(200, __dirname + '/fixtures/venues-explore-single.json') selfRoom = @room selfRoom.user.say('alice', '@hubot lunch') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lunch'] [ 'hubot', 'AVO Nashville (3001 Charlotte Ave Ste 200) - http://www.eatavo.com' ] ] done() catch err done err return , 1000) describe 'hubot-foursquare-lunch missing configuration', -> beforeEach -> Date.now = mockDateNow nock.disableNetConnect() @room = helper.createRoom() afterEach -> Date.now = originalDateNow nock.cleanAll() @room.destroy() # hubot lunch it 'responds with error messages', (done) -> selfRoom = @room selfRoom.user.say('alice', '@hubot lunch') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lunch'] ['hubot', 'Ensure that HUBOT_DEFAULT_LATITUDE is set.'] ['hubot', 'Ensure that HUBOT_DEFAULT_LONGITUDE is set.'] ['hubot', 'Ensure that FOURSQUARE_CLIENT_ID is set.'] ['hubot', 'Ensure that FOURSQUARE_CLIENT_SECRET is set.'] ] done() catch err done err return , 1000)
37249
Helper = require('hubot-test-helper') chai = require 'chai' nock = require 'nock' expect = chai.expect helper = new Helper [ '../src/foursquare-lunch.coffee' ] # Alter time as test runs originalDateNow = Date.now mockDateNow = () -> return Date.parse('Tue Mar 30 2018 14:10:00 GMT-0500 (CDT)') describe 'hubot-foursquare-lunch', -> beforeEach -> process.env.HUBOT_LOG_LEVEL='error' process.env.FOURSQUARE_CLIENT_ID='foobar1' process.env.FOURSQUARE_CLIENT_SECRET='<KEY>' process.env.HUBOT_DEFAULT_LATITUDE=36.1514179 process.env.HUBOT_DEFAULT_LONGITUDE=-86.8262359 Date.now = mockDateNow nock.disableNetConnect() @room = helper.createRoom() afterEach -> delete process.env.HUBOT_LOG_LEVEL delete process.env.FOURSQUARE_CLIENT_ID delete process.env.FOURSQUARE_CLIENT_SECRET delete process.env.HUBOT_DEFAULT_LATITUDE delete process.env.HUBOT_DEFAULT_LONGITUDE Date.now = originalDateNow nock.cleanAll() @room.destroy() # hubot lunch it 'responds with a lunch location', (done) -> nock('https://api.foursquare.com') .get('/v2/venues/explore') .query( price: '1,2,3', openNow: true, query: 'lunch', radius: 1600, ll: '36.1514179,-86.8262359', client_id: 'foobar1', client_secret: '<KEY>' v: '20140806' ) .replyWithFile(200, __dirname + '/fixtures/venues-explore-single.json') selfRoom = @room selfRoom.user.say('alice', '@hubot lunch') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lunch'] [ 'hubot', 'AVO Nashville (3001 Charlotte Ave Ste 200) - http://www.eatavo.com' ] ] done() catch err done err return , 1000) describe 'hubot-foursquare-lunch missing configuration', -> beforeEach -> Date.now = mockDateNow nock.disableNetConnect() @room = helper.createRoom() afterEach -> Date.now = originalDateNow nock.cleanAll() @room.destroy() # hubot lunch it 'responds with error messages', (done) -> selfRoom = @room selfRoom.user.say('alice', '@hubot lunch') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lunch'] ['hubot', 'Ensure that HUBOT_DEFAULT_LATITUDE is set.'] ['hubot', 'Ensure that HUBOT_DEFAULT_LONGITUDE is set.'] ['hubot', 'Ensure that FOURSQUARE_CLIENT_ID is set.'] ['hubot', 'Ensure that FOURSQUARE_CLIENT_SECRET is set.'] ] done() catch err done err return , 1000)
true
Helper = require('hubot-test-helper') chai = require 'chai' nock = require 'nock' expect = chai.expect helper = new Helper [ '../src/foursquare-lunch.coffee' ] # Alter time as test runs originalDateNow = Date.now mockDateNow = () -> return Date.parse('Tue Mar 30 2018 14:10:00 GMT-0500 (CDT)') describe 'hubot-foursquare-lunch', -> beforeEach -> process.env.HUBOT_LOG_LEVEL='error' process.env.FOURSQUARE_CLIENT_ID='foobar1' process.env.FOURSQUARE_CLIENT_SECRET='PI:KEY:<KEY>END_PI' process.env.HUBOT_DEFAULT_LATITUDE=36.1514179 process.env.HUBOT_DEFAULT_LONGITUDE=-86.8262359 Date.now = mockDateNow nock.disableNetConnect() @room = helper.createRoom() afterEach -> delete process.env.HUBOT_LOG_LEVEL delete process.env.FOURSQUARE_CLIENT_ID delete process.env.FOURSQUARE_CLIENT_SECRET delete process.env.HUBOT_DEFAULT_LATITUDE delete process.env.HUBOT_DEFAULT_LONGITUDE Date.now = originalDateNow nock.cleanAll() @room.destroy() # hubot lunch it 'responds with a lunch location', (done) -> nock('https://api.foursquare.com') .get('/v2/venues/explore') .query( price: '1,2,3', openNow: true, query: 'lunch', radius: 1600, ll: '36.1514179,-86.8262359', client_id: 'foobar1', client_secret: 'PI:KEY:<KEY>END_PI' v: '20140806' ) .replyWithFile(200, __dirname + '/fixtures/venues-explore-single.json') selfRoom = @room selfRoom.user.say('alice', '@hubot lunch') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lunch'] [ 'hubot', 'AVO Nashville (3001 Charlotte Ave Ste 200) - http://www.eatavo.com' ] ] done() catch err done err return , 1000) describe 'hubot-foursquare-lunch missing configuration', -> beforeEach -> Date.now = mockDateNow nock.disableNetConnect() @room = helper.createRoom() afterEach -> Date.now = originalDateNow nock.cleanAll() @room.destroy() # hubot lunch it 'responds with error messages', (done) -> selfRoom = @room selfRoom.user.say('alice', '@hubot lunch') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lunch'] ['hubot', 'Ensure that HUBOT_DEFAULT_LATITUDE is set.'] ['hubot', 'Ensure that HUBOT_DEFAULT_LONGITUDE is set.'] ['hubot', 'Ensure that FOURSQUARE_CLIENT_ID is set.'] ['hubot', 'Ensure that FOURSQUARE_CLIENT_SECRET is set.'] ] done() catch err done err return , 1000)
[ { "context": "her.Pedal\n # EVENT EMISSIONS\n # so\n name: \"foot-pedal\"\n constructor: ()->\n return\n event_binding: ", "end": 67, "score": 0.6692014336585999, "start": 62, "tag": "NAME", "value": "pedal" } ]
tool/app/assets/javascripts/tool/stitcher/haws.coffee
The-Hybrid-Atelier/embr
0
class stitcher.Pedal # EVENT EMISSIONS # so name: "foot-pedal" constructor: ()-> return event_binding: ()-> $(document).on "socket-connected", (event, stream)-> window.pedal.subscribe() $(document).on "pedal-state", (event, stream)-> if stream.data == "pedal-up" $("#step-manager .next").click() else if stream.data == "pedal-down" $("#step-manager .previous").click() subscribe: ()-> socket.subscribe(this.name, "pedal-state") on: ()-> window.socket.send_api("PEDAL_ON") off: ()-> window.socket.send_api("PEDAL_OFF") class window.HAWS constructor: (host, port)-> url = 'ws://'+ host+':' + port console.log "Connecting to", url $("#url").html(url) socket = new WebSocket(url) $(document).unload ()-> socket.close() socket.onopen = (event)-> $(document).trigger("socket-connected") message = name: window.NAME version: window.VERSION event: "greeting" socket.send JSON.stringify(message) socket.send_api("PEDAL_OFF") socket.send_api = (command, params={})-> message = api: command: command params: params message = JSON.stringify(message) socket.send(message) socket.onclose = (event)-> $(document).trigger("socket-disconnected") # ATTEMPT RECONNECTION EVERY 5000 ms # _.delay (()-> start_socket(host, port)), 5000 socket.onmessage = (event)-> console.log event stream = JSON.parse(event.data) if stream.event $(document).trigger(stream.event, stream) socket.onerror = (event)-> console.log("Client << ", event) alertify.error("<b>Error</b><p>Could not contact socket server at "+url+"</p>") socket.subscribe = (sender, service)-> socket.jsend subscribe: sender service: service socket.jsend = (message)-> headers = name: window.NAME version: window.VERSION message = _.extend headers, message if this.readyState == this.OPEN this.send JSON.stringify message console.log("Client >>", message) else alertify.error("Lost connection to server (State="+this.readyState+"). Refresh?") return socket
75944
class stitcher.Pedal # EVENT EMISSIONS # so name: "foot-<NAME>" constructor: ()-> return event_binding: ()-> $(document).on "socket-connected", (event, stream)-> window.pedal.subscribe() $(document).on "pedal-state", (event, stream)-> if stream.data == "pedal-up" $("#step-manager .next").click() else if stream.data == "pedal-down" $("#step-manager .previous").click() subscribe: ()-> socket.subscribe(this.name, "pedal-state") on: ()-> window.socket.send_api("PEDAL_ON") off: ()-> window.socket.send_api("PEDAL_OFF") class window.HAWS constructor: (host, port)-> url = 'ws://'+ host+':' + port console.log "Connecting to", url $("#url").html(url) socket = new WebSocket(url) $(document).unload ()-> socket.close() socket.onopen = (event)-> $(document).trigger("socket-connected") message = name: window.NAME version: window.VERSION event: "greeting" socket.send JSON.stringify(message) socket.send_api("PEDAL_OFF") socket.send_api = (command, params={})-> message = api: command: command params: params message = JSON.stringify(message) socket.send(message) socket.onclose = (event)-> $(document).trigger("socket-disconnected") # ATTEMPT RECONNECTION EVERY 5000 ms # _.delay (()-> start_socket(host, port)), 5000 socket.onmessage = (event)-> console.log event stream = JSON.parse(event.data) if stream.event $(document).trigger(stream.event, stream) socket.onerror = (event)-> console.log("Client << ", event) alertify.error("<b>Error</b><p>Could not contact socket server at "+url+"</p>") socket.subscribe = (sender, service)-> socket.jsend subscribe: sender service: service socket.jsend = (message)-> headers = name: window.NAME version: window.VERSION message = _.extend headers, message if this.readyState == this.OPEN this.send JSON.stringify message console.log("Client >>", message) else alertify.error("Lost connection to server (State="+this.readyState+"). Refresh?") return socket
true
class stitcher.Pedal # EVENT EMISSIONS # so name: "foot-PI:NAME:<NAME>END_PI" constructor: ()-> return event_binding: ()-> $(document).on "socket-connected", (event, stream)-> window.pedal.subscribe() $(document).on "pedal-state", (event, stream)-> if stream.data == "pedal-up" $("#step-manager .next").click() else if stream.data == "pedal-down" $("#step-manager .previous").click() subscribe: ()-> socket.subscribe(this.name, "pedal-state") on: ()-> window.socket.send_api("PEDAL_ON") off: ()-> window.socket.send_api("PEDAL_OFF") class window.HAWS constructor: (host, port)-> url = 'ws://'+ host+':' + port console.log "Connecting to", url $("#url").html(url) socket = new WebSocket(url) $(document).unload ()-> socket.close() socket.onopen = (event)-> $(document).trigger("socket-connected") message = name: window.NAME version: window.VERSION event: "greeting" socket.send JSON.stringify(message) socket.send_api("PEDAL_OFF") socket.send_api = (command, params={})-> message = api: command: command params: params message = JSON.stringify(message) socket.send(message) socket.onclose = (event)-> $(document).trigger("socket-disconnected") # ATTEMPT RECONNECTION EVERY 5000 ms # _.delay (()-> start_socket(host, port)), 5000 socket.onmessage = (event)-> console.log event stream = JSON.parse(event.data) if stream.event $(document).trigger(stream.event, stream) socket.onerror = (event)-> console.log("Client << ", event) alertify.error("<b>Error</b><p>Could not contact socket server at "+url+"</p>") socket.subscribe = (sender, service)-> socket.jsend subscribe: sender service: service socket.jsend = (message)-> headers = name: window.NAME version: window.VERSION message = _.extend headers, message if this.readyState == this.OPEN this.send JSON.stringify message console.log("Client >>", message) else alertify.error("Lost connection to server (State="+this.readyState+"). Refresh?") return socket
[ { "context": ", ->\n\n #\n cache = null\n key = helpers.randomString 10\n value = helpers.randomString 200\n\n ", "end": 476, "score": 0.9087032079696655, "start": 453, "tag": "KEY", "value": "helpers.randomString 10" } ]
test/test.coffee
Zuzle/zzcache
1
helpers = require './helpers' util = require 'util' should = require 'should' async = require 'async' _ = require 'underscore' CacheManager = require('../').CacheManager describe 'zzcache:', -> # prepare before (done) -> helpers.before(done) after (done) -> helpers.after(done) # test each provider in loop _.each helpers.providers(), (provider, cb) -> describe provider.name, -> # cache = null key = helpers.randomString 10 value = helpers.randomString 200 # it 'Should be able to connect', (done) -> cache = new CacheManager provider.name, provider.options, null, (error) -> should.not.exist error should.exist cache.provider if provider.name == 'redis' should.exist cache.provider.redis_connection cache.provider.redis_connection.connected.should.be.equal true done() # it 'Should be able to set', (done) -> cache.set key, value, (error) -> should.not.exist error done() # it 'Should be able to get', (done) -> cache.get key, (error, data) -> should.not.exist error should.exist data data.should.be.equal value done() # it 'Should be able to del', (done) -> cache.del key, (error) -> should.not.exist error cache.get key, (error, data) -> should.not.exist data done() # it 'Should be able to expire', (done) -> cache = new CacheManager provider.name, provider.options, 1, (error) -> should.not.exist error cache.set key, value, (error) -> should.not.exist error setTimeout (-> cache.get key, (error, data) -> should.exist error should.not.exist data done() ), 1000 # it 'Should be able to del_pattern', (done) -> prefix = 'del_pattern:' async.waterfall [ (cb) -> data = [] for i in [1..10] key = helpers.randomString 10 value = helpers.randomString 200 data.push key: prefix + key, value: value cb null, data (data, cb) -> for i in [1..10] key = helpers.randomString 10 value = helpers.randomString 200 data.push key: key, value: value cb null, data (data, cb) -> async.each data, ((d, cb_) -> cache.set d.key, d.value, cb_ null), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> if d.key.indexOf prefix == 0 cache.del_pattern prefix, (error) -> should.not.exist error cb_ null else cb_ null ), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> if d.key.indexOf prefix == 0 cache.get prefix, (error, dd) -> should.exist error should.not.exist dd cb_ null else cache.get prefix, (error, dd) -> should.not.exist error should.exist dd cb_ null ), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> cache.del d.key, -> cb_ null ), -> cb null ], (error) -> should.not.exist error done()
100015
helpers = require './helpers' util = require 'util' should = require 'should' async = require 'async' _ = require 'underscore' CacheManager = require('../').CacheManager describe 'zzcache:', -> # prepare before (done) -> helpers.before(done) after (done) -> helpers.after(done) # test each provider in loop _.each helpers.providers(), (provider, cb) -> describe provider.name, -> # cache = null key = <KEY> value = helpers.randomString 200 # it 'Should be able to connect', (done) -> cache = new CacheManager provider.name, provider.options, null, (error) -> should.not.exist error should.exist cache.provider if provider.name == 'redis' should.exist cache.provider.redis_connection cache.provider.redis_connection.connected.should.be.equal true done() # it 'Should be able to set', (done) -> cache.set key, value, (error) -> should.not.exist error done() # it 'Should be able to get', (done) -> cache.get key, (error, data) -> should.not.exist error should.exist data data.should.be.equal value done() # it 'Should be able to del', (done) -> cache.del key, (error) -> should.not.exist error cache.get key, (error, data) -> should.not.exist data done() # it 'Should be able to expire', (done) -> cache = new CacheManager provider.name, provider.options, 1, (error) -> should.not.exist error cache.set key, value, (error) -> should.not.exist error setTimeout (-> cache.get key, (error, data) -> should.exist error should.not.exist data done() ), 1000 # it 'Should be able to del_pattern', (done) -> prefix = 'del_pattern:' async.waterfall [ (cb) -> data = [] for i in [1..10] key = helpers.randomString 10 value = helpers.randomString 200 data.push key: prefix + key, value: value cb null, data (data, cb) -> for i in [1..10] key = helpers.randomString 10 value = helpers.randomString 200 data.push key: key, value: value cb null, data (data, cb) -> async.each data, ((d, cb_) -> cache.set d.key, d.value, cb_ null), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> if d.key.indexOf prefix == 0 cache.del_pattern prefix, (error) -> should.not.exist error cb_ null else cb_ null ), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> if d.key.indexOf prefix == 0 cache.get prefix, (error, dd) -> should.exist error should.not.exist dd cb_ null else cache.get prefix, (error, dd) -> should.not.exist error should.exist dd cb_ null ), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> cache.del d.key, -> cb_ null ), -> cb null ], (error) -> should.not.exist error done()
true
helpers = require './helpers' util = require 'util' should = require 'should' async = require 'async' _ = require 'underscore' CacheManager = require('../').CacheManager describe 'zzcache:', -> # prepare before (done) -> helpers.before(done) after (done) -> helpers.after(done) # test each provider in loop _.each helpers.providers(), (provider, cb) -> describe provider.name, -> # cache = null key = PI:KEY:<KEY>END_PI value = helpers.randomString 200 # it 'Should be able to connect', (done) -> cache = new CacheManager provider.name, provider.options, null, (error) -> should.not.exist error should.exist cache.provider if provider.name == 'redis' should.exist cache.provider.redis_connection cache.provider.redis_connection.connected.should.be.equal true done() # it 'Should be able to set', (done) -> cache.set key, value, (error) -> should.not.exist error done() # it 'Should be able to get', (done) -> cache.get key, (error, data) -> should.not.exist error should.exist data data.should.be.equal value done() # it 'Should be able to del', (done) -> cache.del key, (error) -> should.not.exist error cache.get key, (error, data) -> should.not.exist data done() # it 'Should be able to expire', (done) -> cache = new CacheManager provider.name, provider.options, 1, (error) -> should.not.exist error cache.set key, value, (error) -> should.not.exist error setTimeout (-> cache.get key, (error, data) -> should.exist error should.not.exist data done() ), 1000 # it 'Should be able to del_pattern', (done) -> prefix = 'del_pattern:' async.waterfall [ (cb) -> data = [] for i in [1..10] key = helpers.randomString 10 value = helpers.randomString 200 data.push key: prefix + key, value: value cb null, data (data, cb) -> for i in [1..10] key = helpers.randomString 10 value = helpers.randomString 200 data.push key: key, value: value cb null, data (data, cb) -> async.each data, ((d, cb_) -> cache.set d.key, d.value, cb_ null), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> if d.key.indexOf prefix == 0 cache.del_pattern prefix, (error) -> should.not.exist error cb_ null else cb_ null ), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> if d.key.indexOf prefix == 0 cache.get prefix, (error, dd) -> should.exist error should.not.exist dd cb_ null else cache.get prefix, (error, dd) -> should.not.exist error should.exist dd cb_ null ), -> cb null, data (data, cb) -> async.each data, ((d, cb_) -> cache.del d.key, -> cb_ null ), -> cb null ], (error) -> should.not.exist error done()
[ { "context": "ULISH_LEVEL\n#\n# Commands:\n# None\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nrequest = require 'request-b'\nc", "end": 208, "score": 0.9996975064277649, "start": 201, "tag": "USERNAME", "value": "bouzuya" }, { "context": "L\n#\n# Commands:\n# None\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nrequest = require 'request-b'\ncheerio = requir", "end": 223, "score": 0.9999239444732666, "start": 210, "tag": "EMAIL", "value": "m@bouzuya.net" } ]
src/scripts/auto-nomulish.coffee
bouzuya/hubot-auto-nomulish
0
# Description # A Hubot script that translates into the nomulish words automatically # # Configuration: # HUBOT_AUTO_NOMULISH_P # HUBOT_AUTO_NOMULISH_LEVEL # # Commands: # None # # Author: # bouzuya <m@bouzuya.net> # request = require 'request-b' cheerio = require 'cheerio' config = p: parseFloat(process.env.HUBOT_AUTO_NOMULISH_P ? '0.1') level: process.env.HUBOT_AUTO_NOMULISH_LEVEL ? '4' module.exports = (robot) -> robot.hear /(.+)/i, (res) -> return unless Math.random() < config.p words = res.match[1] request( method: 'post' url: 'http://racing-lagoon.info/nomu/translate.php' headers: Referer: 'http://racing-lagoon.info/nomu/translate.php' form: before: words level: config.level option: 'nochk' new_japanese: '' new_nomulish: '' trans_btn: '_' ) .then (r) -> $ = cheerio.load r.body nomulish = $('textarea[name=after]').val() res.send(nomulish) if nomulish? .catch (e) -> robot.logger.error e res.send 'hubot-auto-nomulish: error'
2777
# Description # A Hubot script that translates into the nomulish words automatically # # Configuration: # HUBOT_AUTO_NOMULISH_P # HUBOT_AUTO_NOMULISH_LEVEL # # Commands: # None # # Author: # bouzuya <<EMAIL>> # request = require 'request-b' cheerio = require 'cheerio' config = p: parseFloat(process.env.HUBOT_AUTO_NOMULISH_P ? '0.1') level: process.env.HUBOT_AUTO_NOMULISH_LEVEL ? '4' module.exports = (robot) -> robot.hear /(.+)/i, (res) -> return unless Math.random() < config.p words = res.match[1] request( method: 'post' url: 'http://racing-lagoon.info/nomu/translate.php' headers: Referer: 'http://racing-lagoon.info/nomu/translate.php' form: before: words level: config.level option: 'nochk' new_japanese: '' new_nomulish: '' trans_btn: '_' ) .then (r) -> $ = cheerio.load r.body nomulish = $('textarea[name=after]').val() res.send(nomulish) if nomulish? .catch (e) -> robot.logger.error e res.send 'hubot-auto-nomulish: error'
true
# Description # A Hubot script that translates into the nomulish words automatically # # Configuration: # HUBOT_AUTO_NOMULISH_P # HUBOT_AUTO_NOMULISH_LEVEL # # Commands: # None # # Author: # bouzuya <PI:EMAIL:<EMAIL>END_PI> # request = require 'request-b' cheerio = require 'cheerio' config = p: parseFloat(process.env.HUBOT_AUTO_NOMULISH_P ? '0.1') level: process.env.HUBOT_AUTO_NOMULISH_LEVEL ? '4' module.exports = (robot) -> robot.hear /(.+)/i, (res) -> return unless Math.random() < config.p words = res.match[1] request( method: 'post' url: 'http://racing-lagoon.info/nomu/translate.php' headers: Referer: 'http://racing-lagoon.info/nomu/translate.php' form: before: words level: config.level option: 'nochk' new_japanese: '' new_nomulish: '' trans_btn: '_' ) .then (r) -> $ = cheerio.load r.body nomulish = $('textarea[name=after]').val() res.send(nomulish) if nomulish? .catch (e) -> robot.logger.error e res.send 'hubot-auto-nomulish: error'
[ { "context": "HighScoreManager\n apiKey: 'guest'\n secret: 'guest'\n\n # Set apiKey and secret and attempt to regi", "end": 511, "score": 0.9671493172645569, "start": 506, "tag": "KEY", "value": "guest" } ]
src/shared/HighScoreManager.coffee
mess110/coffee-engine
1
# @nodoc class HighScoreManager instance = null # Manages high scores # # @example # # To register a new user/game # jNorthPole.createUser('api_key', 'secret') # # @example # hsm = HighScoreManager.get() # hsm.api_key = 'api_key' # hsm.secret = 'secret' # # hsm.addScore('kiki', 210) # hsm.getScores(20) # highest 20 scores # # hsm.responseHandler = (data) -> # # do something else class Singleton.HighScoreManager apiKey: 'guest' secret: 'guest' # Set apiKey and secret and attempt to register if tryRegister is true # # @param [String] apiKey # @param [String] secret # @param [Boolean] tryRegister default false auth: (apiKey, secret, tryRegister = false) -> if tryRegister jNorthPole.createUser(apiKey, secret, (data) -> console.log "api key registered: #{apiKey}" ) @_setTokens(apiKey, secret) @_ensureTokenPresence() @ # Set apiKey and secret # # @param [String] apiKey # @param [String] secret _setTokens: (apiKey, secret) -> @apiKey = apiKey @secret = secret # add a score # # @param [String] name # @param [Number] score addScore: (name, score) -> @_ensureTokenPresence() throw new Error('name required') unless name? throw new Error('score needs to be a number') unless isNumeric(score) json = api_key: @apiKey secret: @secret type: 'highscore' name: name score: score jNorthPole.createStorage json, @responseHandler, @errorHandler # get scores # # @param [Number] limit getScores: (limit = 10, order = 'desc') -> @_ensureTokenPresence() json = api_key: @apiKey secret: @secret type: 'highscore' __limit: limit __sort: { score: order } jNorthPole.getStorage json, @responseHandler, @errorHandler # override this responseHandler: (data) -> console.log data # override this errorHandler: (data, status) -> console.log data _ensureTokenPresence: -> throw new Error('apiKey missing') unless @apiKey? throw new Error('secret missing') unless @secret? @get: () -> instance ?= new Singleton.HighScoreManager() @auth: (apiKey, secret, tryRegister) -> @get().auth(apiKey, secret, tryRegister) @addScore: (name, score) -> @get().addScore(name, score) @getScores: (limit, order) -> @get().getScores(limit, order)
53676
# @nodoc class HighScoreManager instance = null # Manages high scores # # @example # # To register a new user/game # jNorthPole.createUser('api_key', 'secret') # # @example # hsm = HighScoreManager.get() # hsm.api_key = 'api_key' # hsm.secret = 'secret' # # hsm.addScore('kiki', 210) # hsm.getScores(20) # highest 20 scores # # hsm.responseHandler = (data) -> # # do something else class Singleton.HighScoreManager apiKey: 'guest' secret: '<KEY>' # Set apiKey and secret and attempt to register if tryRegister is true # # @param [String] apiKey # @param [String] secret # @param [Boolean] tryRegister default false auth: (apiKey, secret, tryRegister = false) -> if tryRegister jNorthPole.createUser(apiKey, secret, (data) -> console.log "api key registered: #{apiKey}" ) @_setTokens(apiKey, secret) @_ensureTokenPresence() @ # Set apiKey and secret # # @param [String] apiKey # @param [String] secret _setTokens: (apiKey, secret) -> @apiKey = apiKey @secret = secret # add a score # # @param [String] name # @param [Number] score addScore: (name, score) -> @_ensureTokenPresence() throw new Error('name required') unless name? throw new Error('score needs to be a number') unless isNumeric(score) json = api_key: @apiKey secret: @secret type: 'highscore' name: name score: score jNorthPole.createStorage json, @responseHandler, @errorHandler # get scores # # @param [Number] limit getScores: (limit = 10, order = 'desc') -> @_ensureTokenPresence() json = api_key: @apiKey secret: @secret type: 'highscore' __limit: limit __sort: { score: order } jNorthPole.getStorage json, @responseHandler, @errorHandler # override this responseHandler: (data) -> console.log data # override this errorHandler: (data, status) -> console.log data _ensureTokenPresence: -> throw new Error('apiKey missing') unless @apiKey? throw new Error('secret missing') unless @secret? @get: () -> instance ?= new Singleton.HighScoreManager() @auth: (apiKey, secret, tryRegister) -> @get().auth(apiKey, secret, tryRegister) @addScore: (name, score) -> @get().addScore(name, score) @getScores: (limit, order) -> @get().getScores(limit, order)
true
# @nodoc class HighScoreManager instance = null # Manages high scores # # @example # # To register a new user/game # jNorthPole.createUser('api_key', 'secret') # # @example # hsm = HighScoreManager.get() # hsm.api_key = 'api_key' # hsm.secret = 'secret' # # hsm.addScore('kiki', 210) # hsm.getScores(20) # highest 20 scores # # hsm.responseHandler = (data) -> # # do something else class Singleton.HighScoreManager apiKey: 'guest' secret: 'PI:KEY:<KEY>END_PI' # Set apiKey and secret and attempt to register if tryRegister is true # # @param [String] apiKey # @param [String] secret # @param [Boolean] tryRegister default false auth: (apiKey, secret, tryRegister = false) -> if tryRegister jNorthPole.createUser(apiKey, secret, (data) -> console.log "api key registered: #{apiKey}" ) @_setTokens(apiKey, secret) @_ensureTokenPresence() @ # Set apiKey and secret # # @param [String] apiKey # @param [String] secret _setTokens: (apiKey, secret) -> @apiKey = apiKey @secret = secret # add a score # # @param [String] name # @param [Number] score addScore: (name, score) -> @_ensureTokenPresence() throw new Error('name required') unless name? throw new Error('score needs to be a number') unless isNumeric(score) json = api_key: @apiKey secret: @secret type: 'highscore' name: name score: score jNorthPole.createStorage json, @responseHandler, @errorHandler # get scores # # @param [Number] limit getScores: (limit = 10, order = 'desc') -> @_ensureTokenPresence() json = api_key: @apiKey secret: @secret type: 'highscore' __limit: limit __sort: { score: order } jNorthPole.getStorage json, @responseHandler, @errorHandler # override this responseHandler: (data) -> console.log data # override this errorHandler: (data, status) -> console.log data _ensureTokenPresence: -> throw new Error('apiKey missing') unless @apiKey? throw new Error('secret missing') unless @secret? @get: () -> instance ?= new Singleton.HighScoreManager() @auth: (apiKey, secret, tryRegister) -> @get().auth(apiKey, secret, tryRegister) @addScore: (name, score) -> @get().addScore(name, score) @getScores: (limit, order) -> @get().getScores(limit, order)
[ { "context": "ssword || ''\n password = new Buffer(password, 'ucs2')\n\n for b in [0..password.length - 1]\n by", "end": 5474, "score": 0.9964867234230042, "start": 5470, "tag": "PASSWORD", "value": "ucs2" }, { "context": " ' +\n sprintf(\"Hostname:'%s', Username:'%s', Password:'%s', AppName:'%s', ServerName:'%s', L", "end": 6388, "score": 0.7804862260818481, "start": 6386, "tag": "USERNAME", "value": "%s" }, { "context": " sprintf(\"Hostname:'%s', Username:'%s', Password:'%s', AppName:'%s', ServerName:'%s', LibraryName:'%s'", "end": 6403, "score": 0.9987865090370178, "start": 6401, "tag": "PASSWORD", "value": "%s" }, { "context": "s', SSPI:'%s', AttachDbFile:'%s', ChangePassword:'%s'\",\n @loginData.language,\n @logi", "end": 6763, "score": 0.9973984956741333, "start": 6761, "tag": "PASSWORD", "value": "%s" } ]
lib/login7-payload.coffee
chrisinajar/tedious
1
WritableTrackingBuffer = require('./tracking-buffer/writable-tracking-buffer') require('./buffertools') os= require('os') sprintf = require('sprintf').sprintf libraryName = require('./library').name versions = require('./tds-versions').versions FLAGS_1 = ENDIAN_LITTLE: 0x00, ENDIAN_BIG: 0x01, CHARSET_ASCII: 0x00, CHARSET_EBCDIC: 0x02, FLOAT_IEEE_754: 0x00, FLOAT_VAX: 0x04, FLOAT_ND5000: 0x08, BCP_DUMPLOAD_ON: 0x00, BCP_DUMPLOAD_OFF: 0x10, USE_DB_ON: 0x00, USE_DB_OFF: 0x20, INIT_DB_WARN: 0x00, INIT_DB_FATAL: 0x40, SET_LANG_WARN_OFF: 0x00, SET_LANG_WARN_ON: 0x80, FLAGS_2 = INIT_LANG_WARN: 0x00, INIT_LANG_FATAL: 0x01, ODBC_OFF: 0x00, ODBC_ON: 0x02, F_TRAN_BOUNDARY: 0x04, # Removed in TDS 7.2 F_CACHE_CONNECT: 0x08, # Removed in TDS 7.2 USER_NORMAL: 0x00, USER_SERVER: 0x10, USER_REMUSER: 0x20, USER_SQLREPL: 0x40, INTEGRATED_SECURITY_OFF: 0x00, INTEGRATED_SECURITY_ON: 0x80 TYPE_FLAGS = SQL_DFLT: 0x00, SQL_TSQL: 0x01, OLEDB_OFF: 0x00, OLEDB_ON: 0x02, # Introduced in TDS 7.2 READ_ONLY_INTENT: 0x04 # Introduced in TDS 7.4 FLAGS_3 = CHANGE_PASSWORD_NO: 0x00, CHANGE_PASSWORD_YES: 0x01, # Introduced in TDS 7.2 BINARY_XML: 0x02, # Introduced in TDS 7.2 SPAWN_USER_INSTANCE: 0x04, # Introduced in TDS 7.2 UNKNOWN_COLLATION_HANDLING: 0x08 # Introduced in TDS 7.3 DEFAULT_TDS_VERSION = versions['7_2'] ### s2.2.6.3 ### class Login7Payload constructor: (@loginData) -> lengthLength = 4 fixed = @createFixedData() variable = @createVariableData(lengthLength + fixed.length) length = lengthLength + fixed.length + variable.length data = new WritableTrackingBuffer(300) data.writeUInt32LE(length) data.writeBuffer(fixed) data.writeBuffer(variable) @data = data.data createFixedData: -> @tdsVersion = DEFAULT_TDS_VERSION @packetSize = @loginData.packetSize @clientProgVer = 0 @clientPid = process.pid @connectionId = 0 @clientTimeZone = new Date().getTimezoneOffset() @clientLcid = 0x00000409 #Can't figure what form this should take. @flags1 = FLAGS_1.ENDIAN_LITTLE | FLAGS_1.CHARSET_ASCII | FLAGS_1.FLOAT_IEEE_754 | FLAGS_1.BCD_DUMPLOAD_OFF | FLAGS_1.USE_DB_OFF | FLAGS_1.INIT_DB_WARN | FLAGS_1.SET_LANG_WARN_ON @flags2 = FLAGS_2.INIT_LANG_WARN | FLAGS_2.ODBC_OFF | FLAGS_2.USER_NORMAL | FLAGS_2.INTEGRATED_SECURITY_OFF @flags3 = FLAGS_3.CHANGE_PASSWORD_NO | FLAGS_3.UNKNOWN_COLLATION_HANDLING @typeFlags = TYPE_FLAGS.SQL_DFLT | TYPE_FLAGS.OLEDB_OFF buffer = new WritableTrackingBuffer(100) buffer.writeUInt32LE(@tdsVersion) buffer.writeUInt32LE(@packetSize) buffer.writeUInt32LE(@clientProgVer) buffer.writeUInt32LE(@clientPid) buffer.writeUInt32LE(@connectionId) buffer.writeUInt8(@flags1) buffer.writeUInt8(@flags2) buffer.writeUInt8(@typeFlags) buffer.writeUInt8(@flags3) buffer.writeInt32LE(@clientTimeZone) buffer.writeUInt32LE(@clientLcid) buffer.data createVariableData: (offset) -> variableData = offsetsAndLengths: new WritableTrackingBuffer(200) data: new WritableTrackingBuffer(200, 'ucs2') offset: offset + ((9 * 4) + 6 + (3 * 4) + 4) @hostname = os.hostname() @loginData = @loginData || {} @loginData.appName = @loginData.appName || 'Tedious' @libraryName = libraryName # Client ID, should be MAC address or other randomly generated GUID like value. @clientId = new Buffer([1, 2, 3, 4, 5, 6]) @sspi = '' @sspiLong = 0 @attachDbFile = '' @changePassword = '' @addVariableDataString(variableData, @hostname) @addVariableDataString(variableData, @loginData.userName) @addVariableDataBuffer(variableData, @createPasswordBuffer()) @addVariableDataString(variableData, @loginData.appName) @addVariableDataString(variableData, @loginData.serverName) @addVariableDataString(variableData, '') # Reserved for future use. @addVariableDataString(variableData, @libraryName) @addVariableDataString(variableData, @loginData.language) @addVariableDataString(variableData, @loginData.database) variableData.offsetsAndLengths.writeBuffer(@clientId) @addVariableDataString(variableData, @sspi) @addVariableDataString(variableData, @attachDbFile) @addVariableDataString(variableData, @changePassword) # Introduced in TDS 7.2 variableData.offsetsAndLengths.writeUInt32LE(@sspiLong) # Introduced in TDS 7.2 variableData.offsetsAndLengths.data.concat(variableData.data.data) addVariableDataBuffer: (variableData, buffer) -> variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(buffer.length / 2) variableData.data.writeBuffer(buffer) variableData.offset += buffer.length addVariableDataString: (variableData, value) -> value ||= '' variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(value.length) variableData.data.writeString(value); variableData.offset += value.length * 2 createPasswordBuffer: () -> password = @loginData.password || '' password = new Buffer(password, 'ucs2') for b in [0..password.length - 1] byte = password[b] lowNibble = byte & 0x0f highNibble = (byte >> 4) byte = (lowNibble << 4) | highNibble byte = byte ^ 0xa5 password[b] = byte password toString: (indent) -> indent ||= '' indent + 'Login7 - ' + sprintf('TDS:0x%08X, PacketSize:0x%08X, ClientProgVer:0x%08X, ClientPID:0x%08X, ConnectionID:0x%08X', @tdsVersion, @packetSize, @clientProgVer, @clientPid, @connectionId ) + '\n' + indent + ' ' + sprintf('Flags1:0x%02X, Flags2:0x%02X, TypeFlags:0x%02X, Flags3:0x%02X, ClientTimezone:%d, ClientLCID:0x%08X', @flags1, @flags2, @typeFlags, @flags3, @clientTimeZone, @clientLcid ) + '\n' + indent + ' ' + sprintf("Hostname:'%s', Username:'%s', Password:'%s', AppName:'%s', ServerName:'%s', LibraryName:'%s'", @hostname, @loginData.userName, @loginData.password, @loginData.appName, @loginData.serverName, libraryName ) + '\n' + indent + ' ' + sprintf("Language:'%s', Database:'%s', SSPI:'%s', AttachDbFile:'%s', ChangePassword:'%s'", @loginData.language, @loginData.database, @sspi, @attachDbFile @changePassword ) module.exports = Login7Payload
190590
WritableTrackingBuffer = require('./tracking-buffer/writable-tracking-buffer') require('./buffertools') os= require('os') sprintf = require('sprintf').sprintf libraryName = require('./library').name versions = require('./tds-versions').versions FLAGS_1 = ENDIAN_LITTLE: 0x00, ENDIAN_BIG: 0x01, CHARSET_ASCII: 0x00, CHARSET_EBCDIC: 0x02, FLOAT_IEEE_754: 0x00, FLOAT_VAX: 0x04, FLOAT_ND5000: 0x08, BCP_DUMPLOAD_ON: 0x00, BCP_DUMPLOAD_OFF: 0x10, USE_DB_ON: 0x00, USE_DB_OFF: 0x20, INIT_DB_WARN: 0x00, INIT_DB_FATAL: 0x40, SET_LANG_WARN_OFF: 0x00, SET_LANG_WARN_ON: 0x80, FLAGS_2 = INIT_LANG_WARN: 0x00, INIT_LANG_FATAL: 0x01, ODBC_OFF: 0x00, ODBC_ON: 0x02, F_TRAN_BOUNDARY: 0x04, # Removed in TDS 7.2 F_CACHE_CONNECT: 0x08, # Removed in TDS 7.2 USER_NORMAL: 0x00, USER_SERVER: 0x10, USER_REMUSER: 0x20, USER_SQLREPL: 0x40, INTEGRATED_SECURITY_OFF: 0x00, INTEGRATED_SECURITY_ON: 0x80 TYPE_FLAGS = SQL_DFLT: 0x00, SQL_TSQL: 0x01, OLEDB_OFF: 0x00, OLEDB_ON: 0x02, # Introduced in TDS 7.2 READ_ONLY_INTENT: 0x04 # Introduced in TDS 7.4 FLAGS_3 = CHANGE_PASSWORD_NO: 0x00, CHANGE_PASSWORD_YES: 0x01, # Introduced in TDS 7.2 BINARY_XML: 0x02, # Introduced in TDS 7.2 SPAWN_USER_INSTANCE: 0x04, # Introduced in TDS 7.2 UNKNOWN_COLLATION_HANDLING: 0x08 # Introduced in TDS 7.3 DEFAULT_TDS_VERSION = versions['7_2'] ### s2.2.6.3 ### class Login7Payload constructor: (@loginData) -> lengthLength = 4 fixed = @createFixedData() variable = @createVariableData(lengthLength + fixed.length) length = lengthLength + fixed.length + variable.length data = new WritableTrackingBuffer(300) data.writeUInt32LE(length) data.writeBuffer(fixed) data.writeBuffer(variable) @data = data.data createFixedData: -> @tdsVersion = DEFAULT_TDS_VERSION @packetSize = @loginData.packetSize @clientProgVer = 0 @clientPid = process.pid @connectionId = 0 @clientTimeZone = new Date().getTimezoneOffset() @clientLcid = 0x00000409 #Can't figure what form this should take. @flags1 = FLAGS_1.ENDIAN_LITTLE | FLAGS_1.CHARSET_ASCII | FLAGS_1.FLOAT_IEEE_754 | FLAGS_1.BCD_DUMPLOAD_OFF | FLAGS_1.USE_DB_OFF | FLAGS_1.INIT_DB_WARN | FLAGS_1.SET_LANG_WARN_ON @flags2 = FLAGS_2.INIT_LANG_WARN | FLAGS_2.ODBC_OFF | FLAGS_2.USER_NORMAL | FLAGS_2.INTEGRATED_SECURITY_OFF @flags3 = FLAGS_3.CHANGE_PASSWORD_NO | FLAGS_3.UNKNOWN_COLLATION_HANDLING @typeFlags = TYPE_FLAGS.SQL_DFLT | TYPE_FLAGS.OLEDB_OFF buffer = new WritableTrackingBuffer(100) buffer.writeUInt32LE(@tdsVersion) buffer.writeUInt32LE(@packetSize) buffer.writeUInt32LE(@clientProgVer) buffer.writeUInt32LE(@clientPid) buffer.writeUInt32LE(@connectionId) buffer.writeUInt8(@flags1) buffer.writeUInt8(@flags2) buffer.writeUInt8(@typeFlags) buffer.writeUInt8(@flags3) buffer.writeInt32LE(@clientTimeZone) buffer.writeUInt32LE(@clientLcid) buffer.data createVariableData: (offset) -> variableData = offsetsAndLengths: new WritableTrackingBuffer(200) data: new WritableTrackingBuffer(200, 'ucs2') offset: offset + ((9 * 4) + 6 + (3 * 4) + 4) @hostname = os.hostname() @loginData = @loginData || {} @loginData.appName = @loginData.appName || 'Tedious' @libraryName = libraryName # Client ID, should be MAC address or other randomly generated GUID like value. @clientId = new Buffer([1, 2, 3, 4, 5, 6]) @sspi = '' @sspiLong = 0 @attachDbFile = '' @changePassword = '' @addVariableDataString(variableData, @hostname) @addVariableDataString(variableData, @loginData.userName) @addVariableDataBuffer(variableData, @createPasswordBuffer()) @addVariableDataString(variableData, @loginData.appName) @addVariableDataString(variableData, @loginData.serverName) @addVariableDataString(variableData, '') # Reserved for future use. @addVariableDataString(variableData, @libraryName) @addVariableDataString(variableData, @loginData.language) @addVariableDataString(variableData, @loginData.database) variableData.offsetsAndLengths.writeBuffer(@clientId) @addVariableDataString(variableData, @sspi) @addVariableDataString(variableData, @attachDbFile) @addVariableDataString(variableData, @changePassword) # Introduced in TDS 7.2 variableData.offsetsAndLengths.writeUInt32LE(@sspiLong) # Introduced in TDS 7.2 variableData.offsetsAndLengths.data.concat(variableData.data.data) addVariableDataBuffer: (variableData, buffer) -> variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(buffer.length / 2) variableData.data.writeBuffer(buffer) variableData.offset += buffer.length addVariableDataString: (variableData, value) -> value ||= '' variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(value.length) variableData.data.writeString(value); variableData.offset += value.length * 2 createPasswordBuffer: () -> password = @loginData.password || '' password = new Buffer(password, '<PASSWORD>') for b in [0..password.length - 1] byte = password[b] lowNibble = byte & 0x0f highNibble = (byte >> 4) byte = (lowNibble << 4) | highNibble byte = byte ^ 0xa5 password[b] = byte password toString: (indent) -> indent ||= '' indent + 'Login7 - ' + sprintf('TDS:0x%08X, PacketSize:0x%08X, ClientProgVer:0x%08X, ClientPID:0x%08X, ConnectionID:0x%08X', @tdsVersion, @packetSize, @clientProgVer, @clientPid, @connectionId ) + '\n' + indent + ' ' + sprintf('Flags1:0x%02X, Flags2:0x%02X, TypeFlags:0x%02X, Flags3:0x%02X, ClientTimezone:%d, ClientLCID:0x%08X', @flags1, @flags2, @typeFlags, @flags3, @clientTimeZone, @clientLcid ) + '\n' + indent + ' ' + sprintf("Hostname:'%s', Username:'%s', Password:'<PASSWORD>', AppName:'%s', ServerName:'%s', LibraryName:'%s'", @hostname, @loginData.userName, @loginData.password, @loginData.appName, @loginData.serverName, libraryName ) + '\n' + indent + ' ' + sprintf("Language:'%s', Database:'%s', SSPI:'%s', AttachDbFile:'%s', ChangePassword:'<PASSWORD>'", @loginData.language, @loginData.database, @sspi, @attachDbFile @changePassword ) module.exports = Login7Payload
true
WritableTrackingBuffer = require('./tracking-buffer/writable-tracking-buffer') require('./buffertools') os= require('os') sprintf = require('sprintf').sprintf libraryName = require('./library').name versions = require('./tds-versions').versions FLAGS_1 = ENDIAN_LITTLE: 0x00, ENDIAN_BIG: 0x01, CHARSET_ASCII: 0x00, CHARSET_EBCDIC: 0x02, FLOAT_IEEE_754: 0x00, FLOAT_VAX: 0x04, FLOAT_ND5000: 0x08, BCP_DUMPLOAD_ON: 0x00, BCP_DUMPLOAD_OFF: 0x10, USE_DB_ON: 0x00, USE_DB_OFF: 0x20, INIT_DB_WARN: 0x00, INIT_DB_FATAL: 0x40, SET_LANG_WARN_OFF: 0x00, SET_LANG_WARN_ON: 0x80, FLAGS_2 = INIT_LANG_WARN: 0x00, INIT_LANG_FATAL: 0x01, ODBC_OFF: 0x00, ODBC_ON: 0x02, F_TRAN_BOUNDARY: 0x04, # Removed in TDS 7.2 F_CACHE_CONNECT: 0x08, # Removed in TDS 7.2 USER_NORMAL: 0x00, USER_SERVER: 0x10, USER_REMUSER: 0x20, USER_SQLREPL: 0x40, INTEGRATED_SECURITY_OFF: 0x00, INTEGRATED_SECURITY_ON: 0x80 TYPE_FLAGS = SQL_DFLT: 0x00, SQL_TSQL: 0x01, OLEDB_OFF: 0x00, OLEDB_ON: 0x02, # Introduced in TDS 7.2 READ_ONLY_INTENT: 0x04 # Introduced in TDS 7.4 FLAGS_3 = CHANGE_PASSWORD_NO: 0x00, CHANGE_PASSWORD_YES: 0x01, # Introduced in TDS 7.2 BINARY_XML: 0x02, # Introduced in TDS 7.2 SPAWN_USER_INSTANCE: 0x04, # Introduced in TDS 7.2 UNKNOWN_COLLATION_HANDLING: 0x08 # Introduced in TDS 7.3 DEFAULT_TDS_VERSION = versions['7_2'] ### s2.2.6.3 ### class Login7Payload constructor: (@loginData) -> lengthLength = 4 fixed = @createFixedData() variable = @createVariableData(lengthLength + fixed.length) length = lengthLength + fixed.length + variable.length data = new WritableTrackingBuffer(300) data.writeUInt32LE(length) data.writeBuffer(fixed) data.writeBuffer(variable) @data = data.data createFixedData: -> @tdsVersion = DEFAULT_TDS_VERSION @packetSize = @loginData.packetSize @clientProgVer = 0 @clientPid = process.pid @connectionId = 0 @clientTimeZone = new Date().getTimezoneOffset() @clientLcid = 0x00000409 #Can't figure what form this should take. @flags1 = FLAGS_1.ENDIAN_LITTLE | FLAGS_1.CHARSET_ASCII | FLAGS_1.FLOAT_IEEE_754 | FLAGS_1.BCD_DUMPLOAD_OFF | FLAGS_1.USE_DB_OFF | FLAGS_1.INIT_DB_WARN | FLAGS_1.SET_LANG_WARN_ON @flags2 = FLAGS_2.INIT_LANG_WARN | FLAGS_2.ODBC_OFF | FLAGS_2.USER_NORMAL | FLAGS_2.INTEGRATED_SECURITY_OFF @flags3 = FLAGS_3.CHANGE_PASSWORD_NO | FLAGS_3.UNKNOWN_COLLATION_HANDLING @typeFlags = TYPE_FLAGS.SQL_DFLT | TYPE_FLAGS.OLEDB_OFF buffer = new WritableTrackingBuffer(100) buffer.writeUInt32LE(@tdsVersion) buffer.writeUInt32LE(@packetSize) buffer.writeUInt32LE(@clientProgVer) buffer.writeUInt32LE(@clientPid) buffer.writeUInt32LE(@connectionId) buffer.writeUInt8(@flags1) buffer.writeUInt8(@flags2) buffer.writeUInt8(@typeFlags) buffer.writeUInt8(@flags3) buffer.writeInt32LE(@clientTimeZone) buffer.writeUInt32LE(@clientLcid) buffer.data createVariableData: (offset) -> variableData = offsetsAndLengths: new WritableTrackingBuffer(200) data: new WritableTrackingBuffer(200, 'ucs2') offset: offset + ((9 * 4) + 6 + (3 * 4) + 4) @hostname = os.hostname() @loginData = @loginData || {} @loginData.appName = @loginData.appName || 'Tedious' @libraryName = libraryName # Client ID, should be MAC address or other randomly generated GUID like value. @clientId = new Buffer([1, 2, 3, 4, 5, 6]) @sspi = '' @sspiLong = 0 @attachDbFile = '' @changePassword = '' @addVariableDataString(variableData, @hostname) @addVariableDataString(variableData, @loginData.userName) @addVariableDataBuffer(variableData, @createPasswordBuffer()) @addVariableDataString(variableData, @loginData.appName) @addVariableDataString(variableData, @loginData.serverName) @addVariableDataString(variableData, '') # Reserved for future use. @addVariableDataString(variableData, @libraryName) @addVariableDataString(variableData, @loginData.language) @addVariableDataString(variableData, @loginData.database) variableData.offsetsAndLengths.writeBuffer(@clientId) @addVariableDataString(variableData, @sspi) @addVariableDataString(variableData, @attachDbFile) @addVariableDataString(variableData, @changePassword) # Introduced in TDS 7.2 variableData.offsetsAndLengths.writeUInt32LE(@sspiLong) # Introduced in TDS 7.2 variableData.offsetsAndLengths.data.concat(variableData.data.data) addVariableDataBuffer: (variableData, buffer) -> variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(buffer.length / 2) variableData.data.writeBuffer(buffer) variableData.offset += buffer.length addVariableDataString: (variableData, value) -> value ||= '' variableData.offsetsAndLengths.writeUInt16LE(variableData.offset) variableData.offsetsAndLengths.writeUInt16LE(value.length) variableData.data.writeString(value); variableData.offset += value.length * 2 createPasswordBuffer: () -> password = @loginData.password || '' password = new Buffer(password, 'PI:PASSWORD:<PASSWORD>END_PI') for b in [0..password.length - 1] byte = password[b] lowNibble = byte & 0x0f highNibble = (byte >> 4) byte = (lowNibble << 4) | highNibble byte = byte ^ 0xa5 password[b] = byte password toString: (indent) -> indent ||= '' indent + 'Login7 - ' + sprintf('TDS:0x%08X, PacketSize:0x%08X, ClientProgVer:0x%08X, ClientPID:0x%08X, ConnectionID:0x%08X', @tdsVersion, @packetSize, @clientProgVer, @clientPid, @connectionId ) + '\n' + indent + ' ' + sprintf('Flags1:0x%02X, Flags2:0x%02X, TypeFlags:0x%02X, Flags3:0x%02X, ClientTimezone:%d, ClientLCID:0x%08X', @flags1, @flags2, @typeFlags, @flags3, @clientTimeZone, @clientLcid ) + '\n' + indent + ' ' + sprintf("Hostname:'%s', Username:'%s', Password:'PI:PASSWORD:<PASSWORD>END_PI', AppName:'%s', ServerName:'%s', LibraryName:'%s'", @hostname, @loginData.userName, @loginData.password, @loginData.appName, @loginData.serverName, libraryName ) + '\n' + indent + ' ' + sprintf("Language:'%s', Database:'%s', SSPI:'%s', AttachDbFile:'%s', ChangePassword:'PI:PASSWORD:<PASSWORD>END_PI'", @loginData.language, @loginData.database, @sspi, @attachDbFile @changePassword ) module.exports = Login7Payload
[ { "context": "{\n\t\t\tusername: {type:\"text\"},\n\t\t\tpassword: {type:\"password\"}\n\t\t}\n\t}\n", "end": 1012, "score": 0.9009417295455933, "start": 1004, "tag": "PASSWORD", "value": "password" } ]
flick-electric-price/src/flick-electric-price.coffee
madleech/NodeRedFlickElectric
2
FlickAPI = require 'flick-electric-api' module.exports = (RED) -> FlickElectricPrice = (config) -> # set up node RED.nodes.createNode this, config # check credentials unless @credentials.username and @credentials.password @error "Missing username/password" return # set up API flick = new FlickAPI(@credentials.username, @credentials.password) # when an input arrives, get the current price @on 'input', (msg) => flick.get_price() flick.once 'price', (price) => msg.payload = price @send msg # update status flick.on 'error', (err, details) => @error "#{err}: #{details}" @status fill:"red", shape:"dot", text:"error" flick.on 'authenticated', => @status fill:"green", shape:"dot", text:"authenticated" # return null or you'll get odd "TypeError: node.receive is not a function" errors! null RED.nodes.registerType "flick-electric-price", FlickElectricPrice, { credentials: { username: {type:"text"}, password: {type:"password"} } }
57821
FlickAPI = require 'flick-electric-api' module.exports = (RED) -> FlickElectricPrice = (config) -> # set up node RED.nodes.createNode this, config # check credentials unless @credentials.username and @credentials.password @error "Missing username/password" return # set up API flick = new FlickAPI(@credentials.username, @credentials.password) # when an input arrives, get the current price @on 'input', (msg) => flick.get_price() flick.once 'price', (price) => msg.payload = price @send msg # update status flick.on 'error', (err, details) => @error "#{err}: #{details}" @status fill:"red", shape:"dot", text:"error" flick.on 'authenticated', => @status fill:"green", shape:"dot", text:"authenticated" # return null or you'll get odd "TypeError: node.receive is not a function" errors! null RED.nodes.registerType "flick-electric-price", FlickElectricPrice, { credentials: { username: {type:"text"}, password: {type:"<PASSWORD>"} } }
true
FlickAPI = require 'flick-electric-api' module.exports = (RED) -> FlickElectricPrice = (config) -> # set up node RED.nodes.createNode this, config # check credentials unless @credentials.username and @credentials.password @error "Missing username/password" return # set up API flick = new FlickAPI(@credentials.username, @credentials.password) # when an input arrives, get the current price @on 'input', (msg) => flick.get_price() flick.once 'price', (price) => msg.payload = price @send msg # update status flick.on 'error', (err, details) => @error "#{err}: #{details}" @status fill:"red", shape:"dot", text:"error" flick.on 'authenticated', => @status fill:"green", shape:"dot", text:"authenticated" # return null or you'll get odd "TypeError: node.receive is not a function" errors! null RED.nodes.registerType "flick-electric-price", FlickElectricPrice, { credentials: { username: {type:"text"}, password: {type:"PI:PASSWORD:<PASSWORD>END_PI"} } }
[ { "context": " 'userAuth': @userAuth\n 'userGuest': @userGuest\n 'activeRecord': @activeRecord\n 'addTi", "end": 28840, "score": 0.8525897860527039, "start": 28830, "tag": "USERNAME", "value": "@userGuest" }, { "context": " placeholder: @model.get 'title'\n field: 'first_name'\n\n $('placeholder#textarea', @$el).replaceWith", "end": 37887, "score": 0.8257002234458923, "start": 37877, "tag": "NAME", "value": "first_name" } ]
public/assets/js/app.coffee.src.coffee
Miniwe/tracktime
1
process = process or window.process or {} production = SERVER: 'https://ttpms.herokuapp.com' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' test = SERVER: 'http://localhost:5000' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' development = SERVER: 'http://localhost:5000' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' switch process.env?.NODE_ENV when 'production' config = production when 'test' config = test else config = development (module?.exports = config) or @config = config class Tracktime extends Backbone.Model urlRoot: config.SERVER defaults: title: 'TrackTime App' authUser: null initialize: () -> @set 'authUser', new Tracktime.User.Auth() @listenTo @get('authUser'), 'change:authorized', @changeUserStatus @listenTo @get('authUser'), 'destroy', -> @set 'authUser', new Tracktime.User.Auth() @listenTo @get('authUser'), 'change:authorized', @changeUserStatus initCollections: -> @set 'users', new Tracktime.UsersCollection() @set 'records', new Tracktime.RecordsCollection() @set 'projects', new Tracktime.ProjectsCollection() @set 'actions', new Tracktime.ActionsCollection() @listenTo Tracktime.AppChannel, "isOnline", @updateApp unsetCollections: -> @unset 'users' @unset 'actions' @unset 'records' @unset 'projects' @stopListening Tracktime.AppChannel, "isOnline" updateApp: -> @get('users').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' @get('projects').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' @get('records').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' changeUserStatus: -> @setUsetStatus @get('authUser').get('authorized') setUsetStatus: (status) -> if status == true @initCollections() Tracktime.AppChannel.command 'userAuth' else @unsetCollections() Tracktime.AppChannel.command 'userGuest' (module?.exports = Tracktime) or @Tracktime = Tracktime class Tracktime.AdminView extends Backbone.View el: '#panel' className: '' template: JST['admin/index'] views: {} initialize: -> @render() render: -> # $(document).title @model.get 'title' @$el.html @template() initUI: -> $.material.init() (module?.exports = Tracktime.AdminView) or @Tracktime.AdminView = Tracktime.AdminView do -> proxiedSync = Backbone.sync Backbone.sync = (method, model, options) -> options or (options = {}) if !options.crossDomain options.crossDomain = true if !options.xhrFields options.xhrFields = withCredentials: true proxiedSync method, model, options return Backbone.Validation.configure # selector: 'class_v' # labelFormatter: 'label_v' # attributes: 'inputNames' # returns the name attributes of bound view input elements # forceUpdate: true _.extend Backbone.Model.prototype, Backbone.Validation.mixin Backbone.ViewMixin = close: () -> @onClose() if @onClose if @container? $(@container).unbind() @undelegateEvents() @$el.removeData().unbind() @remove() Backbone.View.prototype.remove.call @ return onClose: -> for own key, view of @views view.close() delete @views[key] clear: -> @onClose() setSubView: (key, view) -> @views[key].close() if key of @views @views[key] = view getSubView: (key) -> @views[key] if key of @views Backbone.View.prototype extends Backbone.ViewMixin Handlebars.registerHelper 'link_to', (options) -> attrs = href: '' for own key, value of options.hash if key is 'body' body = Handlebars.Utils.escapeExpression value else attrs[key] = Handlebars.Utils.escapeExpression value new (Handlebars.SafeString) $("<a />", attrs).html(body)[0].outerHTML Handlebars.registerHelper 'safe_val', (value, safeValue) -> out = value || safeValue new Handlebars.SafeString(out) Handlebars.registerHelper 'nl2br', (text) -> text = Handlebars.Utils.escapeExpression text new Handlebars.SafeString text.nl2br() Handlebars.registerHelper 'dateFormat', (date) -> moment = window.moment localeData = moment.localeData('ru') moment(date).format("MMM Do YYYY") # timestamp = Date.parse date # unless _.isNaN(timestamp) # (new Date(timestamp)).toLocalString() # else # new Date() Handlebars.registerHelper 'minuteFormat', (val) -> duration = moment.duration val,'minute' duration.get('hours') + ':' + duration.get('minutes') # currentHour = val / 720 * 12 # hour = Math.floor(currentHour) # minute = Math.round((currentHour - hour) * 60) # "hb: #{hour}:#{minute}" Handlebars.registerHelper 'placeholder', (name) -> placeholder = "<placeholder id='#{name}'></placeholder>" new Handlebars.SafeString placeholder Handlebars.registerHelper 'filteredHref', (options) -> parsedFilter = {} _.extend(parsedFilter, options.hash.filter) if 'filter' of options.hash _.extend(parsedFilter, {user: options.hash.user}) if 'user' of options.hash _.extend(parsedFilter, {project: options.hash.project}) if 'project' of options.hash delete parsedFilter[options.hash.exclude] if 'exclude' of options.hash and options.hash.exclude of parsedFilter if _.keys(parsedFilter).length > 0 '/' + _.map(parsedFilter, (value,key) -> "#{key}/#{value}").join '/' else '' (($) -> snackbarOptions = content: '' style: '' timeout: 2000 htmlAllowed: true $.extend ( alert: (params) -> if _.isString params snackbarOptions.content = params else snackbarOptions = $.extend {},snackbarOptions,params $.snackbar snackbarOptions ) ) jQuery String::capitalizeFirstLetter = -> @charAt(0).toUpperCase() + @slice(1) String::nl2br = -> (@ + '').replace /([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2' String::letter = -> @charAt(0).toUpperCase() class Tracktime.Collection extends Backbone.Collection addModel: (params, options) -> newModel = new @model params if newModel.isValid() @add newModel unless options.ajaxSync? options.ajaxSync = Tracktime.AppChannel.request 'isOnline' newModel.save {}, options else $.alert 'Erros validation from add curModel to collection' fetch: (options) -> @resetLocalStorage() if options? and options.ajaxSync == true _success = options.success options.success = (collection, response, optionsSuccess) => @syncCollection(response) _success.apply(@, collection, response, options) if _.isFunction(_success) super options syncCollection: (models) -> # по всем remote model которые вроде как в коллекции уже _.each models, (model) => curModel = @get(model._id) localModel = @localStorage.find curModel # если нет локальной то сохраняем (локально) unless localModel curModel.save ajaxSync: false # иначе else # если локальная старее то обновляем с новых данных (локально) modelUpdatetAt = (new Date(model.updatedAt)).getTime() localUpdatetAt = (new Date(localModel.updatedAt)).getTime() if localModel.isDeleted # do nothing curModel.set {'isDeleted': true}, {trigger: false} else if localUpdatetAt < modelUpdatetAt curModel.save model, ajaxSync: false # иначе есть если локальная новее то else if localUpdatetAt > modelUpdatetAt # обновляем модель пришедшую в коллекции # сохраняем ее удаленно curModel.save localModel, ajaxSync: true # по всем local моделям localModels = @localStorage.findAll() _.each _.clone(localModels), (model) => collectionModel = @get(model._id) # если удалена if model.isDeleted if model._id.length > 24 destroedModel = new @model {_id: model._id, subject: 'model to delete'} destroedModel.destroy ajaxSync: false else modelUpdatetAt = (new Date(model.updatedAt)).getTime() if collectionModel? and modelUpdatetAt > (new Date(collectionModel.get('updatedAt'))).getTime() destroedModel = collectionModel else destroedModel = new @model (model) # то удаляем локально и удаленно # и из коллекции если есть destroedModel.destroy ajaxSync: true else # если нет в коллекции unless collectionModel replacedModel = new @model {_id: model._id} replacedModel.fetch {ajaxSync: false} newModel = replacedModel.toJSON() delete newModel._id # то сохраняем ее удаленно # добавляем в коллекцию @addModel newModel, success: (model, response) => # заменяем на новосохраненную replacedModel.destroy {ajaxSync: false} resetLocalStorage: () -> @localStorage = new Backbone.LocalStorage @collectionName (module?.exports = Tracktime.Collection) or @Tracktime.Collection = Tracktime.Collection class Tracktime.Model extends Backbone.Model sync: (method, model, options) -> options = options or {} switch method when 'create' if options.ajaxSync _success = options.success _model = model.clone() options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success _model.id = model._id _model.set '_id', model._id Backbone.sync method, _model, options Backbone.sync method, model, options when 'read' Backbone.sync method, model, options when 'patch' Backbone.sync method, model, options when 'update' if options.ajaxSync _success = options.success _model = model options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success Backbone.sync method, _model, options Backbone.sync method, model, options when 'delete' if options.ajaxSync == true model.save {'isDeleted': true}, {ajaxSync: false} _success = options.success _model = model options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success Backbone.sync method, _model, options Backbone.sync method, model, options else Backbone.sync method, model, options else $.alert "unknown method #{method}" Backbone.sync method, model, options class Tracktime.Action extends Backbone.Model idAttribute: "_id" collectionName: config.collection.actions url: '/actions' #receive on activate actions for user (!) defaults: _id: null title: 'Default action' isActive: null isVisible: false canClose: false attributes: () -> id: @model.cid setActive: () -> @collection.setActive @ processAction: (options) -> $.alert 'Void Action' (module?.exports = Tracktime.Action) or @Tracktime.Action = Tracktime.Action class Tracktime.Action.Project extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add project' projectModel: null formAction: '#' btnClass: 'btn-material-purple' btnClassEdit: 'btn-material-blue' navbarClass: 'navbar-inverse' icon: className: 'mdi-content-add-circle' classNameEdit: 'mdi-content-add-circle-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'projectModel', new Tracktime.Project() unless @get('projectModel') instanceof Tracktime.Project processAction: () -> projectModel = @get 'projectModel' if projectModel.isValid() if projectModel.isNew() Tracktime.AppChannel.command 'newProject', projectModel.toJSON() projectModel.clear().set(projectModel.defaults) else projectModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'Project: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('projectModel').isEdit = false @get('projectModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.Project) or @Tracktime.Action.Project = Tracktime.Action.Project class Tracktime.Action.Record extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add record' recordModel: null formAction: '#' btnClass: 'btn-material-green' btnClassEdit: 'btn-material-lime' navbarClass: 'navbar-primary' icon: className: 'mdi-action-bookmark' classNameEdit: 'mdi-action-bookmark-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'recordModel', new Tracktime.Record() unless @get('recordModel') instanceof Tracktime.Record processAction: () -> recordModel = @get 'recordModel' if recordModel.isValid() if recordModel.isNew() Tracktime.AppChannel.command 'newRecord', recordModel.toJSON() recordModel.clear().set(recordModel.defaults) else recordModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'Record: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('recordModel').isEdit = false @get('recordModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.Record) or @Tracktime.Action.Record = Tracktime.Action.Record class Tracktime.Action.Search extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Search' formAction: '#' btnClass: 'btn-white' btnClassEdit: 'btn-white' navbarClass: 'navbar-material-light-blue' icon: className: 'mdi-action-search' classNameEdit: 'mdi-action-search' letter: '' isActive: null isVisible: true initialize: (options = {}) -> @set options processAction: (options) -> @search() search: () -> $.alert 'search start' (module?.exports = Tracktime.Action.Search) or @Tracktime.Action.Search = Tracktime.Action.Search class Tracktime.Action.User extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add user' userModel: null formAction: '#' btnClass: 'btn-material-deep-orange' btnClassEdit: 'btn-material-amber' navbarClass: 'navbar-material-yellow' icon: className: 'mdi-social-person' classNameEdit: 'mdi-social-person-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'userModel', new Tracktime.User() unless @get('userModel') instanceof Tracktime.User processAction: () -> userModel = @get 'userModel' if userModel.isValid() if userModel.isNew() Tracktime.AppChannel.command 'newUser', userModel.toJSON() userModel.clear().set(userModel.defaults) else userModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'User: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('userModel').isEdit = false @get('userModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.User) or @Tracktime.Action.User = Tracktime.Action.User class Tracktime.Project extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.projects urlRoot: config.SERVER + '/' + 'projects' localStorage: new Backbone.LocalStorage 'projects' defaults: _id: null name: '' description: '' updatedAt: (new Date()).toISOString() isDeleted: false validation: name: required: true minLength: 4 msg: 'Please enter a valid name' initialize: -> @isEdit = false @on 'change:name', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: () -> # @todo add good validation true updateUpdatedAt: () -> @set 'updatedAt', (new Date()).toISOString() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit project', type: 'Project', canClose: true}, title: 'Edit project: ' + @get('name').substr(0, 40) projectModel: @ scope: 'edit:action' (module?.exports = Tracktime.Project) or @Tracktime.Project = Tracktime.Project class Tracktime.Record extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.records urlRoot: config.SERVER + '/' + 'records' localStorage: new Backbone.LocalStorage 'records' defaults: _id: null subject: '' description: '' date: () -> (new Date()).toISOString() updatedAt: (new Date()).toISOString() recordDate: '' recordTime: 0 project: 0 user: 0 isDeleted: false validation: subject: required: true minLength: 4 msg: 'Please enter a valid subject' initialize: -> @isEdit = false @on 'change:subject change:recordTime change:recordDate change:project', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: -> # @todo add good validation true isSatisfied: (filter) -> _.isMatch @attributes, filter updateUpdatedAt: () -> @set 'updatedAt', new Date() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit record', type: 'Record', canClose: true}, title: 'Edit record: ' + @get('subject').substr(0, 40) recordModel: @ scope: 'edit:action' addTime: (diff) -> time = parseInt @get('recordTime'), 10 @set 'recordTime', (time + diff) @save {}, ajaxSync: true (module?.exports = Tracktime.Record) or @Tracktime.Record = Tracktime.Record class Tracktime.User extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.users urlRoot: config.SERVER + '/' + 'users' localStorage: new Backbone.LocalStorage 'users' defaults: _id: null first_name: '' last_name: '' email: '' password: '' description: '' default_pay_rate: '' updatedAt: (new Date()).toISOString() activeRecord: '' startedAt: null isDeleted: false validation: first_name: required: true minLength: 4 msg: 'Please enter a valid first_name' initialize: -> @isEdit = false @on 'change:first_name', @updateUpdatedAt @on 'change:last_name', @updateUpdatedAt @on 'change:description', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: () -> # @todo add good validation true updateUpdatedAt: () -> @set 'updatedAt', (new Date()).toISOString() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit user', type: 'User', canClose: true}, title: 'Edit user: ' + @get('first_name').substr(0, 40) userModel: @ scope: 'edit:action' (module?.exports = Tracktime.User) or @Tracktime.User = Tracktime.User class Tracktime.User.Auth extends Backbone.Model idAttribute: "_id" urlRoot: config.SERVER + '/' + '' defaults: authorized: null initialize: -> @fetch ajaxSync: true url: config.SERVER + '/auth_user' success: (model, response, options) => @set 'authorized', true error: (model, response, options) => @set 'authorized', false login: (params) -> @save params, ajaxSync: true url: config.SERVER + '/login' success: (model, response, options) => @set response @set 'authorized', true $.alert "Welcome back, #{response.first_name} #{response.last_name}!" window.location.hash = '#records' error: (model, response, options) => if response.responseJSON? @trigger 'flash', response.responseJSON.error else @trigger 'flash', scope: "unknown" msg: 'Send request error' signin: (params) -> _.extend params, status: 'active' k_status: 'active' updatedAt: (new Date()).toISOString() isDeleted: 'false' @save params, ajaxSync: true url: config.SERVER + '/register' success: (model, response, options) => @set response @set 'authorized', true $.alert "Welcome, #{response.name} !" error: (model, response, options) => @trigger 'flash', response.responseJSON.error forgotpasswrod: -> fullName: -> "#{@get('first_name')} #{@get('last_name')}" logout: -> $.alert "Goodbay, #{@fullName()}!" @set 'authorized', false @destroy ajaxSync: true url: config.SERVER + '/logout/' + @id success: (model, response, options) => window.location.href = '#' window.location.reload() error: (model, response, options) => console.log 'logout error' setActiveRecord: (record, status) -> if @get('activeRecord') Tracktime.AppChannel.command 'addTime', @get('activeRecord'), @get('startedAt') if status params = activeRecord: record.id startedAt: (new Date()).toISOString() else params = activeRecord: '' startedAt: null @save params, ajaxSync: true url: config.SERVER + '/users/' + @id success: (model, response, options) => record.trigger 'isActive', status error: (model, response, options) => @trigger 'flash', response.responseJSON.error (module?.exports = Tracktime.User.Auth) or @Tracktime.User.Auth = Tracktime.User.Auth class Tracktime.ActionsCollection extends Backbone.Collection model: Tracktime.Action collectionName: config.collection.actions url: '/actions' localStorage: new Backbone.LocalStorage @collectionName defaultActions: [ { title: 'Add Record', type: 'Record' } { title: 'Search', type: 'Search' } ] active: null initialize: -> @on 'remove', @setDefaultActive _.each @defaultActions, @addAction addAction: (action, params = {}) => @push new Tracktime.Action[action.type] _.extend action, params if (Tracktime.Action[action.type]) setDefaultActive: -> @at(0).setActive() unless @findWhere isActive: true setActive: (active) -> @active?.set 'isActive', false active.set 'isActive', true @active = active @trigger 'change:active', @active getActive: -> @active getActions: -> _.filter @models, (model) -> model.get('isVisible') (module?.exports = Tracktime.ActionsCollection) or @Tracktime.ActionsCollection = Tracktime.ActionsCollection class Tracktime.ProjectsCollection extends Tracktime.Collection model: Tracktime.Project collectionName: config.collection.projects url: config?.SERVER + '/projects' urlRoot: config?.SERVER + '/projects' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @on 'sync', @makeList comparator: (model) -> - (new Date(model.get('date'))).getTime() addProject: (options) -> _.extend options, {date: (new Date()).toISOString()} success = (result) => $.alert content: 'Project: save success' timeout: 2000 style: 'btn-success' error = () => $.alert 'Project: save error' @addModel options, success: success, error: error makeList: -> list = {} _.each @models, (model, index) -> list[model.get('_id')] = model.get('name') Tracktime.AppChannel.reply 'projectsList', () -> list useProject: (id) -> project = @get(id) if project.has('useCount') useCount = project.get('useCount') + 1 else useCount = 1 project.save {'useCount': useCount}, {ajaxSync: false} (module?.exports = Tracktime.ProjectsCollection) or @Tracktime.ProjectsCollection = Tracktime.ProjectsCollection class Tracktime.RecordsCollection extends Tracktime.Collection model: Tracktime.Record collectionName: config.collection.records url: config?.SERVER + '/records' urlRoot: config?.SERVER + '/records' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @filter = {} @defaultFilter = isDeleted: false comparator: (model) -> - (new Date(model.get('date'))).getTime() setFilter: (filter) -> @resetFilter() unless filter == null pairs = filter.match(/((user|project)\/[a-z0-9A-Z]{24})+/g) if pairs _.each pairs, (pair, index) -> _p = pair.split '/' @filter[_p[0]] = _p[1] , @ @filter resetFilter: -> @filter = _.clone @defaultFilter removeFilter: (key) -> if key of @filter delete @filter[key] getFilter: (removeDefault = true) -> result = {} if removeDefault keys = _.keys @defaultFilter result = _.omit @filter, keys else result = @filter result addRecord: (options) -> _.extend options, {date: (new Date()).toISOString()} options.recordDate = (new Date()).toISOString() if _.isEmpty(options.recordDate) success = (result) => $.alert content: 'Record: save success' timeout: 2000 style: 'btn-success' @trigger 'newRecord', result error = () => $.alert 'Record: save error' @addModel options, success: success, error: error getModels: (except = []) -> models = {} limit = 6 if @length > 0 models = _.filter @models, (model) => model.isSatisfied @filter models = _.filter models, (model) -> _.indexOf(except, model.id) == -1 _.first models, limit (module?.exports = Tracktime.RecordsCollection) or @Tracktime.RecordsCollection = Tracktime.RecordsCollection class Tracktime.UsersCollection extends Tracktime.Collection model: Tracktime.User collectionName: config.collection.users url: config?.SERVER + '/users' urlRoot: config?.SERVER + '/users' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @on 'sync', @makeList addUser: (options) -> _.extend options, {date: (new Date()).toISOString()} success = (result) => $.alert content: 'User: save success' timeout: 2000 style: 'btn-success' error = () => $.alert 'User: save error' @addModel options, success: success, error: error makeList: (collection, models) -> list = {} _.each collection.models, (model, index) -> list[model.get('_id')] = "#{model.get('first_name')} #{model.get('last_name')}" Tracktime.AppChannel.reply 'usersList', () -> list (module?.exports = Tracktime.UsersCollection) or @Tracktime.UsersCollection = Tracktime.UsersCollection Tracktime.AppChannel = Backbone.Radio.channel 'app' _.extend Tracktime.AppChannel, isOnline: null userStatus: null router: null init: -> @on 'isOnline', (status) => @isOnline = status @on 'userStatus', (status) => @changeUserStatus status @checkOnline() @setWindowListeners() @model = new Tracktime() @bindComply() @bindRequest() return @ checkOnline: -> if window.navigator.onLine == true @checkServer() else @trigger 'isOnline', false checkServer: -> deferred = $.Deferred() serverOnlineCallback = (status) => @trigger 'isOnline', true successCallback = (result) => @trigger 'isOnline', true deferred.resolve() errorCallback = (jqXHR, textStatus, errorThrown) => @trigger 'isOnline', false deferred.resolve() try $.ajax url: "#{config.SERVER}/status" async: false dataType: 'jsonp' jsonpCallback: 'serverOnlineCallback' success: successCallback error: errorCallback catch exception_var @trigger 'isOnline', false return deferred.promise() setWindowListeners: -> window.addEventListener "offline", (e) => @trigger 'isOnline', false , false window.addEventListener "online", (e) => @checkServer() , false bindComply: -> @comply 'start': @startApp 'newRecord': @newRecord 'newProject': @newProject 'newUser': @newUser 'useProject': @useProject 'addAction': @addAction 'serverOnline': @serverOnline 'serverOffline': @serverOffline 'checkOnline': @checkOnline 'userAuth': @userAuth 'userGuest': @userGuest 'activeRecord': @activeRecord 'addTime': @addTime bindRequest: -> @reply 'isOnline', => @isOnline @reply 'userStatus', => @userStatus @reply 'projects', => @model.get 'projects' @reply 'users', => @model.get 'users' @reply 'projectsList', => {} @reply 'usersList', => {} startApp: -> Backbone.history.start pushState: false newRecord: (options) -> _.extend options, user: @model.get('authUser').id @model.get('records').addRecord(options) newProject: (options) -> @model.get('projects').addProject(options) newUser: (options) -> @model.get('users').addUser(options) addAction: (options, params) -> action = @model.get('actions').addAction(options, params) action.setActive() activeRecord: (record, status) -> @model.get('authUser').setActiveRecord record, status addTime: (record, start) -> # diff = moment(new Date()) - moment(new Date(start)) record = @model.get('records').get(record) if record instanceof Tracktime.Record record.addTime moment(new Date()).diff(new Date(start), 'second') serverOnline: -> @trigger 'isOnline', true useProject: (id) -> @model.get('projects').useProject id serverOffline: -> @trigger 'isOnline', false userAuth: -> @trigger 'userStatus', true userGuest: -> @trigger 'userStatus', false changeUserStatus: (status) -> # @todo here get user session - if success status true else false if @router != null @router.view.close() delete @router.view if status == true @router = new Tracktime.AppRouter model: @model @trigger 'isOnline', @isOnline else @router = new Tracktime.GuestRouter model: @model checkActive: (id) -> id == @model.get('authUser').get('activeRecord') (module?.exports = Tracktime.AppChannel) or @Tracktime.AppChannel = Tracktime.AppChannel class Tracktime.ActionView extends Backbone.View tagName: 'li' className: 'btn' events: 'click a': 'setActive' initialize: () -> # _.bindAll @model, 'change:isActive', @update setActive: () -> @model.setActive() (module?.exports = Tracktime.ActionView) or @Tracktime.ActionView = Tracktime.ActionView class Tracktime.ActionsView extends Backbone.View el: '#actions-form' menu: '#actions-form' template: JST['actions/actions'] views: {} initialize: (options) -> _.extend @, options @listenTo @collection, 'change:active', @renderAction @listenTo @collection, 'add', @addAction @render() render: () -> @$el.html @template() @menu = $('.dropdown-menu', '.select-action', @$el) _.each @collection.getActions(), @addAction @collection.at(0).setActive() addAction: (action) => listBtn = new Tracktime.ActionView.ListBtn model: action @menu.append listBtn.$el @setSubView "listBtn-#{listBtn.cid}", listBtn $('[data-toggle="tooltip"]', listBtn.$el).tooltip() renderAction: (action) -> if Tracktime.ActionView[action.get('type')] @$el.parents('.navbar').attr 'class', "navbar #{action.get('navbarClass')} shadow-z-1" @setSubView "actionDetails", new Tracktime.ActionView[action.get('type')] model: action (module?.exports = Tracktime.ActionsView) or @Tracktime.ActionsView = Tracktime.ActionsView class Tracktime.ActionView.ActiveBtn extends Backbone.View el: '#action_type' initialize: () -> @render() render: () -> model = @model.toJSON() if model.canClose model.btnClass = model.btnClassEdit model.icon.className = model.icon.classNameEdit @$el .attr 'class', "btn btn-fab #{model.btnClass} dropdown-toggle " .find('i').attr('title', model.title).attr('class', model.icon.className).html model.icon.letter (module?.exports = Tracktime.ActionView.ActiveBtn) or @Tracktime.ActionView.ActiveBtn = Tracktime.ActionView.ActiveBtn class Tracktime.ActionView.ListBtn extends Backbone.View tagName: 'li' template: JST['actions/listbtn'] events: 'click': 'actionActive' initialize: (options) -> _.extend @, options @render() @listenTo @model, 'change:isActive', @updateActionControl @listenTo @model, 'destroy', @close render: () -> model = @model.toJSON() if model.canClose model.btnClass = model.btnClassEdit model.icon.className = model.icon.classNameEdit @$el.html @template model if @model.get('isActive') == true @$el.addClass 'active' @updateActionControl() else @$el.removeClass 'active' actionActive: (event) -> event.preventDefault() @model.setActive() updateActionControl: () -> @$el.siblings().removeClass 'active' @$el.addClass 'active' $("#action_type").replaceWith (new Tracktime.ActionView.ActiveBtn model: @model).$el (module?.exports = Tracktime.ActionView.ListBtn) or @Tracktime.ActionView.ListBtn = Tracktime.ActionView.ListBtn class Tracktime.ActionView.Project extends Backbone.View container: '.action-wrapper' template: JST['actions/details/project'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'projectModel' placeholder: @model.get 'title' field: 'name' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() textarea.on 'tSubmit', @sendForm $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' textareaInput: (event) => window.setTimeout () => diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.currentTarget).val() , 500 sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.Project) or @Tracktime.ActionView.Project = Tracktime.ActionView.Project class Tracktime.ActionView.Record extends Backbone.View container: '.action-wrapper' template: JST['actions/details/record'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'recordModel' placeholder: @model.get 'title' field: 'subject' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() window.setTimeout () => textarea.$el.trigger 'input' , 100 textarea.on 'tSubmit', @sendForm $('placeholder#slider', @$el).replaceWith (new Tracktime.Element.Slider model: @model.get 'recordModel' field: 'recordTime' ).$el $('placeholder#selectday', @$el).replaceWith (new Tracktime.Element.SelectDay model: @model.get 'recordModel' field: 'recordDate' ).$el projectDefinition = new Tracktime.Element.ProjectDefinition model: @model.get 'recordModel' field: 'project' $('.floating-label', "#actions-form").append projectDefinition.$el $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' $('[data-toggle="tooltip"]').tooltip() textareaInput: (event) -> diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.target).val() sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.Record) or @Tracktime.ActionView.Record = Tracktime.ActionView.Record class Tracktime.ActionView.Search extends Backbone.View container: '.action-wrapper' template: JST['actions/details/search'] tmpDetails: {} views: {} initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() (module?.exports = Tracktime.ActionView.Search) or @Tracktime.ActionView.Search = Tracktime.ActionView.Search class Tracktime.ActionView.User extends Backbone.View container: '.action-wrapper' template: JST['actions/details/user'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'userModel' placeholder: @model.get 'title' field: 'first_name' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() textarea.on 'tSubmit', @sendForm $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' textareaInput: (event) => window.setTimeout () => diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.target).val() , 500 sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.User) or @Tracktime.ActionView.User = Tracktime.ActionView.User class Tracktime.AdminView.Header extends Backbone.View container: '#header' template: JST['admin/layout/header'] initialize: (options) -> @render() render: () -> $(@container).html @$el.html @template() (module?.exports = Tracktime.AdminView.Header) or @Tracktime.AdminView.Header = Tracktime.AdminView.Header class Tracktime.AdminView.ActionView extends Backbone.View tagName: 'li' className: 'list-group-item' template: JST['actions/admin_action'] events: 'click .btn-call-action': "callAction" 'click .edit.btn': "editAction" initialize: -> @render() render: -> @$el.html @template @model.toJSON() editAction: -> callAction: -> $.alert 'Test action call' (module?.exports = Tracktime.AdminView.ActionView) or @Tracktime.AdminView.ActionView = Tracktime.AdminView.ActionView class Tracktime.AdminView.ActionsView extends Backbone.View container: '#main' template: JST['admin/actions'] templateHeader: JST['admin/actions_header'] tagName: 'ul' className: 'list-group' views: {} actionsTypes: ['Project', 'Record', 'User', 'Search'] initialize: () -> @render() render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Actions'} @$el.prepend @templateHeader() @renderActionsList() renderActionsList: () -> _.each @actionsTypes, (atype) => actionView = new Tracktime.AdminView.ActionView model: new Tracktime.Action[atype]() @$el.append actionView.el @setSubView "atype-#{atype}", actionView , @ (module?.exports = Tracktime.AdminView.ActionsView) or @Tracktime.AdminView.ActionsView = Tracktime.AdminView.ActionsView class Tracktime.AdminView.Dashboard extends Backbone.View container: '#main' template: JST['admin/dashboard'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template() (module?.exports = Tracktime.AdminView.Dashboard) or @Tracktime.AdminView.Dashboard = Tracktime.AdminView.Dashboard class Tracktime.AdminView.ProjectsView extends Backbone.View container: '#main' template: JST['admin/projects'] tagName: 'ul' className: 'list-group' views: {} initialize: () -> @render() @listenTo @collection, "reset", @resetProjectsList @listenTo @collection, "add", @addProject @listenTo @collection, "remove", @removeProject render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Projects'} @resetProjectsList() resetProjectsList: () -> _.each @collection.where(isDeleted: false), (project) => projectView = new Tracktime.AdminView.ProjectView { model: project } @$el.append projectView.el @setSubView "project-#{project.cid}", projectView , @ addProject: (project, collection, params) -> projectView = new Tracktime.AdminView.ProjectView { model: project } $(projectView.el).prependTo @$el @setSubView "project-#{project.cid}", projectView removeProject: (project, args...) -> projectView = @getSubView "project-#{project.cid}" projectView.close() if projectView (module?.exports = Tracktime.AdminView.ProjectsView) or @Tracktime.AdminView.ProjectsView = Tracktime.AdminView.ProjectsView class Tracktime.AdminView.UsersView extends Backbone.View container: '#main' template: JST['admin/users'] tagName: 'ul' className: 'list-group' views: {} initialize: () -> @render() @listenTo @collection, "reset", @resetUsersList @listenTo @collection, "add", @addUser @listenTo @collection, "remove", @removeUser render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Users'} @resetUsersList() resetUsersList: () -> _.each @collection.where(isDeleted: false), (user) => userView = new Tracktime.AdminView.UserView { model: user } @$el.append userView.el @setSubView "user-#{user.cid}", userView , @ addUser: (user, collection, params) -> userView = new Tracktime.AdminView.UserView { model: user } $(userView.el).prependTo @$el @setSubView "user-#{user.cid}", userView removeUser: (user, args...) -> userView = @getSubView "user-#{user.cid}" userView.close() if userView (module?.exports = Tracktime.AdminView.UsersView) or @Tracktime.AdminView.UsersView = Tracktime.AdminView.UsersView class Tracktime.AppView extends Backbone.View container: '#panel' className: '' template: JST['global/app'] views: {} initialize: -> @render() render: -> $(@container).html @$el.html @template @model.toJSON() initUI: -> $.material.init() (module?.exports = Tracktime.AppView) or @Tracktime.AppView = Tracktime.AppView class Tracktime.Element extends Backbone.View initialize: () -> @render() render: () -> @$el.html 'void element' (module?.exports = Tracktime.Element) or @Tracktime.Element = Tracktime.Element class Tracktime.Element.ElementCloseAction extends Tracktime.Element tagName: 'button' className: 'btn btn-close-action btn-fab btn-flat btn-fab-mini' hint: 'Cancel action' events: 'click': 'closeAction' initialize: (options = {}) -> _.extend @, options @render() render: () -> @$el .attr 'title', @hint .append $('<i />', class: 'mdi-content-remove') closeAction: () => @model.destroy() (module?.exports = Tracktime.Element.ElementCloseAction) or @Tracktime.Element.ElementCloseAction = Tracktime.Element.ElementCloseAction class Tracktime.Element.ProjectDefinition extends Tracktime.Element className: 'project_definition' template: JST['elements/project_definition'] defaultTitle: 'Select project' searchStr: '' events: 'click .btn-white': 'selectProject' initialize: (options = {}) -> _.extend @, options @render() @projects = Tracktime.AppChannel.request 'projects' @projectsList = Tracktime.AppChannel.request 'projectsList' @projects.on 'sync', @renderList render: -> @$el.html @template title: @defaultTitle @renderList() $('.input-cont', @$el) .on 'click', (event) -> event.stopPropagation() $('.input-cont input', @$el) .on 'keyup', @setSearch setSearch: (event) => @searchStr = $(event.currentTarget).val().toLowerCase() @renderList() getList: (limit = 5) -> @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList unless _.isEmpty @searchStr keys = _.filter keys, (key) => @projectsList[key].toLowerCase().indexOf(@searchStr) > -1 sublist = {} i = 0 limit = Math.min(limit, keys.length) while i < limit sublist[ keys[i] ] = @projectsList[ keys[i] ] i++ sublist renderList: => list = @getList() menu = $('.dropdown-menu', @$el) menu.children('.item').remove() @updateTitle() for own key, value of list menu.append $("<li class='item'><a class='btn btn-white' data-project='#{key}' href='##{key}'>#{value}</a></li>") menu.append $("<li class='item'><a class='btn btn-white' data-project='0' href='#0'><span class='text-muted'>No project</span></a></li>") getTitle: -> projectId = @model.get @field if projectId of @projectsList "to " + @projectsList[projectId] else @defaultTitle selectProject: (event) => event.preventDefault() projectId = $(event.currentTarget).data 'project' @model.set @field, projectId Tracktime.AppChannel.command 'useProject', projectId @updateTitle() @$el.parents('.form-control-wrapper').find('textarea').focus() updateTitle: -> $('.project_definition-toggler span.caption', @$el).text @getTitle() (module?.exports = Tracktime.Element.ProjectDefinition) or @Tracktime.Element.ProjectDefinition = Tracktime.Element.ProjectDefinition class Tracktime.Element.SelectDay extends Tracktime.Element className: 'btn-group select-day' template: JST['elements/selectday'] events: 'click button.btn': 'setDay' initialize: (options = {}) -> # @tmpDetails.recordDate = $(".select-day > .btn .caption ruby rt").html() _.extend @, options @render() @changeField() @listenTo @model, "change:#{@field}", @changeField render: -> @$el.html @template @setDays() setDays: -> moment = window.moment localeData = moment.localeData('ru') current: name: localeData.weekdays(moment()) day: moment().format("MMM Do YYYY") value: moment().toISOString() days: [ name: localeData.weekdays(moment().subtract(2, 'days')) day: moment().subtract(2, 'day').format("MMM Do YYYY") value: moment().subtract(2, 'day').toISOString() , name: localeData.weekdays(moment().subtract(1, 'day')) day: moment().subtract(1, 'day').format("MMM Do YYYY") value: moment().subtract(1, 'day').toISOString() , name: localeData.weekdays(moment()) day: moment().format("MMM Do YYYY") value: moment().toISOString() ] changeField: => # @$el.val @model.get @field # найти в списке тот день который есть в field и нажать на эту кнопку changeInput: (value) => @model.set @field, value, {silent: true} setDay: (event) -> event.preventDefault() $(".dropdown-toggle ruby", @$el).html $('ruby', event.currentTarget).html() @changeInput $(event.currentTarget).data('value') # $(".dropdown-toggle ruby rt", @$el).html() (module?.exports = Tracktime.Element.SelectDay) or @Tracktime.Element.SelectDay = Tracktime.Element.SelectDay class Tracktime.Element.Slider extends Tracktime.Element className: 'slider shor btn-primary slider-material-orange' initialize: (options = {}) -> _.extend @, options @render() @changeField() @listenTo @model, "change:#{@field}", @changeField render: () -> @$el .noUiSlider start: [0] step: 5 range: {'min': [ 0 ], 'max': [ 720 ] } .on slide: (event, inval) => if inval? and _.isNumber parseFloat inval @changeInput parseFloat inval val = inval else val = 0 currentHour = val / 720 * 12 hour = Math.floor(currentHour) minute = (currentHour - hour) * 60 $('.slider .noUi-handle').attr 'data-before', hour $('.slider .noUi-handle').attr 'data-after', Math.round(minute) @$el .noUiSlider_pips mode: 'values' values: [0,60*1,60*2,60*3,60*4,60*5,60*6,60*7,60*8,60*9,60*10,60*11,60*12] density: 2 format: to: (value) -> value / 60 from: (value) -> value changeField: () => newVal = 0 fieldValue = @model.get(@field) if fieldValue? and _.isNumber parseFloat fieldValue newVal = parseFloat @model.get @field @$el.val(newVal).trigger('slide') changeInput: (value) => @model.set @field, parseFloat(value) or 0, {silent: true} (module?.exports = Tracktime.Element.Slider) or @Tracktime.Element.Slider = Tracktime.Element.Slider #<textarea class="form-control floating-label" placeholder="textarea floating label"></textarea> class Tracktime.Element.Textarea extends Tracktime.Element name: 'action_text' tagName: 'textarea' className: 'form-control floating-label' events: 'keydown': 'fixEnter' 'keyup': 'changeInput' 'change': 'changeInput' initialize: (options = {}) -> _.extend @, options @name = "#{@name}-#{@model.cid}" @render() @listenTo @model, "change:#{@field}", @changeField render: () -> @$el.attr 'name', @name @$el.attr 'placeholder', @placeholder @$el.val @model.get @field changeField: () => @$el.val(@model.get @field).trigger('input') changeInput: (event) => @model.set @field, $(event.target).val(), {silent: true} fixEnter: (event) => if event.keyCode == 13 and not event.shiftKey event.preventDefault() @trigger 'tSubmit' (module?.exports = Tracktime.Element.Textarea) or @Tracktime.Element.Textarea = Tracktime.Element.Textarea class Tracktime.GuestView extends Backbone.View container: '#panel' className: '' template: JST['global/guest'] views: {} initialize: -> @render() render: -> $(@container).html @$el.html @template @model.toJSON() @setSubView 'login', new Tracktime.GuestView.Login model: @model @setSubView 'signin', new Tracktime.GuestView.Signin model: @model @setSubView 'fopass', new Tracktime.GuestView.Fopass model: @model initUI: -> $.material.init() (module?.exports = Tracktime.AppView) or @Tracktime.AppView = Tracktime.AppView class Tracktime.GuestView.Fopass extends Backbone.View el: '#forgotpassword' events: 'click .btn-forgotpassword': 'forgotpasswordProcess' initialize: () -> forgotpasswordProcess: (event) -> event.preventDefault() $.alert 'fopass process' (module?.exports = Tracktime.GuestView.Fopass) or @Tracktime.GuestView.Fopass = Tracktime.GuestView.Fopass class Tracktime.GuestView.Login extends Backbone.View el: '#login > form' events: 'submit': 'loginProcess' initialize: () -> @listenTo @model.get('authUser'), 'flash', @showFlash loginProcess: (event) -> event.preventDefault() @model.get('authUser').login email: $('[name=email]',@$el).val() password: $('[name=password]',@$el).val() showFlash: (message) -> $.alert message.scope.capitalizeFirstLetter() + " Error: #{message.msg}" (module?.exports = Tracktime.GuestView.Login) or @Tracktime.GuestView.Login = Tracktime.GuestView.Login class Tracktime.GuestView.Signin extends Backbone.View el: '#signin > form' events: 'submit': 'signinProcess' initialize: () -> @listenTo @model.get('authUser'), 'flash', @showFlash signinProcess: (event) -> event.preventDefault() if @checkInput() @model.get('authUser').signin first_name: $('[name=first_name]',@$el).val() last_name: $('[name=last_name]',@$el).val() email: $('[name=email]',@$el).val() password: $('[name=password]',@$el).val() checkInput: -> result = true if _.isEmpty $('[name=first_name]',@$el).val() @showFlash scope: "Signin", msg: 'First Name empty' result = false if _.isEmpty $('[name=last_name]',@$el).val() @showFlash scope: "Signin", msg: 'Last Name empty' result = false if _.isEmpty $('[name=email]',@$el).val() @showFlash scope: "Signin", msg: 'Email empty' result = false if _.isEmpty $('[name=password]',@$el).val() @showFlash scope: "Signin", msg: 'Password empty' result = false if $('[name=password]',@$el).val() != $('[name=repassword]',@$el).val() @showFlash scope: "Signin", msg: 'Repassword incorrect' result = false result showFlash: (message) -> $.alert content: message.scope.capitalizeFirstLetter() + " Error: #{message.msg}" style: "btn-danger" (module?.exports = Tracktime.GuestView.Signin) or @Tracktime.GuestView.Signin = Tracktime.GuestView.Signin class Tracktime.AppView.Footer extends Backbone.View container: '#footer' template: JST['layout/footer'] events: 'click #click-me': 'clickMe' 'click #window-close': 'windowClose' initialize: () -> @render() render: () -> $(@container).html @$el.html @template @model?.toJSON() clickMe: (event) -> event.preventDefault() $.alert 'Subview :: ' + $(event.target).attr 'href' windowClose: (event) -> event.preventDefault() $.alert 'Close window' window.close() (module?.exports = Tracktime.AppView.Footer) or @Tracktime.AppView.Footer = Tracktime.AppView.Footer class Tracktime.AppView.Header extends Backbone.View container: '#header' template: JST['layout/header'] views: {} initialize: (options) -> @options = options @render() render: () -> $(@container).html @$el.html @template() @setSubView 'actions', new Tracktime.ActionsView collection: @model.get('actions') (module?.exports = Tracktime.AppView.Header) or @Tracktime.AppView.Header = Tracktime.AppView.Header class Tracktime.AppView.Main extends Backbone.View el: '#main' template: JST['layout/main'] views: {} initialize: () -> @render() @bindEvents() render: () -> @$el.html @template @model?.toJSON() @renderRecords() bindEvents: -> @listenTo @model.get('records'), "reset", @renderRecords renderRecords: -> recordsView = new Tracktime.RecordsView {collection: @model.get('records')} @$el.html recordsView.el (module?.exports = Tracktime.AppView.Main) or @Tracktime.AppView.Main = Tracktime.AppView.Main class Tracktime.AppView.Menu extends Backbone.View container: '#menu' template: JST['layout/menu'] searchStr: '' events: 'change #isOnline': 'updateOnlineStatus' initialize: -> @render() @bindEvents() @projects = Tracktime.AppChannel.request 'projects' @projectsList = Tracktime.AppChannel.request 'projectsList' @projects.on 'all', @renderMenuList bindEvents: -> @listenTo Tracktime.AppChannel, "isOnline", (status) -> $('#isOnline').prop 'checked', status @slideout = new Slideout 'panel': $('#panel')[0] 'menu': $('#menu')[0] 'padding': 256 'tolerance': 70 $("#menuToggler").on 'click', => @slideout.toggle() $(".input-search", @container).on 'keyup', @setSearch setSearch: (event) => @searchStr = $(event.currentTarget).val().toLowerCase() @searchProject() searchProject: (event) -> @renderSearchList() getSearchList: (limit = 5) -> @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList unless _.isEmpty @searchStr keys = _.filter keys, (key) => @projectsList[key].toLowerCase().indexOf(@searchStr) > -1 sublist = {} i = 0 limit = Math.min(limit, keys.length) while i < limit sublist[ keys[i] ] = @projectsList[ keys[i] ] i++ sublist renderMenuList: => menu = $('#projects-section .list-style-group', @container) menu.children('.project-link').remove() limit = 5 @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList if keys.length > 0 keys = _.sortBy keys, (key) => count = @projects.get(key).get('useCount') count = unless count == undefined then count else 0 - count i = 0 while i < limit project = @projects.get keys[i] menu.append $("<a class='list-group-item project-link' href='#records/project/#{project.id}'>#{project.get('name')}</a>").on 'click', 'a', @navTo i++ renderSearchList: => list = @getSearchList() menu = $('.menu-projects', @container) menu.children().remove() for own key, value of list menu.append $("<li><a href='#records/project/#{key}'>#{value}</a></li>").on 'click', 'a', @navTo if _.size(list) > 0 if _.isEmpty(@searchStr) menu.dropdown().hide() else menu.dropdown().show() else menu.dropdown().hide() navTo: (event) -> href = $(event.currentTarget).attr('href') projectId = href.substr(-24) Tracktime.AppChannel.command 'useProject', projectId window.location.hash = href $('.menu-projects', @container).dropdown().hide() updateOnlineStatus: (event) -> if $(event.target).is(":checked") Tracktime.AppChannel.command 'checkOnline' else Tracktime.AppChannel.command 'serverOffline' render: -> $(@container).html @$el.html @template @model?.toJSON() _.each @model.get('projects').models, (model) => projectLink = $('<a />', {class: 'list-group-item', href:"#projects/#{model.get('_id')}"}).html model.get('name') projectLink.appendTo "#projects-section .list-style-group" close: -> @slideout.close() super (module?.exports = Tracktime.AppView.Menu) or @Tracktime.AppView.Menu = Tracktime.AppView.Menu class Tracktime.AdminView.ProjectView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['projects/admin_project'] events: 'click .btn.delete': "deleteProject" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editProject" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:name", @changeName @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel attributes: -> id: @model.cid render: -> @$el.html @template @model.toJSON() $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'name' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:name' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeName: -> $('.subject', @$el).html (@model.get('name') + '').nl2br() $('.name_edit', @$el).val @model.get 'name' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update project' timeout: 2000 style: 'btn-info' editProject: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteProject: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete project' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.AdminView.ProjectView) or @Tracktime.AdminView.ProjectView = Tracktime.AdminView.ProjectView class Tracktime.ProjectView extends Backbone.View container: '#main' template: JST['projects/project'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Project Details View HERE'} (module?.exports = Tracktime.ProjectView) or @Tracktime.ProjectView = Tracktime.ProjectView class Tracktime.ProjectsView extends Backbone.View container: '#main' template: JST['projecs/projecs'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Projects HERE - Only view'} (module?.exports = Tracktime.ProjectsView) or @Tracktime.ProjectsView = Tracktime.ProjectsView class Tracktime.RecordView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['records/record'] events: 'click .btn.delete': "deleteRecord" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editRecord" 'click .btn[role=do-active]': "toggleActive" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:subject", @changeSubject @listenTo @model, "change:project", @changeProject @listenTo @model, "change:recordTime", @changeRecordTime @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel @listenTo @model, "isActive", @setActiveState @projects = Tracktime.AppChannel.request 'projects' @projects.on 'sync', @renderProjectInfo @users = Tracktime.AppChannel.request 'users' @users.on 'sync', @renderUserInfo attributes: -> id: @model.cid render: -> @$el.html @template _.extend {filter: @model.collection.getFilter()}, @model.toJSON() $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'subject' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm @$el.addClass 'current' if Tracktime.AppChannel.checkActive @model.id @changeRecordTime() @renderProjectInfo() @renderUserInfo() toggleActive: -> Tracktime.AppChannel.command 'activeRecord', @model, not(Tracktime.AppChannel.checkActive @model.id) setActiveState: (status) -> console.log 'try set acgive state', status, @$el $('.list-group-item').removeClass 'current' @$el.toggleClass 'current', status changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:subject' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeSubject: -> $('.subject', @$el).html (@model.get('subject') + '').nl2br() $('.subject_edit', @$el).val @model.get 'subject' changeRecordTime: -> duration = moment.duration(parseInt(@model.get('recordTime'), 10),'minute') durationStr = duration.get('hours') + ':' + duration.get('minutes') $('.recordTime .value', @$el).html durationStr changeProject: -> @renderProjectInfo() renderProjectInfo: => project_id = @model.get('project') @projectsList = Tracktime.AppChannel.request 'projectsList' if project_id of @projectsList title = @projectsList[project_id] $(".record-info-project span", @$el).html title $(".record-info-project", @$el).removeClass 'hidden' $(".btn.type i", @$el).removeClass().addClass('letter').html title.letter() else $(".record-info-project", @$el).addClass 'hidden' $(".btn.type i", @$el).removeClass().addClass('mdi-action-bookmark-outline').html '' renderUserInfo: => user_id = @model.get('user') @usersList = Tracktime.AppChannel.request 'usersList' if user_id of @usersList title = @usersList[user_id] $(".record-info-user span", @$el).html title $(".record-info-user", @$el).removeClass 'hidden' else $(".record-info-user", @$el).addClass 'hidden' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update record' timeout: 2000 style: 'btn-info' editRecord: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteRecord: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete record' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.RecordView) or @Tracktime.RecordView = Tracktime.RecordView class Tracktime.RecordsView extends Backbone.View container: '#main' template: JST['records/records'] tagName: 'ul' className: 'list-group' initialize: () -> @views = {} @render() @listenTo @collection, "sync", @resetRecordsList @listenTo @collection, "remove", @removeRecord # @listenTo @collection, "add", @addRecord @listenTo @collection, "newRecord", @newRecord $('.removeFilter', @container).on 'click', @removeFilter $('.btn-loadmore', @container).on 'click', @loadMoreRecords $('.scrollWrapper').on 'scroll', @autoLoadMoreRecords @projects = Tracktime.AppChannel.request 'projects' @projects.on 'sync', @updateProjectInfo @users = Tracktime.AppChannel.request 'users' @users.on 'sync', @updateUserInfo render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Records', filter: @collection.getFilter()} @resetRecordsList() @updateProjectInfo() @updateUserInfo() $('.btn-loadmore', @container).appendTo @container autoLoadMoreRecords: (event) => delta = $(window).height() - $('.btn-loadmore').offset().top - $('.btn-loadmore').height() $('.btn-loadmore', @container).click() if delta > 0 loadMoreRecords: (event) => modelsNewCount = @resetRecordsList() if modelsNewCount > 0 $('.btn-loadmore', @container).show().appendTo @container else $('.btn-loadmore', @container).remove() newRecord: (record) -> @addRecord(record) # @loadMoreRecords() # dateEl = moment(record.get('recordDate') ).format("YYYY-MM-DD") # if $("##{dateEl}").length > 0 # $('.scrollWrapper').scrollTop($("##{dateEl}").offset().top + $(".scrollWrapper").scrollTop() - 78) sortRecords: -> parentCont = '#main .list-group' sortedList = $('.list-group-item', parentCont).sort (a, b) -> timeA = new Date($('.record-info time', a).attr('datetime')).getTime() timeB = new Date($('.record-info time', b).attr('datetime')).getTime() timeB - timeA dates = $.unique($('.record-info time', parentCont).map((i, el) -> moment($(el).attr('datetime')).format("YYYY-MM-DD") )).sort (a, b) -> b > a _.each dates, (el, b) -> if $("##{el}").length < 1 $(parentCont).append $("<ul> /", {id: el}).append $("<li />", {class: 'list-group-items-group navbar navbar-primary'}).html moment(el).format("Do MMMM YYYY") _.each sortedList, (item) -> id = moment($('.record-info time', item).attr('datetime')).format("YYYY-MM-DD") $("##{id}", parentCont).append item resetRecordsList_old: -> frag = document.createDocumentFragment() models = @collection.getModels @exceptRecords() _.each models, (record) -> recordView = @setSubView "record-#{record.cid}", new Tracktime.RecordView model: record frag.appendChild recordView.el , @ @$el.prepend frag @sortRecords() resetRecordsList: -> parentCont = '#main .list-group' models = @collection.getModels @exceptRecords() _.each models, (record) -> recordView = @setSubView "record-#{record.cid}", new Tracktime.RecordView model: record @listGroup(record).append recordView.el , @ models.length listGroup: (record) -> parentCont = '#main .list-group' # получить дату группы из модели groupDate = moment(record.get('recordDate')).format("YYYY-MM-DD") group = null # если группа существует то вернуть ев jquery if $("##{groupDate}").length > 0 group = $("##{groupDate}") # иначе else # создать группу с заголовком group = $("<ul> /", {id: groupDate}).append $("<li />", {class: 'list-group-items-group navbar navbar-primary'}).html moment(groupDate).format("Do MMMM YYYY") # если списков нет то добавить группу просто if $(".list-group > ul", parentCont).length < 1 $(parentCont).append group # иначе else # получить массив id групп - добавить в него новый элемент # отсортировать по убыыванию groups = $("ul.list-group > ul").map( (idx, el) -> $(el).attr('id') ) groups.push groupDate groups = groups.sort( (a, b) -> b > a ) # получить индекс в массиве groupIndex = _. indexOf groups, groupDate # если индекс равен длине массива то добавить группу в конец # иначе если индекс равен 0 массива то добавить группу в начало if groupIndex == 0 $(parentCont).prepend group # если есть предыдущий искомому элемент полученный по индексу то добавть ul после предыдушего else prevIndexGroup = groups[groupIndex - 1] $("##{prevIndexGroup}").after group group exceptRecords: () -> _.pluck $('.list-group-item > div', @container), 'id' updateProjectInfo: -> @projectsList = Tracktime.AppChannel.request 'projectsList' key = $('.removeFilter[data-exclude=project]', @container).data('value') if key of @projectsList $('.removeFilter[data-exclude=project] .caption', @container).text @projectsList[key] updateUserInfo: -> @usersList = Tracktime.AppChannel.request 'usersList' key = $('.removeFilter[data-exclude=user]', @container).data('value') if key of @usersList $('.removeFilter[data-exclude=user] .caption', @container).text @usersList[key] addRecord: (record, collection, params) -> # add record - depricated if record.isSatisfied @collection.filter recordView = new Tracktime.RecordView { model: record } $(recordView.el).insertAfter $('.list-group-items-group', @listGroup(record)) $('.btn[role="do-active"]', recordView.el).click() # @setSubView "record-#{record.cid}", recordView removeFilter: (event) => key = $(event.currentTarget).data('exclude') # remove key from collection filter @collection.removeFilter key # remove all records from list @$el.find('.list-group > li').remove() # refresh filter list in header $(event.currentTarget).remove() # add records by filter from collection @resetRecordsList() removeRecord: (record, args...) -> recordView = @getSubView "record-#{record.cid}" recordView.close() if recordView (module?.exports = Tracktime.RecordsView) or @Tracktime.RecordsView = Tracktime.RecordsView class Tracktime.ReportView extends Backbone.View container: '#main' template: JST['reports/report'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Report Details HERE'} (module?.exports = Tracktime.ReportView) or @Tracktime.ReportView = Tracktime.ReportView class Tracktime.ReportsView extends Backbone.View container: '#main' template: JST['reports/reports'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Reports HERE'} (module?.exports = Tracktime.ReportsView) or @Tracktime.ReportsView = Tracktime.ReportsView class Tracktime.AdminView.UserView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['users/admin_user'] events: 'click .btn.delete': "deleteUser" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editUser" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:first_name", @changeName @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel attributes: -> id: @model.cid render: -> data = _.extend {}, @model.toJSON(), hash: window.md5 @model.get('email').toLowerCase() @$el.html @template data $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'first_name' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:first_name' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeName: -> $('.subject', @$el).html (@model.get('first_name') + '').nl2br() $('.name_edit', @$el).val @model.get 'first_name' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update user' timeout: 2000 style: 'btn-info' editUser: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteUser: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete user' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.AdminView.UserView) or @Tracktime.AdminView.UserView = Tracktime.AdminView.UserView class Tracktime.UserView extends Backbone.View container: '#main' template: JST['users/user'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User index'} (module?.exports = Tracktime.UserView) or @Tracktime.UserView = Tracktime.UserView class Tracktime.UserView.Details extends Backbone.View container: '#main' template: JST['users/details'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User details HERE'} (module?.exports = Tracktime.UserView.Details) or @Tracktime.UserView.Details = Tracktime.UserView.Details class Tracktime.UserView.Rates extends Backbone.View container: '#main' template: JST['users/rates'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User Rates'} (module?.exports = Tracktime.UserView.Rates) or @Tracktime.UserView.Rates = Tracktime.UserView.Rates $ -> Tracktime.AppChannel.init().command 'start' return class Tracktime.AdminRouter extends Backbone.SubRoute routes: '': 'dashboard' 'users': 'users' 'projects': 'projects' 'dashboard': 'dashboard' 'actions': 'actions' initialize: (options) -> _.extend @, options dashboard: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.Dashboard() users: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.UsersView collection: @parent.model.get 'users' newAction = @parent.model.get('actions').addAction title: 'Add users' type: 'User' , scope: 'admin:users' newAction.setActive() projects: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.ProjectsView collection: @parent.model.get 'projects' newAction = @parent.model.get('actions').addAction title: 'Add projects' type: 'Project' , scope: 'admin:projects' newAction.setActive() actions: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.ActionsView collection: @parent.model.get 'actions' (module?.exports = Tracktime.AdminRouter) or @Tracktime.AdminRouter = Tracktime.AdminRouter class Tracktime.AppRouter extends Backbone.Router routes: '': 'index' #index 'projects*subroute': 'invokeProjectsRouter' #Projects 'records*subroute': 'invokeRecordsRouter' #Projects 'reports*subroute': 'invokeReportsRouter' #Reports 'user*subroute': 'invokeUserRouter' #User 'admin*subroute': 'invokeAdminRouter' #Admin '*actions': 'default' #??? initialize: (options) -> _.extend @, options @on 'route', (route, params) => @removeActionsExcept(route) unless route.substr(0,6) == 'invoke' @initInterface() # @navigate 'projects', trigger: true, replace: false Backbone.history.loadUrl(Backbone.history.fragment); addListener: (subroute, scope) -> @listenTo subroute, 'route', (route, params) => @removeActionsExcept "#{scope}:#{route}" invokeProjectsRouter: (subroute) -> unless @projectsRouter @projectsRouter = new Tracktime.ProjectsRouter 'projects', parent: @ @addListener @projectsRouter, 'projects' invokeRecordsRouter: (subroute) -> unless @recordsRouter @recordsRouter = new Tracktime.RecordsRouter 'records', parent: @ @addListener @recordsRouter, 'records' invokeReportsRouter: (subroute) -> unless @reportsRouter @reportsRouter = new Tracktime.ReportsRouter 'reports', parent: @ @addListener @reportsRouter, 'reports' invokeUserRouter: (subroute) -> unless @userRouter @userRouter = new Tracktime.UserRouter 'user', parent: @ @addListener @userRouter, 'users' invokeAdminRouter: (subroute) -> unless @adminRouter @adminRouter = new Tracktime.AdminRouter 'admin', parent: @ @addListener @adminRouter, 'admin' initInterface: () -> @view = new Tracktime.AppView model: @model @view.setSubView 'header', new Tracktime.AppView.Header model: @model @view.setSubView 'footer', new Tracktime.AppView.Footer() @view.setSubView 'menu', new Tracktime.AppView.Menu model: @model @view.initUI() index: -> # @navigate 'projects', trigger: true, replace: false default: (actions) -> $.alert 'Unknown page' @navigate '', true removeActionsExcept: (route) -> if @model.get('actions') _.each @model.get('actions').models, (action) -> action.destroy() if action && action.has('scope') and action.get('scope') isnt route (module?.exports = Tracktime.AppRouter) or @Tracktime.AppRouter = Tracktime.AppRouter class Tracktime.GuestRouter extends Backbone.Router routes: '': 'index' #index '*actions': 'default' #??? initialize: (options) -> _.extend @, options @initInterface() # @navigate '/', trigger: true, replace: false Backbone.history.loadUrl(Backbone.history.fragment); initInterface: () -> @view = new Tracktime.GuestView model: @model # @view.setSubView 'header', new Tracktime.GuestView.Header model: @model # @view.setSubView 'footer', new Tracktime.AppView.Footer() # @view.setSubView 'menu', new Tracktime.AppView.Menu model: @model @view.initUI() index: -> # $.alert 'Guest index page' default: (actions) -> # $.alert 'Unknown guest page' @navigate '', true (module?.exports = Tracktime.GuestRouter) or @Tracktime.GuestRouter = Tracktime.GuestRouter class Tracktime.ProjectsRouter extends Backbone.SubRoute routes: '': 'list' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options list: () -> $.alert "whole records list in projects section" @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' details: (id) -> @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' edit: (id) -> $.alert "projects edit #{id}" delete: (id) -> $.alert "projects delete #{id}" add: (id) -> $.alert "projects add #{id}" save: (id) -> $.alert "projects save #{id}" (module?.exports = Tracktime.ProjectsRouter) or @Tracktime.ProjectsRouter = Tracktime.ProjectsRouter class Tracktime.RecordsRouter extends Backbone.SubRoute routes: '': 'list' '*filter': 'listFilter' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options list: () -> collection = @parent.model.get 'records' collection.resetFilter() @parent.view.setSubView 'main', new Tracktime.RecordsView collection: collection listFilter: (filter) -> collection = @parent.model.get 'records' collection.setFilter filter @parent.view.setSubView 'main', new Tracktime.RecordsView collection: collection details: (id) -> $.alert "details" @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' edit: (id) -> $.alert "records edit #{id}" delete: (id) -> $.alert "records delete #{id}" add: (id) -> $.alert "records add #{id}" save: (id) -> $.alert "records save #{id}" (module?.exports = Tracktime.RecordsRouter) or @Tracktime.RecordsRouter = Tracktime.RecordsRouter class Tracktime.ReportsRouter extends Backbone.SubRoute routes: '': 'list' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options @parent.view.setSubView 'main', new Tracktime.ReportsView() list: () -> @parent.view.setSubView 'main', new Tracktime.ReportsView() details: (id) -> @parent.view.setSubView 'main', new Tracktime.ReportView() edit: (id) -> $.alert "reports edit #{id}" delete: (id) -> $.alert "reports delete #{id}" add: (id) -> $.alert "reports add #{id}" save: (id) -> $.alert "reports save #{id}" (module?.exports = Tracktime.ReportsRouter) or @Tracktime.ReportsRouter = Tracktime.ReportsRouter class Tracktime.UserRouter extends Backbone.SubRoute routes: '': 'details' 'rates': 'rates' 'logout': 'logout' initialize: (options) -> _.extend @, options # @parent.view.setSubView 'main', new Tracktime.UserView() details: () -> @parent.view.setSubView 'main', new Tracktime.UserView.Details() rates: () -> @parent.view.setSubView 'main', new Tracktime.UserView.Rates() logout: () -> @parent.model.get('authUser').logout() (module?.exports = Tracktime.UserRouter) or @Tracktime.UserRouter = Tracktime.UserRouter
116251
process = process or window.process or {} production = SERVER: 'https://ttpms.herokuapp.com' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' test = SERVER: 'http://localhost:5000' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' development = SERVER: 'http://localhost:5000' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' switch process.env?.NODE_ENV when 'production' config = production when 'test' config = test else config = development (module?.exports = config) or @config = config class Tracktime extends Backbone.Model urlRoot: config.SERVER defaults: title: 'TrackTime App' authUser: null initialize: () -> @set 'authUser', new Tracktime.User.Auth() @listenTo @get('authUser'), 'change:authorized', @changeUserStatus @listenTo @get('authUser'), 'destroy', -> @set 'authUser', new Tracktime.User.Auth() @listenTo @get('authUser'), 'change:authorized', @changeUserStatus initCollections: -> @set 'users', new Tracktime.UsersCollection() @set 'records', new Tracktime.RecordsCollection() @set 'projects', new Tracktime.ProjectsCollection() @set 'actions', new Tracktime.ActionsCollection() @listenTo Tracktime.AppChannel, "isOnline", @updateApp unsetCollections: -> @unset 'users' @unset 'actions' @unset 'records' @unset 'projects' @stopListening Tracktime.AppChannel, "isOnline" updateApp: -> @get('users').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' @get('projects').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' @get('records').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' changeUserStatus: -> @setUsetStatus @get('authUser').get('authorized') setUsetStatus: (status) -> if status == true @initCollections() Tracktime.AppChannel.command 'userAuth' else @unsetCollections() Tracktime.AppChannel.command 'userGuest' (module?.exports = Tracktime) or @Tracktime = Tracktime class Tracktime.AdminView extends Backbone.View el: '#panel' className: '' template: JST['admin/index'] views: {} initialize: -> @render() render: -> # $(document).title @model.get 'title' @$el.html @template() initUI: -> $.material.init() (module?.exports = Tracktime.AdminView) or @Tracktime.AdminView = Tracktime.AdminView do -> proxiedSync = Backbone.sync Backbone.sync = (method, model, options) -> options or (options = {}) if !options.crossDomain options.crossDomain = true if !options.xhrFields options.xhrFields = withCredentials: true proxiedSync method, model, options return Backbone.Validation.configure # selector: 'class_v' # labelFormatter: 'label_v' # attributes: 'inputNames' # returns the name attributes of bound view input elements # forceUpdate: true _.extend Backbone.Model.prototype, Backbone.Validation.mixin Backbone.ViewMixin = close: () -> @onClose() if @onClose if @container? $(@container).unbind() @undelegateEvents() @$el.removeData().unbind() @remove() Backbone.View.prototype.remove.call @ return onClose: -> for own key, view of @views view.close() delete @views[key] clear: -> @onClose() setSubView: (key, view) -> @views[key].close() if key of @views @views[key] = view getSubView: (key) -> @views[key] if key of @views Backbone.View.prototype extends Backbone.ViewMixin Handlebars.registerHelper 'link_to', (options) -> attrs = href: '' for own key, value of options.hash if key is 'body' body = Handlebars.Utils.escapeExpression value else attrs[key] = Handlebars.Utils.escapeExpression value new (Handlebars.SafeString) $("<a />", attrs).html(body)[0].outerHTML Handlebars.registerHelper 'safe_val', (value, safeValue) -> out = value || safeValue new Handlebars.SafeString(out) Handlebars.registerHelper 'nl2br', (text) -> text = Handlebars.Utils.escapeExpression text new Handlebars.SafeString text.nl2br() Handlebars.registerHelper 'dateFormat', (date) -> moment = window.moment localeData = moment.localeData('ru') moment(date).format("MMM Do YYYY") # timestamp = Date.parse date # unless _.isNaN(timestamp) # (new Date(timestamp)).toLocalString() # else # new Date() Handlebars.registerHelper 'minuteFormat', (val) -> duration = moment.duration val,'minute' duration.get('hours') + ':' + duration.get('minutes') # currentHour = val / 720 * 12 # hour = Math.floor(currentHour) # minute = Math.round((currentHour - hour) * 60) # "hb: #{hour}:#{minute}" Handlebars.registerHelper 'placeholder', (name) -> placeholder = "<placeholder id='#{name}'></placeholder>" new Handlebars.SafeString placeholder Handlebars.registerHelper 'filteredHref', (options) -> parsedFilter = {} _.extend(parsedFilter, options.hash.filter) if 'filter' of options.hash _.extend(parsedFilter, {user: options.hash.user}) if 'user' of options.hash _.extend(parsedFilter, {project: options.hash.project}) if 'project' of options.hash delete parsedFilter[options.hash.exclude] if 'exclude' of options.hash and options.hash.exclude of parsedFilter if _.keys(parsedFilter).length > 0 '/' + _.map(parsedFilter, (value,key) -> "#{key}/#{value}").join '/' else '' (($) -> snackbarOptions = content: '' style: '' timeout: 2000 htmlAllowed: true $.extend ( alert: (params) -> if _.isString params snackbarOptions.content = params else snackbarOptions = $.extend {},snackbarOptions,params $.snackbar snackbarOptions ) ) jQuery String::capitalizeFirstLetter = -> @charAt(0).toUpperCase() + @slice(1) String::nl2br = -> (@ + '').replace /([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2' String::letter = -> @charAt(0).toUpperCase() class Tracktime.Collection extends Backbone.Collection addModel: (params, options) -> newModel = new @model params if newModel.isValid() @add newModel unless options.ajaxSync? options.ajaxSync = Tracktime.AppChannel.request 'isOnline' newModel.save {}, options else $.alert 'Erros validation from add curModel to collection' fetch: (options) -> @resetLocalStorage() if options? and options.ajaxSync == true _success = options.success options.success = (collection, response, optionsSuccess) => @syncCollection(response) _success.apply(@, collection, response, options) if _.isFunction(_success) super options syncCollection: (models) -> # по всем remote model которые вроде как в коллекции уже _.each models, (model) => curModel = @get(model._id) localModel = @localStorage.find curModel # если нет локальной то сохраняем (локально) unless localModel curModel.save ajaxSync: false # иначе else # если локальная старее то обновляем с новых данных (локально) modelUpdatetAt = (new Date(model.updatedAt)).getTime() localUpdatetAt = (new Date(localModel.updatedAt)).getTime() if localModel.isDeleted # do nothing curModel.set {'isDeleted': true}, {trigger: false} else if localUpdatetAt < modelUpdatetAt curModel.save model, ajaxSync: false # иначе есть если локальная новее то else if localUpdatetAt > modelUpdatetAt # обновляем модель пришедшую в коллекции # сохраняем ее удаленно curModel.save localModel, ajaxSync: true # по всем local моделям localModels = @localStorage.findAll() _.each _.clone(localModels), (model) => collectionModel = @get(model._id) # если удалена if model.isDeleted if model._id.length > 24 destroedModel = new @model {_id: model._id, subject: 'model to delete'} destroedModel.destroy ajaxSync: false else modelUpdatetAt = (new Date(model.updatedAt)).getTime() if collectionModel? and modelUpdatetAt > (new Date(collectionModel.get('updatedAt'))).getTime() destroedModel = collectionModel else destroedModel = new @model (model) # то удаляем локально и удаленно # и из коллекции если есть destroedModel.destroy ajaxSync: true else # если нет в коллекции unless collectionModel replacedModel = new @model {_id: model._id} replacedModel.fetch {ajaxSync: false} newModel = replacedModel.toJSON() delete newModel._id # то сохраняем ее удаленно # добавляем в коллекцию @addModel newModel, success: (model, response) => # заменяем на новосохраненную replacedModel.destroy {ajaxSync: false} resetLocalStorage: () -> @localStorage = new Backbone.LocalStorage @collectionName (module?.exports = Tracktime.Collection) or @Tracktime.Collection = Tracktime.Collection class Tracktime.Model extends Backbone.Model sync: (method, model, options) -> options = options or {} switch method when 'create' if options.ajaxSync _success = options.success _model = model.clone() options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success _model.id = model._id _model.set '_id', model._id Backbone.sync method, _model, options Backbone.sync method, model, options when 'read' Backbone.sync method, model, options when 'patch' Backbone.sync method, model, options when 'update' if options.ajaxSync _success = options.success _model = model options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success Backbone.sync method, _model, options Backbone.sync method, model, options when 'delete' if options.ajaxSync == true model.save {'isDeleted': true}, {ajaxSync: false} _success = options.success _model = model options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success Backbone.sync method, _model, options Backbone.sync method, model, options else Backbone.sync method, model, options else $.alert "unknown method #{method}" Backbone.sync method, model, options class Tracktime.Action extends Backbone.Model idAttribute: "_id" collectionName: config.collection.actions url: '/actions' #receive on activate actions for user (!) defaults: _id: null title: 'Default action' isActive: null isVisible: false canClose: false attributes: () -> id: @model.cid setActive: () -> @collection.setActive @ processAction: (options) -> $.alert 'Void Action' (module?.exports = Tracktime.Action) or @Tracktime.Action = Tracktime.Action class Tracktime.Action.Project extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add project' projectModel: null formAction: '#' btnClass: 'btn-material-purple' btnClassEdit: 'btn-material-blue' navbarClass: 'navbar-inverse' icon: className: 'mdi-content-add-circle' classNameEdit: 'mdi-content-add-circle-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'projectModel', new Tracktime.Project() unless @get('projectModel') instanceof Tracktime.Project processAction: () -> projectModel = @get 'projectModel' if projectModel.isValid() if projectModel.isNew() Tracktime.AppChannel.command 'newProject', projectModel.toJSON() projectModel.clear().set(projectModel.defaults) else projectModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'Project: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('projectModel').isEdit = false @get('projectModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.Project) or @Tracktime.Action.Project = Tracktime.Action.Project class Tracktime.Action.Record extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add record' recordModel: null formAction: '#' btnClass: 'btn-material-green' btnClassEdit: 'btn-material-lime' navbarClass: 'navbar-primary' icon: className: 'mdi-action-bookmark' classNameEdit: 'mdi-action-bookmark-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'recordModel', new Tracktime.Record() unless @get('recordModel') instanceof Tracktime.Record processAction: () -> recordModel = @get 'recordModel' if recordModel.isValid() if recordModel.isNew() Tracktime.AppChannel.command 'newRecord', recordModel.toJSON() recordModel.clear().set(recordModel.defaults) else recordModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'Record: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('recordModel').isEdit = false @get('recordModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.Record) or @Tracktime.Action.Record = Tracktime.Action.Record class Tracktime.Action.Search extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Search' formAction: '#' btnClass: 'btn-white' btnClassEdit: 'btn-white' navbarClass: 'navbar-material-light-blue' icon: className: 'mdi-action-search' classNameEdit: 'mdi-action-search' letter: '' isActive: null isVisible: true initialize: (options = {}) -> @set options processAction: (options) -> @search() search: () -> $.alert 'search start' (module?.exports = Tracktime.Action.Search) or @Tracktime.Action.Search = Tracktime.Action.Search class Tracktime.Action.User extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add user' userModel: null formAction: '#' btnClass: 'btn-material-deep-orange' btnClassEdit: 'btn-material-amber' navbarClass: 'navbar-material-yellow' icon: className: 'mdi-social-person' classNameEdit: 'mdi-social-person-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'userModel', new Tracktime.User() unless @get('userModel') instanceof Tracktime.User processAction: () -> userModel = @get 'userModel' if userModel.isValid() if userModel.isNew() Tracktime.AppChannel.command 'newUser', userModel.toJSON() userModel.clear().set(userModel.defaults) else userModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'User: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('userModel').isEdit = false @get('userModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.User) or @Tracktime.Action.User = Tracktime.Action.User class Tracktime.Project extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.projects urlRoot: config.SERVER + '/' + 'projects' localStorage: new Backbone.LocalStorage 'projects' defaults: _id: null name: '' description: '' updatedAt: (new Date()).toISOString() isDeleted: false validation: name: required: true minLength: 4 msg: 'Please enter a valid name' initialize: -> @isEdit = false @on 'change:name', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: () -> # @todo add good validation true updateUpdatedAt: () -> @set 'updatedAt', (new Date()).toISOString() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit project', type: 'Project', canClose: true}, title: 'Edit project: ' + @get('name').substr(0, 40) projectModel: @ scope: 'edit:action' (module?.exports = Tracktime.Project) or @Tracktime.Project = Tracktime.Project class Tracktime.Record extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.records urlRoot: config.SERVER + '/' + 'records' localStorage: new Backbone.LocalStorage 'records' defaults: _id: null subject: '' description: '' date: () -> (new Date()).toISOString() updatedAt: (new Date()).toISOString() recordDate: '' recordTime: 0 project: 0 user: 0 isDeleted: false validation: subject: required: true minLength: 4 msg: 'Please enter a valid subject' initialize: -> @isEdit = false @on 'change:subject change:recordTime change:recordDate change:project', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: -> # @todo add good validation true isSatisfied: (filter) -> _.isMatch @attributes, filter updateUpdatedAt: () -> @set 'updatedAt', new Date() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit record', type: 'Record', canClose: true}, title: 'Edit record: ' + @get('subject').substr(0, 40) recordModel: @ scope: 'edit:action' addTime: (diff) -> time = parseInt @get('recordTime'), 10 @set 'recordTime', (time + diff) @save {}, ajaxSync: true (module?.exports = Tracktime.Record) or @Tracktime.Record = Tracktime.Record class Tracktime.User extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.users urlRoot: config.SERVER + '/' + 'users' localStorage: new Backbone.LocalStorage 'users' defaults: _id: null first_name: '' last_name: '' email: '' password: '' description: '' default_pay_rate: '' updatedAt: (new Date()).toISOString() activeRecord: '' startedAt: null isDeleted: false validation: first_name: required: true minLength: 4 msg: 'Please enter a valid first_name' initialize: -> @isEdit = false @on 'change:first_name', @updateUpdatedAt @on 'change:last_name', @updateUpdatedAt @on 'change:description', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: () -> # @todo add good validation true updateUpdatedAt: () -> @set 'updatedAt', (new Date()).toISOString() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit user', type: 'User', canClose: true}, title: 'Edit user: ' + @get('first_name').substr(0, 40) userModel: @ scope: 'edit:action' (module?.exports = Tracktime.User) or @Tracktime.User = Tracktime.User class Tracktime.User.Auth extends Backbone.Model idAttribute: "_id" urlRoot: config.SERVER + '/' + '' defaults: authorized: null initialize: -> @fetch ajaxSync: true url: config.SERVER + '/auth_user' success: (model, response, options) => @set 'authorized', true error: (model, response, options) => @set 'authorized', false login: (params) -> @save params, ajaxSync: true url: config.SERVER + '/login' success: (model, response, options) => @set response @set 'authorized', true $.alert "Welcome back, #{response.first_name} #{response.last_name}!" window.location.hash = '#records' error: (model, response, options) => if response.responseJSON? @trigger 'flash', response.responseJSON.error else @trigger 'flash', scope: "unknown" msg: 'Send request error' signin: (params) -> _.extend params, status: 'active' k_status: 'active' updatedAt: (new Date()).toISOString() isDeleted: 'false' @save params, ajaxSync: true url: config.SERVER + '/register' success: (model, response, options) => @set response @set 'authorized', true $.alert "Welcome, #{response.name} !" error: (model, response, options) => @trigger 'flash', response.responseJSON.error forgotpasswrod: -> fullName: -> "#{@get('first_name')} #{@get('last_name')}" logout: -> $.alert "Goodbay, #{@fullName()}!" @set 'authorized', false @destroy ajaxSync: true url: config.SERVER + '/logout/' + @id success: (model, response, options) => window.location.href = '#' window.location.reload() error: (model, response, options) => console.log 'logout error' setActiveRecord: (record, status) -> if @get('activeRecord') Tracktime.AppChannel.command 'addTime', @get('activeRecord'), @get('startedAt') if status params = activeRecord: record.id startedAt: (new Date()).toISOString() else params = activeRecord: '' startedAt: null @save params, ajaxSync: true url: config.SERVER + '/users/' + @id success: (model, response, options) => record.trigger 'isActive', status error: (model, response, options) => @trigger 'flash', response.responseJSON.error (module?.exports = Tracktime.User.Auth) or @Tracktime.User.Auth = Tracktime.User.Auth class Tracktime.ActionsCollection extends Backbone.Collection model: Tracktime.Action collectionName: config.collection.actions url: '/actions' localStorage: new Backbone.LocalStorage @collectionName defaultActions: [ { title: 'Add Record', type: 'Record' } { title: 'Search', type: 'Search' } ] active: null initialize: -> @on 'remove', @setDefaultActive _.each @defaultActions, @addAction addAction: (action, params = {}) => @push new Tracktime.Action[action.type] _.extend action, params if (Tracktime.Action[action.type]) setDefaultActive: -> @at(0).setActive() unless @findWhere isActive: true setActive: (active) -> @active?.set 'isActive', false active.set 'isActive', true @active = active @trigger 'change:active', @active getActive: -> @active getActions: -> _.filter @models, (model) -> model.get('isVisible') (module?.exports = Tracktime.ActionsCollection) or @Tracktime.ActionsCollection = Tracktime.ActionsCollection class Tracktime.ProjectsCollection extends Tracktime.Collection model: Tracktime.Project collectionName: config.collection.projects url: config?.SERVER + '/projects' urlRoot: config?.SERVER + '/projects' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @on 'sync', @makeList comparator: (model) -> - (new Date(model.get('date'))).getTime() addProject: (options) -> _.extend options, {date: (new Date()).toISOString()} success = (result) => $.alert content: 'Project: save success' timeout: 2000 style: 'btn-success' error = () => $.alert 'Project: save error' @addModel options, success: success, error: error makeList: -> list = {} _.each @models, (model, index) -> list[model.get('_id')] = model.get('name') Tracktime.AppChannel.reply 'projectsList', () -> list useProject: (id) -> project = @get(id) if project.has('useCount') useCount = project.get('useCount') + 1 else useCount = 1 project.save {'useCount': useCount}, {ajaxSync: false} (module?.exports = Tracktime.ProjectsCollection) or @Tracktime.ProjectsCollection = Tracktime.ProjectsCollection class Tracktime.RecordsCollection extends Tracktime.Collection model: Tracktime.Record collectionName: config.collection.records url: config?.SERVER + '/records' urlRoot: config?.SERVER + '/records' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @filter = {} @defaultFilter = isDeleted: false comparator: (model) -> - (new Date(model.get('date'))).getTime() setFilter: (filter) -> @resetFilter() unless filter == null pairs = filter.match(/((user|project)\/[a-z0-9A-Z]{24})+/g) if pairs _.each pairs, (pair, index) -> _p = pair.split '/' @filter[_p[0]] = _p[1] , @ @filter resetFilter: -> @filter = _.clone @defaultFilter removeFilter: (key) -> if key of @filter delete @filter[key] getFilter: (removeDefault = true) -> result = {} if removeDefault keys = _.keys @defaultFilter result = _.omit @filter, keys else result = @filter result addRecord: (options) -> _.extend options, {date: (new Date()).toISOString()} options.recordDate = (new Date()).toISOString() if _.isEmpty(options.recordDate) success = (result) => $.alert content: 'Record: save success' timeout: 2000 style: 'btn-success' @trigger 'newRecord', result error = () => $.alert 'Record: save error' @addModel options, success: success, error: error getModels: (except = []) -> models = {} limit = 6 if @length > 0 models = _.filter @models, (model) => model.isSatisfied @filter models = _.filter models, (model) -> _.indexOf(except, model.id) == -1 _.first models, limit (module?.exports = Tracktime.RecordsCollection) or @Tracktime.RecordsCollection = Tracktime.RecordsCollection class Tracktime.UsersCollection extends Tracktime.Collection model: Tracktime.User collectionName: config.collection.users url: config?.SERVER + '/users' urlRoot: config?.SERVER + '/users' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @on 'sync', @makeList addUser: (options) -> _.extend options, {date: (new Date()).toISOString()} success = (result) => $.alert content: 'User: save success' timeout: 2000 style: 'btn-success' error = () => $.alert 'User: save error' @addModel options, success: success, error: error makeList: (collection, models) -> list = {} _.each collection.models, (model, index) -> list[model.get('_id')] = "#{model.get('first_name')} #{model.get('last_name')}" Tracktime.AppChannel.reply 'usersList', () -> list (module?.exports = Tracktime.UsersCollection) or @Tracktime.UsersCollection = Tracktime.UsersCollection Tracktime.AppChannel = Backbone.Radio.channel 'app' _.extend Tracktime.AppChannel, isOnline: null userStatus: null router: null init: -> @on 'isOnline', (status) => @isOnline = status @on 'userStatus', (status) => @changeUserStatus status @checkOnline() @setWindowListeners() @model = new Tracktime() @bindComply() @bindRequest() return @ checkOnline: -> if window.navigator.onLine == true @checkServer() else @trigger 'isOnline', false checkServer: -> deferred = $.Deferred() serverOnlineCallback = (status) => @trigger 'isOnline', true successCallback = (result) => @trigger 'isOnline', true deferred.resolve() errorCallback = (jqXHR, textStatus, errorThrown) => @trigger 'isOnline', false deferred.resolve() try $.ajax url: "#{config.SERVER}/status" async: false dataType: 'jsonp' jsonpCallback: 'serverOnlineCallback' success: successCallback error: errorCallback catch exception_var @trigger 'isOnline', false return deferred.promise() setWindowListeners: -> window.addEventListener "offline", (e) => @trigger 'isOnline', false , false window.addEventListener "online", (e) => @checkServer() , false bindComply: -> @comply 'start': @startApp 'newRecord': @newRecord 'newProject': @newProject 'newUser': @newUser 'useProject': @useProject 'addAction': @addAction 'serverOnline': @serverOnline 'serverOffline': @serverOffline 'checkOnline': @checkOnline 'userAuth': @userAuth 'userGuest': @userGuest 'activeRecord': @activeRecord 'addTime': @addTime bindRequest: -> @reply 'isOnline', => @isOnline @reply 'userStatus', => @userStatus @reply 'projects', => @model.get 'projects' @reply 'users', => @model.get 'users' @reply 'projectsList', => {} @reply 'usersList', => {} startApp: -> Backbone.history.start pushState: false newRecord: (options) -> _.extend options, user: @model.get('authUser').id @model.get('records').addRecord(options) newProject: (options) -> @model.get('projects').addProject(options) newUser: (options) -> @model.get('users').addUser(options) addAction: (options, params) -> action = @model.get('actions').addAction(options, params) action.setActive() activeRecord: (record, status) -> @model.get('authUser').setActiveRecord record, status addTime: (record, start) -> # diff = moment(new Date()) - moment(new Date(start)) record = @model.get('records').get(record) if record instanceof Tracktime.Record record.addTime moment(new Date()).diff(new Date(start), 'second') serverOnline: -> @trigger 'isOnline', true useProject: (id) -> @model.get('projects').useProject id serverOffline: -> @trigger 'isOnline', false userAuth: -> @trigger 'userStatus', true userGuest: -> @trigger 'userStatus', false changeUserStatus: (status) -> # @todo here get user session - if success status true else false if @router != null @router.view.close() delete @router.view if status == true @router = new Tracktime.AppRouter model: @model @trigger 'isOnline', @isOnline else @router = new Tracktime.GuestRouter model: @model checkActive: (id) -> id == @model.get('authUser').get('activeRecord') (module?.exports = Tracktime.AppChannel) or @Tracktime.AppChannel = Tracktime.AppChannel class Tracktime.ActionView extends Backbone.View tagName: 'li' className: 'btn' events: 'click a': 'setActive' initialize: () -> # _.bindAll @model, 'change:isActive', @update setActive: () -> @model.setActive() (module?.exports = Tracktime.ActionView) or @Tracktime.ActionView = Tracktime.ActionView class Tracktime.ActionsView extends Backbone.View el: '#actions-form' menu: '#actions-form' template: JST['actions/actions'] views: {} initialize: (options) -> _.extend @, options @listenTo @collection, 'change:active', @renderAction @listenTo @collection, 'add', @addAction @render() render: () -> @$el.html @template() @menu = $('.dropdown-menu', '.select-action', @$el) _.each @collection.getActions(), @addAction @collection.at(0).setActive() addAction: (action) => listBtn = new Tracktime.ActionView.ListBtn model: action @menu.append listBtn.$el @setSubView "listBtn-#{listBtn.cid}", listBtn $('[data-toggle="tooltip"]', listBtn.$el).tooltip() renderAction: (action) -> if Tracktime.ActionView[action.get('type')] @$el.parents('.navbar').attr 'class', "navbar #{action.get('navbarClass')} shadow-z-1" @setSubView "actionDetails", new Tracktime.ActionView[action.get('type')] model: action (module?.exports = Tracktime.ActionsView) or @Tracktime.ActionsView = Tracktime.ActionsView class Tracktime.ActionView.ActiveBtn extends Backbone.View el: '#action_type' initialize: () -> @render() render: () -> model = @model.toJSON() if model.canClose model.btnClass = model.btnClassEdit model.icon.className = model.icon.classNameEdit @$el .attr 'class', "btn btn-fab #{model.btnClass} dropdown-toggle " .find('i').attr('title', model.title).attr('class', model.icon.className).html model.icon.letter (module?.exports = Tracktime.ActionView.ActiveBtn) or @Tracktime.ActionView.ActiveBtn = Tracktime.ActionView.ActiveBtn class Tracktime.ActionView.ListBtn extends Backbone.View tagName: 'li' template: JST['actions/listbtn'] events: 'click': 'actionActive' initialize: (options) -> _.extend @, options @render() @listenTo @model, 'change:isActive', @updateActionControl @listenTo @model, 'destroy', @close render: () -> model = @model.toJSON() if model.canClose model.btnClass = model.btnClassEdit model.icon.className = model.icon.classNameEdit @$el.html @template model if @model.get('isActive') == true @$el.addClass 'active' @updateActionControl() else @$el.removeClass 'active' actionActive: (event) -> event.preventDefault() @model.setActive() updateActionControl: () -> @$el.siblings().removeClass 'active' @$el.addClass 'active' $("#action_type").replaceWith (new Tracktime.ActionView.ActiveBtn model: @model).$el (module?.exports = Tracktime.ActionView.ListBtn) or @Tracktime.ActionView.ListBtn = Tracktime.ActionView.ListBtn class Tracktime.ActionView.Project extends Backbone.View container: '.action-wrapper' template: JST['actions/details/project'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'projectModel' placeholder: @model.get 'title' field: 'name' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() textarea.on 'tSubmit', @sendForm $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' textareaInput: (event) => window.setTimeout () => diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.currentTarget).val() , 500 sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.Project) or @Tracktime.ActionView.Project = Tracktime.ActionView.Project class Tracktime.ActionView.Record extends Backbone.View container: '.action-wrapper' template: JST['actions/details/record'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'recordModel' placeholder: @model.get 'title' field: 'subject' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() window.setTimeout () => textarea.$el.trigger 'input' , 100 textarea.on 'tSubmit', @sendForm $('placeholder#slider', @$el).replaceWith (new Tracktime.Element.Slider model: @model.get 'recordModel' field: 'recordTime' ).$el $('placeholder#selectday', @$el).replaceWith (new Tracktime.Element.SelectDay model: @model.get 'recordModel' field: 'recordDate' ).$el projectDefinition = new Tracktime.Element.ProjectDefinition model: @model.get 'recordModel' field: 'project' $('.floating-label', "#actions-form").append projectDefinition.$el $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' $('[data-toggle="tooltip"]').tooltip() textareaInput: (event) -> diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.target).val() sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.Record) or @Tracktime.ActionView.Record = Tracktime.ActionView.Record class Tracktime.ActionView.Search extends Backbone.View container: '.action-wrapper' template: JST['actions/details/search'] tmpDetails: {} views: {} initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() (module?.exports = Tracktime.ActionView.Search) or @Tracktime.ActionView.Search = Tracktime.ActionView.Search class Tracktime.ActionView.User extends Backbone.View container: '.action-wrapper' template: JST['actions/details/user'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'userModel' placeholder: @model.get 'title' field: '<NAME>' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() textarea.on 'tSubmit', @sendForm $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' textareaInput: (event) => window.setTimeout () => diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.target).val() , 500 sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.User) or @Tracktime.ActionView.User = Tracktime.ActionView.User class Tracktime.AdminView.Header extends Backbone.View container: '#header' template: JST['admin/layout/header'] initialize: (options) -> @render() render: () -> $(@container).html @$el.html @template() (module?.exports = Tracktime.AdminView.Header) or @Tracktime.AdminView.Header = Tracktime.AdminView.Header class Tracktime.AdminView.ActionView extends Backbone.View tagName: 'li' className: 'list-group-item' template: JST['actions/admin_action'] events: 'click .btn-call-action': "callAction" 'click .edit.btn': "editAction" initialize: -> @render() render: -> @$el.html @template @model.toJSON() editAction: -> callAction: -> $.alert 'Test action call' (module?.exports = Tracktime.AdminView.ActionView) or @Tracktime.AdminView.ActionView = Tracktime.AdminView.ActionView class Tracktime.AdminView.ActionsView extends Backbone.View container: '#main' template: JST['admin/actions'] templateHeader: JST['admin/actions_header'] tagName: 'ul' className: 'list-group' views: {} actionsTypes: ['Project', 'Record', 'User', 'Search'] initialize: () -> @render() render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Actions'} @$el.prepend @templateHeader() @renderActionsList() renderActionsList: () -> _.each @actionsTypes, (atype) => actionView = new Tracktime.AdminView.ActionView model: new Tracktime.Action[atype]() @$el.append actionView.el @setSubView "atype-#{atype}", actionView , @ (module?.exports = Tracktime.AdminView.ActionsView) or @Tracktime.AdminView.ActionsView = Tracktime.AdminView.ActionsView class Tracktime.AdminView.Dashboard extends Backbone.View container: '#main' template: JST['admin/dashboard'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template() (module?.exports = Tracktime.AdminView.Dashboard) or @Tracktime.AdminView.Dashboard = Tracktime.AdminView.Dashboard class Tracktime.AdminView.ProjectsView extends Backbone.View container: '#main' template: JST['admin/projects'] tagName: 'ul' className: 'list-group' views: {} initialize: () -> @render() @listenTo @collection, "reset", @resetProjectsList @listenTo @collection, "add", @addProject @listenTo @collection, "remove", @removeProject render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Projects'} @resetProjectsList() resetProjectsList: () -> _.each @collection.where(isDeleted: false), (project) => projectView = new Tracktime.AdminView.ProjectView { model: project } @$el.append projectView.el @setSubView "project-#{project.cid}", projectView , @ addProject: (project, collection, params) -> projectView = new Tracktime.AdminView.ProjectView { model: project } $(projectView.el).prependTo @$el @setSubView "project-#{project.cid}", projectView removeProject: (project, args...) -> projectView = @getSubView "project-#{project.cid}" projectView.close() if projectView (module?.exports = Tracktime.AdminView.ProjectsView) or @Tracktime.AdminView.ProjectsView = Tracktime.AdminView.ProjectsView class Tracktime.AdminView.UsersView extends Backbone.View container: '#main' template: JST['admin/users'] tagName: 'ul' className: 'list-group' views: {} initialize: () -> @render() @listenTo @collection, "reset", @resetUsersList @listenTo @collection, "add", @addUser @listenTo @collection, "remove", @removeUser render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Users'} @resetUsersList() resetUsersList: () -> _.each @collection.where(isDeleted: false), (user) => userView = new Tracktime.AdminView.UserView { model: user } @$el.append userView.el @setSubView "user-#{user.cid}", userView , @ addUser: (user, collection, params) -> userView = new Tracktime.AdminView.UserView { model: user } $(userView.el).prependTo @$el @setSubView "user-#{user.cid}", userView removeUser: (user, args...) -> userView = @getSubView "user-#{user.cid}" userView.close() if userView (module?.exports = Tracktime.AdminView.UsersView) or @Tracktime.AdminView.UsersView = Tracktime.AdminView.UsersView class Tracktime.AppView extends Backbone.View container: '#panel' className: '' template: JST['global/app'] views: {} initialize: -> @render() render: -> $(@container).html @$el.html @template @model.toJSON() initUI: -> $.material.init() (module?.exports = Tracktime.AppView) or @Tracktime.AppView = Tracktime.AppView class Tracktime.Element extends Backbone.View initialize: () -> @render() render: () -> @$el.html 'void element' (module?.exports = Tracktime.Element) or @Tracktime.Element = Tracktime.Element class Tracktime.Element.ElementCloseAction extends Tracktime.Element tagName: 'button' className: 'btn btn-close-action btn-fab btn-flat btn-fab-mini' hint: 'Cancel action' events: 'click': 'closeAction' initialize: (options = {}) -> _.extend @, options @render() render: () -> @$el .attr 'title', @hint .append $('<i />', class: 'mdi-content-remove') closeAction: () => @model.destroy() (module?.exports = Tracktime.Element.ElementCloseAction) or @Tracktime.Element.ElementCloseAction = Tracktime.Element.ElementCloseAction class Tracktime.Element.ProjectDefinition extends Tracktime.Element className: 'project_definition' template: JST['elements/project_definition'] defaultTitle: 'Select project' searchStr: '' events: 'click .btn-white': 'selectProject' initialize: (options = {}) -> _.extend @, options @render() @projects = Tracktime.AppChannel.request 'projects' @projectsList = Tracktime.AppChannel.request 'projectsList' @projects.on 'sync', @renderList render: -> @$el.html @template title: @defaultTitle @renderList() $('.input-cont', @$el) .on 'click', (event) -> event.stopPropagation() $('.input-cont input', @$el) .on 'keyup', @setSearch setSearch: (event) => @searchStr = $(event.currentTarget).val().toLowerCase() @renderList() getList: (limit = 5) -> @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList unless _.isEmpty @searchStr keys = _.filter keys, (key) => @projectsList[key].toLowerCase().indexOf(@searchStr) > -1 sublist = {} i = 0 limit = Math.min(limit, keys.length) while i < limit sublist[ keys[i] ] = @projectsList[ keys[i] ] i++ sublist renderList: => list = @getList() menu = $('.dropdown-menu', @$el) menu.children('.item').remove() @updateTitle() for own key, value of list menu.append $("<li class='item'><a class='btn btn-white' data-project='#{key}' href='##{key}'>#{value}</a></li>") menu.append $("<li class='item'><a class='btn btn-white' data-project='0' href='#0'><span class='text-muted'>No project</span></a></li>") getTitle: -> projectId = @model.get @field if projectId of @projectsList "to " + @projectsList[projectId] else @defaultTitle selectProject: (event) => event.preventDefault() projectId = $(event.currentTarget).data 'project' @model.set @field, projectId Tracktime.AppChannel.command 'useProject', projectId @updateTitle() @$el.parents('.form-control-wrapper').find('textarea').focus() updateTitle: -> $('.project_definition-toggler span.caption', @$el).text @getTitle() (module?.exports = Tracktime.Element.ProjectDefinition) or @Tracktime.Element.ProjectDefinition = Tracktime.Element.ProjectDefinition class Tracktime.Element.SelectDay extends Tracktime.Element className: 'btn-group select-day' template: JST['elements/selectday'] events: 'click button.btn': 'setDay' initialize: (options = {}) -> # @tmpDetails.recordDate = $(".select-day > .btn .caption ruby rt").html() _.extend @, options @render() @changeField() @listenTo @model, "change:#{@field}", @changeField render: -> @$el.html @template @setDays() setDays: -> moment = window.moment localeData = moment.localeData('ru') current: name: localeData.weekdays(moment()) day: moment().format("MMM Do YYYY") value: moment().toISOString() days: [ name: localeData.weekdays(moment().subtract(2, 'days')) day: moment().subtract(2, 'day').format("MMM Do YYYY") value: moment().subtract(2, 'day').toISOString() , name: localeData.weekdays(moment().subtract(1, 'day')) day: moment().subtract(1, 'day').format("MMM Do YYYY") value: moment().subtract(1, 'day').toISOString() , name: localeData.weekdays(moment()) day: moment().format("MMM Do YYYY") value: moment().toISOString() ] changeField: => # @$el.val @model.get @field # найти в списке тот день который есть в field и нажать на эту кнопку changeInput: (value) => @model.set @field, value, {silent: true} setDay: (event) -> event.preventDefault() $(".dropdown-toggle ruby", @$el).html $('ruby', event.currentTarget).html() @changeInput $(event.currentTarget).data('value') # $(".dropdown-toggle ruby rt", @$el).html() (module?.exports = Tracktime.Element.SelectDay) or @Tracktime.Element.SelectDay = Tracktime.Element.SelectDay class Tracktime.Element.Slider extends Tracktime.Element className: 'slider shor btn-primary slider-material-orange' initialize: (options = {}) -> _.extend @, options @render() @changeField() @listenTo @model, "change:#{@field}", @changeField render: () -> @$el .noUiSlider start: [0] step: 5 range: {'min': [ 0 ], 'max': [ 720 ] } .on slide: (event, inval) => if inval? and _.isNumber parseFloat inval @changeInput parseFloat inval val = inval else val = 0 currentHour = val / 720 * 12 hour = Math.floor(currentHour) minute = (currentHour - hour) * 60 $('.slider .noUi-handle').attr 'data-before', hour $('.slider .noUi-handle').attr 'data-after', Math.round(minute) @$el .noUiSlider_pips mode: 'values' values: [0,60*1,60*2,60*3,60*4,60*5,60*6,60*7,60*8,60*9,60*10,60*11,60*12] density: 2 format: to: (value) -> value / 60 from: (value) -> value changeField: () => newVal = 0 fieldValue = @model.get(@field) if fieldValue? and _.isNumber parseFloat fieldValue newVal = parseFloat @model.get @field @$el.val(newVal).trigger('slide') changeInput: (value) => @model.set @field, parseFloat(value) or 0, {silent: true} (module?.exports = Tracktime.Element.Slider) or @Tracktime.Element.Slider = Tracktime.Element.Slider #<textarea class="form-control floating-label" placeholder="textarea floating label"></textarea> class Tracktime.Element.Textarea extends Tracktime.Element name: 'action_text' tagName: 'textarea' className: 'form-control floating-label' events: 'keydown': 'fixEnter' 'keyup': 'changeInput' 'change': 'changeInput' initialize: (options = {}) -> _.extend @, options @name = "#{@name}-#{@model.cid}" @render() @listenTo @model, "change:#{@field}", @changeField render: () -> @$el.attr 'name', @name @$el.attr 'placeholder', @placeholder @$el.val @model.get @field changeField: () => @$el.val(@model.get @field).trigger('input') changeInput: (event) => @model.set @field, $(event.target).val(), {silent: true} fixEnter: (event) => if event.keyCode == 13 and not event.shiftKey event.preventDefault() @trigger 'tSubmit' (module?.exports = Tracktime.Element.Textarea) or @Tracktime.Element.Textarea = Tracktime.Element.Textarea class Tracktime.GuestView extends Backbone.View container: '#panel' className: '' template: JST['global/guest'] views: {} initialize: -> @render() render: -> $(@container).html @$el.html @template @model.toJSON() @setSubView 'login', new Tracktime.GuestView.Login model: @model @setSubView 'signin', new Tracktime.GuestView.Signin model: @model @setSubView 'fopass', new Tracktime.GuestView.Fopass model: @model initUI: -> $.material.init() (module?.exports = Tracktime.AppView) or @Tracktime.AppView = Tracktime.AppView class Tracktime.GuestView.Fopass extends Backbone.View el: '#forgotpassword' events: 'click .btn-forgotpassword': 'forgotpasswordProcess' initialize: () -> forgotpasswordProcess: (event) -> event.preventDefault() $.alert 'fopass process' (module?.exports = Tracktime.GuestView.Fopass) or @Tracktime.GuestView.Fopass = Tracktime.GuestView.Fopass class Tracktime.GuestView.Login extends Backbone.View el: '#login > form' events: 'submit': 'loginProcess' initialize: () -> @listenTo @model.get('authUser'), 'flash', @showFlash loginProcess: (event) -> event.preventDefault() @model.get('authUser').login email: $('[name=email]',@$el).val() password: $('[name=password]',@$el).val() showFlash: (message) -> $.alert message.scope.capitalizeFirstLetter() + " Error: #{message.msg}" (module?.exports = Tracktime.GuestView.Login) or @Tracktime.GuestView.Login = Tracktime.GuestView.Login class Tracktime.GuestView.Signin extends Backbone.View el: '#signin > form' events: 'submit': 'signinProcess' initialize: () -> @listenTo @model.get('authUser'), 'flash', @showFlash signinProcess: (event) -> event.preventDefault() if @checkInput() @model.get('authUser').signin first_name: $('[name=first_name]',@$el).val() last_name: $('[name=last_name]',@$el).val() email: $('[name=email]',@$el).val() password: $('[name=password]',@$el).val() checkInput: -> result = true if _.isEmpty $('[name=first_name]',@$el).val() @showFlash scope: "Signin", msg: 'First Name empty' result = false if _.isEmpty $('[name=last_name]',@$el).val() @showFlash scope: "Signin", msg: 'Last Name empty' result = false if _.isEmpty $('[name=email]',@$el).val() @showFlash scope: "Signin", msg: 'Email empty' result = false if _.isEmpty $('[name=password]',@$el).val() @showFlash scope: "Signin", msg: 'Password empty' result = false if $('[name=password]',@$el).val() != $('[name=repassword]',@$el).val() @showFlash scope: "Signin", msg: 'Repassword incorrect' result = false result showFlash: (message) -> $.alert content: message.scope.capitalizeFirstLetter() + " Error: #{message.msg}" style: "btn-danger" (module?.exports = Tracktime.GuestView.Signin) or @Tracktime.GuestView.Signin = Tracktime.GuestView.Signin class Tracktime.AppView.Footer extends Backbone.View container: '#footer' template: JST['layout/footer'] events: 'click #click-me': 'clickMe' 'click #window-close': 'windowClose' initialize: () -> @render() render: () -> $(@container).html @$el.html @template @model?.toJSON() clickMe: (event) -> event.preventDefault() $.alert 'Subview :: ' + $(event.target).attr 'href' windowClose: (event) -> event.preventDefault() $.alert 'Close window' window.close() (module?.exports = Tracktime.AppView.Footer) or @Tracktime.AppView.Footer = Tracktime.AppView.Footer class Tracktime.AppView.Header extends Backbone.View container: '#header' template: JST['layout/header'] views: {} initialize: (options) -> @options = options @render() render: () -> $(@container).html @$el.html @template() @setSubView 'actions', new Tracktime.ActionsView collection: @model.get('actions') (module?.exports = Tracktime.AppView.Header) or @Tracktime.AppView.Header = Tracktime.AppView.Header class Tracktime.AppView.Main extends Backbone.View el: '#main' template: JST['layout/main'] views: {} initialize: () -> @render() @bindEvents() render: () -> @$el.html @template @model?.toJSON() @renderRecords() bindEvents: -> @listenTo @model.get('records'), "reset", @renderRecords renderRecords: -> recordsView = new Tracktime.RecordsView {collection: @model.get('records')} @$el.html recordsView.el (module?.exports = Tracktime.AppView.Main) or @Tracktime.AppView.Main = Tracktime.AppView.Main class Tracktime.AppView.Menu extends Backbone.View container: '#menu' template: JST['layout/menu'] searchStr: '' events: 'change #isOnline': 'updateOnlineStatus' initialize: -> @render() @bindEvents() @projects = Tracktime.AppChannel.request 'projects' @projectsList = Tracktime.AppChannel.request 'projectsList' @projects.on 'all', @renderMenuList bindEvents: -> @listenTo Tracktime.AppChannel, "isOnline", (status) -> $('#isOnline').prop 'checked', status @slideout = new Slideout 'panel': $('#panel')[0] 'menu': $('#menu')[0] 'padding': 256 'tolerance': 70 $("#menuToggler").on 'click', => @slideout.toggle() $(".input-search", @container).on 'keyup', @setSearch setSearch: (event) => @searchStr = $(event.currentTarget).val().toLowerCase() @searchProject() searchProject: (event) -> @renderSearchList() getSearchList: (limit = 5) -> @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList unless _.isEmpty @searchStr keys = _.filter keys, (key) => @projectsList[key].toLowerCase().indexOf(@searchStr) > -1 sublist = {} i = 0 limit = Math.min(limit, keys.length) while i < limit sublist[ keys[i] ] = @projectsList[ keys[i] ] i++ sublist renderMenuList: => menu = $('#projects-section .list-style-group', @container) menu.children('.project-link').remove() limit = 5 @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList if keys.length > 0 keys = _.sortBy keys, (key) => count = @projects.get(key).get('useCount') count = unless count == undefined then count else 0 - count i = 0 while i < limit project = @projects.get keys[i] menu.append $("<a class='list-group-item project-link' href='#records/project/#{project.id}'>#{project.get('name')}</a>").on 'click', 'a', @navTo i++ renderSearchList: => list = @getSearchList() menu = $('.menu-projects', @container) menu.children().remove() for own key, value of list menu.append $("<li><a href='#records/project/#{key}'>#{value}</a></li>").on 'click', 'a', @navTo if _.size(list) > 0 if _.isEmpty(@searchStr) menu.dropdown().hide() else menu.dropdown().show() else menu.dropdown().hide() navTo: (event) -> href = $(event.currentTarget).attr('href') projectId = href.substr(-24) Tracktime.AppChannel.command 'useProject', projectId window.location.hash = href $('.menu-projects', @container).dropdown().hide() updateOnlineStatus: (event) -> if $(event.target).is(":checked") Tracktime.AppChannel.command 'checkOnline' else Tracktime.AppChannel.command 'serverOffline' render: -> $(@container).html @$el.html @template @model?.toJSON() _.each @model.get('projects').models, (model) => projectLink = $('<a />', {class: 'list-group-item', href:"#projects/#{model.get('_id')}"}).html model.get('name') projectLink.appendTo "#projects-section .list-style-group" close: -> @slideout.close() super (module?.exports = Tracktime.AppView.Menu) or @Tracktime.AppView.Menu = Tracktime.AppView.Menu class Tracktime.AdminView.ProjectView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['projects/admin_project'] events: 'click .btn.delete': "deleteProject" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editProject" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:name", @changeName @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel attributes: -> id: @model.cid render: -> @$el.html @template @model.toJSON() $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'name' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:name' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeName: -> $('.subject', @$el).html (@model.get('name') + '').nl2br() $('.name_edit', @$el).val @model.get 'name' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update project' timeout: 2000 style: 'btn-info' editProject: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteProject: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete project' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.AdminView.ProjectView) or @Tracktime.AdminView.ProjectView = Tracktime.AdminView.ProjectView class Tracktime.ProjectView extends Backbone.View container: '#main' template: JST['projects/project'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Project Details View HERE'} (module?.exports = Tracktime.ProjectView) or @Tracktime.ProjectView = Tracktime.ProjectView class Tracktime.ProjectsView extends Backbone.View container: '#main' template: JST['projecs/projecs'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Projects HERE - Only view'} (module?.exports = Tracktime.ProjectsView) or @Tracktime.ProjectsView = Tracktime.ProjectsView class Tracktime.RecordView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['records/record'] events: 'click .btn.delete': "deleteRecord" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editRecord" 'click .btn[role=do-active]': "toggleActive" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:subject", @changeSubject @listenTo @model, "change:project", @changeProject @listenTo @model, "change:recordTime", @changeRecordTime @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel @listenTo @model, "isActive", @setActiveState @projects = Tracktime.AppChannel.request 'projects' @projects.on 'sync', @renderProjectInfo @users = Tracktime.AppChannel.request 'users' @users.on 'sync', @renderUserInfo attributes: -> id: @model.cid render: -> @$el.html @template _.extend {filter: @model.collection.getFilter()}, @model.toJSON() $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'subject' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm @$el.addClass 'current' if Tracktime.AppChannel.checkActive @model.id @changeRecordTime() @renderProjectInfo() @renderUserInfo() toggleActive: -> Tracktime.AppChannel.command 'activeRecord', @model, not(Tracktime.AppChannel.checkActive @model.id) setActiveState: (status) -> console.log 'try set acgive state', status, @$el $('.list-group-item').removeClass 'current' @$el.toggleClass 'current', status changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:subject' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeSubject: -> $('.subject', @$el).html (@model.get('subject') + '').nl2br() $('.subject_edit', @$el).val @model.get 'subject' changeRecordTime: -> duration = moment.duration(parseInt(@model.get('recordTime'), 10),'minute') durationStr = duration.get('hours') + ':' + duration.get('minutes') $('.recordTime .value', @$el).html durationStr changeProject: -> @renderProjectInfo() renderProjectInfo: => project_id = @model.get('project') @projectsList = Tracktime.AppChannel.request 'projectsList' if project_id of @projectsList title = @projectsList[project_id] $(".record-info-project span", @$el).html title $(".record-info-project", @$el).removeClass 'hidden' $(".btn.type i", @$el).removeClass().addClass('letter').html title.letter() else $(".record-info-project", @$el).addClass 'hidden' $(".btn.type i", @$el).removeClass().addClass('mdi-action-bookmark-outline').html '' renderUserInfo: => user_id = @model.get('user') @usersList = Tracktime.AppChannel.request 'usersList' if user_id of @usersList title = @usersList[user_id] $(".record-info-user span", @$el).html title $(".record-info-user", @$el).removeClass 'hidden' else $(".record-info-user", @$el).addClass 'hidden' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update record' timeout: 2000 style: 'btn-info' editRecord: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteRecord: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete record' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.RecordView) or @Tracktime.RecordView = Tracktime.RecordView class Tracktime.RecordsView extends Backbone.View container: '#main' template: JST['records/records'] tagName: 'ul' className: 'list-group' initialize: () -> @views = {} @render() @listenTo @collection, "sync", @resetRecordsList @listenTo @collection, "remove", @removeRecord # @listenTo @collection, "add", @addRecord @listenTo @collection, "newRecord", @newRecord $('.removeFilter', @container).on 'click', @removeFilter $('.btn-loadmore', @container).on 'click', @loadMoreRecords $('.scrollWrapper').on 'scroll', @autoLoadMoreRecords @projects = Tracktime.AppChannel.request 'projects' @projects.on 'sync', @updateProjectInfo @users = Tracktime.AppChannel.request 'users' @users.on 'sync', @updateUserInfo render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Records', filter: @collection.getFilter()} @resetRecordsList() @updateProjectInfo() @updateUserInfo() $('.btn-loadmore', @container).appendTo @container autoLoadMoreRecords: (event) => delta = $(window).height() - $('.btn-loadmore').offset().top - $('.btn-loadmore').height() $('.btn-loadmore', @container).click() if delta > 0 loadMoreRecords: (event) => modelsNewCount = @resetRecordsList() if modelsNewCount > 0 $('.btn-loadmore', @container).show().appendTo @container else $('.btn-loadmore', @container).remove() newRecord: (record) -> @addRecord(record) # @loadMoreRecords() # dateEl = moment(record.get('recordDate') ).format("YYYY-MM-DD") # if $("##{dateEl}").length > 0 # $('.scrollWrapper').scrollTop($("##{dateEl}").offset().top + $(".scrollWrapper").scrollTop() - 78) sortRecords: -> parentCont = '#main .list-group' sortedList = $('.list-group-item', parentCont).sort (a, b) -> timeA = new Date($('.record-info time', a).attr('datetime')).getTime() timeB = new Date($('.record-info time', b).attr('datetime')).getTime() timeB - timeA dates = $.unique($('.record-info time', parentCont).map((i, el) -> moment($(el).attr('datetime')).format("YYYY-MM-DD") )).sort (a, b) -> b > a _.each dates, (el, b) -> if $("##{el}").length < 1 $(parentCont).append $("<ul> /", {id: el}).append $("<li />", {class: 'list-group-items-group navbar navbar-primary'}).html moment(el).format("Do MMMM YYYY") _.each sortedList, (item) -> id = moment($('.record-info time', item).attr('datetime')).format("YYYY-MM-DD") $("##{id}", parentCont).append item resetRecordsList_old: -> frag = document.createDocumentFragment() models = @collection.getModels @exceptRecords() _.each models, (record) -> recordView = @setSubView "record-#{record.cid}", new Tracktime.RecordView model: record frag.appendChild recordView.el , @ @$el.prepend frag @sortRecords() resetRecordsList: -> parentCont = '#main .list-group' models = @collection.getModels @exceptRecords() _.each models, (record) -> recordView = @setSubView "record-#{record.cid}", new Tracktime.RecordView model: record @listGroup(record).append recordView.el , @ models.length listGroup: (record) -> parentCont = '#main .list-group' # получить дату группы из модели groupDate = moment(record.get('recordDate')).format("YYYY-MM-DD") group = null # если группа существует то вернуть ев jquery if $("##{groupDate}").length > 0 group = $("##{groupDate}") # иначе else # создать группу с заголовком group = $("<ul> /", {id: groupDate}).append $("<li />", {class: 'list-group-items-group navbar navbar-primary'}).html moment(groupDate).format("Do MMMM YYYY") # если списков нет то добавить группу просто if $(".list-group > ul", parentCont).length < 1 $(parentCont).append group # иначе else # получить массив id групп - добавить в него новый элемент # отсортировать по убыыванию groups = $("ul.list-group > ul").map( (idx, el) -> $(el).attr('id') ) groups.push groupDate groups = groups.sort( (a, b) -> b > a ) # получить индекс в массиве groupIndex = _. indexOf groups, groupDate # если индекс равен длине массива то добавить группу в конец # иначе если индекс равен 0 массива то добавить группу в начало if groupIndex == 0 $(parentCont).prepend group # если есть предыдущий искомому элемент полученный по индексу то добавть ul после предыдушего else prevIndexGroup = groups[groupIndex - 1] $("##{prevIndexGroup}").after group group exceptRecords: () -> _.pluck $('.list-group-item > div', @container), 'id' updateProjectInfo: -> @projectsList = Tracktime.AppChannel.request 'projectsList' key = $('.removeFilter[data-exclude=project]', @container).data('value') if key of @projectsList $('.removeFilter[data-exclude=project] .caption', @container).text @projectsList[key] updateUserInfo: -> @usersList = Tracktime.AppChannel.request 'usersList' key = $('.removeFilter[data-exclude=user]', @container).data('value') if key of @usersList $('.removeFilter[data-exclude=user] .caption', @container).text @usersList[key] addRecord: (record, collection, params) -> # add record - depricated if record.isSatisfied @collection.filter recordView = new Tracktime.RecordView { model: record } $(recordView.el).insertAfter $('.list-group-items-group', @listGroup(record)) $('.btn[role="do-active"]', recordView.el).click() # @setSubView "record-#{record.cid}", recordView removeFilter: (event) => key = $(event.currentTarget).data('exclude') # remove key from collection filter @collection.removeFilter key # remove all records from list @$el.find('.list-group > li').remove() # refresh filter list in header $(event.currentTarget).remove() # add records by filter from collection @resetRecordsList() removeRecord: (record, args...) -> recordView = @getSubView "record-#{record.cid}" recordView.close() if recordView (module?.exports = Tracktime.RecordsView) or @Tracktime.RecordsView = Tracktime.RecordsView class Tracktime.ReportView extends Backbone.View container: '#main' template: JST['reports/report'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Report Details HERE'} (module?.exports = Tracktime.ReportView) or @Tracktime.ReportView = Tracktime.ReportView class Tracktime.ReportsView extends Backbone.View container: '#main' template: JST['reports/reports'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Reports HERE'} (module?.exports = Tracktime.ReportsView) or @Tracktime.ReportsView = Tracktime.ReportsView class Tracktime.AdminView.UserView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['users/admin_user'] events: 'click .btn.delete': "deleteUser" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editUser" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:first_name", @changeName @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel attributes: -> id: @model.cid render: -> data = _.extend {}, @model.toJSON(), hash: window.md5 @model.get('email').toLowerCase() @$el.html @template data $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'first_name' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:first_name' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeName: -> $('.subject', @$el).html (@model.get('first_name') + '').nl2br() $('.name_edit', @$el).val @model.get 'first_name' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update user' timeout: 2000 style: 'btn-info' editUser: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteUser: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete user' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.AdminView.UserView) or @Tracktime.AdminView.UserView = Tracktime.AdminView.UserView class Tracktime.UserView extends Backbone.View container: '#main' template: JST['users/user'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User index'} (module?.exports = Tracktime.UserView) or @Tracktime.UserView = Tracktime.UserView class Tracktime.UserView.Details extends Backbone.View container: '#main' template: JST['users/details'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User details HERE'} (module?.exports = Tracktime.UserView.Details) or @Tracktime.UserView.Details = Tracktime.UserView.Details class Tracktime.UserView.Rates extends Backbone.View container: '#main' template: JST['users/rates'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User Rates'} (module?.exports = Tracktime.UserView.Rates) or @Tracktime.UserView.Rates = Tracktime.UserView.Rates $ -> Tracktime.AppChannel.init().command 'start' return class Tracktime.AdminRouter extends Backbone.SubRoute routes: '': 'dashboard' 'users': 'users' 'projects': 'projects' 'dashboard': 'dashboard' 'actions': 'actions' initialize: (options) -> _.extend @, options dashboard: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.Dashboard() users: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.UsersView collection: @parent.model.get 'users' newAction = @parent.model.get('actions').addAction title: 'Add users' type: 'User' , scope: 'admin:users' newAction.setActive() projects: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.ProjectsView collection: @parent.model.get 'projects' newAction = @parent.model.get('actions').addAction title: 'Add projects' type: 'Project' , scope: 'admin:projects' newAction.setActive() actions: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.ActionsView collection: @parent.model.get 'actions' (module?.exports = Tracktime.AdminRouter) or @Tracktime.AdminRouter = Tracktime.AdminRouter class Tracktime.AppRouter extends Backbone.Router routes: '': 'index' #index 'projects*subroute': 'invokeProjectsRouter' #Projects 'records*subroute': 'invokeRecordsRouter' #Projects 'reports*subroute': 'invokeReportsRouter' #Reports 'user*subroute': 'invokeUserRouter' #User 'admin*subroute': 'invokeAdminRouter' #Admin '*actions': 'default' #??? initialize: (options) -> _.extend @, options @on 'route', (route, params) => @removeActionsExcept(route) unless route.substr(0,6) == 'invoke' @initInterface() # @navigate 'projects', trigger: true, replace: false Backbone.history.loadUrl(Backbone.history.fragment); addListener: (subroute, scope) -> @listenTo subroute, 'route', (route, params) => @removeActionsExcept "#{scope}:#{route}" invokeProjectsRouter: (subroute) -> unless @projectsRouter @projectsRouter = new Tracktime.ProjectsRouter 'projects', parent: @ @addListener @projectsRouter, 'projects' invokeRecordsRouter: (subroute) -> unless @recordsRouter @recordsRouter = new Tracktime.RecordsRouter 'records', parent: @ @addListener @recordsRouter, 'records' invokeReportsRouter: (subroute) -> unless @reportsRouter @reportsRouter = new Tracktime.ReportsRouter 'reports', parent: @ @addListener @reportsRouter, 'reports' invokeUserRouter: (subroute) -> unless @userRouter @userRouter = new Tracktime.UserRouter 'user', parent: @ @addListener @userRouter, 'users' invokeAdminRouter: (subroute) -> unless @adminRouter @adminRouter = new Tracktime.AdminRouter 'admin', parent: @ @addListener @adminRouter, 'admin' initInterface: () -> @view = new Tracktime.AppView model: @model @view.setSubView 'header', new Tracktime.AppView.Header model: @model @view.setSubView 'footer', new Tracktime.AppView.Footer() @view.setSubView 'menu', new Tracktime.AppView.Menu model: @model @view.initUI() index: -> # @navigate 'projects', trigger: true, replace: false default: (actions) -> $.alert 'Unknown page' @navigate '', true removeActionsExcept: (route) -> if @model.get('actions') _.each @model.get('actions').models, (action) -> action.destroy() if action && action.has('scope') and action.get('scope') isnt route (module?.exports = Tracktime.AppRouter) or @Tracktime.AppRouter = Tracktime.AppRouter class Tracktime.GuestRouter extends Backbone.Router routes: '': 'index' #index '*actions': 'default' #??? initialize: (options) -> _.extend @, options @initInterface() # @navigate '/', trigger: true, replace: false Backbone.history.loadUrl(Backbone.history.fragment); initInterface: () -> @view = new Tracktime.GuestView model: @model # @view.setSubView 'header', new Tracktime.GuestView.Header model: @model # @view.setSubView 'footer', new Tracktime.AppView.Footer() # @view.setSubView 'menu', new Tracktime.AppView.Menu model: @model @view.initUI() index: -> # $.alert 'Guest index page' default: (actions) -> # $.alert 'Unknown guest page' @navigate '', true (module?.exports = Tracktime.GuestRouter) or @Tracktime.GuestRouter = Tracktime.GuestRouter class Tracktime.ProjectsRouter extends Backbone.SubRoute routes: '': 'list' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options list: () -> $.alert "whole records list in projects section" @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' details: (id) -> @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' edit: (id) -> $.alert "projects edit #{id}" delete: (id) -> $.alert "projects delete #{id}" add: (id) -> $.alert "projects add #{id}" save: (id) -> $.alert "projects save #{id}" (module?.exports = Tracktime.ProjectsRouter) or @Tracktime.ProjectsRouter = Tracktime.ProjectsRouter class Tracktime.RecordsRouter extends Backbone.SubRoute routes: '': 'list' '*filter': 'listFilter' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options list: () -> collection = @parent.model.get 'records' collection.resetFilter() @parent.view.setSubView 'main', new Tracktime.RecordsView collection: collection listFilter: (filter) -> collection = @parent.model.get 'records' collection.setFilter filter @parent.view.setSubView 'main', new Tracktime.RecordsView collection: collection details: (id) -> $.alert "details" @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' edit: (id) -> $.alert "records edit #{id}" delete: (id) -> $.alert "records delete #{id}" add: (id) -> $.alert "records add #{id}" save: (id) -> $.alert "records save #{id}" (module?.exports = Tracktime.RecordsRouter) or @Tracktime.RecordsRouter = Tracktime.RecordsRouter class Tracktime.ReportsRouter extends Backbone.SubRoute routes: '': 'list' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options @parent.view.setSubView 'main', new Tracktime.ReportsView() list: () -> @parent.view.setSubView 'main', new Tracktime.ReportsView() details: (id) -> @parent.view.setSubView 'main', new Tracktime.ReportView() edit: (id) -> $.alert "reports edit #{id}" delete: (id) -> $.alert "reports delete #{id}" add: (id) -> $.alert "reports add #{id}" save: (id) -> $.alert "reports save #{id}" (module?.exports = Tracktime.ReportsRouter) or @Tracktime.ReportsRouter = Tracktime.ReportsRouter class Tracktime.UserRouter extends Backbone.SubRoute routes: '': 'details' 'rates': 'rates' 'logout': 'logout' initialize: (options) -> _.extend @, options # @parent.view.setSubView 'main', new Tracktime.UserView() details: () -> @parent.view.setSubView 'main', new Tracktime.UserView.Details() rates: () -> @parent.view.setSubView 'main', new Tracktime.UserView.Rates() logout: () -> @parent.model.get('authUser').logout() (module?.exports = Tracktime.UserRouter) or @Tracktime.UserRouter = Tracktime.UserRouter
true
process = process or window.process or {} production = SERVER: 'https://ttpms.herokuapp.com' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' test = SERVER: 'http://localhost:5000' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' development = SERVER: 'http://localhost:5000' collection: records: 'records' projects: 'projects' actions: 'actions' users: 'users' switch process.env?.NODE_ENV when 'production' config = production when 'test' config = test else config = development (module?.exports = config) or @config = config class Tracktime extends Backbone.Model urlRoot: config.SERVER defaults: title: 'TrackTime App' authUser: null initialize: () -> @set 'authUser', new Tracktime.User.Auth() @listenTo @get('authUser'), 'change:authorized', @changeUserStatus @listenTo @get('authUser'), 'destroy', -> @set 'authUser', new Tracktime.User.Auth() @listenTo @get('authUser'), 'change:authorized', @changeUserStatus initCollections: -> @set 'users', new Tracktime.UsersCollection() @set 'records', new Tracktime.RecordsCollection() @set 'projects', new Tracktime.ProjectsCollection() @set 'actions', new Tracktime.ActionsCollection() @listenTo Tracktime.AppChannel, "isOnline", @updateApp unsetCollections: -> @unset 'users' @unset 'actions' @unset 'records' @unset 'projects' @stopListening Tracktime.AppChannel, "isOnline" updateApp: -> @get('users').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' @get('projects').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' @get('records').fetch ajaxSync: Tracktime.AppChannel.request 'isOnline' changeUserStatus: -> @setUsetStatus @get('authUser').get('authorized') setUsetStatus: (status) -> if status == true @initCollections() Tracktime.AppChannel.command 'userAuth' else @unsetCollections() Tracktime.AppChannel.command 'userGuest' (module?.exports = Tracktime) or @Tracktime = Tracktime class Tracktime.AdminView extends Backbone.View el: '#panel' className: '' template: JST['admin/index'] views: {} initialize: -> @render() render: -> # $(document).title @model.get 'title' @$el.html @template() initUI: -> $.material.init() (module?.exports = Tracktime.AdminView) or @Tracktime.AdminView = Tracktime.AdminView do -> proxiedSync = Backbone.sync Backbone.sync = (method, model, options) -> options or (options = {}) if !options.crossDomain options.crossDomain = true if !options.xhrFields options.xhrFields = withCredentials: true proxiedSync method, model, options return Backbone.Validation.configure # selector: 'class_v' # labelFormatter: 'label_v' # attributes: 'inputNames' # returns the name attributes of bound view input elements # forceUpdate: true _.extend Backbone.Model.prototype, Backbone.Validation.mixin Backbone.ViewMixin = close: () -> @onClose() if @onClose if @container? $(@container).unbind() @undelegateEvents() @$el.removeData().unbind() @remove() Backbone.View.prototype.remove.call @ return onClose: -> for own key, view of @views view.close() delete @views[key] clear: -> @onClose() setSubView: (key, view) -> @views[key].close() if key of @views @views[key] = view getSubView: (key) -> @views[key] if key of @views Backbone.View.prototype extends Backbone.ViewMixin Handlebars.registerHelper 'link_to', (options) -> attrs = href: '' for own key, value of options.hash if key is 'body' body = Handlebars.Utils.escapeExpression value else attrs[key] = Handlebars.Utils.escapeExpression value new (Handlebars.SafeString) $("<a />", attrs).html(body)[0].outerHTML Handlebars.registerHelper 'safe_val', (value, safeValue) -> out = value || safeValue new Handlebars.SafeString(out) Handlebars.registerHelper 'nl2br', (text) -> text = Handlebars.Utils.escapeExpression text new Handlebars.SafeString text.nl2br() Handlebars.registerHelper 'dateFormat', (date) -> moment = window.moment localeData = moment.localeData('ru') moment(date).format("MMM Do YYYY") # timestamp = Date.parse date # unless _.isNaN(timestamp) # (new Date(timestamp)).toLocalString() # else # new Date() Handlebars.registerHelper 'minuteFormat', (val) -> duration = moment.duration val,'minute' duration.get('hours') + ':' + duration.get('minutes') # currentHour = val / 720 * 12 # hour = Math.floor(currentHour) # minute = Math.round((currentHour - hour) * 60) # "hb: #{hour}:#{minute}" Handlebars.registerHelper 'placeholder', (name) -> placeholder = "<placeholder id='#{name}'></placeholder>" new Handlebars.SafeString placeholder Handlebars.registerHelper 'filteredHref', (options) -> parsedFilter = {} _.extend(parsedFilter, options.hash.filter) if 'filter' of options.hash _.extend(parsedFilter, {user: options.hash.user}) if 'user' of options.hash _.extend(parsedFilter, {project: options.hash.project}) if 'project' of options.hash delete parsedFilter[options.hash.exclude] if 'exclude' of options.hash and options.hash.exclude of parsedFilter if _.keys(parsedFilter).length > 0 '/' + _.map(parsedFilter, (value,key) -> "#{key}/#{value}").join '/' else '' (($) -> snackbarOptions = content: '' style: '' timeout: 2000 htmlAllowed: true $.extend ( alert: (params) -> if _.isString params snackbarOptions.content = params else snackbarOptions = $.extend {},snackbarOptions,params $.snackbar snackbarOptions ) ) jQuery String::capitalizeFirstLetter = -> @charAt(0).toUpperCase() + @slice(1) String::nl2br = -> (@ + '').replace /([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2' String::letter = -> @charAt(0).toUpperCase() class Tracktime.Collection extends Backbone.Collection addModel: (params, options) -> newModel = new @model params if newModel.isValid() @add newModel unless options.ajaxSync? options.ajaxSync = Tracktime.AppChannel.request 'isOnline' newModel.save {}, options else $.alert 'Erros validation from add curModel to collection' fetch: (options) -> @resetLocalStorage() if options? and options.ajaxSync == true _success = options.success options.success = (collection, response, optionsSuccess) => @syncCollection(response) _success.apply(@, collection, response, options) if _.isFunction(_success) super options syncCollection: (models) -> # по всем remote model которые вроде как в коллекции уже _.each models, (model) => curModel = @get(model._id) localModel = @localStorage.find curModel # если нет локальной то сохраняем (локально) unless localModel curModel.save ajaxSync: false # иначе else # если локальная старее то обновляем с новых данных (локально) modelUpdatetAt = (new Date(model.updatedAt)).getTime() localUpdatetAt = (new Date(localModel.updatedAt)).getTime() if localModel.isDeleted # do nothing curModel.set {'isDeleted': true}, {trigger: false} else if localUpdatetAt < modelUpdatetAt curModel.save model, ajaxSync: false # иначе есть если локальная новее то else if localUpdatetAt > modelUpdatetAt # обновляем модель пришедшую в коллекции # сохраняем ее удаленно curModel.save localModel, ajaxSync: true # по всем local моделям localModels = @localStorage.findAll() _.each _.clone(localModels), (model) => collectionModel = @get(model._id) # если удалена if model.isDeleted if model._id.length > 24 destroedModel = new @model {_id: model._id, subject: 'model to delete'} destroedModel.destroy ajaxSync: false else modelUpdatetAt = (new Date(model.updatedAt)).getTime() if collectionModel? and modelUpdatetAt > (new Date(collectionModel.get('updatedAt'))).getTime() destroedModel = collectionModel else destroedModel = new @model (model) # то удаляем локально и удаленно # и из коллекции если есть destroedModel.destroy ajaxSync: true else # если нет в коллекции unless collectionModel replacedModel = new @model {_id: model._id} replacedModel.fetch {ajaxSync: false} newModel = replacedModel.toJSON() delete newModel._id # то сохраняем ее удаленно # добавляем в коллекцию @addModel newModel, success: (model, response) => # заменяем на новосохраненную replacedModel.destroy {ajaxSync: false} resetLocalStorage: () -> @localStorage = new Backbone.LocalStorage @collectionName (module?.exports = Tracktime.Collection) or @Tracktime.Collection = Tracktime.Collection class Tracktime.Model extends Backbone.Model sync: (method, model, options) -> options = options or {} switch method when 'create' if options.ajaxSync _success = options.success _model = model.clone() options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success _model.id = model._id _model.set '_id', model._id Backbone.sync method, _model, options Backbone.sync method, model, options when 'read' Backbone.sync method, model, options when 'patch' Backbone.sync method, model, options when 'update' if options.ajaxSync _success = options.success _model = model options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success Backbone.sync method, _model, options Backbone.sync method, model, options when 'delete' if options.ajaxSync == true model.save {'isDeleted': true}, {ajaxSync: false} _success = options.success _model = model options.success = (model, response) -> options.ajaxSync = !options.ajaxSync options.success = _success Backbone.sync method, _model, options Backbone.sync method, model, options else Backbone.sync method, model, options else $.alert "unknown method #{method}" Backbone.sync method, model, options class Tracktime.Action extends Backbone.Model idAttribute: "_id" collectionName: config.collection.actions url: '/actions' #receive on activate actions for user (!) defaults: _id: null title: 'Default action' isActive: null isVisible: false canClose: false attributes: () -> id: @model.cid setActive: () -> @collection.setActive @ processAction: (options) -> $.alert 'Void Action' (module?.exports = Tracktime.Action) or @Tracktime.Action = Tracktime.Action class Tracktime.Action.Project extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add project' projectModel: null formAction: '#' btnClass: 'btn-material-purple' btnClassEdit: 'btn-material-blue' navbarClass: 'navbar-inverse' icon: className: 'mdi-content-add-circle' classNameEdit: 'mdi-content-add-circle-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'projectModel', new Tracktime.Project() unless @get('projectModel') instanceof Tracktime.Project processAction: () -> projectModel = @get 'projectModel' if projectModel.isValid() if projectModel.isNew() Tracktime.AppChannel.command 'newProject', projectModel.toJSON() projectModel.clear().set(projectModel.defaults) else projectModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'Project: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('projectModel').isEdit = false @get('projectModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.Project) or @Tracktime.Action.Project = Tracktime.Action.Project class Tracktime.Action.Record extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add record' recordModel: null formAction: '#' btnClass: 'btn-material-green' btnClassEdit: 'btn-material-lime' navbarClass: 'navbar-primary' icon: className: 'mdi-action-bookmark' classNameEdit: 'mdi-action-bookmark-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'recordModel', new Tracktime.Record() unless @get('recordModel') instanceof Tracktime.Record processAction: () -> recordModel = @get 'recordModel' if recordModel.isValid() if recordModel.isNew() Tracktime.AppChannel.command 'newRecord', recordModel.toJSON() recordModel.clear().set(recordModel.defaults) else recordModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'Record: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('recordModel').isEdit = false @get('recordModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.Record) or @Tracktime.Action.Record = Tracktime.Action.Record class Tracktime.Action.Search extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Search' formAction: '#' btnClass: 'btn-white' btnClassEdit: 'btn-white' navbarClass: 'navbar-material-light-blue' icon: className: 'mdi-action-search' classNameEdit: 'mdi-action-search' letter: '' isActive: null isVisible: true initialize: (options = {}) -> @set options processAction: (options) -> @search() search: () -> $.alert 'search start' (module?.exports = Tracktime.Action.Search) or @Tracktime.Action.Search = Tracktime.Action.Search class Tracktime.Action.User extends Tracktime.Action defaults: _.extend {}, Tracktime.Action.prototype.defaults, title: 'Add user' userModel: null formAction: '#' btnClass: 'btn-material-deep-orange' btnClassEdit: 'btn-material-amber' navbarClass: 'navbar-material-yellow' icon: className: 'mdi-social-person' classNameEdit: 'mdi-social-person-outline' letter: '' isActive: null isVisible: true initialize: () -> @set 'userModel', new Tracktime.User() unless @get('userModel') instanceof Tracktime.User processAction: () -> userModel = @get 'userModel' if userModel.isValid() if userModel.isNew() Tracktime.AppChannel.command 'newUser', userModel.toJSON() userModel.clear().set(userModel.defaults) else userModel.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: () => $.alert content: 'User: update success' timeout: 2000 style: 'btn-success' @destroy() destroy: (args...) -> @get('userModel').isEdit = false @get('userModel').trigger 'change:isEdit' super args... (module?.exports = Tracktime.Action.User) or @Tracktime.Action.User = Tracktime.Action.User class Tracktime.Project extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.projects urlRoot: config.SERVER + '/' + 'projects' localStorage: new Backbone.LocalStorage 'projects' defaults: _id: null name: '' description: '' updatedAt: (new Date()).toISOString() isDeleted: false validation: name: required: true minLength: 4 msg: 'Please enter a valid name' initialize: -> @isEdit = false @on 'change:name', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: () -> # @todo add good validation true updateUpdatedAt: () -> @set 'updatedAt', (new Date()).toISOString() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit project', type: 'Project', canClose: true}, title: 'Edit project: ' + @get('name').substr(0, 40) projectModel: @ scope: 'edit:action' (module?.exports = Tracktime.Project) or @Tracktime.Project = Tracktime.Project class Tracktime.Record extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.records urlRoot: config.SERVER + '/' + 'records' localStorage: new Backbone.LocalStorage 'records' defaults: _id: null subject: '' description: '' date: () -> (new Date()).toISOString() updatedAt: (new Date()).toISOString() recordDate: '' recordTime: 0 project: 0 user: 0 isDeleted: false validation: subject: required: true minLength: 4 msg: 'Please enter a valid subject' initialize: -> @isEdit = false @on 'change:subject change:recordTime change:recordDate change:project', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: -> # @todo add good validation true isSatisfied: (filter) -> _.isMatch @attributes, filter updateUpdatedAt: () -> @set 'updatedAt', new Date() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit record', type: 'Record', canClose: true}, title: 'Edit record: ' + @get('subject').substr(0, 40) recordModel: @ scope: 'edit:action' addTime: (diff) -> time = parseInt @get('recordTime'), 10 @set 'recordTime', (time + diff) @save {}, ajaxSync: true (module?.exports = Tracktime.Record) or @Tracktime.Record = Tracktime.Record class Tracktime.User extends Tracktime.Model idAttribute: "_id" collectionName: config.collection.users urlRoot: config.SERVER + '/' + 'users' localStorage: new Backbone.LocalStorage 'users' defaults: _id: null first_name: '' last_name: '' email: '' password: '' description: '' default_pay_rate: '' updatedAt: (new Date()).toISOString() activeRecord: '' startedAt: null isDeleted: false validation: first_name: required: true minLength: 4 msg: 'Please enter a valid first_name' initialize: -> @isEdit = false @on 'change:first_name', @updateUpdatedAt @on 'change:last_name', @updateUpdatedAt @on 'change:description', @updateUpdatedAt @on 'change:isEdit', @changeIsEdit isValid: () -> # @todo add good validation true updateUpdatedAt: () -> @set 'updatedAt', (new Date()).toISOString() changeIsEdit: -> if @isEdit Tracktime.AppChannel.command 'addAction', {title: 'Edit user', type: 'User', canClose: true}, title: 'Edit user: ' + @get('first_name').substr(0, 40) userModel: @ scope: 'edit:action' (module?.exports = Tracktime.User) or @Tracktime.User = Tracktime.User class Tracktime.User.Auth extends Backbone.Model idAttribute: "_id" urlRoot: config.SERVER + '/' + '' defaults: authorized: null initialize: -> @fetch ajaxSync: true url: config.SERVER + '/auth_user' success: (model, response, options) => @set 'authorized', true error: (model, response, options) => @set 'authorized', false login: (params) -> @save params, ajaxSync: true url: config.SERVER + '/login' success: (model, response, options) => @set response @set 'authorized', true $.alert "Welcome back, #{response.first_name} #{response.last_name}!" window.location.hash = '#records' error: (model, response, options) => if response.responseJSON? @trigger 'flash', response.responseJSON.error else @trigger 'flash', scope: "unknown" msg: 'Send request error' signin: (params) -> _.extend params, status: 'active' k_status: 'active' updatedAt: (new Date()).toISOString() isDeleted: 'false' @save params, ajaxSync: true url: config.SERVER + '/register' success: (model, response, options) => @set response @set 'authorized', true $.alert "Welcome, #{response.name} !" error: (model, response, options) => @trigger 'flash', response.responseJSON.error forgotpasswrod: -> fullName: -> "#{@get('first_name')} #{@get('last_name')}" logout: -> $.alert "Goodbay, #{@fullName()}!" @set 'authorized', false @destroy ajaxSync: true url: config.SERVER + '/logout/' + @id success: (model, response, options) => window.location.href = '#' window.location.reload() error: (model, response, options) => console.log 'logout error' setActiveRecord: (record, status) -> if @get('activeRecord') Tracktime.AppChannel.command 'addTime', @get('activeRecord'), @get('startedAt') if status params = activeRecord: record.id startedAt: (new Date()).toISOString() else params = activeRecord: '' startedAt: null @save params, ajaxSync: true url: config.SERVER + '/users/' + @id success: (model, response, options) => record.trigger 'isActive', status error: (model, response, options) => @trigger 'flash', response.responseJSON.error (module?.exports = Tracktime.User.Auth) or @Tracktime.User.Auth = Tracktime.User.Auth class Tracktime.ActionsCollection extends Backbone.Collection model: Tracktime.Action collectionName: config.collection.actions url: '/actions' localStorage: new Backbone.LocalStorage @collectionName defaultActions: [ { title: 'Add Record', type: 'Record' } { title: 'Search', type: 'Search' } ] active: null initialize: -> @on 'remove', @setDefaultActive _.each @defaultActions, @addAction addAction: (action, params = {}) => @push new Tracktime.Action[action.type] _.extend action, params if (Tracktime.Action[action.type]) setDefaultActive: -> @at(0).setActive() unless @findWhere isActive: true setActive: (active) -> @active?.set 'isActive', false active.set 'isActive', true @active = active @trigger 'change:active', @active getActive: -> @active getActions: -> _.filter @models, (model) -> model.get('isVisible') (module?.exports = Tracktime.ActionsCollection) or @Tracktime.ActionsCollection = Tracktime.ActionsCollection class Tracktime.ProjectsCollection extends Tracktime.Collection model: Tracktime.Project collectionName: config.collection.projects url: config?.SERVER + '/projects' urlRoot: config?.SERVER + '/projects' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @on 'sync', @makeList comparator: (model) -> - (new Date(model.get('date'))).getTime() addProject: (options) -> _.extend options, {date: (new Date()).toISOString()} success = (result) => $.alert content: 'Project: save success' timeout: 2000 style: 'btn-success' error = () => $.alert 'Project: save error' @addModel options, success: success, error: error makeList: -> list = {} _.each @models, (model, index) -> list[model.get('_id')] = model.get('name') Tracktime.AppChannel.reply 'projectsList', () -> list useProject: (id) -> project = @get(id) if project.has('useCount') useCount = project.get('useCount') + 1 else useCount = 1 project.save {'useCount': useCount}, {ajaxSync: false} (module?.exports = Tracktime.ProjectsCollection) or @Tracktime.ProjectsCollection = Tracktime.ProjectsCollection class Tracktime.RecordsCollection extends Tracktime.Collection model: Tracktime.Record collectionName: config.collection.records url: config?.SERVER + '/records' urlRoot: config?.SERVER + '/records' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @filter = {} @defaultFilter = isDeleted: false comparator: (model) -> - (new Date(model.get('date'))).getTime() setFilter: (filter) -> @resetFilter() unless filter == null pairs = filter.match(/((user|project)\/[a-z0-9A-Z]{24})+/g) if pairs _.each pairs, (pair, index) -> _p = pair.split '/' @filter[_p[0]] = _p[1] , @ @filter resetFilter: -> @filter = _.clone @defaultFilter removeFilter: (key) -> if key of @filter delete @filter[key] getFilter: (removeDefault = true) -> result = {} if removeDefault keys = _.keys @defaultFilter result = _.omit @filter, keys else result = @filter result addRecord: (options) -> _.extend options, {date: (new Date()).toISOString()} options.recordDate = (new Date()).toISOString() if _.isEmpty(options.recordDate) success = (result) => $.alert content: 'Record: save success' timeout: 2000 style: 'btn-success' @trigger 'newRecord', result error = () => $.alert 'Record: save error' @addModel options, success: success, error: error getModels: (except = []) -> models = {} limit = 6 if @length > 0 models = _.filter @models, (model) => model.isSatisfied @filter models = _.filter models, (model) -> _.indexOf(except, model.id) == -1 _.first models, limit (module?.exports = Tracktime.RecordsCollection) or @Tracktime.RecordsCollection = Tracktime.RecordsCollection class Tracktime.UsersCollection extends Tracktime.Collection model: Tracktime.User collectionName: config.collection.users url: config?.SERVER + '/users' urlRoot: config?.SERVER + '/users' localStorage: new Backbone.LocalStorage @collectionName initialize: () -> @on 'sync', @makeList addUser: (options) -> _.extend options, {date: (new Date()).toISOString()} success = (result) => $.alert content: 'User: save success' timeout: 2000 style: 'btn-success' error = () => $.alert 'User: save error' @addModel options, success: success, error: error makeList: (collection, models) -> list = {} _.each collection.models, (model, index) -> list[model.get('_id')] = "#{model.get('first_name')} #{model.get('last_name')}" Tracktime.AppChannel.reply 'usersList', () -> list (module?.exports = Tracktime.UsersCollection) or @Tracktime.UsersCollection = Tracktime.UsersCollection Tracktime.AppChannel = Backbone.Radio.channel 'app' _.extend Tracktime.AppChannel, isOnline: null userStatus: null router: null init: -> @on 'isOnline', (status) => @isOnline = status @on 'userStatus', (status) => @changeUserStatus status @checkOnline() @setWindowListeners() @model = new Tracktime() @bindComply() @bindRequest() return @ checkOnline: -> if window.navigator.onLine == true @checkServer() else @trigger 'isOnline', false checkServer: -> deferred = $.Deferred() serverOnlineCallback = (status) => @trigger 'isOnline', true successCallback = (result) => @trigger 'isOnline', true deferred.resolve() errorCallback = (jqXHR, textStatus, errorThrown) => @trigger 'isOnline', false deferred.resolve() try $.ajax url: "#{config.SERVER}/status" async: false dataType: 'jsonp' jsonpCallback: 'serverOnlineCallback' success: successCallback error: errorCallback catch exception_var @trigger 'isOnline', false return deferred.promise() setWindowListeners: -> window.addEventListener "offline", (e) => @trigger 'isOnline', false , false window.addEventListener "online", (e) => @checkServer() , false bindComply: -> @comply 'start': @startApp 'newRecord': @newRecord 'newProject': @newProject 'newUser': @newUser 'useProject': @useProject 'addAction': @addAction 'serverOnline': @serverOnline 'serverOffline': @serverOffline 'checkOnline': @checkOnline 'userAuth': @userAuth 'userGuest': @userGuest 'activeRecord': @activeRecord 'addTime': @addTime bindRequest: -> @reply 'isOnline', => @isOnline @reply 'userStatus', => @userStatus @reply 'projects', => @model.get 'projects' @reply 'users', => @model.get 'users' @reply 'projectsList', => {} @reply 'usersList', => {} startApp: -> Backbone.history.start pushState: false newRecord: (options) -> _.extend options, user: @model.get('authUser').id @model.get('records').addRecord(options) newProject: (options) -> @model.get('projects').addProject(options) newUser: (options) -> @model.get('users').addUser(options) addAction: (options, params) -> action = @model.get('actions').addAction(options, params) action.setActive() activeRecord: (record, status) -> @model.get('authUser').setActiveRecord record, status addTime: (record, start) -> # diff = moment(new Date()) - moment(new Date(start)) record = @model.get('records').get(record) if record instanceof Tracktime.Record record.addTime moment(new Date()).diff(new Date(start), 'second') serverOnline: -> @trigger 'isOnline', true useProject: (id) -> @model.get('projects').useProject id serverOffline: -> @trigger 'isOnline', false userAuth: -> @trigger 'userStatus', true userGuest: -> @trigger 'userStatus', false changeUserStatus: (status) -> # @todo here get user session - if success status true else false if @router != null @router.view.close() delete @router.view if status == true @router = new Tracktime.AppRouter model: @model @trigger 'isOnline', @isOnline else @router = new Tracktime.GuestRouter model: @model checkActive: (id) -> id == @model.get('authUser').get('activeRecord') (module?.exports = Tracktime.AppChannel) or @Tracktime.AppChannel = Tracktime.AppChannel class Tracktime.ActionView extends Backbone.View tagName: 'li' className: 'btn' events: 'click a': 'setActive' initialize: () -> # _.bindAll @model, 'change:isActive', @update setActive: () -> @model.setActive() (module?.exports = Tracktime.ActionView) or @Tracktime.ActionView = Tracktime.ActionView class Tracktime.ActionsView extends Backbone.View el: '#actions-form' menu: '#actions-form' template: JST['actions/actions'] views: {} initialize: (options) -> _.extend @, options @listenTo @collection, 'change:active', @renderAction @listenTo @collection, 'add', @addAction @render() render: () -> @$el.html @template() @menu = $('.dropdown-menu', '.select-action', @$el) _.each @collection.getActions(), @addAction @collection.at(0).setActive() addAction: (action) => listBtn = new Tracktime.ActionView.ListBtn model: action @menu.append listBtn.$el @setSubView "listBtn-#{listBtn.cid}", listBtn $('[data-toggle="tooltip"]', listBtn.$el).tooltip() renderAction: (action) -> if Tracktime.ActionView[action.get('type')] @$el.parents('.navbar').attr 'class', "navbar #{action.get('navbarClass')} shadow-z-1" @setSubView "actionDetails", new Tracktime.ActionView[action.get('type')] model: action (module?.exports = Tracktime.ActionsView) or @Tracktime.ActionsView = Tracktime.ActionsView class Tracktime.ActionView.ActiveBtn extends Backbone.View el: '#action_type' initialize: () -> @render() render: () -> model = @model.toJSON() if model.canClose model.btnClass = model.btnClassEdit model.icon.className = model.icon.classNameEdit @$el .attr 'class', "btn btn-fab #{model.btnClass} dropdown-toggle " .find('i').attr('title', model.title).attr('class', model.icon.className).html model.icon.letter (module?.exports = Tracktime.ActionView.ActiveBtn) or @Tracktime.ActionView.ActiveBtn = Tracktime.ActionView.ActiveBtn class Tracktime.ActionView.ListBtn extends Backbone.View tagName: 'li' template: JST['actions/listbtn'] events: 'click': 'actionActive' initialize: (options) -> _.extend @, options @render() @listenTo @model, 'change:isActive', @updateActionControl @listenTo @model, 'destroy', @close render: () -> model = @model.toJSON() if model.canClose model.btnClass = model.btnClassEdit model.icon.className = model.icon.classNameEdit @$el.html @template model if @model.get('isActive') == true @$el.addClass 'active' @updateActionControl() else @$el.removeClass 'active' actionActive: (event) -> event.preventDefault() @model.setActive() updateActionControl: () -> @$el.siblings().removeClass 'active' @$el.addClass 'active' $("#action_type").replaceWith (new Tracktime.ActionView.ActiveBtn model: @model).$el (module?.exports = Tracktime.ActionView.ListBtn) or @Tracktime.ActionView.ListBtn = Tracktime.ActionView.ListBtn class Tracktime.ActionView.Project extends Backbone.View container: '.action-wrapper' template: JST['actions/details/project'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'projectModel' placeholder: @model.get 'title' field: 'name' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() textarea.on 'tSubmit', @sendForm $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' textareaInput: (event) => window.setTimeout () => diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.currentTarget).val() , 500 sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.Project) or @Tracktime.ActionView.Project = Tracktime.ActionView.Project class Tracktime.ActionView.Record extends Backbone.View container: '.action-wrapper' template: JST['actions/details/record'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'recordModel' placeholder: @model.get 'title' field: 'subject' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() window.setTimeout () => textarea.$el.trigger 'input' , 100 textarea.on 'tSubmit', @sendForm $('placeholder#slider', @$el).replaceWith (new Tracktime.Element.Slider model: @model.get 'recordModel' field: 'recordTime' ).$el $('placeholder#selectday', @$el).replaceWith (new Tracktime.Element.SelectDay model: @model.get 'recordModel' field: 'recordDate' ).$el projectDefinition = new Tracktime.Element.ProjectDefinition model: @model.get 'recordModel' field: 'project' $('.floating-label', "#actions-form").append projectDefinition.$el $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' $('[data-toggle="tooltip"]').tooltip() textareaInput: (event) -> diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.target).val() sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.Record) or @Tracktime.ActionView.Record = Tracktime.ActionView.Record class Tracktime.ActionView.Search extends Backbone.View container: '.action-wrapper' template: JST['actions/details/search'] tmpDetails: {} views: {} initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() (module?.exports = Tracktime.ActionView.Search) or @Tracktime.ActionView.Search = Tracktime.ActionView.Search class Tracktime.ActionView.User extends Backbone.View container: '.action-wrapper' template: JST['actions/details/user'] views: {} events: 'click #send-form': 'sendForm' 'input textarea': 'textareaInput' initialize: (options) -> _.extend @, options @render() render: () -> $(@container).html @$el.html @template @model.toJSON() textarea = new Tracktime.Element.Textarea model: @model.get 'userModel' placeholder: @model.get 'title' field: 'PI:NAME:<NAME>END_PI' $('placeholder#textarea', @$el).replaceWith textarea.$el $.material.input "[name=#{textarea.name}]" textarea.$el.textareaAutoSize().focus() textarea.on 'tSubmit', @sendForm $('placeholder#btn_close_action', @$el).replaceWith (new Tracktime.Element.ElementCloseAction model: @model ).$el if @model.get 'canClose' textareaInput: (event) => window.setTimeout () => diff = $('#actions-form').outerHeight() - $('.navbar').outerHeight(true) $('#actions-form').toggleClass "shadow-z-2", (diff > 10) $(".details-container").toggleClass 'hidden', _.isEmpty $(event.target).val() , 500 sendForm: () => @model.processAction() (module?.exports = Tracktime.ActionView.User) or @Tracktime.ActionView.User = Tracktime.ActionView.User class Tracktime.AdminView.Header extends Backbone.View container: '#header' template: JST['admin/layout/header'] initialize: (options) -> @render() render: () -> $(@container).html @$el.html @template() (module?.exports = Tracktime.AdminView.Header) or @Tracktime.AdminView.Header = Tracktime.AdminView.Header class Tracktime.AdminView.ActionView extends Backbone.View tagName: 'li' className: 'list-group-item' template: JST['actions/admin_action'] events: 'click .btn-call-action': "callAction" 'click .edit.btn': "editAction" initialize: -> @render() render: -> @$el.html @template @model.toJSON() editAction: -> callAction: -> $.alert 'Test action call' (module?.exports = Tracktime.AdminView.ActionView) or @Tracktime.AdminView.ActionView = Tracktime.AdminView.ActionView class Tracktime.AdminView.ActionsView extends Backbone.View container: '#main' template: JST['admin/actions'] templateHeader: JST['admin/actions_header'] tagName: 'ul' className: 'list-group' views: {} actionsTypes: ['Project', 'Record', 'User', 'Search'] initialize: () -> @render() render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Actions'} @$el.prepend @templateHeader() @renderActionsList() renderActionsList: () -> _.each @actionsTypes, (atype) => actionView = new Tracktime.AdminView.ActionView model: new Tracktime.Action[atype]() @$el.append actionView.el @setSubView "atype-#{atype}", actionView , @ (module?.exports = Tracktime.AdminView.ActionsView) or @Tracktime.AdminView.ActionsView = Tracktime.AdminView.ActionsView class Tracktime.AdminView.Dashboard extends Backbone.View container: '#main' template: JST['admin/dashboard'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template() (module?.exports = Tracktime.AdminView.Dashboard) or @Tracktime.AdminView.Dashboard = Tracktime.AdminView.Dashboard class Tracktime.AdminView.ProjectsView extends Backbone.View container: '#main' template: JST['admin/projects'] tagName: 'ul' className: 'list-group' views: {} initialize: () -> @render() @listenTo @collection, "reset", @resetProjectsList @listenTo @collection, "add", @addProject @listenTo @collection, "remove", @removeProject render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Projects'} @resetProjectsList() resetProjectsList: () -> _.each @collection.where(isDeleted: false), (project) => projectView = new Tracktime.AdminView.ProjectView { model: project } @$el.append projectView.el @setSubView "project-#{project.cid}", projectView , @ addProject: (project, collection, params) -> projectView = new Tracktime.AdminView.ProjectView { model: project } $(projectView.el).prependTo @$el @setSubView "project-#{project.cid}", projectView removeProject: (project, args...) -> projectView = @getSubView "project-#{project.cid}" projectView.close() if projectView (module?.exports = Tracktime.AdminView.ProjectsView) or @Tracktime.AdminView.ProjectsView = Tracktime.AdminView.ProjectsView class Tracktime.AdminView.UsersView extends Backbone.View container: '#main' template: JST['admin/users'] tagName: 'ul' className: 'list-group' views: {} initialize: () -> @render() @listenTo @collection, "reset", @resetUsersList @listenTo @collection, "add", @addUser @listenTo @collection, "remove", @removeUser render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Users'} @resetUsersList() resetUsersList: () -> _.each @collection.where(isDeleted: false), (user) => userView = new Tracktime.AdminView.UserView { model: user } @$el.append userView.el @setSubView "user-#{user.cid}", userView , @ addUser: (user, collection, params) -> userView = new Tracktime.AdminView.UserView { model: user } $(userView.el).prependTo @$el @setSubView "user-#{user.cid}", userView removeUser: (user, args...) -> userView = @getSubView "user-#{user.cid}" userView.close() if userView (module?.exports = Tracktime.AdminView.UsersView) or @Tracktime.AdminView.UsersView = Tracktime.AdminView.UsersView class Tracktime.AppView extends Backbone.View container: '#panel' className: '' template: JST['global/app'] views: {} initialize: -> @render() render: -> $(@container).html @$el.html @template @model.toJSON() initUI: -> $.material.init() (module?.exports = Tracktime.AppView) or @Tracktime.AppView = Tracktime.AppView class Tracktime.Element extends Backbone.View initialize: () -> @render() render: () -> @$el.html 'void element' (module?.exports = Tracktime.Element) or @Tracktime.Element = Tracktime.Element class Tracktime.Element.ElementCloseAction extends Tracktime.Element tagName: 'button' className: 'btn btn-close-action btn-fab btn-flat btn-fab-mini' hint: 'Cancel action' events: 'click': 'closeAction' initialize: (options = {}) -> _.extend @, options @render() render: () -> @$el .attr 'title', @hint .append $('<i />', class: 'mdi-content-remove') closeAction: () => @model.destroy() (module?.exports = Tracktime.Element.ElementCloseAction) or @Tracktime.Element.ElementCloseAction = Tracktime.Element.ElementCloseAction class Tracktime.Element.ProjectDefinition extends Tracktime.Element className: 'project_definition' template: JST['elements/project_definition'] defaultTitle: 'Select project' searchStr: '' events: 'click .btn-white': 'selectProject' initialize: (options = {}) -> _.extend @, options @render() @projects = Tracktime.AppChannel.request 'projects' @projectsList = Tracktime.AppChannel.request 'projectsList' @projects.on 'sync', @renderList render: -> @$el.html @template title: @defaultTitle @renderList() $('.input-cont', @$el) .on 'click', (event) -> event.stopPropagation() $('.input-cont input', @$el) .on 'keyup', @setSearch setSearch: (event) => @searchStr = $(event.currentTarget).val().toLowerCase() @renderList() getList: (limit = 5) -> @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList unless _.isEmpty @searchStr keys = _.filter keys, (key) => @projectsList[key].toLowerCase().indexOf(@searchStr) > -1 sublist = {} i = 0 limit = Math.min(limit, keys.length) while i < limit sublist[ keys[i] ] = @projectsList[ keys[i] ] i++ sublist renderList: => list = @getList() menu = $('.dropdown-menu', @$el) menu.children('.item').remove() @updateTitle() for own key, value of list menu.append $("<li class='item'><a class='btn btn-white' data-project='#{key}' href='##{key}'>#{value}</a></li>") menu.append $("<li class='item'><a class='btn btn-white' data-project='0' href='#0'><span class='text-muted'>No project</span></a></li>") getTitle: -> projectId = @model.get @field if projectId of @projectsList "to " + @projectsList[projectId] else @defaultTitle selectProject: (event) => event.preventDefault() projectId = $(event.currentTarget).data 'project' @model.set @field, projectId Tracktime.AppChannel.command 'useProject', projectId @updateTitle() @$el.parents('.form-control-wrapper').find('textarea').focus() updateTitle: -> $('.project_definition-toggler span.caption', @$el).text @getTitle() (module?.exports = Tracktime.Element.ProjectDefinition) or @Tracktime.Element.ProjectDefinition = Tracktime.Element.ProjectDefinition class Tracktime.Element.SelectDay extends Tracktime.Element className: 'btn-group select-day' template: JST['elements/selectday'] events: 'click button.btn': 'setDay' initialize: (options = {}) -> # @tmpDetails.recordDate = $(".select-day > .btn .caption ruby rt").html() _.extend @, options @render() @changeField() @listenTo @model, "change:#{@field}", @changeField render: -> @$el.html @template @setDays() setDays: -> moment = window.moment localeData = moment.localeData('ru') current: name: localeData.weekdays(moment()) day: moment().format("MMM Do YYYY") value: moment().toISOString() days: [ name: localeData.weekdays(moment().subtract(2, 'days')) day: moment().subtract(2, 'day').format("MMM Do YYYY") value: moment().subtract(2, 'day').toISOString() , name: localeData.weekdays(moment().subtract(1, 'day')) day: moment().subtract(1, 'day').format("MMM Do YYYY") value: moment().subtract(1, 'day').toISOString() , name: localeData.weekdays(moment()) day: moment().format("MMM Do YYYY") value: moment().toISOString() ] changeField: => # @$el.val @model.get @field # найти в списке тот день который есть в field и нажать на эту кнопку changeInput: (value) => @model.set @field, value, {silent: true} setDay: (event) -> event.preventDefault() $(".dropdown-toggle ruby", @$el).html $('ruby', event.currentTarget).html() @changeInput $(event.currentTarget).data('value') # $(".dropdown-toggle ruby rt", @$el).html() (module?.exports = Tracktime.Element.SelectDay) or @Tracktime.Element.SelectDay = Tracktime.Element.SelectDay class Tracktime.Element.Slider extends Tracktime.Element className: 'slider shor btn-primary slider-material-orange' initialize: (options = {}) -> _.extend @, options @render() @changeField() @listenTo @model, "change:#{@field}", @changeField render: () -> @$el .noUiSlider start: [0] step: 5 range: {'min': [ 0 ], 'max': [ 720 ] } .on slide: (event, inval) => if inval? and _.isNumber parseFloat inval @changeInput parseFloat inval val = inval else val = 0 currentHour = val / 720 * 12 hour = Math.floor(currentHour) minute = (currentHour - hour) * 60 $('.slider .noUi-handle').attr 'data-before', hour $('.slider .noUi-handle').attr 'data-after', Math.round(minute) @$el .noUiSlider_pips mode: 'values' values: [0,60*1,60*2,60*3,60*4,60*5,60*6,60*7,60*8,60*9,60*10,60*11,60*12] density: 2 format: to: (value) -> value / 60 from: (value) -> value changeField: () => newVal = 0 fieldValue = @model.get(@field) if fieldValue? and _.isNumber parseFloat fieldValue newVal = parseFloat @model.get @field @$el.val(newVal).trigger('slide') changeInput: (value) => @model.set @field, parseFloat(value) or 0, {silent: true} (module?.exports = Tracktime.Element.Slider) or @Tracktime.Element.Slider = Tracktime.Element.Slider #<textarea class="form-control floating-label" placeholder="textarea floating label"></textarea> class Tracktime.Element.Textarea extends Tracktime.Element name: 'action_text' tagName: 'textarea' className: 'form-control floating-label' events: 'keydown': 'fixEnter' 'keyup': 'changeInput' 'change': 'changeInput' initialize: (options = {}) -> _.extend @, options @name = "#{@name}-#{@model.cid}" @render() @listenTo @model, "change:#{@field}", @changeField render: () -> @$el.attr 'name', @name @$el.attr 'placeholder', @placeholder @$el.val @model.get @field changeField: () => @$el.val(@model.get @field).trigger('input') changeInput: (event) => @model.set @field, $(event.target).val(), {silent: true} fixEnter: (event) => if event.keyCode == 13 and not event.shiftKey event.preventDefault() @trigger 'tSubmit' (module?.exports = Tracktime.Element.Textarea) or @Tracktime.Element.Textarea = Tracktime.Element.Textarea class Tracktime.GuestView extends Backbone.View container: '#panel' className: '' template: JST['global/guest'] views: {} initialize: -> @render() render: -> $(@container).html @$el.html @template @model.toJSON() @setSubView 'login', new Tracktime.GuestView.Login model: @model @setSubView 'signin', new Tracktime.GuestView.Signin model: @model @setSubView 'fopass', new Tracktime.GuestView.Fopass model: @model initUI: -> $.material.init() (module?.exports = Tracktime.AppView) or @Tracktime.AppView = Tracktime.AppView class Tracktime.GuestView.Fopass extends Backbone.View el: '#forgotpassword' events: 'click .btn-forgotpassword': 'forgotpasswordProcess' initialize: () -> forgotpasswordProcess: (event) -> event.preventDefault() $.alert 'fopass process' (module?.exports = Tracktime.GuestView.Fopass) or @Tracktime.GuestView.Fopass = Tracktime.GuestView.Fopass class Tracktime.GuestView.Login extends Backbone.View el: '#login > form' events: 'submit': 'loginProcess' initialize: () -> @listenTo @model.get('authUser'), 'flash', @showFlash loginProcess: (event) -> event.preventDefault() @model.get('authUser').login email: $('[name=email]',@$el).val() password: $('[name=password]',@$el).val() showFlash: (message) -> $.alert message.scope.capitalizeFirstLetter() + " Error: #{message.msg}" (module?.exports = Tracktime.GuestView.Login) or @Tracktime.GuestView.Login = Tracktime.GuestView.Login class Tracktime.GuestView.Signin extends Backbone.View el: '#signin > form' events: 'submit': 'signinProcess' initialize: () -> @listenTo @model.get('authUser'), 'flash', @showFlash signinProcess: (event) -> event.preventDefault() if @checkInput() @model.get('authUser').signin first_name: $('[name=first_name]',@$el).val() last_name: $('[name=last_name]',@$el).val() email: $('[name=email]',@$el).val() password: $('[name=password]',@$el).val() checkInput: -> result = true if _.isEmpty $('[name=first_name]',@$el).val() @showFlash scope: "Signin", msg: 'First Name empty' result = false if _.isEmpty $('[name=last_name]',@$el).val() @showFlash scope: "Signin", msg: 'Last Name empty' result = false if _.isEmpty $('[name=email]',@$el).val() @showFlash scope: "Signin", msg: 'Email empty' result = false if _.isEmpty $('[name=password]',@$el).val() @showFlash scope: "Signin", msg: 'Password empty' result = false if $('[name=password]',@$el).val() != $('[name=repassword]',@$el).val() @showFlash scope: "Signin", msg: 'Repassword incorrect' result = false result showFlash: (message) -> $.alert content: message.scope.capitalizeFirstLetter() + " Error: #{message.msg}" style: "btn-danger" (module?.exports = Tracktime.GuestView.Signin) or @Tracktime.GuestView.Signin = Tracktime.GuestView.Signin class Tracktime.AppView.Footer extends Backbone.View container: '#footer' template: JST['layout/footer'] events: 'click #click-me': 'clickMe' 'click #window-close': 'windowClose' initialize: () -> @render() render: () -> $(@container).html @$el.html @template @model?.toJSON() clickMe: (event) -> event.preventDefault() $.alert 'Subview :: ' + $(event.target).attr 'href' windowClose: (event) -> event.preventDefault() $.alert 'Close window' window.close() (module?.exports = Tracktime.AppView.Footer) or @Tracktime.AppView.Footer = Tracktime.AppView.Footer class Tracktime.AppView.Header extends Backbone.View container: '#header' template: JST['layout/header'] views: {} initialize: (options) -> @options = options @render() render: () -> $(@container).html @$el.html @template() @setSubView 'actions', new Tracktime.ActionsView collection: @model.get('actions') (module?.exports = Tracktime.AppView.Header) or @Tracktime.AppView.Header = Tracktime.AppView.Header class Tracktime.AppView.Main extends Backbone.View el: '#main' template: JST['layout/main'] views: {} initialize: () -> @render() @bindEvents() render: () -> @$el.html @template @model?.toJSON() @renderRecords() bindEvents: -> @listenTo @model.get('records'), "reset", @renderRecords renderRecords: -> recordsView = new Tracktime.RecordsView {collection: @model.get('records')} @$el.html recordsView.el (module?.exports = Tracktime.AppView.Main) or @Tracktime.AppView.Main = Tracktime.AppView.Main class Tracktime.AppView.Menu extends Backbone.View container: '#menu' template: JST['layout/menu'] searchStr: '' events: 'change #isOnline': 'updateOnlineStatus' initialize: -> @render() @bindEvents() @projects = Tracktime.AppChannel.request 'projects' @projectsList = Tracktime.AppChannel.request 'projectsList' @projects.on 'all', @renderMenuList bindEvents: -> @listenTo Tracktime.AppChannel, "isOnline", (status) -> $('#isOnline').prop 'checked', status @slideout = new Slideout 'panel': $('#panel')[0] 'menu': $('#menu')[0] 'padding': 256 'tolerance': 70 $("#menuToggler").on 'click', => @slideout.toggle() $(".input-search", @container).on 'keyup', @setSearch setSearch: (event) => @searchStr = $(event.currentTarget).val().toLowerCase() @searchProject() searchProject: (event) -> @renderSearchList() getSearchList: (limit = 5) -> @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList unless _.isEmpty @searchStr keys = _.filter keys, (key) => @projectsList[key].toLowerCase().indexOf(@searchStr) > -1 sublist = {} i = 0 limit = Math.min(limit, keys.length) while i < limit sublist[ keys[i] ] = @projectsList[ keys[i] ] i++ sublist renderMenuList: => menu = $('#projects-section .list-style-group', @container) menu.children('.project-link').remove() limit = 5 @projectsList = Tracktime.AppChannel.request 'projectsList' keys = _.keys @projectsList if keys.length > 0 keys = _.sortBy keys, (key) => count = @projects.get(key).get('useCount') count = unless count == undefined then count else 0 - count i = 0 while i < limit project = @projects.get keys[i] menu.append $("<a class='list-group-item project-link' href='#records/project/#{project.id}'>#{project.get('name')}</a>").on 'click', 'a', @navTo i++ renderSearchList: => list = @getSearchList() menu = $('.menu-projects', @container) menu.children().remove() for own key, value of list menu.append $("<li><a href='#records/project/#{key}'>#{value}</a></li>").on 'click', 'a', @navTo if _.size(list) > 0 if _.isEmpty(@searchStr) menu.dropdown().hide() else menu.dropdown().show() else menu.dropdown().hide() navTo: (event) -> href = $(event.currentTarget).attr('href') projectId = href.substr(-24) Tracktime.AppChannel.command 'useProject', projectId window.location.hash = href $('.menu-projects', @container).dropdown().hide() updateOnlineStatus: (event) -> if $(event.target).is(":checked") Tracktime.AppChannel.command 'checkOnline' else Tracktime.AppChannel.command 'serverOffline' render: -> $(@container).html @$el.html @template @model?.toJSON() _.each @model.get('projects').models, (model) => projectLink = $('<a />', {class: 'list-group-item', href:"#projects/#{model.get('_id')}"}).html model.get('name') projectLink.appendTo "#projects-section .list-style-group" close: -> @slideout.close() super (module?.exports = Tracktime.AppView.Menu) or @Tracktime.AppView.Menu = Tracktime.AppView.Menu class Tracktime.AdminView.ProjectView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['projects/admin_project'] events: 'click .btn.delete': "deleteProject" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editProject" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:name", @changeName @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel attributes: -> id: @model.cid render: -> @$el.html @template @model.toJSON() $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'name' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:name' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeName: -> $('.subject', @$el).html (@model.get('name') + '').nl2br() $('.name_edit', @$el).val @model.get 'name' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update project' timeout: 2000 style: 'btn-info' editProject: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteProject: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete project' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.AdminView.ProjectView) or @Tracktime.AdminView.ProjectView = Tracktime.AdminView.ProjectView class Tracktime.ProjectView extends Backbone.View container: '#main' template: JST['projects/project'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Project Details View HERE'} (module?.exports = Tracktime.ProjectView) or @Tracktime.ProjectView = Tracktime.ProjectView class Tracktime.ProjectsView extends Backbone.View container: '#main' template: JST['projecs/projecs'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Projects HERE - Only view'} (module?.exports = Tracktime.ProjectsView) or @Tracktime.ProjectsView = Tracktime.ProjectsView class Tracktime.RecordView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['records/record'] events: 'click .btn.delete': "deleteRecord" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editRecord" 'click .btn[role=do-active]': "toggleActive" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:subject", @changeSubject @listenTo @model, "change:project", @changeProject @listenTo @model, "change:recordTime", @changeRecordTime @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel @listenTo @model, "isActive", @setActiveState @projects = Tracktime.AppChannel.request 'projects' @projects.on 'sync', @renderProjectInfo @users = Tracktime.AppChannel.request 'users' @users.on 'sync', @renderUserInfo attributes: -> id: @model.cid render: -> @$el.html @template _.extend {filter: @model.collection.getFilter()}, @model.toJSON() $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'subject' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm @$el.addClass 'current' if Tracktime.AppChannel.checkActive @model.id @changeRecordTime() @renderProjectInfo() @renderUserInfo() toggleActive: -> Tracktime.AppChannel.command 'activeRecord', @model, not(Tracktime.AppChannel.checkActive @model.id) setActiveState: (status) -> console.log 'try set acgive state', status, @$el $('.list-group-item').removeClass 'current' @$el.toggleClass 'current', status changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:subject' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeSubject: -> $('.subject', @$el).html (@model.get('subject') + '').nl2br() $('.subject_edit', @$el).val @model.get 'subject' changeRecordTime: -> duration = moment.duration(parseInt(@model.get('recordTime'), 10),'minute') durationStr = duration.get('hours') + ':' + duration.get('minutes') $('.recordTime .value', @$el).html durationStr changeProject: -> @renderProjectInfo() renderProjectInfo: => project_id = @model.get('project') @projectsList = Tracktime.AppChannel.request 'projectsList' if project_id of @projectsList title = @projectsList[project_id] $(".record-info-project span", @$el).html title $(".record-info-project", @$el).removeClass 'hidden' $(".btn.type i", @$el).removeClass().addClass('letter').html title.letter() else $(".record-info-project", @$el).addClass 'hidden' $(".btn.type i", @$el).removeClass().addClass('mdi-action-bookmark-outline').html '' renderUserInfo: => user_id = @model.get('user') @usersList = Tracktime.AppChannel.request 'usersList' if user_id of @usersList title = @usersList[user_id] $(".record-info-user span", @$el).html title $(".record-info-user", @$el).removeClass 'hidden' else $(".record-info-user", @$el).addClass 'hidden' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update record' timeout: 2000 style: 'btn-info' editRecord: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteRecord: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete record' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.RecordView) or @Tracktime.RecordView = Tracktime.RecordView class Tracktime.RecordsView extends Backbone.View container: '#main' template: JST['records/records'] tagName: 'ul' className: 'list-group' initialize: () -> @views = {} @render() @listenTo @collection, "sync", @resetRecordsList @listenTo @collection, "remove", @removeRecord # @listenTo @collection, "add", @addRecord @listenTo @collection, "newRecord", @newRecord $('.removeFilter', @container).on 'click', @removeFilter $('.btn-loadmore', @container).on 'click', @loadMoreRecords $('.scrollWrapper').on 'scroll', @autoLoadMoreRecords @projects = Tracktime.AppChannel.request 'projects' @projects.on 'sync', @updateProjectInfo @users = Tracktime.AppChannel.request 'users' @users.on 'sync', @updateUserInfo render: () -> $(@container).html @$el.html '' @$el.before @template {title: 'Records', filter: @collection.getFilter()} @resetRecordsList() @updateProjectInfo() @updateUserInfo() $('.btn-loadmore', @container).appendTo @container autoLoadMoreRecords: (event) => delta = $(window).height() - $('.btn-loadmore').offset().top - $('.btn-loadmore').height() $('.btn-loadmore', @container).click() if delta > 0 loadMoreRecords: (event) => modelsNewCount = @resetRecordsList() if modelsNewCount > 0 $('.btn-loadmore', @container).show().appendTo @container else $('.btn-loadmore', @container).remove() newRecord: (record) -> @addRecord(record) # @loadMoreRecords() # dateEl = moment(record.get('recordDate') ).format("YYYY-MM-DD") # if $("##{dateEl}").length > 0 # $('.scrollWrapper').scrollTop($("##{dateEl}").offset().top + $(".scrollWrapper").scrollTop() - 78) sortRecords: -> parentCont = '#main .list-group' sortedList = $('.list-group-item', parentCont).sort (a, b) -> timeA = new Date($('.record-info time', a).attr('datetime')).getTime() timeB = new Date($('.record-info time', b).attr('datetime')).getTime() timeB - timeA dates = $.unique($('.record-info time', parentCont).map((i, el) -> moment($(el).attr('datetime')).format("YYYY-MM-DD") )).sort (a, b) -> b > a _.each dates, (el, b) -> if $("##{el}").length < 1 $(parentCont).append $("<ul> /", {id: el}).append $("<li />", {class: 'list-group-items-group navbar navbar-primary'}).html moment(el).format("Do MMMM YYYY") _.each sortedList, (item) -> id = moment($('.record-info time', item).attr('datetime')).format("YYYY-MM-DD") $("##{id}", parentCont).append item resetRecordsList_old: -> frag = document.createDocumentFragment() models = @collection.getModels @exceptRecords() _.each models, (record) -> recordView = @setSubView "record-#{record.cid}", new Tracktime.RecordView model: record frag.appendChild recordView.el , @ @$el.prepend frag @sortRecords() resetRecordsList: -> parentCont = '#main .list-group' models = @collection.getModels @exceptRecords() _.each models, (record) -> recordView = @setSubView "record-#{record.cid}", new Tracktime.RecordView model: record @listGroup(record).append recordView.el , @ models.length listGroup: (record) -> parentCont = '#main .list-group' # получить дату группы из модели groupDate = moment(record.get('recordDate')).format("YYYY-MM-DD") group = null # если группа существует то вернуть ев jquery if $("##{groupDate}").length > 0 group = $("##{groupDate}") # иначе else # создать группу с заголовком group = $("<ul> /", {id: groupDate}).append $("<li />", {class: 'list-group-items-group navbar navbar-primary'}).html moment(groupDate).format("Do MMMM YYYY") # если списков нет то добавить группу просто if $(".list-group > ul", parentCont).length < 1 $(parentCont).append group # иначе else # получить массив id групп - добавить в него новый элемент # отсортировать по убыыванию groups = $("ul.list-group > ul").map( (idx, el) -> $(el).attr('id') ) groups.push groupDate groups = groups.sort( (a, b) -> b > a ) # получить индекс в массиве groupIndex = _. indexOf groups, groupDate # если индекс равен длине массива то добавить группу в конец # иначе если индекс равен 0 массива то добавить группу в начало if groupIndex == 0 $(parentCont).prepend group # если есть предыдущий искомому элемент полученный по индексу то добавть ul после предыдушего else prevIndexGroup = groups[groupIndex - 1] $("##{prevIndexGroup}").after group group exceptRecords: () -> _.pluck $('.list-group-item > div', @container), 'id' updateProjectInfo: -> @projectsList = Tracktime.AppChannel.request 'projectsList' key = $('.removeFilter[data-exclude=project]', @container).data('value') if key of @projectsList $('.removeFilter[data-exclude=project] .caption', @container).text @projectsList[key] updateUserInfo: -> @usersList = Tracktime.AppChannel.request 'usersList' key = $('.removeFilter[data-exclude=user]', @container).data('value') if key of @usersList $('.removeFilter[data-exclude=user] .caption', @container).text @usersList[key] addRecord: (record, collection, params) -> # add record - depricated if record.isSatisfied @collection.filter recordView = new Tracktime.RecordView { model: record } $(recordView.el).insertAfter $('.list-group-items-group', @listGroup(record)) $('.btn[role="do-active"]', recordView.el).click() # @setSubView "record-#{record.cid}", recordView removeFilter: (event) => key = $(event.currentTarget).data('exclude') # remove key from collection filter @collection.removeFilter key # remove all records from list @$el.find('.list-group > li').remove() # refresh filter list in header $(event.currentTarget).remove() # add records by filter from collection @resetRecordsList() removeRecord: (record, args...) -> recordView = @getSubView "record-#{record.cid}" recordView.close() if recordView (module?.exports = Tracktime.RecordsView) or @Tracktime.RecordsView = Tracktime.RecordsView class Tracktime.ReportView extends Backbone.View container: '#main' template: JST['reports/report'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Report Details HERE'} (module?.exports = Tracktime.ReportView) or @Tracktime.ReportView = Tracktime.ReportView class Tracktime.ReportsView extends Backbone.View container: '#main' template: JST['reports/reports'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'Reports HERE'} (module?.exports = Tracktime.ReportsView) or @Tracktime.ReportsView = Tracktime.ReportsView class Tracktime.AdminView.UserView extends Backbone.View tagName: 'li' className: 'list-group-item shadow-z-1' template: JST['users/admin_user'] events: 'click .btn.delete': "deleteUser" 'click .subject': "toggleInlineEdit" 'click .edit.btn': "editUser" initialize: -> unless @model.get 'isDeleted' @render() @listenTo @model, "change:isDeleted", @changeIsDeleted @listenTo @model, "change:first_name", @changeName @listenTo @model, "change:isEdit", @changeIsEdit @listenTo @model, "sync", @syncModel attributes: -> id: @model.cid render: -> data = _.extend {}, @model.toJSON(), hash: window.md5 @model.get('email').toLowerCase() @$el.html @template data $('.subject_edit', @$el) .on('keydown', @fixEnter) .textareaAutoSize() textarea = new Tracktime.Element.Textarea model: @model className: 'subject_edit form-control hidden' field: 'first_name' $('placeholder#textarea', @$el).replaceWith textarea.$el textarea.on 'tSubmit', @sendForm changeIsEdit: -> @$el.toggleClass 'editmode', @model.isEdit == true syncModel: (model, options, params) -> model.isEdit = false model.trigger 'change:isEdit' model.trigger 'change:first_name' #todo update all elements after changeIsDeleted: -> @$el.remove() # @todo possible not need changeName: -> $('.subject', @$el).html (@model.get('first_name') + '').nl2br() $('.name_edit', @$el).val @model.get 'first_name' toggleInlineEdit: -> @$el.find('.subject_edit').css 'min-height', @$el.find('.subject').height() @$el.find('.subject, .subject_edit').css('border', 'apx solid blue').toggleClass 'hidden' @$el.find('.subject_edit').textareaAutoSize().focus() sendForm: => @toggleInlineEdit() @model.save {}, ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'update user' timeout: 2000 style: 'btn-info' editUser: -> $('.scrollWrapper').animate 'scrollTop': @$el.offset().top - $('.scrollWrapper').offset().top + $('.scrollWrapper').scrollTop() , 400, (event) => @model.isEdit = true @model.trigger 'change:isEdit' deleteUser: (event) -> event.preventDefault() @model.destroy ajaxSync: Tracktime.AppChannel.request 'isOnline' success: (model, respond) -> $.alert content: 'delete user' timeout: 2000 style: 'btn-danger' (module?.exports = Tracktime.AdminView.UserView) or @Tracktime.AdminView.UserView = Tracktime.AdminView.UserView class Tracktime.UserView extends Backbone.View container: '#main' template: JST['users/user'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User index'} (module?.exports = Tracktime.UserView) or @Tracktime.UserView = Tracktime.UserView class Tracktime.UserView.Details extends Backbone.View container: '#main' template: JST['users/details'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User details HERE'} (module?.exports = Tracktime.UserView.Details) or @Tracktime.UserView.Details = Tracktime.UserView.Details class Tracktime.UserView.Rates extends Backbone.View container: '#main' template: JST['users/rates'] initialize: () -> @render() render: () -> $(@container).html @$el.html @template {title: 'User Rates'} (module?.exports = Tracktime.UserView.Rates) or @Tracktime.UserView.Rates = Tracktime.UserView.Rates $ -> Tracktime.AppChannel.init().command 'start' return class Tracktime.AdminRouter extends Backbone.SubRoute routes: '': 'dashboard' 'users': 'users' 'projects': 'projects' 'dashboard': 'dashboard' 'actions': 'actions' initialize: (options) -> _.extend @, options dashboard: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.Dashboard() users: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.UsersView collection: @parent.model.get 'users' newAction = @parent.model.get('actions').addAction title: 'Add users' type: 'User' , scope: 'admin:users' newAction.setActive() projects: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.ProjectsView collection: @parent.model.get 'projects' newAction = @parent.model.get('actions').addAction title: 'Add projects' type: 'Project' , scope: 'admin:projects' newAction.setActive() actions: () -> @parent.view.setSubView 'main', new Tracktime.AdminView.ActionsView collection: @parent.model.get 'actions' (module?.exports = Tracktime.AdminRouter) or @Tracktime.AdminRouter = Tracktime.AdminRouter class Tracktime.AppRouter extends Backbone.Router routes: '': 'index' #index 'projects*subroute': 'invokeProjectsRouter' #Projects 'records*subroute': 'invokeRecordsRouter' #Projects 'reports*subroute': 'invokeReportsRouter' #Reports 'user*subroute': 'invokeUserRouter' #User 'admin*subroute': 'invokeAdminRouter' #Admin '*actions': 'default' #??? initialize: (options) -> _.extend @, options @on 'route', (route, params) => @removeActionsExcept(route) unless route.substr(0,6) == 'invoke' @initInterface() # @navigate 'projects', trigger: true, replace: false Backbone.history.loadUrl(Backbone.history.fragment); addListener: (subroute, scope) -> @listenTo subroute, 'route', (route, params) => @removeActionsExcept "#{scope}:#{route}" invokeProjectsRouter: (subroute) -> unless @projectsRouter @projectsRouter = new Tracktime.ProjectsRouter 'projects', parent: @ @addListener @projectsRouter, 'projects' invokeRecordsRouter: (subroute) -> unless @recordsRouter @recordsRouter = new Tracktime.RecordsRouter 'records', parent: @ @addListener @recordsRouter, 'records' invokeReportsRouter: (subroute) -> unless @reportsRouter @reportsRouter = new Tracktime.ReportsRouter 'reports', parent: @ @addListener @reportsRouter, 'reports' invokeUserRouter: (subroute) -> unless @userRouter @userRouter = new Tracktime.UserRouter 'user', parent: @ @addListener @userRouter, 'users' invokeAdminRouter: (subroute) -> unless @adminRouter @adminRouter = new Tracktime.AdminRouter 'admin', parent: @ @addListener @adminRouter, 'admin' initInterface: () -> @view = new Tracktime.AppView model: @model @view.setSubView 'header', new Tracktime.AppView.Header model: @model @view.setSubView 'footer', new Tracktime.AppView.Footer() @view.setSubView 'menu', new Tracktime.AppView.Menu model: @model @view.initUI() index: -> # @navigate 'projects', trigger: true, replace: false default: (actions) -> $.alert 'Unknown page' @navigate '', true removeActionsExcept: (route) -> if @model.get('actions') _.each @model.get('actions').models, (action) -> action.destroy() if action && action.has('scope') and action.get('scope') isnt route (module?.exports = Tracktime.AppRouter) or @Tracktime.AppRouter = Tracktime.AppRouter class Tracktime.GuestRouter extends Backbone.Router routes: '': 'index' #index '*actions': 'default' #??? initialize: (options) -> _.extend @, options @initInterface() # @navigate '/', trigger: true, replace: false Backbone.history.loadUrl(Backbone.history.fragment); initInterface: () -> @view = new Tracktime.GuestView model: @model # @view.setSubView 'header', new Tracktime.GuestView.Header model: @model # @view.setSubView 'footer', new Tracktime.AppView.Footer() # @view.setSubView 'menu', new Tracktime.AppView.Menu model: @model @view.initUI() index: -> # $.alert 'Guest index page' default: (actions) -> # $.alert 'Unknown guest page' @navigate '', true (module?.exports = Tracktime.GuestRouter) or @Tracktime.GuestRouter = Tracktime.GuestRouter class Tracktime.ProjectsRouter extends Backbone.SubRoute routes: '': 'list' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options list: () -> $.alert "whole records list in projects section" @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' details: (id) -> @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' edit: (id) -> $.alert "projects edit #{id}" delete: (id) -> $.alert "projects delete #{id}" add: (id) -> $.alert "projects add #{id}" save: (id) -> $.alert "projects save #{id}" (module?.exports = Tracktime.ProjectsRouter) or @Tracktime.ProjectsRouter = Tracktime.ProjectsRouter class Tracktime.RecordsRouter extends Backbone.SubRoute routes: '': 'list' '*filter': 'listFilter' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options list: () -> collection = @parent.model.get 'records' collection.resetFilter() @parent.view.setSubView 'main', new Tracktime.RecordsView collection: collection listFilter: (filter) -> collection = @parent.model.get 'records' collection.setFilter filter @parent.view.setSubView 'main', new Tracktime.RecordsView collection: collection details: (id) -> $.alert "details" @parent.view.setSubView 'main', new Tracktime.RecordsView collection: @parent.model.get 'records' edit: (id) -> $.alert "records edit #{id}" delete: (id) -> $.alert "records delete #{id}" add: (id) -> $.alert "records add #{id}" save: (id) -> $.alert "records save #{id}" (module?.exports = Tracktime.RecordsRouter) or @Tracktime.RecordsRouter = Tracktime.RecordsRouter class Tracktime.ReportsRouter extends Backbone.SubRoute routes: '': 'list' ':id': 'details' ':id/edit': 'edit' ':id/delete': 'delete' ':id/add': 'add' ':id/save': 'save' initialize: (options) -> _.extend @, options @parent.view.setSubView 'main', new Tracktime.ReportsView() list: () -> @parent.view.setSubView 'main', new Tracktime.ReportsView() details: (id) -> @parent.view.setSubView 'main', new Tracktime.ReportView() edit: (id) -> $.alert "reports edit #{id}" delete: (id) -> $.alert "reports delete #{id}" add: (id) -> $.alert "reports add #{id}" save: (id) -> $.alert "reports save #{id}" (module?.exports = Tracktime.ReportsRouter) or @Tracktime.ReportsRouter = Tracktime.ReportsRouter class Tracktime.UserRouter extends Backbone.SubRoute routes: '': 'details' 'rates': 'rates' 'logout': 'logout' initialize: (options) -> _.extend @, options # @parent.view.setSubView 'main', new Tracktime.UserView() details: () -> @parent.view.setSubView 'main', new Tracktime.UserView.Details() rates: () -> @parent.view.setSubView 'main', new Tracktime.UserView.Rates() logout: () -> @parent.model.get('authUser').logout() (module?.exports = Tracktime.UserRouter) or @Tracktime.UserRouter = Tracktime.UserRouter
[ { "context": "ports backwards\n * @namespace backwards\n * @author Svein Olav Risdal\n * @copyright 2014 Svein Olav Risdal\n * @license\n", "end": 184, "score": 0.9999013543128967, "start": 167, "tag": "NAME", "value": "Svein Olav Risdal" }, { "context": "ds\n * @author Svein Olav Risdal\n * @copyright 2014 Svein Olav Risdal\n * @license\n * The MIT License (MIT)\n * \n * Copyr", "end": 221, "score": 0.9999003410339355, "start": 204, "tag": "NAME", "value": "Svein Olav Risdal" }, { "context": " * The MIT License (MIT)\n * \n * Copyright (c) 2014 Svein Olav Risdal\n *\n * Permission is hereby granted, free of charg", "end": 302, "score": 0.9998985528945923, "start": 285, "tag": "NAME", "value": "Svein Olav Risdal" }, { "context": " age : 29,\n gender: \"male\",\n name : \"John Doe\"\n };\n\n extend( obj, { age: 30, name: \"John ", "end": 20207, "score": 0.9998085498809814, "start": 20199, "tag": "NAME", "value": "John Doe" }, { "context": "n Doe\"\n };\n\n extend( obj, { age: 30, name: \"John Doe Sr.\" } );\n // { id: 1, age: 30, gender: \"male\", nam", "end": 20263, "score": 0.9685724377632141, "start": 20252, "tag": "NAME", "value": "John Doe Sr" }, { "context": ";\n // { id: 1, age: 30, gender: \"male\", name: \"John Doe Sr.\" }\n\n extend( obj, { id: 2 } );\n // { id: 2, ", "end": 20330, "score": 0.9867227673530579, "start": 20319, "tag": "NAME", "value": "John Doe Sr" }, { "context": ";\n // { id: 2, age: 30, gender: \"male\", name: \"John Doe Sr.\" }\n\n extend( {}, obj, { id: 2, age: 0, name: \"J", "end": 20425, "score": 0.9927511215209961, "start": 20414, "tag": "NAME", "value": "John Doe Sr" }, { "context": "\" }\n\n extend( {}, obj, { id: 2, age: 0, name: \"John Doe Jr.\" } );\n // { id: 2, age: 0, gender: \"male\", name", "end": 20487, "score": 0.9942108392715454, "start": 20476, "tag": "NAME", "value": "John Doe Jr" }, { "context": ");\n // { id: 2, age: 0, gender: \"male\", name: \"John Doe Jr.\" }\n###\n\nextend = (objects...) ->\n acc = {}\n forE", "end": 20553, "score": 0.9991706013679504, "start": 20542, "tag": "NAME", "value": "John Doe Jr" }, { "context": " 29,\n gender: \"male\",\n name : \"John Doe\"\n }\n ;\n\n pick( 3, array ); /", "end": 30206, "score": 0.9997811317443848, "start": 30198, "tag": "NAME", "value": "John Doe" }, { "context": "rld!\"\n pick( ['name'], object ); // { name: \"John Doe\" }\n###\n\nfirst = (i, x) -> x[0...i]\nlast = (i, x)", "end": 30449, "score": 0.9997873306274414, "start": 30441, "tag": "NAME", "value": "John Doe" }, { "context": " 29,\n gender: \"male\",\n name : \"John Doe\"\n }\n ;\n\n omit( 3, array ); ", "end": 31289, "score": 0.9998195171356201, "start": 31281, "tag": "NAME", "value": "John Doe" }, { "context": "( ['id', 'age', 'gender'], object ); // { name: \"John Doe\" }\n###\n\nomit = (i, x) ->\n if isNumber i\n if i", "end": 31602, "score": 0.9997068643569946, "start": 31594, "tag": "NAME", "value": "John Doe" }, { "context": "Either = curry Either\n\n\n# https://gist.github.com/brettz9/6093105\n# if backwards.CLIENT_SIDE\n# try\n# ", "end": 34747, "score": 0.9897186756134033, "start": 34740, "tag": "USERNAME", "value": "brettz9" } ]
src/backwards.coffee
Omega3k/backwards.js
0
"use strict" ###* * A set of utility functions for funtional programming in JavaScript. * @type {Object} * @exports backwards * @namespace backwards * @author Svein Olav Risdal * @copyright 2014 Svein Olav Risdal * @license * The MIT License (MIT) * * Copyright (c) 2014 Svein Olav Risdal * * 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. ### backwards = {} array = Array arrayProto = array.prototype slice = arrayProto.slice object = Object objectProto = object.prototype toString = objectProto.toString hasOwn = objectProto.hasOwnProperty noop = () -> add = (a, b) -> a + b subtract = (a, b) -> a - b multiply = (a, b) -> a * b divide = (a, b) -> a / b append = (a, b) -> a += b concat = (a, b) -> a.concat b push = (a, b) -> a.push b ###* * The identity function. * @memberOf backwards * @sign a -> a * @param {x} x Any value. * @return {x} Any value. * @example * id( "some value" ); //=> "some value" * id( 1234 ); //=> 1234 ### I = (x) -> x backwards.I = I K = (x) -> () -> x ###* The __VERSION__ property is a string indicating the version of __backwards__ as a string value. @property VERSION @type String @final @public ### backwards.VERSION = "undefined" ###* The __CLIENT_SIDE__ property is a boolean indicating if the current environment is client-side (a browser) or not. @property CLIENT_SIDE @type Boolean @final @public ### backwards.CLIENT_SIDE = document? ###* The __SERVER_SIDE__ property is a boolean indicating if the current environment is server-side (f.ex. Node.js) or not. @property SERVER_SIDE @type Boolean @final @public ### backwards.SERVER_SIDE = not backwards.CLIENT_SIDE ###* This function is an internal function that is used by 'curry' to create curried functions from functions that take more than one parameter. @method __curry @private @param f {Function} The function to be curried. @param args* {"any"} Arguments that should be applied to the resulting function. @return {Function} A curried function. ### __curry = (f, args...) -> (params...) -> f.apply @, args.concat params ###* Create a curried function from a function that normally takes multiple parameters. @method curry @public @param f {Function} The function to be curried. @param [length] {Number} An optional parameter defining how many parameters the given function has. @return {Function} A curried function. @example function concat ( a, b ) { return a.concat( b ); } var curriedConcat = curry( concat ) // A curried function , oneAndTwo = curriedConcat( [1, 2] ) // A curried function , oneTwoAndThree = oneAndTwo( [3] ) // [1, 2, 3] , oneTwoAndFour = oneAndTwo( [4] ) // [1, 2, 4] ; ### curry = (f, length = f.length) -> newFunction = (args...) -> if args.length < length curry __curry.apply(@, [f].concat(args)), length - args.length else f.apply @, args newFunction.toString = () -> f.toString() newFunction.curried = true return newFunction backwards.curry = curry ###* * Compose your functions into a single function. * @memberOf backwards * @sign (b -> c) -> (a -> b) -> (a -> c) * @param {...function} fs Two or more functions to compose. * @return {function} The resulting function. * @example * function addOne (x) { * return x + 1; * } * * function timesTwo (x) { * return x * 2; * } * * var nine = compose( addOne, timesTwo ) //=> 9 * , ten = compose( timesTwo, addOne ) //=> 10 * ; ### compose = (fs...) -> (args...) -> i = fs.length while i-- then args = [fs[i].apply @, args] args[0] backwards.compose = compose ###* Check if an Object is of a particular type. @method isTypeOf @public @param type {String} The String representation of the Object. @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value representing whether x is a type. @example var isBoolean = isTypeOf( 'Boolean' ) // A composed function , passed = isBoolean( true ) // true , failed = isBoolean( {} ) // false ; ### isTypeOf = curry (type, x) -> str = "[object #{ type }]" toString.call(x) is str backwards.isTypeOf = isTypeOf ###* Check if an object is a DOM element. @method isElement @public @param x {"any"} The object you wish to check the type of. @return {Boolean} A boolean value. @example isElement( document.createElement("div") ); // true isElement( {} ); // false isElement( false ); // false ### isElement = (x) -> not not( x and x.nodeType is 1 ) backwards.isElement = isElement ###* Check if an Object is an Arguments object. @method isArguments @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isArguments( arguments ) // true , failed = isArguments( false ) // false ; ### isArguments = do () -> if isTypeOf "Arguments", arguments then isTypeOf "Arguments" else (x) -> x? and hasOwn.call x, "callee" backwards.isArguments = isArguments ###* Check if an Object is an Array. @method isArray @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isArray( [1, 2, 3] ) // true , failed = isArray( false ) // false ; ### isArray = Array.isArray or isTypeOf "Array" backwards.isArray = isArray ###* Check if an Object is a Boolean. @method isBoolean @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isBoolean( true ) // true , passes = isBoolean( false ) // true , failed = isBoolean( 0 ) // false ; ### isBoolean = (x) -> x is true or x is false or isTypeOf "Boolean", x backwards.isBoolean = isBoolean ###* Check if an Object is a Date. @method isDate @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isDate( new Date() ) // true , failed = isDate( +new Date() ) // false , fails = isDate( false ) // false ; ### isDate = isTypeOf "Date" backwards.isDate = isDate ###* Check if an Object is an Error. @method isError @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isError( new Error() ) // true , passes = isError( new TypeError() ) // true , failed = isError( false ) // false ; ### isError = isTypeOf "Error" backwards.isError = isError ###* Check if an Object is a finite number. @method isFinite @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example isFinite( 1234 ); // true isFinite( NaN ); // true isFinite( new Number() ); // true isFinite( +new Date() ); // true isFinite( Infinity ); // false ### # isFinite :: a -> Boolean # isFinite = (x) -> # isFinite(x) and not isNaN parseFloat x isFinite = Number.isFinite or (x) -> isNumber(x) and not isNaN(x) and x isnt Infinity and x > 0 backwards.isFinite = isFinite ###* Check if an Object is a Function. @method isFunction @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var noop = function () {} , passed = isFunction( noop ) // true , passes = isFunction( new Function() ) // true , failed = isFunction( false ) // false ; ### isFunction = do () -> if typeof /./ isnt "function" (x) -> typeof x is "function" else isTypeOf "Function" backwards.isFunction = isFunction ###* Check if an Object is a NaN object. @method isNaN @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNaN( NaN ) // true , passes = isNaN( new Number() ) // false , failed = isNaN( false ) // false ; ### backwards.isNaN = Number.isNaN or (x) -> typeof x is "number" && isNaN x ###* Check if an Object is a Null object. @method isNull @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNull( null ) // true , failed = isNull( false ) // false ; ### isNull = (x) -> x is null or isTypeOf "Null", x backwards.isNull = isNull ###* Check if an Object is a Number. @method isNumber @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNumber( 123 ) // true , failed = isNumber( false ) // false ; ### isNumber = isTypeOf "Number" backwards.isNumber = isNumber ###* Check if an Object is an Object. @method isObject @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isObject( {} ) // true , failed = isObject( false ) // false ; ### isObject = (x) -> if not x? or isArguments( x ) or isElement( x ) or isFunction( x.then ) return false else return isTypeOf "Object", x backwards.isObject = isObject ###* Check if an Object is a Promise. @method isPromise @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var promise = new Promise(function (resolve, reject) { resolve( "I am a promise" ); }); isPromise( promise ); // true isPromise( {} ); // false ### isPromise = (x) -> return true if isTypeOf "Promise", x if x? return true if typeof x.then is "function" false backwards.isPromise = isPromise ###* Check if an Object is a regular expression ( RegExp ). @method isRegExp @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isRegExp( /./ ) // true , passes = isRegExp( new RegExp() ) // true , failed = isRegExp( false ) // false ; ### isRegExp = isTypeOf "RegExp" backwards.isRegExp = isRegExp ###* Check if an Object is a String. @method isString @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isString( "string" ) // true , failed = isString( false ) // false ; ### isString = isTypeOf "String" backwards.isString = isString ###* Check if an Object is undefined. @method isUndefined @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isUndefined( void 0 ) // true , failed = isUndefined( false ) // false ; ### isUndefined = (x) -> x is undefined or isTypeOf "Undefined", x backwards.isUndefined = isUndefined # exists :: a -> Boolean # exists = (x) -> # typeof x isnt "undefined" and x isnt null exists = (x) -> x? backwards.exists = exists # isEmpty :: Array|Object -> Boolean isEmpty = (x) -> if isObject x return false for own key of x else if isArray x return false if x.length true backwards.isEmpty = isEmpty # forEachQuickEscape = (f, xs) -> # for x, i in xs # result = f x, i, xs # return result if result? ###* forEach executes the provided callback once for each element present in the array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value undefined. callback is invoked with three arguments: the element value the element index, key or undefined the array or object being traversed or undefined The range of elements processed by forEach is set before the first invocation of callback. Elements that are appended to the array after the call to forEach begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach visits them; elements that are deleted before being visited are not visited. @method forEach @public @param f {Function} The function you wish to execute over each element in the object. @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param x {"any"} The object you wish to iterate over. @return {undefined} @example var f = function (value, key, object) { console.log( value, key ); }; forEach( f, [1, 2, 3] ); // undefined forEach( f, { id: 1, name: "string" } ); // undefined forEach( f, "Hello folks!" ); // undefined ### forEach = (f, xs) -> if xs.length or isArray xs f value, key, xs for value, key in xs else if isObject xs for key, value of xs f value, key, xs if hasOwn.call xs, key else f xs return backwards.forEach = curry forEach ###* The __map__ function calls the provided callback function (f) once for each element in an array, in ascending order, and constructs a new array from the results. __callback__ is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values. callback is invoked with three arguments: the element value the element index, key or undefined the array or object being traversed or undefined The __map__ function does not mutate the array on which it is called (although callback, if invoked, may do so). The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time map visits them; elements that are deleted are not visited. @method map @public @param f {Function} The function you wish to execute over each element in the object. @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param xs {"any"} The object you wish to iterate over. @return {"any"} @example var addOne = function (x) { return x + 1; }; map( addOne, [1, 2, 3] ); // [2, 3, 4] map( addOne, { id: 1, name: "string" } ); // ["id1", "name1"] map( addOne, "Hello folks!" ); // "Hello folks!1" ### map = (f, xs) -> if isArray( xs ) or isObject( xs ) acc = [] forEach (value, index, object) -> if value? acc.push f value, index, object else acc.push undefined return , xs acc else if xs? if isFunction xs.map then xs.map f else if isPromise xs then xs.then f else f xs else xs backwards.map = curry map filter = (f, xs) -> if isArray xs acc = [] map (value, index, array) -> acc.push value if f value, index, array , xs acc else xs if f xs backwards.filter = curry filter keys = (x) -> acc = [] forEach (value, key, object) -> acc.push key , x acc ###* __reduce__ executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring. The callback function (__f__) is invoked with four arguments: The initial value (or return value from the previous callback invocation). The element value. The element index, key or undefined. The array or object being traversed or undefined. The first time the callback function (__f__) is called, __accumulator__ and __value__ can be one of two values. If initial value (__acc__) is provided in the call to reduce, then __accumulator__ will be equal to initial value and __value__ will be equal to the first value in the array. If no initial value (__acc__) was provided, then __accumulator__ will be equal to the first value in the array and __value__ will be equal to the second. If the array or object (__x__) is empty and no initial value (__acc__) is provided, a TypeError will be thrown. If the array or object (__x__) only has one element (regardless of position) and no initial value (__acc__) is provided, or if initial value (__acc__) is provided but the array or object (__x__) is empty, the solo value will be returned without calling callback function (__f__). @method reduce @public @param f {Function} The callback function. @param f.accumulator {"any"} The initial value (or return value from the previous callback invocation). @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param acc {"any"} The initial value. @param x {"any"} The object you wish to reduce. @return {"any"|TypeError} Returns the reduced value, or a TypeError if given an empty object and no initial value. @example var add = function (a, b) { return a + b; } , append = function (a, b) { return a.concat(b); } , flatten = reduce( append, [] ) ; reduce( add, 0 , [0, 1, 2, 3] ); // 6 reduce( add, undefined, [0, 1, 2, 3] ); // 6 flatten( [[0, 1], [2, 3], [4, 5]] ); // [0, 1, 2, 3, 4, 5] ### reduce = (f, acc, x) -> if not acc? and isEmpty x throw new TypeError "Reduce of empty object with no initial value" if isArray(x) or isObject(x) forEach (value, key, object) -> if acc is undefined then acc = value else acc = f acc, value, key, object return , x else acc = f acc, x acc backwards.reduce = curry reduce max = backwards.reduce (max, num) -> if max > num then max else num , undefined min = backwards.reduce (min, num) -> if min < num then min else num , undefined ###* The __extend__ function takes two or more objects and returns the first object (__acc__) extended with the properties (and values) of the other objects in ascending order. @method extend @public @param acc {Object} The object you wish to extend. @param objects* {Object} The objects you wish to be extended to __acc__. @return {Object} Returns the first object (__acc__) extended with the other objects properties and values in ascending order. @example var obj = { id : 1, age : 29, gender: "male", name : "John Doe" }; extend( obj, { age: 30, name: "John Doe Sr." } ); // { id: 1, age: 30, gender: "male", name: "John Doe Sr." } extend( obj, { id: 2 } ); // { id: 2, age: 30, gender: "male", name: "John Doe Sr." } extend( {}, obj, { id: 2, age: 0, name: "John Doe Jr." } ); // { id: 2, age: 0, gender: "male", name: "John Doe Jr." } ### extend = (objects...) -> acc = {} forEach (object) -> forEach (value, key) -> acc[key] = value return , object , objects acc backwards.extend = curry extend ###* The __copy__ function takes an Object and returns a fresh copy of the Object. @method copy @public @param x {"any"} The Object you wish to copy. @return {"any"} A fresh copy of the given Object. @example copy( [1, 2, 3] ); // [1, 2, 3] copy( { id: 1, name: "string" } ); // { id: 1, name: "string" } ### copy = (x) -> if isObject x then extend x else map I, x backwards.copy = copy ###* The __flatten__ function takes an array of arrays and flattens the array one level. @method flatten @public @param x {Array} The Array you wish to flatten. @return {Array} A flattened Array. @example var array = [[1, 2], [3, 4], [5, 6]]; flatten( array ); // [1, 2, 3, 4, 5, 6] ### flatten = backwards.reduce concat, [] backwards.flatten = flatten ###* The __indexOf__ function returns the first index at which a given element can be found, or -1 if it could not be found. If the index (__i__) is greater than or equal to the array or string length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array or string. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. If __x__ is a string, __i__ is greater than or equal to __x__.length and __search__ is an empty string ("") then __x__.length is returned. @method indexOf @public @param search {"mixed"} The element to locate in the array. @param i {Number} The index to start the search at. @param x {Array|String} The array or string you wish to search. @return {Number} The first index at which a given element can be found, or -1 if not found. @example var array = [2, 5, 9]; indexOf( 2, 0, array ); // 0 indexOf( 7, 0, array ); // -1 indexOf( 9, 2, array ); // 2 indexOf( 2, -1, array ); // -1 indexOf( 2, -3, array ); // 0 ### indexOf = (search, i, x) -> len = x.length i = i or 0 isNaN = backwards.isNaN if len is 0 or i >= len if search is "" and isString x return len else return -1 else if i < 0 i = len + i if i < 0 i = 0 if isArray x while i < len return i if x[i] is search or isNaN( search ) and isNaN( x[i] ) i++ else if isString x return x.indexOf search, i -1 backwards.indexOf = curry indexOf ###* The __contains__ function returns true if a given element can be found in the array, or false if it is not present. If the index is greater than or equal to the array's length, false is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. @method contains @public @param search {"mixed"} The element to locate in the array. @param i {Number} The index to start the search at. @param x {Array|String} The Array you wish to search in. @return {Boolean} Returns true if *search* is found in the *Array*, or false if it is not found. @example var array = [1, 2, 3, NaN]; contains( 2, 0, array ); // true contains( 4, 0, array ); // false contains( 3, 3, array ); // false contains( 3, -2, array ); // true contains( NaN, 0, array ); // true ### contains = (search, i, x) -> ( indexOf search, i, x ) isnt -1 backwards.contains = curry contains ###* The __some__ function takes a predicate function and an array and returns true if some of the values in the array conforms with the predicate function, or false if not. It returns false if given an empty array. @method some @public @param f {Function} A predicate function. @param xs {Array} The array you wish to check. @return {Boolean} Returns true if some of the values in the array conforms with the predicate function, or false if not. It returns false if given an empty array. @example var predicate = function (x) { return x > 10 }; some( predicate, [12, 5, 8, 1, 4] ); // true some( predicate, [2, 5, 8, 1, 4] ); // false some( predicate, [] ); // false ### some = (f, xs) -> return true for x in xs when f x false backwards.some = curry some ###* The __every__ function takes a predicate function and an array and returns true if every value in the array conforms with the predicate function, or false if not. It returns true if given an empty array. @method every @public @param f {Function} A predicate function. @param xs {Array} The array you wish to check. @return {Boolean} Returns true if every value in the array conforms with the predicate function, or false if not. It returns true if given an empty array. @example var predicate = function (x) { return x > 10 }; every( predicate, [] ); // true every( predicate, [12, 54, 18, 130, 44] ); // true every( predicate, [12, 5, 8, 130, 44] ); // false ### every = (f, xs) -> return false for x in xs when not f x true backwards.every = curry every ###* The __delete__ function takes an element and an array or string, and deletes the first occurence of that element from the list. It returns a new array or string. @method delete @public @param x {"any"} The element to delete. @param xs {Array|String} The array or string you wish to delete an element from. @return {Array|String} Returns an array or string without causing side-effects on the given array or string. @example delete( 12 , [12, 54, 18, NaN, "element"] ); // [54,18,NaN,"element"] delete( NaN , [12, 54, 18, NaN, "element"] ); // [12,54,18,"element"] delete( "element" , [12, 54, 18, NaN, "element"] ); // [12,54,18,NaN] delete( 1234 , [12, 54, 18, NaN, "element"] ); // [12,54,18,NaN,"element"] delete( "e" , "element" ); // "lement" delete( "ele" , "element" ); // "ment" ### _delete = (x, xs) -> i = indexOf x, 0, xs n = x.length or 1 if i isnt -1 and xs.length xs[0...i].concat xs[i+n...xs.length] else xs backwards.delete = curry _delete ###* The __partition__ function takes a predicate function and an array or a string, and returns an array with two indexes. The first index in the resulting array contains all the elements that conforms to the predicate function, and the second index contains all the elements that does not. @method partition @public @param f {Function} The predicate function. @param xs {Array|String} The array or string you wish to partition. @return {Array} Returns an array with two indexes. The first index contains all the elements that conforms to the predicate function, and the second index contains all the elements that does not. @example var partition = backwards.partition , indexOf = backwards.indexOf , array = [12, 54, 18, NaN, "element"] , string = "elementary eh!" , predicateArray, predicateString; predicateArray = function (x) { return x > 15; }; predicateString = function (x) { return indexOf( x, 0, "element" ); }; partition( predicateArray, array ); // [[54, 18], [12, NaN, "element"]] partition( predicateString, string ); // [ // ["e","l","e","m","e","n","t","e"], // ["a","r","y"," ","h","!"] // ] ### partition = (f, xs) -> acc = [[], []] xs = toArray xs if isString xs forEach (x, i, xs) -> if f x, i, xs then acc[0].push x else acc[1].push x return , xs acc backwards.partition = curry partition toArray = (xs) -> if isFunction xs.charAt result = [] forEach (value, index, string) -> result.push string.charAt index , xs else result = copy xs result escape = (html) -> # result = new String html result = html .replace /&/g, "&amp;" .replace /</g, "&lt;" .replace />/g, "&gt;" .replace /"/g, "&quot;" if result is "#{ html }" then html else result unescape = (html) -> # result = new String html result = html .replace /&amp;/g, "&" .replace /&lt;/g, "<" .replace /&gt;/g, ">" .replace /&quot;/g, '"' if result is "#{ html }" then html else result either = (a, b) -> b ? a backwards.either = curry either maybe = (f, x) -> if x? then f x else undefined backwards.maybe = curry maybe ###* The __pick__ function returns a subset of the given object. If given a positive number and an array or string it will return the first __i__ indexes of the object. If given a negative number and an array or string it will return the last __i__ indexes of the object. If given an array of strings and an object it will return an object containing the keys / properties that was listed in __i__. @method pick @public @param i {Number|Array} The number of indexes you wish to extract, or an array of strings which represents the keys of the object you wish to extract. @param x {Array|String|Object} An array, string or object @return {Array|String|Object} A subset of the object. @example var array = [1, 2, 3, 4, 5] , string = "Hello World!" , object = { id : 1, age : 29, gender: "male", name : "John Doe" } ; pick( 3, array ); // [1, 2, 3] pick( -2, array ); // [4, 5] pick( 5, string ); // "Hello" pick( -6, string ); // "World!" pick( ['name'], object ); // { name: "John Doe" } ### first = (i, x) -> x[0...i] last = (i, x) -> x[i...x.length] pick = (i, x) -> if isNumber i if i > 0 then first i, x else last i, x else acc = {} value = undefined forEach (key) -> value = x[key] acc[key] = value if value return , i acc backwards.pick = curry pick ###* Drops a subset of the given object, from the beginning to *i*, and returns the rest of the object. @method omit @public @param i {Number|Array} The number of indexes you wish to extract @param x {Array|String|Object} An Array, String or Object @return {Array|String|Object} A subset of *x* from index *i* to the end @example var array = [1, 2, 3, 4, 5] , string = "Hello World!" , object = { id : 1, age : 29, gender: "male", name : "John Doe" } ; omit( 3, array ); // [4, 5] omit( -2, array ); // [1, 2, 3] omit( 6, string ); // "World!" omit( -7, string ); // "Hello" omit( ['id', 'age', 'gender'], object ); // { name: "John Doe" } ### omit = (i, x) -> if isNumber i if i > 0 then last i, x else first i, x else acc = {} forEach (value, key) -> if not contains key, 0, i acc[key] = value return , x acc backwards.omit = curry omit # toString = (x) -> # # if x then x.toString() # if isArray x then "[#{ x.toString() }]" # else if isObject x then "{#{ reduce toString, '', x }}" # else if x is false then "false" # else if x is 0 then "0" # else "undefined" # if window? # # console = ( window.console = window.console or {} ) # console = console or {} # forEach (method) -> # console[ method ] = noop if not console[ method ] # undefined # , [ # "assert" # "clear" # "count" # "debug" # "dir" # "dirxml" # "error" # "exception" # "group" # "groupCollapsed" # "groupEnd" # "info" # "log" # "markTimeline" # "profile" # "profileEnd" # "table" # "time" # "timeEnd" # "timeStamp" # "trace" # "warn" # ] backwards.log = (x) -> try console.log x catch e alert x x pluck = (key, xs) -> xs[key] backwards.pluck = curry pluck split = curry (regexp, string) -> string.split regexp join = curry (regexp, array) -> array.join regexp lines = split /\r\n|\r|\n/ unlines = join "\n" # forEach (type) -> # backwards["is#{ type }"] = (x) -> # toString.call( x ).slice( 8, -1 ) is type # return # , "Arguments Array Boolean Date Error Function Null Number Object Promise RegExp String Undefined".split " " ###* A monad that may or may not contain a value. The Maybe monad implements the map interface. @class Maybe @memberof backwards @constructor @public @example var monad = new Maybe( 1234 ); // Maybe( 1234 ) monad instanceof Maybe // true ### # class Maybe # constructor: (value) -> # return new Maybe value if not ( @ instanceof Maybe ) # @value = value # return @ # ###* # The __map__ function takes a transformation function and returns a new monad with the result of the transformation. # @method map # @public # @param f {Function} A function that applies a transform to the value and returns the new value. # @return {Maybe} Returns a new Maybe monad. # @example # var monadOne = new Maybe( 1234 ) # , monadTwo = monad.map( addOne ); # function addOne (x) { # return x + 1; # } # monadOne // Maybe( 1234 ) # monadTwo // Maybe( 2345 ) # ### # map: (f) -> # value = @value # if value? # new Maybe f value # else @ # toString: () -> # "[maybe " + omit 8, toString.call @value # valueOf: () -> # @.value # backwards.Maybe = Maybe # class Either # constructor: (left, right) -> # return new Either left, right if not ( @ instanceof Either ) # @left = left # @right = right # return @ # map: (f) -> # right = @right # if right? # new Either @left, f right # else @ # backwards.Either = curry Either # https://gist.github.com/brettz9/6093105 # if backwards.CLIENT_SIDE # try # slice.call document.documentElement # catch error # oldSlice = slice # slice = (beginning, end) -> # acc = [] # if @charAt # f = (x, i, xs) -> # acc.push xs.charAt i # return # else # f = (x) -> # acc.push x # return # forEach f, @ # return oldSlice.call acc, beginning, end or acc.length # if backwards.CLIENT_SIDE # try # slice.call document.documentElement # catch error # oldSlice = slice # slice = (beginning, end) -> # acc = [] # if @charAt # acc.push @charAt i for x, i in @ # else # acc.push x for x, i in @ # return oldSlice.call acc, beginning, end or acc.length # Export backwards object # ======================= # AMD ( almond.js, r.js ... ) if define? and define.amd define "backwards", [], () -> backwards # Node.js / CommonJS-like else if exports? if module? and module.exports module.exports = backwards else exports.backwards = backwards # Global Object else if window? window.backwards = backwards # Return backwards if none of the above else throw new Error "backwards.js could not be exported. " ### IDEAS, NOTES & BACKLOG ====================== BACKLOG IDEAS * Make the backwards object itself a function that can be invoked in the following ways: Debug mode: Pass a string which represents the method you would like returned. This will return the method wrapped in a "try, catch" which will return valuable information when debugging ( an error message containing an url to where you can find more information about how to use the method ). Extended with prototype: Pass in any kind of object to get back the object extended with a backwards-prototype. Like for example: backwards( [0, 1, 2, 3] ).map( (x) -> x + 1 ) // [1, 2, 3, 4] NOTES: Make sure that the prototype way of invocation should work on strings as well, meaning that invocation with a string that does not represent a method on the backwards object should return the string extended with the backwards prototype. ### # { error, success } = options # (( root, name, f ) -> # # Register as a named AMD module # if define? and define.amd # define name, [], f # # Register as a CommonJS-like module # else if exports? # if module? and module.exports # module.exports = f() # else # exports[name] = f() # # Register as a global object on the window # else # root[name] = f() # undefined # )( this, "backwards", () -> backwards ) # # Game Loop # while running # now = Date.now() # delta = now - lastTime # buffer += delta # while buffer >= TICK # update TICK # buffer -= TICK # render() # lastTime = now # https://www.youtube.com/watch?v=XcS-LdEBUkE # # map :: (a -> b) -> [a] -> [b] # map = (f, [x, xs...]) -> # if x is undefined # [] # else # [f(x), map(f, xs)...] # # length :: [a] -> Int # length = ([x, xs...]) -> # if x is undefined # 0 # else # 1 + length xs
168249
"use strict" ###* * A set of utility functions for funtional programming in JavaScript. * @type {Object} * @exports backwards * @namespace backwards * @author <NAME> * @copyright 2014 <NAME> * @license * The MIT License (MIT) * * Copyright (c) 2014 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ### backwards = {} array = Array arrayProto = array.prototype slice = arrayProto.slice object = Object objectProto = object.prototype toString = objectProto.toString hasOwn = objectProto.hasOwnProperty noop = () -> add = (a, b) -> a + b subtract = (a, b) -> a - b multiply = (a, b) -> a * b divide = (a, b) -> a / b append = (a, b) -> a += b concat = (a, b) -> a.concat b push = (a, b) -> a.push b ###* * The identity function. * @memberOf backwards * @sign a -> a * @param {x} x Any value. * @return {x} Any value. * @example * id( "some value" ); //=> "some value" * id( 1234 ); //=> 1234 ### I = (x) -> x backwards.I = I K = (x) -> () -> x ###* The __VERSION__ property is a string indicating the version of __backwards__ as a string value. @property VERSION @type String @final @public ### backwards.VERSION = "undefined" ###* The __CLIENT_SIDE__ property is a boolean indicating if the current environment is client-side (a browser) or not. @property CLIENT_SIDE @type Boolean @final @public ### backwards.CLIENT_SIDE = document? ###* The __SERVER_SIDE__ property is a boolean indicating if the current environment is server-side (f.ex. Node.js) or not. @property SERVER_SIDE @type Boolean @final @public ### backwards.SERVER_SIDE = not backwards.CLIENT_SIDE ###* This function is an internal function that is used by 'curry' to create curried functions from functions that take more than one parameter. @method __curry @private @param f {Function} The function to be curried. @param args* {"any"} Arguments that should be applied to the resulting function. @return {Function} A curried function. ### __curry = (f, args...) -> (params...) -> f.apply @, args.concat params ###* Create a curried function from a function that normally takes multiple parameters. @method curry @public @param f {Function} The function to be curried. @param [length] {Number} An optional parameter defining how many parameters the given function has. @return {Function} A curried function. @example function concat ( a, b ) { return a.concat( b ); } var curriedConcat = curry( concat ) // A curried function , oneAndTwo = curriedConcat( [1, 2] ) // A curried function , oneTwoAndThree = oneAndTwo( [3] ) // [1, 2, 3] , oneTwoAndFour = oneAndTwo( [4] ) // [1, 2, 4] ; ### curry = (f, length = f.length) -> newFunction = (args...) -> if args.length < length curry __curry.apply(@, [f].concat(args)), length - args.length else f.apply @, args newFunction.toString = () -> f.toString() newFunction.curried = true return newFunction backwards.curry = curry ###* * Compose your functions into a single function. * @memberOf backwards * @sign (b -> c) -> (a -> b) -> (a -> c) * @param {...function} fs Two or more functions to compose. * @return {function} The resulting function. * @example * function addOne (x) { * return x + 1; * } * * function timesTwo (x) { * return x * 2; * } * * var nine = compose( addOne, timesTwo ) //=> 9 * , ten = compose( timesTwo, addOne ) //=> 10 * ; ### compose = (fs...) -> (args...) -> i = fs.length while i-- then args = [fs[i].apply @, args] args[0] backwards.compose = compose ###* Check if an Object is of a particular type. @method isTypeOf @public @param type {String} The String representation of the Object. @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value representing whether x is a type. @example var isBoolean = isTypeOf( 'Boolean' ) // A composed function , passed = isBoolean( true ) // true , failed = isBoolean( {} ) // false ; ### isTypeOf = curry (type, x) -> str = "[object #{ type }]" toString.call(x) is str backwards.isTypeOf = isTypeOf ###* Check if an object is a DOM element. @method isElement @public @param x {"any"} The object you wish to check the type of. @return {Boolean} A boolean value. @example isElement( document.createElement("div") ); // true isElement( {} ); // false isElement( false ); // false ### isElement = (x) -> not not( x and x.nodeType is 1 ) backwards.isElement = isElement ###* Check if an Object is an Arguments object. @method isArguments @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isArguments( arguments ) // true , failed = isArguments( false ) // false ; ### isArguments = do () -> if isTypeOf "Arguments", arguments then isTypeOf "Arguments" else (x) -> x? and hasOwn.call x, "callee" backwards.isArguments = isArguments ###* Check if an Object is an Array. @method isArray @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isArray( [1, 2, 3] ) // true , failed = isArray( false ) // false ; ### isArray = Array.isArray or isTypeOf "Array" backwards.isArray = isArray ###* Check if an Object is a Boolean. @method isBoolean @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isBoolean( true ) // true , passes = isBoolean( false ) // true , failed = isBoolean( 0 ) // false ; ### isBoolean = (x) -> x is true or x is false or isTypeOf "Boolean", x backwards.isBoolean = isBoolean ###* Check if an Object is a Date. @method isDate @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isDate( new Date() ) // true , failed = isDate( +new Date() ) // false , fails = isDate( false ) // false ; ### isDate = isTypeOf "Date" backwards.isDate = isDate ###* Check if an Object is an Error. @method isError @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isError( new Error() ) // true , passes = isError( new TypeError() ) // true , failed = isError( false ) // false ; ### isError = isTypeOf "Error" backwards.isError = isError ###* Check if an Object is a finite number. @method isFinite @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example isFinite( 1234 ); // true isFinite( NaN ); // true isFinite( new Number() ); // true isFinite( +new Date() ); // true isFinite( Infinity ); // false ### # isFinite :: a -> Boolean # isFinite = (x) -> # isFinite(x) and not isNaN parseFloat x isFinite = Number.isFinite or (x) -> isNumber(x) and not isNaN(x) and x isnt Infinity and x > 0 backwards.isFinite = isFinite ###* Check if an Object is a Function. @method isFunction @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var noop = function () {} , passed = isFunction( noop ) // true , passes = isFunction( new Function() ) // true , failed = isFunction( false ) // false ; ### isFunction = do () -> if typeof /./ isnt "function" (x) -> typeof x is "function" else isTypeOf "Function" backwards.isFunction = isFunction ###* Check if an Object is a NaN object. @method isNaN @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNaN( NaN ) // true , passes = isNaN( new Number() ) // false , failed = isNaN( false ) // false ; ### backwards.isNaN = Number.isNaN or (x) -> typeof x is "number" && isNaN x ###* Check if an Object is a Null object. @method isNull @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNull( null ) // true , failed = isNull( false ) // false ; ### isNull = (x) -> x is null or isTypeOf "Null", x backwards.isNull = isNull ###* Check if an Object is a Number. @method isNumber @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNumber( 123 ) // true , failed = isNumber( false ) // false ; ### isNumber = isTypeOf "Number" backwards.isNumber = isNumber ###* Check if an Object is an Object. @method isObject @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isObject( {} ) // true , failed = isObject( false ) // false ; ### isObject = (x) -> if not x? or isArguments( x ) or isElement( x ) or isFunction( x.then ) return false else return isTypeOf "Object", x backwards.isObject = isObject ###* Check if an Object is a Promise. @method isPromise @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var promise = new Promise(function (resolve, reject) { resolve( "I am a promise" ); }); isPromise( promise ); // true isPromise( {} ); // false ### isPromise = (x) -> return true if isTypeOf "Promise", x if x? return true if typeof x.then is "function" false backwards.isPromise = isPromise ###* Check if an Object is a regular expression ( RegExp ). @method isRegExp @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isRegExp( /./ ) // true , passes = isRegExp( new RegExp() ) // true , failed = isRegExp( false ) // false ; ### isRegExp = isTypeOf "RegExp" backwards.isRegExp = isRegExp ###* Check if an Object is a String. @method isString @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isString( "string" ) // true , failed = isString( false ) // false ; ### isString = isTypeOf "String" backwards.isString = isString ###* Check if an Object is undefined. @method isUndefined @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isUndefined( void 0 ) // true , failed = isUndefined( false ) // false ; ### isUndefined = (x) -> x is undefined or isTypeOf "Undefined", x backwards.isUndefined = isUndefined # exists :: a -> Boolean # exists = (x) -> # typeof x isnt "undefined" and x isnt null exists = (x) -> x? backwards.exists = exists # isEmpty :: Array|Object -> Boolean isEmpty = (x) -> if isObject x return false for own key of x else if isArray x return false if x.length true backwards.isEmpty = isEmpty # forEachQuickEscape = (f, xs) -> # for x, i in xs # result = f x, i, xs # return result if result? ###* forEach executes the provided callback once for each element present in the array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value undefined. callback is invoked with three arguments: the element value the element index, key or undefined the array or object being traversed or undefined The range of elements processed by forEach is set before the first invocation of callback. Elements that are appended to the array after the call to forEach begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach visits them; elements that are deleted before being visited are not visited. @method forEach @public @param f {Function} The function you wish to execute over each element in the object. @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param x {"any"} The object you wish to iterate over. @return {undefined} @example var f = function (value, key, object) { console.log( value, key ); }; forEach( f, [1, 2, 3] ); // undefined forEach( f, { id: 1, name: "string" } ); // undefined forEach( f, "Hello folks!" ); // undefined ### forEach = (f, xs) -> if xs.length or isArray xs f value, key, xs for value, key in xs else if isObject xs for key, value of xs f value, key, xs if hasOwn.call xs, key else f xs return backwards.forEach = curry forEach ###* The __map__ function calls the provided callback function (f) once for each element in an array, in ascending order, and constructs a new array from the results. __callback__ is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values. callback is invoked with three arguments: the element value the element index, key or undefined the array or object being traversed or undefined The __map__ function does not mutate the array on which it is called (although callback, if invoked, may do so). The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time map visits them; elements that are deleted are not visited. @method map @public @param f {Function} The function you wish to execute over each element in the object. @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param xs {"any"} The object you wish to iterate over. @return {"any"} @example var addOne = function (x) { return x + 1; }; map( addOne, [1, 2, 3] ); // [2, 3, 4] map( addOne, { id: 1, name: "string" } ); // ["id1", "name1"] map( addOne, "Hello folks!" ); // "Hello folks!1" ### map = (f, xs) -> if isArray( xs ) or isObject( xs ) acc = [] forEach (value, index, object) -> if value? acc.push f value, index, object else acc.push undefined return , xs acc else if xs? if isFunction xs.map then xs.map f else if isPromise xs then xs.then f else f xs else xs backwards.map = curry map filter = (f, xs) -> if isArray xs acc = [] map (value, index, array) -> acc.push value if f value, index, array , xs acc else xs if f xs backwards.filter = curry filter keys = (x) -> acc = [] forEach (value, key, object) -> acc.push key , x acc ###* __reduce__ executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring. The callback function (__f__) is invoked with four arguments: The initial value (or return value from the previous callback invocation). The element value. The element index, key or undefined. The array or object being traversed or undefined. The first time the callback function (__f__) is called, __accumulator__ and __value__ can be one of two values. If initial value (__acc__) is provided in the call to reduce, then __accumulator__ will be equal to initial value and __value__ will be equal to the first value in the array. If no initial value (__acc__) was provided, then __accumulator__ will be equal to the first value in the array and __value__ will be equal to the second. If the array or object (__x__) is empty and no initial value (__acc__) is provided, a TypeError will be thrown. If the array or object (__x__) only has one element (regardless of position) and no initial value (__acc__) is provided, or if initial value (__acc__) is provided but the array or object (__x__) is empty, the solo value will be returned without calling callback function (__f__). @method reduce @public @param f {Function} The callback function. @param f.accumulator {"any"} The initial value (or return value from the previous callback invocation). @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param acc {"any"} The initial value. @param x {"any"} The object you wish to reduce. @return {"any"|TypeError} Returns the reduced value, or a TypeError if given an empty object and no initial value. @example var add = function (a, b) { return a + b; } , append = function (a, b) { return a.concat(b); } , flatten = reduce( append, [] ) ; reduce( add, 0 , [0, 1, 2, 3] ); // 6 reduce( add, undefined, [0, 1, 2, 3] ); // 6 flatten( [[0, 1], [2, 3], [4, 5]] ); // [0, 1, 2, 3, 4, 5] ### reduce = (f, acc, x) -> if not acc? and isEmpty x throw new TypeError "Reduce of empty object with no initial value" if isArray(x) or isObject(x) forEach (value, key, object) -> if acc is undefined then acc = value else acc = f acc, value, key, object return , x else acc = f acc, x acc backwards.reduce = curry reduce max = backwards.reduce (max, num) -> if max > num then max else num , undefined min = backwards.reduce (min, num) -> if min < num then min else num , undefined ###* The __extend__ function takes two or more objects and returns the first object (__acc__) extended with the properties (and values) of the other objects in ascending order. @method extend @public @param acc {Object} The object you wish to extend. @param objects* {Object} The objects you wish to be extended to __acc__. @return {Object} Returns the first object (__acc__) extended with the other objects properties and values in ascending order. @example var obj = { id : 1, age : 29, gender: "male", name : "<NAME>" }; extend( obj, { age: 30, name: "<NAME>." } ); // { id: 1, age: 30, gender: "male", name: "<NAME>." } extend( obj, { id: 2 } ); // { id: 2, age: 30, gender: "male", name: "<NAME>." } extend( {}, obj, { id: 2, age: 0, name: "<NAME>." } ); // { id: 2, age: 0, gender: "male", name: "<NAME>." } ### extend = (objects...) -> acc = {} forEach (object) -> forEach (value, key) -> acc[key] = value return , object , objects acc backwards.extend = curry extend ###* The __copy__ function takes an Object and returns a fresh copy of the Object. @method copy @public @param x {"any"} The Object you wish to copy. @return {"any"} A fresh copy of the given Object. @example copy( [1, 2, 3] ); // [1, 2, 3] copy( { id: 1, name: "string" } ); // { id: 1, name: "string" } ### copy = (x) -> if isObject x then extend x else map I, x backwards.copy = copy ###* The __flatten__ function takes an array of arrays and flattens the array one level. @method flatten @public @param x {Array} The Array you wish to flatten. @return {Array} A flattened Array. @example var array = [[1, 2], [3, 4], [5, 6]]; flatten( array ); // [1, 2, 3, 4, 5, 6] ### flatten = backwards.reduce concat, [] backwards.flatten = flatten ###* The __indexOf__ function returns the first index at which a given element can be found, or -1 if it could not be found. If the index (__i__) is greater than or equal to the array or string length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array or string. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. If __x__ is a string, __i__ is greater than or equal to __x__.length and __search__ is an empty string ("") then __x__.length is returned. @method indexOf @public @param search {"mixed"} The element to locate in the array. @param i {Number} The index to start the search at. @param x {Array|String} The array or string you wish to search. @return {Number} The first index at which a given element can be found, or -1 if not found. @example var array = [2, 5, 9]; indexOf( 2, 0, array ); // 0 indexOf( 7, 0, array ); // -1 indexOf( 9, 2, array ); // 2 indexOf( 2, -1, array ); // -1 indexOf( 2, -3, array ); // 0 ### indexOf = (search, i, x) -> len = x.length i = i or 0 isNaN = backwards.isNaN if len is 0 or i >= len if search is "" and isString x return len else return -1 else if i < 0 i = len + i if i < 0 i = 0 if isArray x while i < len return i if x[i] is search or isNaN( search ) and isNaN( x[i] ) i++ else if isString x return x.indexOf search, i -1 backwards.indexOf = curry indexOf ###* The __contains__ function returns true if a given element can be found in the array, or false if it is not present. If the index is greater than or equal to the array's length, false is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. @method contains @public @param search {"mixed"} The element to locate in the array. @param i {Number} The index to start the search at. @param x {Array|String} The Array you wish to search in. @return {Boolean} Returns true if *search* is found in the *Array*, or false if it is not found. @example var array = [1, 2, 3, NaN]; contains( 2, 0, array ); // true contains( 4, 0, array ); // false contains( 3, 3, array ); // false contains( 3, -2, array ); // true contains( NaN, 0, array ); // true ### contains = (search, i, x) -> ( indexOf search, i, x ) isnt -1 backwards.contains = curry contains ###* The __some__ function takes a predicate function and an array and returns true if some of the values in the array conforms with the predicate function, or false if not. It returns false if given an empty array. @method some @public @param f {Function} A predicate function. @param xs {Array} The array you wish to check. @return {Boolean} Returns true if some of the values in the array conforms with the predicate function, or false if not. It returns false if given an empty array. @example var predicate = function (x) { return x > 10 }; some( predicate, [12, 5, 8, 1, 4] ); // true some( predicate, [2, 5, 8, 1, 4] ); // false some( predicate, [] ); // false ### some = (f, xs) -> return true for x in xs when f x false backwards.some = curry some ###* The __every__ function takes a predicate function and an array and returns true if every value in the array conforms with the predicate function, or false if not. It returns true if given an empty array. @method every @public @param f {Function} A predicate function. @param xs {Array} The array you wish to check. @return {Boolean} Returns true if every value in the array conforms with the predicate function, or false if not. It returns true if given an empty array. @example var predicate = function (x) { return x > 10 }; every( predicate, [] ); // true every( predicate, [12, 54, 18, 130, 44] ); // true every( predicate, [12, 5, 8, 130, 44] ); // false ### every = (f, xs) -> return false for x in xs when not f x true backwards.every = curry every ###* The __delete__ function takes an element and an array or string, and deletes the first occurence of that element from the list. It returns a new array or string. @method delete @public @param x {"any"} The element to delete. @param xs {Array|String} The array or string you wish to delete an element from. @return {Array|String} Returns an array or string without causing side-effects on the given array or string. @example delete( 12 , [12, 54, 18, NaN, "element"] ); // [54,18,NaN,"element"] delete( NaN , [12, 54, 18, NaN, "element"] ); // [12,54,18,"element"] delete( "element" , [12, 54, 18, NaN, "element"] ); // [12,54,18,NaN] delete( 1234 , [12, 54, 18, NaN, "element"] ); // [12,54,18,NaN,"element"] delete( "e" , "element" ); // "lement" delete( "ele" , "element" ); // "ment" ### _delete = (x, xs) -> i = indexOf x, 0, xs n = x.length or 1 if i isnt -1 and xs.length xs[0...i].concat xs[i+n...xs.length] else xs backwards.delete = curry _delete ###* The __partition__ function takes a predicate function and an array or a string, and returns an array with two indexes. The first index in the resulting array contains all the elements that conforms to the predicate function, and the second index contains all the elements that does not. @method partition @public @param f {Function} The predicate function. @param xs {Array|String} The array or string you wish to partition. @return {Array} Returns an array with two indexes. The first index contains all the elements that conforms to the predicate function, and the second index contains all the elements that does not. @example var partition = backwards.partition , indexOf = backwards.indexOf , array = [12, 54, 18, NaN, "element"] , string = "elementary eh!" , predicateArray, predicateString; predicateArray = function (x) { return x > 15; }; predicateString = function (x) { return indexOf( x, 0, "element" ); }; partition( predicateArray, array ); // [[54, 18], [12, NaN, "element"]] partition( predicateString, string ); // [ // ["e","l","e","m","e","n","t","e"], // ["a","r","y"," ","h","!"] // ] ### partition = (f, xs) -> acc = [[], []] xs = toArray xs if isString xs forEach (x, i, xs) -> if f x, i, xs then acc[0].push x else acc[1].push x return , xs acc backwards.partition = curry partition toArray = (xs) -> if isFunction xs.charAt result = [] forEach (value, index, string) -> result.push string.charAt index , xs else result = copy xs result escape = (html) -> # result = new String html result = html .replace /&/g, "&amp;" .replace /</g, "&lt;" .replace />/g, "&gt;" .replace /"/g, "&quot;" if result is "#{ html }" then html else result unescape = (html) -> # result = new String html result = html .replace /&amp;/g, "&" .replace /&lt;/g, "<" .replace /&gt;/g, ">" .replace /&quot;/g, '"' if result is "#{ html }" then html else result either = (a, b) -> b ? a backwards.either = curry either maybe = (f, x) -> if x? then f x else undefined backwards.maybe = curry maybe ###* The __pick__ function returns a subset of the given object. If given a positive number and an array or string it will return the first __i__ indexes of the object. If given a negative number and an array or string it will return the last __i__ indexes of the object. If given an array of strings and an object it will return an object containing the keys / properties that was listed in __i__. @method pick @public @param i {Number|Array} The number of indexes you wish to extract, or an array of strings which represents the keys of the object you wish to extract. @param x {Array|String|Object} An array, string or object @return {Array|String|Object} A subset of the object. @example var array = [1, 2, 3, 4, 5] , string = "Hello World!" , object = { id : 1, age : 29, gender: "male", name : "<NAME>" } ; pick( 3, array ); // [1, 2, 3] pick( -2, array ); // [4, 5] pick( 5, string ); // "Hello" pick( -6, string ); // "World!" pick( ['name'], object ); // { name: "<NAME>" } ### first = (i, x) -> x[0...i] last = (i, x) -> x[i...x.length] pick = (i, x) -> if isNumber i if i > 0 then first i, x else last i, x else acc = {} value = undefined forEach (key) -> value = x[key] acc[key] = value if value return , i acc backwards.pick = curry pick ###* Drops a subset of the given object, from the beginning to *i*, and returns the rest of the object. @method omit @public @param i {Number|Array} The number of indexes you wish to extract @param x {Array|String|Object} An Array, String or Object @return {Array|String|Object} A subset of *x* from index *i* to the end @example var array = [1, 2, 3, 4, 5] , string = "Hello World!" , object = { id : 1, age : 29, gender: "male", name : "<NAME>" } ; omit( 3, array ); // [4, 5] omit( -2, array ); // [1, 2, 3] omit( 6, string ); // "World!" omit( -7, string ); // "Hello" omit( ['id', 'age', 'gender'], object ); // { name: "<NAME>" } ### omit = (i, x) -> if isNumber i if i > 0 then last i, x else first i, x else acc = {} forEach (value, key) -> if not contains key, 0, i acc[key] = value return , x acc backwards.omit = curry omit # toString = (x) -> # # if x then x.toString() # if isArray x then "[#{ x.toString() }]" # else if isObject x then "{#{ reduce toString, '', x }}" # else if x is false then "false" # else if x is 0 then "0" # else "undefined" # if window? # # console = ( window.console = window.console or {} ) # console = console or {} # forEach (method) -> # console[ method ] = noop if not console[ method ] # undefined # , [ # "assert" # "clear" # "count" # "debug" # "dir" # "dirxml" # "error" # "exception" # "group" # "groupCollapsed" # "groupEnd" # "info" # "log" # "markTimeline" # "profile" # "profileEnd" # "table" # "time" # "timeEnd" # "timeStamp" # "trace" # "warn" # ] backwards.log = (x) -> try console.log x catch e alert x x pluck = (key, xs) -> xs[key] backwards.pluck = curry pluck split = curry (regexp, string) -> string.split regexp join = curry (regexp, array) -> array.join regexp lines = split /\r\n|\r|\n/ unlines = join "\n" # forEach (type) -> # backwards["is#{ type }"] = (x) -> # toString.call( x ).slice( 8, -1 ) is type # return # , "Arguments Array Boolean Date Error Function Null Number Object Promise RegExp String Undefined".split " " ###* A monad that may or may not contain a value. The Maybe monad implements the map interface. @class Maybe @memberof backwards @constructor @public @example var monad = new Maybe( 1234 ); // Maybe( 1234 ) monad instanceof Maybe // true ### # class Maybe # constructor: (value) -> # return new Maybe value if not ( @ instanceof Maybe ) # @value = value # return @ # ###* # The __map__ function takes a transformation function and returns a new monad with the result of the transformation. # @method map # @public # @param f {Function} A function that applies a transform to the value and returns the new value. # @return {Maybe} Returns a new Maybe monad. # @example # var monadOne = new Maybe( 1234 ) # , monadTwo = monad.map( addOne ); # function addOne (x) { # return x + 1; # } # monadOne // Maybe( 1234 ) # monadTwo // Maybe( 2345 ) # ### # map: (f) -> # value = @value # if value? # new Maybe f value # else @ # toString: () -> # "[maybe " + omit 8, toString.call @value # valueOf: () -> # @.value # backwards.Maybe = Maybe # class Either # constructor: (left, right) -> # return new Either left, right if not ( @ instanceof Either ) # @left = left # @right = right # return @ # map: (f) -> # right = @right # if right? # new Either @left, f right # else @ # backwards.Either = curry Either # https://gist.github.com/brettz9/6093105 # if backwards.CLIENT_SIDE # try # slice.call document.documentElement # catch error # oldSlice = slice # slice = (beginning, end) -> # acc = [] # if @charAt # f = (x, i, xs) -> # acc.push xs.charAt i # return # else # f = (x) -> # acc.push x # return # forEach f, @ # return oldSlice.call acc, beginning, end or acc.length # if backwards.CLIENT_SIDE # try # slice.call document.documentElement # catch error # oldSlice = slice # slice = (beginning, end) -> # acc = [] # if @charAt # acc.push @charAt i for x, i in @ # else # acc.push x for x, i in @ # return oldSlice.call acc, beginning, end or acc.length # Export backwards object # ======================= # AMD ( almond.js, r.js ... ) if define? and define.amd define "backwards", [], () -> backwards # Node.js / CommonJS-like else if exports? if module? and module.exports module.exports = backwards else exports.backwards = backwards # Global Object else if window? window.backwards = backwards # Return backwards if none of the above else throw new Error "backwards.js could not be exported. " ### IDEAS, NOTES & BACKLOG ====================== BACKLOG IDEAS * Make the backwards object itself a function that can be invoked in the following ways: Debug mode: Pass a string which represents the method you would like returned. This will return the method wrapped in a "try, catch" which will return valuable information when debugging ( an error message containing an url to where you can find more information about how to use the method ). Extended with prototype: Pass in any kind of object to get back the object extended with a backwards-prototype. Like for example: backwards( [0, 1, 2, 3] ).map( (x) -> x + 1 ) // [1, 2, 3, 4] NOTES: Make sure that the prototype way of invocation should work on strings as well, meaning that invocation with a string that does not represent a method on the backwards object should return the string extended with the backwards prototype. ### # { error, success } = options # (( root, name, f ) -> # # Register as a named AMD module # if define? and define.amd # define name, [], f # # Register as a CommonJS-like module # else if exports? # if module? and module.exports # module.exports = f() # else # exports[name] = f() # # Register as a global object on the window # else # root[name] = f() # undefined # )( this, "backwards", () -> backwards ) # # Game Loop # while running # now = Date.now() # delta = now - lastTime # buffer += delta # while buffer >= TICK # update TICK # buffer -= TICK # render() # lastTime = now # https://www.youtube.com/watch?v=XcS-LdEBUkE # # map :: (a -> b) -> [a] -> [b] # map = (f, [x, xs...]) -> # if x is undefined # [] # else # [f(x), map(f, xs)...] # # length :: [a] -> Int # length = ([x, xs...]) -> # if x is undefined # 0 # else # 1 + length xs
true
"use strict" ###* * A set of utility functions for funtional programming in JavaScript. * @type {Object} * @exports backwards * @namespace backwards * @author PI:NAME:<NAME>END_PI * @copyright 2014 PI:NAME:<NAME>END_PI * @license * The MIT License (MIT) * * Copyright (c) 2014 PI:NAME:<NAME>END_PI * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ### backwards = {} array = Array arrayProto = array.prototype slice = arrayProto.slice object = Object objectProto = object.prototype toString = objectProto.toString hasOwn = objectProto.hasOwnProperty noop = () -> add = (a, b) -> a + b subtract = (a, b) -> a - b multiply = (a, b) -> a * b divide = (a, b) -> a / b append = (a, b) -> a += b concat = (a, b) -> a.concat b push = (a, b) -> a.push b ###* * The identity function. * @memberOf backwards * @sign a -> a * @param {x} x Any value. * @return {x} Any value. * @example * id( "some value" ); //=> "some value" * id( 1234 ); //=> 1234 ### I = (x) -> x backwards.I = I K = (x) -> () -> x ###* The __VERSION__ property is a string indicating the version of __backwards__ as a string value. @property VERSION @type String @final @public ### backwards.VERSION = "undefined" ###* The __CLIENT_SIDE__ property is a boolean indicating if the current environment is client-side (a browser) or not. @property CLIENT_SIDE @type Boolean @final @public ### backwards.CLIENT_SIDE = document? ###* The __SERVER_SIDE__ property is a boolean indicating if the current environment is server-side (f.ex. Node.js) or not. @property SERVER_SIDE @type Boolean @final @public ### backwards.SERVER_SIDE = not backwards.CLIENT_SIDE ###* This function is an internal function that is used by 'curry' to create curried functions from functions that take more than one parameter. @method __curry @private @param f {Function} The function to be curried. @param args* {"any"} Arguments that should be applied to the resulting function. @return {Function} A curried function. ### __curry = (f, args...) -> (params...) -> f.apply @, args.concat params ###* Create a curried function from a function that normally takes multiple parameters. @method curry @public @param f {Function} The function to be curried. @param [length] {Number} An optional parameter defining how many parameters the given function has. @return {Function} A curried function. @example function concat ( a, b ) { return a.concat( b ); } var curriedConcat = curry( concat ) // A curried function , oneAndTwo = curriedConcat( [1, 2] ) // A curried function , oneTwoAndThree = oneAndTwo( [3] ) // [1, 2, 3] , oneTwoAndFour = oneAndTwo( [4] ) // [1, 2, 4] ; ### curry = (f, length = f.length) -> newFunction = (args...) -> if args.length < length curry __curry.apply(@, [f].concat(args)), length - args.length else f.apply @, args newFunction.toString = () -> f.toString() newFunction.curried = true return newFunction backwards.curry = curry ###* * Compose your functions into a single function. * @memberOf backwards * @sign (b -> c) -> (a -> b) -> (a -> c) * @param {...function} fs Two or more functions to compose. * @return {function} The resulting function. * @example * function addOne (x) { * return x + 1; * } * * function timesTwo (x) { * return x * 2; * } * * var nine = compose( addOne, timesTwo ) //=> 9 * , ten = compose( timesTwo, addOne ) //=> 10 * ; ### compose = (fs...) -> (args...) -> i = fs.length while i-- then args = [fs[i].apply @, args] args[0] backwards.compose = compose ###* Check if an Object is of a particular type. @method isTypeOf @public @param type {String} The String representation of the Object. @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value representing whether x is a type. @example var isBoolean = isTypeOf( 'Boolean' ) // A composed function , passed = isBoolean( true ) // true , failed = isBoolean( {} ) // false ; ### isTypeOf = curry (type, x) -> str = "[object #{ type }]" toString.call(x) is str backwards.isTypeOf = isTypeOf ###* Check if an object is a DOM element. @method isElement @public @param x {"any"} The object you wish to check the type of. @return {Boolean} A boolean value. @example isElement( document.createElement("div") ); // true isElement( {} ); // false isElement( false ); // false ### isElement = (x) -> not not( x and x.nodeType is 1 ) backwards.isElement = isElement ###* Check if an Object is an Arguments object. @method isArguments @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isArguments( arguments ) // true , failed = isArguments( false ) // false ; ### isArguments = do () -> if isTypeOf "Arguments", arguments then isTypeOf "Arguments" else (x) -> x? and hasOwn.call x, "callee" backwards.isArguments = isArguments ###* Check if an Object is an Array. @method isArray @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isArray( [1, 2, 3] ) // true , failed = isArray( false ) // false ; ### isArray = Array.isArray or isTypeOf "Array" backwards.isArray = isArray ###* Check if an Object is a Boolean. @method isBoolean @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isBoolean( true ) // true , passes = isBoolean( false ) // true , failed = isBoolean( 0 ) // false ; ### isBoolean = (x) -> x is true or x is false or isTypeOf "Boolean", x backwards.isBoolean = isBoolean ###* Check if an Object is a Date. @method isDate @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isDate( new Date() ) // true , failed = isDate( +new Date() ) // false , fails = isDate( false ) // false ; ### isDate = isTypeOf "Date" backwards.isDate = isDate ###* Check if an Object is an Error. @method isError @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isError( new Error() ) // true , passes = isError( new TypeError() ) // true , failed = isError( false ) // false ; ### isError = isTypeOf "Error" backwards.isError = isError ###* Check if an Object is a finite number. @method isFinite @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example isFinite( 1234 ); // true isFinite( NaN ); // true isFinite( new Number() ); // true isFinite( +new Date() ); // true isFinite( Infinity ); // false ### # isFinite :: a -> Boolean # isFinite = (x) -> # isFinite(x) and not isNaN parseFloat x isFinite = Number.isFinite or (x) -> isNumber(x) and not isNaN(x) and x isnt Infinity and x > 0 backwards.isFinite = isFinite ###* Check if an Object is a Function. @method isFunction @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var noop = function () {} , passed = isFunction( noop ) // true , passes = isFunction( new Function() ) // true , failed = isFunction( false ) // false ; ### isFunction = do () -> if typeof /./ isnt "function" (x) -> typeof x is "function" else isTypeOf "Function" backwards.isFunction = isFunction ###* Check if an Object is a NaN object. @method isNaN @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNaN( NaN ) // true , passes = isNaN( new Number() ) // false , failed = isNaN( false ) // false ; ### backwards.isNaN = Number.isNaN or (x) -> typeof x is "number" && isNaN x ###* Check if an Object is a Null object. @method isNull @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNull( null ) // true , failed = isNull( false ) // false ; ### isNull = (x) -> x is null or isTypeOf "Null", x backwards.isNull = isNull ###* Check if an Object is a Number. @method isNumber @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isNumber( 123 ) // true , failed = isNumber( false ) // false ; ### isNumber = isTypeOf "Number" backwards.isNumber = isNumber ###* Check if an Object is an Object. @method isObject @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isObject( {} ) // true , failed = isObject( false ) // false ; ### isObject = (x) -> if not x? or isArguments( x ) or isElement( x ) or isFunction( x.then ) return false else return isTypeOf "Object", x backwards.isObject = isObject ###* Check if an Object is a Promise. @method isPromise @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var promise = new Promise(function (resolve, reject) { resolve( "I am a promise" ); }); isPromise( promise ); // true isPromise( {} ); // false ### isPromise = (x) -> return true if isTypeOf "Promise", x if x? return true if typeof x.then is "function" false backwards.isPromise = isPromise ###* Check if an Object is a regular expression ( RegExp ). @method isRegExp @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isRegExp( /./ ) // true , passes = isRegExp( new RegExp() ) // true , failed = isRegExp( false ) // false ; ### isRegExp = isTypeOf "RegExp" backwards.isRegExp = isRegExp ###* Check if an Object is a String. @method isString @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isString( "string" ) // true , failed = isString( false ) // false ; ### isString = isTypeOf "String" backwards.isString = isString ###* Check if an Object is undefined. @method isUndefined @public @param x {"any"} The Object you wish to check the type of. @return {Boolean} A Boolean value. @example var passed = isUndefined( void 0 ) // true , failed = isUndefined( false ) // false ; ### isUndefined = (x) -> x is undefined or isTypeOf "Undefined", x backwards.isUndefined = isUndefined # exists :: a -> Boolean # exists = (x) -> # typeof x isnt "undefined" and x isnt null exists = (x) -> x? backwards.exists = exists # isEmpty :: Array|Object -> Boolean isEmpty = (x) -> if isObject x return false for own key of x else if isArray x return false if x.length true backwards.isEmpty = isEmpty # forEachQuickEscape = (f, xs) -> # for x, i in xs # result = f x, i, xs # return result if result? ###* forEach executes the provided callback once for each element present in the array in ascending order. It is not invoked for indexes that have been deleted or elided. However, it is executed for elements that are present and have the value undefined. callback is invoked with three arguments: the element value the element index, key or undefined the array or object being traversed or undefined The range of elements processed by forEach is set before the first invocation of callback. Elements that are appended to the array after the call to forEach begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach visits them; elements that are deleted before being visited are not visited. @method forEach @public @param f {Function} The function you wish to execute over each element in the object. @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param x {"any"} The object you wish to iterate over. @return {undefined} @example var f = function (value, key, object) { console.log( value, key ); }; forEach( f, [1, 2, 3] ); // undefined forEach( f, { id: 1, name: "string" } ); // undefined forEach( f, "Hello folks!" ); // undefined ### forEach = (f, xs) -> if xs.length or isArray xs f value, key, xs for value, key in xs else if isObject xs for key, value of xs f value, key, xs if hasOwn.call xs, key else f xs return backwards.forEach = curry forEach ###* The __map__ function calls the provided callback function (f) once for each element in an array, in ascending order, and constructs a new array from the results. __callback__ is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that are undefined, those which have been deleted or which have never been assigned values. callback is invoked with three arguments: the element value the element index, key or undefined the array or object being traversed or undefined The __map__ function does not mutate the array on which it is called (although callback, if invoked, may do so). The range of elements processed by map is set before the first invocation of callback. Elements which are appended to the array after the call to map begins will not be visited by callback. If existing elements of the array are changed, or deleted, their value as passed to callback will be the value at the time map visits them; elements that are deleted are not visited. @method map @public @param f {Function} The function you wish to execute over each element in the object. @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param xs {"any"} The object you wish to iterate over. @return {"any"} @example var addOne = function (x) { return x + 1; }; map( addOne, [1, 2, 3] ); // [2, 3, 4] map( addOne, { id: 1, name: "string" } ); // ["id1", "name1"] map( addOne, "Hello folks!" ); // "Hello folks!1" ### map = (f, xs) -> if isArray( xs ) or isObject( xs ) acc = [] forEach (value, index, object) -> if value? acc.push f value, index, object else acc.push undefined return , xs acc else if xs? if isFunction xs.map then xs.map f else if isPromise xs then xs.then f else f xs else xs backwards.map = curry map filter = (f, xs) -> if isArray xs acc = [] map (value, index, array) -> acc.push value if f value, index, array , xs acc else xs if f xs backwards.filter = curry filter keys = (x) -> acc = [] forEach (value, key, object) -> acc.push key , x acc ###* __reduce__ executes the callback function once for each element present in the array, excluding holes in the array, receiving four arguments: the initial value (or value from the previous callback call), the value of the current element, the current index, and the array over which iteration is occurring. The callback function (__f__) is invoked with four arguments: The initial value (or return value from the previous callback invocation). The element value. The element index, key or undefined. The array or object being traversed or undefined. The first time the callback function (__f__) is called, __accumulator__ and __value__ can be one of two values. If initial value (__acc__) is provided in the call to reduce, then __accumulator__ will be equal to initial value and __value__ will be equal to the first value in the array. If no initial value (__acc__) was provided, then __accumulator__ will be equal to the first value in the array and __value__ will be equal to the second. If the array or object (__x__) is empty and no initial value (__acc__) is provided, a TypeError will be thrown. If the array or object (__x__) only has one element (regardless of position) and no initial value (__acc__) is provided, or if initial value (__acc__) is provided but the array or object (__x__) is empty, the solo value will be returned without calling callback function (__f__). @method reduce @public @param f {Function} The callback function. @param f.accumulator {"any"} The initial value (or return value from the previous callback invocation). @param f.value {"any"} The element value. @param f.key {Number|String|undefined} The element index, key or undefined. @param f.object {Array|Object|undefined} The array or object being traversed or undefined. @param acc {"any"} The initial value. @param x {"any"} The object you wish to reduce. @return {"any"|TypeError} Returns the reduced value, or a TypeError if given an empty object and no initial value. @example var add = function (a, b) { return a + b; } , append = function (a, b) { return a.concat(b); } , flatten = reduce( append, [] ) ; reduce( add, 0 , [0, 1, 2, 3] ); // 6 reduce( add, undefined, [0, 1, 2, 3] ); // 6 flatten( [[0, 1], [2, 3], [4, 5]] ); // [0, 1, 2, 3, 4, 5] ### reduce = (f, acc, x) -> if not acc? and isEmpty x throw new TypeError "Reduce of empty object with no initial value" if isArray(x) or isObject(x) forEach (value, key, object) -> if acc is undefined then acc = value else acc = f acc, value, key, object return , x else acc = f acc, x acc backwards.reduce = curry reduce max = backwards.reduce (max, num) -> if max > num then max else num , undefined min = backwards.reduce (min, num) -> if min < num then min else num , undefined ###* The __extend__ function takes two or more objects and returns the first object (__acc__) extended with the properties (and values) of the other objects in ascending order. @method extend @public @param acc {Object} The object you wish to extend. @param objects* {Object} The objects you wish to be extended to __acc__. @return {Object} Returns the first object (__acc__) extended with the other objects properties and values in ascending order. @example var obj = { id : 1, age : 29, gender: "male", name : "PI:NAME:<NAME>END_PI" }; extend( obj, { age: 30, name: "PI:NAME:<NAME>END_PI." } ); // { id: 1, age: 30, gender: "male", name: "PI:NAME:<NAME>END_PI." } extend( obj, { id: 2 } ); // { id: 2, age: 30, gender: "male", name: "PI:NAME:<NAME>END_PI." } extend( {}, obj, { id: 2, age: 0, name: "PI:NAME:<NAME>END_PI." } ); // { id: 2, age: 0, gender: "male", name: "PI:NAME:<NAME>END_PI." } ### extend = (objects...) -> acc = {} forEach (object) -> forEach (value, key) -> acc[key] = value return , object , objects acc backwards.extend = curry extend ###* The __copy__ function takes an Object and returns a fresh copy of the Object. @method copy @public @param x {"any"} The Object you wish to copy. @return {"any"} A fresh copy of the given Object. @example copy( [1, 2, 3] ); // [1, 2, 3] copy( { id: 1, name: "string" } ); // { id: 1, name: "string" } ### copy = (x) -> if isObject x then extend x else map I, x backwards.copy = copy ###* The __flatten__ function takes an array of arrays and flattens the array one level. @method flatten @public @param x {Array} The Array you wish to flatten. @return {Array} A flattened Array. @example var array = [[1, 2], [3, 4], [5, 6]]; flatten( array ); // [1, 2, 3, 4, 5, 6] ### flatten = backwards.reduce concat, [] backwards.flatten = flatten ###* The __indexOf__ function returns the first index at which a given element can be found, or -1 if it could not be found. If the index (__i__) is greater than or equal to the array or string length, -1 is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array or string. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. If __x__ is a string, __i__ is greater than or equal to __x__.length and __search__ is an empty string ("") then __x__.length is returned. @method indexOf @public @param search {"mixed"} The element to locate in the array. @param i {Number} The index to start the search at. @param x {Array|String} The array or string you wish to search. @return {Number} The first index at which a given element can be found, or -1 if not found. @example var array = [2, 5, 9]; indexOf( 2, 0, array ); // 0 indexOf( 7, 0, array ); // -1 indexOf( 9, 2, array ); // 2 indexOf( 2, -1, array ); // -1 indexOf( 2, -3, array ); // 0 ### indexOf = (search, i, x) -> len = x.length i = i or 0 isNaN = backwards.isNaN if len is 0 or i >= len if search is "" and isString x return len else return -1 else if i < 0 i = len + i if i < 0 i = 0 if isArray x while i < len return i if x[i] is search or isNaN( search ) and isNaN( x[i] ) i++ else if isString x return x.indexOf search, i -1 backwards.indexOf = curry indexOf ###* The __contains__ function returns true if a given element can be found in the array, or false if it is not present. If the index is greater than or equal to the array's length, false is returned, which means the array will not be searched. If the provided index value is a negative number, it is taken as the offset from the end of the array. Note: if the provided index is negative, the array is still searched from front to back. If the calculated index is less than 0, then the whole array will be searched. @method contains @public @param search {"mixed"} The element to locate in the array. @param i {Number} The index to start the search at. @param x {Array|String} The Array you wish to search in. @return {Boolean} Returns true if *search* is found in the *Array*, or false if it is not found. @example var array = [1, 2, 3, NaN]; contains( 2, 0, array ); // true contains( 4, 0, array ); // false contains( 3, 3, array ); // false contains( 3, -2, array ); // true contains( NaN, 0, array ); // true ### contains = (search, i, x) -> ( indexOf search, i, x ) isnt -1 backwards.contains = curry contains ###* The __some__ function takes a predicate function and an array and returns true if some of the values in the array conforms with the predicate function, or false if not. It returns false if given an empty array. @method some @public @param f {Function} A predicate function. @param xs {Array} The array you wish to check. @return {Boolean} Returns true if some of the values in the array conforms with the predicate function, or false if not. It returns false if given an empty array. @example var predicate = function (x) { return x > 10 }; some( predicate, [12, 5, 8, 1, 4] ); // true some( predicate, [2, 5, 8, 1, 4] ); // false some( predicate, [] ); // false ### some = (f, xs) -> return true for x in xs when f x false backwards.some = curry some ###* The __every__ function takes a predicate function and an array and returns true if every value in the array conforms with the predicate function, or false if not. It returns true if given an empty array. @method every @public @param f {Function} A predicate function. @param xs {Array} The array you wish to check. @return {Boolean} Returns true if every value in the array conforms with the predicate function, or false if not. It returns true if given an empty array. @example var predicate = function (x) { return x > 10 }; every( predicate, [] ); // true every( predicate, [12, 54, 18, 130, 44] ); // true every( predicate, [12, 5, 8, 130, 44] ); // false ### every = (f, xs) -> return false for x in xs when not f x true backwards.every = curry every ###* The __delete__ function takes an element and an array or string, and deletes the first occurence of that element from the list. It returns a new array or string. @method delete @public @param x {"any"} The element to delete. @param xs {Array|String} The array or string you wish to delete an element from. @return {Array|String} Returns an array or string without causing side-effects on the given array or string. @example delete( 12 , [12, 54, 18, NaN, "element"] ); // [54,18,NaN,"element"] delete( NaN , [12, 54, 18, NaN, "element"] ); // [12,54,18,"element"] delete( "element" , [12, 54, 18, NaN, "element"] ); // [12,54,18,NaN] delete( 1234 , [12, 54, 18, NaN, "element"] ); // [12,54,18,NaN,"element"] delete( "e" , "element" ); // "lement" delete( "ele" , "element" ); // "ment" ### _delete = (x, xs) -> i = indexOf x, 0, xs n = x.length or 1 if i isnt -1 and xs.length xs[0...i].concat xs[i+n...xs.length] else xs backwards.delete = curry _delete ###* The __partition__ function takes a predicate function and an array or a string, and returns an array with two indexes. The first index in the resulting array contains all the elements that conforms to the predicate function, and the second index contains all the elements that does not. @method partition @public @param f {Function} The predicate function. @param xs {Array|String} The array or string you wish to partition. @return {Array} Returns an array with two indexes. The first index contains all the elements that conforms to the predicate function, and the second index contains all the elements that does not. @example var partition = backwards.partition , indexOf = backwards.indexOf , array = [12, 54, 18, NaN, "element"] , string = "elementary eh!" , predicateArray, predicateString; predicateArray = function (x) { return x > 15; }; predicateString = function (x) { return indexOf( x, 0, "element" ); }; partition( predicateArray, array ); // [[54, 18], [12, NaN, "element"]] partition( predicateString, string ); // [ // ["e","l","e","m","e","n","t","e"], // ["a","r","y"," ","h","!"] // ] ### partition = (f, xs) -> acc = [[], []] xs = toArray xs if isString xs forEach (x, i, xs) -> if f x, i, xs then acc[0].push x else acc[1].push x return , xs acc backwards.partition = curry partition toArray = (xs) -> if isFunction xs.charAt result = [] forEach (value, index, string) -> result.push string.charAt index , xs else result = copy xs result escape = (html) -> # result = new String html result = html .replace /&/g, "&amp;" .replace /</g, "&lt;" .replace />/g, "&gt;" .replace /"/g, "&quot;" if result is "#{ html }" then html else result unescape = (html) -> # result = new String html result = html .replace /&amp;/g, "&" .replace /&lt;/g, "<" .replace /&gt;/g, ">" .replace /&quot;/g, '"' if result is "#{ html }" then html else result either = (a, b) -> b ? a backwards.either = curry either maybe = (f, x) -> if x? then f x else undefined backwards.maybe = curry maybe ###* The __pick__ function returns a subset of the given object. If given a positive number and an array or string it will return the first __i__ indexes of the object. If given a negative number and an array or string it will return the last __i__ indexes of the object. If given an array of strings and an object it will return an object containing the keys / properties that was listed in __i__. @method pick @public @param i {Number|Array} The number of indexes you wish to extract, or an array of strings which represents the keys of the object you wish to extract. @param x {Array|String|Object} An array, string or object @return {Array|String|Object} A subset of the object. @example var array = [1, 2, 3, 4, 5] , string = "Hello World!" , object = { id : 1, age : 29, gender: "male", name : "PI:NAME:<NAME>END_PI" } ; pick( 3, array ); // [1, 2, 3] pick( -2, array ); // [4, 5] pick( 5, string ); // "Hello" pick( -6, string ); // "World!" pick( ['name'], object ); // { name: "PI:NAME:<NAME>END_PI" } ### first = (i, x) -> x[0...i] last = (i, x) -> x[i...x.length] pick = (i, x) -> if isNumber i if i > 0 then first i, x else last i, x else acc = {} value = undefined forEach (key) -> value = x[key] acc[key] = value if value return , i acc backwards.pick = curry pick ###* Drops a subset of the given object, from the beginning to *i*, and returns the rest of the object. @method omit @public @param i {Number|Array} The number of indexes you wish to extract @param x {Array|String|Object} An Array, String or Object @return {Array|String|Object} A subset of *x* from index *i* to the end @example var array = [1, 2, 3, 4, 5] , string = "Hello World!" , object = { id : 1, age : 29, gender: "male", name : "PI:NAME:<NAME>END_PI" } ; omit( 3, array ); // [4, 5] omit( -2, array ); // [1, 2, 3] omit( 6, string ); // "World!" omit( -7, string ); // "Hello" omit( ['id', 'age', 'gender'], object ); // { name: "PI:NAME:<NAME>END_PI" } ### omit = (i, x) -> if isNumber i if i > 0 then last i, x else first i, x else acc = {} forEach (value, key) -> if not contains key, 0, i acc[key] = value return , x acc backwards.omit = curry omit # toString = (x) -> # # if x then x.toString() # if isArray x then "[#{ x.toString() }]" # else if isObject x then "{#{ reduce toString, '', x }}" # else if x is false then "false" # else if x is 0 then "0" # else "undefined" # if window? # # console = ( window.console = window.console or {} ) # console = console or {} # forEach (method) -> # console[ method ] = noop if not console[ method ] # undefined # , [ # "assert" # "clear" # "count" # "debug" # "dir" # "dirxml" # "error" # "exception" # "group" # "groupCollapsed" # "groupEnd" # "info" # "log" # "markTimeline" # "profile" # "profileEnd" # "table" # "time" # "timeEnd" # "timeStamp" # "trace" # "warn" # ] backwards.log = (x) -> try console.log x catch e alert x x pluck = (key, xs) -> xs[key] backwards.pluck = curry pluck split = curry (regexp, string) -> string.split regexp join = curry (regexp, array) -> array.join regexp lines = split /\r\n|\r|\n/ unlines = join "\n" # forEach (type) -> # backwards["is#{ type }"] = (x) -> # toString.call( x ).slice( 8, -1 ) is type # return # , "Arguments Array Boolean Date Error Function Null Number Object Promise RegExp String Undefined".split " " ###* A monad that may or may not contain a value. The Maybe monad implements the map interface. @class Maybe @memberof backwards @constructor @public @example var monad = new Maybe( 1234 ); // Maybe( 1234 ) monad instanceof Maybe // true ### # class Maybe # constructor: (value) -> # return new Maybe value if not ( @ instanceof Maybe ) # @value = value # return @ # ###* # The __map__ function takes a transformation function and returns a new monad with the result of the transformation. # @method map # @public # @param f {Function} A function that applies a transform to the value and returns the new value. # @return {Maybe} Returns a new Maybe monad. # @example # var monadOne = new Maybe( 1234 ) # , monadTwo = monad.map( addOne ); # function addOne (x) { # return x + 1; # } # monadOne // Maybe( 1234 ) # monadTwo // Maybe( 2345 ) # ### # map: (f) -> # value = @value # if value? # new Maybe f value # else @ # toString: () -> # "[maybe " + omit 8, toString.call @value # valueOf: () -> # @.value # backwards.Maybe = Maybe # class Either # constructor: (left, right) -> # return new Either left, right if not ( @ instanceof Either ) # @left = left # @right = right # return @ # map: (f) -> # right = @right # if right? # new Either @left, f right # else @ # backwards.Either = curry Either # https://gist.github.com/brettz9/6093105 # if backwards.CLIENT_SIDE # try # slice.call document.documentElement # catch error # oldSlice = slice # slice = (beginning, end) -> # acc = [] # if @charAt # f = (x, i, xs) -> # acc.push xs.charAt i # return # else # f = (x) -> # acc.push x # return # forEach f, @ # return oldSlice.call acc, beginning, end or acc.length # if backwards.CLIENT_SIDE # try # slice.call document.documentElement # catch error # oldSlice = slice # slice = (beginning, end) -> # acc = [] # if @charAt # acc.push @charAt i for x, i in @ # else # acc.push x for x, i in @ # return oldSlice.call acc, beginning, end or acc.length # Export backwards object # ======================= # AMD ( almond.js, r.js ... ) if define? and define.amd define "backwards", [], () -> backwards # Node.js / CommonJS-like else if exports? if module? and module.exports module.exports = backwards else exports.backwards = backwards # Global Object else if window? window.backwards = backwards # Return backwards if none of the above else throw new Error "backwards.js could not be exported. " ### IDEAS, NOTES & BACKLOG ====================== BACKLOG IDEAS * Make the backwards object itself a function that can be invoked in the following ways: Debug mode: Pass a string which represents the method you would like returned. This will return the method wrapped in a "try, catch" which will return valuable information when debugging ( an error message containing an url to where you can find more information about how to use the method ). Extended with prototype: Pass in any kind of object to get back the object extended with a backwards-prototype. Like for example: backwards( [0, 1, 2, 3] ).map( (x) -> x + 1 ) // [1, 2, 3, 4] NOTES: Make sure that the prototype way of invocation should work on strings as well, meaning that invocation with a string that does not represent a method on the backwards object should return the string extended with the backwards prototype. ### # { error, success } = options # (( root, name, f ) -> # # Register as a named AMD module # if define? and define.amd # define name, [], f # # Register as a CommonJS-like module # else if exports? # if module? and module.exports # module.exports = f() # else # exports[name] = f() # # Register as a global object on the window # else # root[name] = f() # undefined # )( this, "backwards", () -> backwards ) # # Game Loop # while running # now = Date.now() # delta = now - lastTime # buffer += delta # while buffer >= TICK # update TICK # buffer -= TICK # render() # lastTime = now # https://www.youtube.com/watch?v=XcS-LdEBUkE # # map :: (a -> b) -> [a] -> [b] # map = (f, [x, xs...]) -> # if x is undefined # [] # else # [f(x), map(f, xs)...] # # length :: [a] -> Int # length = ([x, xs...]) -> # if x is undefined # 0 # else # 1 + length xs
[ { "context": " constructor: ->\n super()\n @name = \"Naga\"\n @hp = 250\n @atk = 7\n getNextAc", "end": 300, "score": 0.9983514547348022, "start": 296, "tag": "NAME", "value": "Naga" } ]
src/entity/enemy/naga.coffee
zekoff/1gam-battle
0
BaseEnemy = require './base' Constrict = require '../../ability/enemy/constrict' Poison = require '../../ability/enemy/poison' Leech = require '../../ability/enemy/leech' Bite = require '../../ability/enemy/bite' class Naga extends BaseEnemy constructor: -> super() @name = "Naga" @hp = 250 @atk = 7 getNextAction: -> chance = game.rnd.frac() if chance < .2 return new Constrict() else if chance < .4 return new Poison() else if chance < .7 return new Leech() else return new Bite() module.exports = Naga
163744
BaseEnemy = require './base' Constrict = require '../../ability/enemy/constrict' Poison = require '../../ability/enemy/poison' Leech = require '../../ability/enemy/leech' Bite = require '../../ability/enemy/bite' class Naga extends BaseEnemy constructor: -> super() @name = "<NAME>" @hp = 250 @atk = 7 getNextAction: -> chance = game.rnd.frac() if chance < .2 return new Constrict() else if chance < .4 return new Poison() else if chance < .7 return new Leech() else return new Bite() module.exports = Naga
true
BaseEnemy = require './base' Constrict = require '../../ability/enemy/constrict' Poison = require '../../ability/enemy/poison' Leech = require '../../ability/enemy/leech' Bite = require '../../ability/enemy/bite' class Naga extends BaseEnemy constructor: -> super() @name = "PI:NAME:<NAME>END_PI" @hp = 250 @atk = 7 getNextAction: -> chance = game.rnd.frac() if chance < .2 return new Constrict() else if chance < .4 return new Poison() else if chance < .7 return new Leech() else return new Bite() module.exports = Naga
[ { "context": "C/KvTiHZgyhwHP8Tkx2Ygd+4EDMwpXpAnlRtuJu+vFozMLF2a0lXAfOowkbYxYe1+RF2Yhb2IT9MQv9eVHOxTGsSwxGcCZm4WdelLuSHg8QatGZeh5KyQtxB/NwCIfRgtt5US6IWbiJgZTTWZ/UrsG1xLQHL2IWeqrYd+dF2YdunMRVBMRaLMckXiVwK3r/I0E/tqXzW0xgdX0VYCrFOjO2Va+PuJTO4/iE8Xq8RhuWqdj2FAdxpDo7ZmEUF/KiXIwxrMJUvYqibSrTdx2nUeZFeRaX8SFm4Suk5PcYiVnYAtU2bkBHzMJgXpTNOIHtqfdeLMUS3Mcz7GFmkNbjHr6jK2ZhsJp+XpQt6ec6jKIB86cLJNA+9GFOamsAb1Qc+qJic2PSagzv/iqQirQn6mvS1SQ+Y0WawkXJjUcxC5uhdpbSw9iKLjzEt7QnE6QpxWmb/wA4250STmTc7QAAAABJRU5ErkJggg==\"\n event_type: \"tap\"\n default_order: 10\n\nmodule.e", "end": 1672, "score": 0.997952938079834, "start": 1238, "tag": "KEY", "value": "lXAfOowkbYxYe1+RF2Yhb2IT9MQv9eVHOxTGsSwxGcCZm4WdelLuSHg8QatGZeh5KyQtxB/NwCIfRgtt5US6IWbiJgZTTWZ/UrsG1xLQHL2IWeqrYd+dF2YdunMRVBMRaLMckXiVwK3r/I0E/tqXzW0xgdX0VYCrFOjO2Va+PuJTO4/iE8Xq8RhuWqdj2FAdxpDo7ZmEUF/KiXIwxrMJUvYqibSrTdx2nUeZFeRaX8SFm4Suk5PcYiVnYAtU2bkBHzMJgXpTNOIHtqfdeLMUS3Mcz7GFmkNbjHr6jK2ZhsJp+XpQt6ec6jKIB86cLJNA+9GFOamsAb1Qc+qJic2PSagzv/iqQirQn6mvS1SQ+Y0WawkXJjUcxC5uhdpbSw9iKLjzEt7QnE6QpxWmb/wA4250STmTc7QAAAABJRU5ErkJggg==\"" } ]
bokehjs/src/coffee/tool/gestures/tap_tool.coffee
rothnic/bokeh
1
_ = require "underscore" SelectTool = require "./select_tool" class TapToolView extends SelectTool.View _tap: (e) -> canvas = @plot_view.canvas vx = canvas.sx_to_vx(e.bokeh.sx) vy = canvas.sy_to_vy(e.bokeh.sy) append = e.srcEvent.shiftKey ? false @_select(vx, vy, true, append) _select: (vx, vy, final, append) -> geometry = { type: 'point' vx: vx vy: vy } callback = @mget("callback") for r in @mget('renderers') ds = r.get('data_source') sm = ds.get('selection_manager') sm.select(@, @plot_view.renderers[r.id], geometry, final, append) if callback? then callback.execute(ds) @_save_geometry(geometry, final, append) return null class TapTool extends SelectTool.Model default_view: TapToolView type: "TapTool" tool_name: "Tap" icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAHWSURBVDiNbdJfaI9RGAfwz/7JNlLGjdxLyDU2u0EIx6uc7UIpF5pIU1OSGzfkUhvSiuSCvZbXGxeT0IxcSYlIiVxSJmqZzbj4nbafcer0nM75Ps/5Pt/vU2PWyouyAbsRsTJdv0SOGzELE9X4mlnJ7TiOtentV3qqS/EJTsUsDP9TIC/KvTiHZgyhwHP8Tkx2Ygd+4EDMwpXpAnlRtuJu+vFozMLF2a0lXAfOowkbYxYe1+RF2Yhb2IT9MQv9eVHOxTGsSwxGcCZm4WdelLuSHg8QatGZeh5KyQtxB/NwCIfRgtt5US6IWbiJgZTTWZ/UrsG1xLQHL2IWeqrYd+dF2YdunMRVBMRaLMckXiVwK3r/I0E/tqXzW0xgdX0VYCrFOjO2Va+PuJTO4/iE8Xq8RhuWqdj2FAdxpDo7ZmEUF/KiXIwxrMJUvYqibSrTdx2nUeZFeRaX8SFm4Suk5PcYiVnYAtU2bkBHzMJgXpTNOIHtqfdeLMUS3Mcz7GFmkNbjHr6jK2ZhsJp+XpQt6ec6jKIB86cLJNA+9GFOamsAb1Qc+qJic2PSagzv/iqQirQn6mvS1SQ+Y0WawkXJjUcxC5uhdpbSw9iKLjzEt7QnE6QpxWmb/wA4250STmTc7QAAAABJRU5ErkJggg==" event_type: "tap" default_order: 10 module.exports = Model: TapTool View: TapToolView
35245
_ = require "underscore" SelectTool = require "./select_tool" class TapToolView extends SelectTool.View _tap: (e) -> canvas = @plot_view.canvas vx = canvas.sx_to_vx(e.bokeh.sx) vy = canvas.sy_to_vy(e.bokeh.sy) append = e.srcEvent.shiftKey ? false @_select(vx, vy, true, append) _select: (vx, vy, final, append) -> geometry = { type: 'point' vx: vx vy: vy } callback = @mget("callback") for r in @mget('renderers') ds = r.get('data_source') sm = ds.get('selection_manager') sm.select(@, @plot_view.renderers[r.id], geometry, final, append) if callback? then callback.execute(ds) @_save_geometry(geometry, final, append) return null class TapTool extends SelectTool.Model default_view: TapToolView type: "TapTool" tool_name: "Tap" icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAHWSURBVDiNbdJfaI9RGAfwz/7JNlLGjdxLyDU2u0EIx6uc7UIpF5pIU1OSGzfkUhvSiuSCvZbXGxeT0IxcSYlIiVxSJmqZzbj4nbafcer0nM75Ps/5Pt/vU2PWyouyAbsRsTJdv0SOGzELE9X4mlnJ7TiOtentV3qqS/EJTsUsDP9TIC/KvTiHZgyhwHP8Tkx2Ygd+4EDMwpXpAnlRtuJu+vFozMLF2a0<KEY> event_type: "tap" default_order: 10 module.exports = Model: TapTool View: TapToolView
true
_ = require "underscore" SelectTool = require "./select_tool" class TapToolView extends SelectTool.View _tap: (e) -> canvas = @plot_view.canvas vx = canvas.sx_to_vx(e.bokeh.sx) vy = canvas.sy_to_vy(e.bokeh.sy) append = e.srcEvent.shiftKey ? false @_select(vx, vy, true, append) _select: (vx, vy, final, append) -> geometry = { type: 'point' vx: vx vy: vy } callback = @mget("callback") for r in @mget('renderers') ds = r.get('data_source') sm = ds.get('selection_manager') sm.select(@, @plot_view.renderers[r.id], geometry, final, append) if callback? then callback.execute(ds) @_save_geometry(geometry, final, append) return null class TapTool extends SelectTool.Model default_view: TapToolView type: "TapTool" tool_name: "Tap" icon: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAHWSURBVDiNbdJfaI9RGAfwz/7JNlLGjdxLyDU2u0EIx6uc7UIpF5pIU1OSGzfkUhvSiuSCvZbXGxeT0IxcSYlIiVxSJmqZzbj4nbafcer0nM75Ps/5Pt/vU2PWyouyAbsRsTJdv0SOGzELE9X4mlnJ7TiOtentV3qqS/EJTsUsDP9TIC/KvTiHZgyhwHP8Tkx2Ygd+4EDMwpXpAnlRtuJu+vFozMLF2a0PI:KEY:<KEY>END_PI event_type: "tap" default_order: 10 module.exports = Model: TapTool View: TapToolView
[ { "context": "atch\n forms\n\n# Deinflect Rules 20081220-0509 | by Jonathan Zarate | http://www.polarcloud.com\n#\nrules =\n 9:\n \"く", "end": 524, "score": 0.999906063079834, "start": 509, "tag": "NAME", "value": "Jonathan Zarate" } ]
src/deinflect.coffee
ashchan/japanese-coffee-kit
8
# Verb Deinflection # Deinflector = exports? and exports or @Deinflector = {} # Returns possible dictionary forms for a given verb # including itself # Note: combine rules are not used. Deinflector.deinflect = (verb) -> forms = [verb] for len in (k for k, v of rules when k <= verb.length) beginning = verb.substr 0, verb.length - len ending = verb.substr -len forms.push "#{beginning}#{form}" for match, form of rules[len] when ending is match forms # Deinflect Rules 20081220-0509 | by Jonathan Zarate | http://www.polarcloud.com # rules = 9: "くありませんでした": "い" 7: "いませんでした": "う" "きませんでした": "く" "きませんでした": "くる" "ぎませんでした": "ぐ" "しませんでした": "す" "しませんでした": "する" "ちませんでした": "つ" "にませんでした": "ぬ" "びませんでした": "ぶ" "みませんでした": "む" "りませんでした": "る" 6: "くありません": "い" "ませんでした": "る" 5: "いましょう": "う" "きましょう": "く" "きましょう": "くる" "ぎましょう": "ぐ" "しましょう": "す" "しましょう": "する" "ちましょう": "つ" "にましょう": "ぬ" "びましょう": "ぶ" "みましょう": "む" "りましょう": "る" 4: "いじゃう": "ぐ" "いすぎる": "う" "いちゃう": "く" "いなさい": "う" "いました": "う" "いません": "う" "かったら": "い" "かったり": "い" "きすぎる": "く" "きすぎる": "くる" "ぎすぎる": "ぐ" "きちゃう": "くる" "きなさい": "く" "きなさい": "くる" "ぎなさい": "ぐ" "きました": "く" "きました": "くる" "ぎました": "ぐ" "きません": "く" "きません": "くる" "ぎません": "ぐ" "こさせる": "くる" "こられる": "くる" "しすぎる": "す" "しすぎる": "する" "しちゃう": "す" "しちゃう": "する" "しなさい": "す" "しなさい": "する" "しました": "す" "しました": "する" "しません": "す" "しません": "する" "ちすぎる": "つ" "ちなさい": "つ" "ちました": "つ" "ちません": "つ" "っちゃう": "う" "っちゃう": "く" "っちゃう": "つ" "っちゃう": "る" "にすぎる": "ぬ" "になさい": "ぬ" "にました": "ぬ" "にません": "ぬ" "びすぎる": "ぶ" "びなさい": "ぶ" "びました": "ぶ" "びません": "ぶ" "ましょう": "る" "みすぎる": "む" "みなさい": "む" "みました": "む" "みません": "む" "りすぎる": "る" "りなさい": "る" "りました": "る" "りません": "る" "んじゃう": "ぬ" "んじゃう": "ぶ" "んじゃう": "む" 3: "いそう": "う" "いたい": "う" "いたら": "く" "いだら": "ぐ" "いたり": "く" "いだり": "ぐ" "います": "う" "かせる": "く" "がせる": "ぐ" "かった": "い" "かない": "く" "がない": "ぐ" "かれる": "く" "がれる": "ぐ" "きそう": "く" "きそう": "くる" "ぎそう": "ぐ" "きたい": "く" "きたい": "くる" "ぎたい": "ぐ" "きたら": "くる" "きたり": "くる" "きます": "く" "きます": "くる" "ぎます": "ぐ" "くない": "い" "ければ": "い" "こない": "くる" "こよう": "くる" "これる": "くる" "させる": "する" "させる": "る" "さない": "す" "される": "す" "される": "する" "しそう": "す" "しそう": "する" "したい": "す" "したい": "する" "したら": "す" "したら": "する" "したり": "す" "したり": "する" "しない": "する" "します": "す" "します": "する" "しよう": "する" "すぎる": "い" "すぎる": "る" "たせる": "つ" "たない": "つ" "たれる": "つ" "ちそう": "つ" "ちたい": "つ" "ちます": "つ" "ちゃう": "る" "ったら": "う" "ったら": "つ" "ったら": "る" "ったり": "う" "ったり": "つ" "ったり": "る" "なさい": "る" "なせる": "ぬ" "なない": "ぬ" "なれる": "ぬ" "にそう": "ぬ" "にたい": "ぬ" "にます": "ぬ" "ばせる": "ぶ" "ばない": "ぶ" "ばれる": "ぶ" "びそう": "ぶ" "びたい": "ぶ" "びます": "ぶ" "ました": "る" "ませる": "む" "ません": "る" "まない": "む" "まれる": "む" "みそう": "む" "みたい": "む" "みます": "む" "らせる": "る" "らない": "る" "られる": "る" "りそう": "る" "りたい": "る" "ります": "る" "わせる": "う" "わない": "う" "われる": "う" "んだら": "ぬ" "んだら": "ぶ" "んだら": "む" "んだり": "ぬ" "んだり": "ぶ" "んだり": "む" 2: "いた": "く" "いだ": "ぐ" "いて": "く" "いで": "ぐ" "えば": "う" "える": "う" "おう": "う" "かず": "く" "がず": "ぐ" "きた": "くる" "きて": "くる" "くて": "い" "けば": "く" "げば": "ぐ" "ける": "く" "げる": "ぐ" "こい": "くる" "こう": "く" "ごう": "ぐ" "こず": "くる" "さず": "す" "した": "す" "した": "する" "して": "す" "して": "する" "しろ": "する" "せず": "する" "せば": "す" "せよ": "する" "せる": "す" "そう": "い" "そう": "す" "そう": "る" "たい": "る" "たず": "つ" "たら": "る" "たり": "る" "った": "う" "った": "く" "った": "つ" "った": "る" "って": "う" "って": "く" "って": "つ" "って": "る" "てば": "つ" "てる": "つ" "とう": "つ" "ない": "る" "なず": "ぬ" "ねば": "ぬ" "ねる": "ぬ" "のう": "ぬ" "ばず": "ぶ" "べば": "ぶ" "べる": "ぶ" "ぼう": "ぶ" "ます": "る" "まず": "む" "めば": "む" "める": "む" "もう": "む" "よう": "る" "らず": "る" "れば": "る" "れる": "る" "ろう": "る" "わず": "う" "んだ": "ぬ" "んだ": "ぶ" "んだ": "む" "んで": "ぬ" "んで": "ぶ" "んで": "む" 1: "い": "いる" "い": "う" "い": "る" "え": "う" "え": "える" "き": "きる" "き": "く" "ぎ": "ぎる" "ぎ": "ぐ" "く": "い" "け": "く" "け": "ける" "げ": "ぐ" "げ": "げる" "さ": "い" "し": "す" "じ": "じる" "ず": "る" "せ": "す" "せ": "せる" "ぜ": "ぜる" "た": "る" "ち": "ちる" "ち": "つ" "て": "つ" "て": "てる" "て": "る" "で": "でる" "な": "" "に": "にる" "に": "ぬ" "ね": "ぬ" "ね": "ねる" "ひ": "ひる" "び": "びる" "び": "ぶ" "へ": "へる" "べ": "ぶ" "べ": "べる" "み": "みる" "み": "む" "め": "む" "め": "める" "よ": "る" "り": "りる" "り": "る" "れ": "る" "れ": "れる" "ろ": "る"
218638
# Verb Deinflection # Deinflector = exports? and exports or @Deinflector = {} # Returns possible dictionary forms for a given verb # including itself # Note: combine rules are not used. Deinflector.deinflect = (verb) -> forms = [verb] for len in (k for k, v of rules when k <= verb.length) beginning = verb.substr 0, verb.length - len ending = verb.substr -len forms.push "#{beginning}#{form}" for match, form of rules[len] when ending is match forms # Deinflect Rules 20081220-0509 | by <NAME> | http://www.polarcloud.com # rules = 9: "くありませんでした": "い" 7: "いませんでした": "う" "きませんでした": "く" "きませんでした": "くる" "ぎませんでした": "ぐ" "しませんでした": "す" "しませんでした": "する" "ちませんでした": "つ" "にませんでした": "ぬ" "びませんでした": "ぶ" "みませんでした": "む" "りませんでした": "る" 6: "くありません": "い" "ませんでした": "る" 5: "いましょう": "う" "きましょう": "く" "きましょう": "くる" "ぎましょう": "ぐ" "しましょう": "す" "しましょう": "する" "ちましょう": "つ" "にましょう": "ぬ" "びましょう": "ぶ" "みましょう": "む" "りましょう": "る" 4: "いじゃう": "ぐ" "いすぎる": "う" "いちゃう": "く" "いなさい": "う" "いました": "う" "いません": "う" "かったら": "い" "かったり": "い" "きすぎる": "く" "きすぎる": "くる" "ぎすぎる": "ぐ" "きちゃう": "くる" "きなさい": "く" "きなさい": "くる" "ぎなさい": "ぐ" "きました": "く" "きました": "くる" "ぎました": "ぐ" "きません": "く" "きません": "くる" "ぎません": "ぐ" "こさせる": "くる" "こられる": "くる" "しすぎる": "す" "しすぎる": "する" "しちゃう": "す" "しちゃう": "する" "しなさい": "す" "しなさい": "する" "しました": "す" "しました": "する" "しません": "す" "しません": "する" "ちすぎる": "つ" "ちなさい": "つ" "ちました": "つ" "ちません": "つ" "っちゃう": "う" "っちゃう": "く" "っちゃう": "つ" "っちゃう": "る" "にすぎる": "ぬ" "になさい": "ぬ" "にました": "ぬ" "にません": "ぬ" "びすぎる": "ぶ" "びなさい": "ぶ" "びました": "ぶ" "びません": "ぶ" "ましょう": "る" "みすぎる": "む" "みなさい": "む" "みました": "む" "みません": "む" "りすぎる": "る" "りなさい": "る" "りました": "る" "りません": "る" "んじゃう": "ぬ" "んじゃう": "ぶ" "んじゃう": "む" 3: "いそう": "う" "いたい": "う" "いたら": "く" "いだら": "ぐ" "いたり": "く" "いだり": "ぐ" "います": "う" "かせる": "く" "がせる": "ぐ" "かった": "い" "かない": "く" "がない": "ぐ" "かれる": "く" "がれる": "ぐ" "きそう": "く" "きそう": "くる" "ぎそう": "ぐ" "きたい": "く" "きたい": "くる" "ぎたい": "ぐ" "きたら": "くる" "きたり": "くる" "きます": "く" "きます": "くる" "ぎます": "ぐ" "くない": "い" "ければ": "い" "こない": "くる" "こよう": "くる" "これる": "くる" "させる": "する" "させる": "る" "さない": "す" "される": "す" "される": "する" "しそう": "す" "しそう": "する" "したい": "す" "したい": "する" "したら": "す" "したら": "する" "したり": "す" "したり": "する" "しない": "する" "します": "す" "します": "する" "しよう": "する" "すぎる": "い" "すぎる": "る" "たせる": "つ" "たない": "つ" "たれる": "つ" "ちそう": "つ" "ちたい": "つ" "ちます": "つ" "ちゃう": "る" "ったら": "う" "ったら": "つ" "ったら": "る" "ったり": "う" "ったり": "つ" "ったり": "る" "なさい": "る" "なせる": "ぬ" "なない": "ぬ" "なれる": "ぬ" "にそう": "ぬ" "にたい": "ぬ" "にます": "ぬ" "ばせる": "ぶ" "ばない": "ぶ" "ばれる": "ぶ" "びそう": "ぶ" "びたい": "ぶ" "びます": "ぶ" "ました": "る" "ませる": "む" "ません": "る" "まない": "む" "まれる": "む" "みそう": "む" "みたい": "む" "みます": "む" "らせる": "る" "らない": "る" "られる": "る" "りそう": "る" "りたい": "る" "ります": "る" "わせる": "う" "わない": "う" "われる": "う" "んだら": "ぬ" "んだら": "ぶ" "んだら": "む" "んだり": "ぬ" "んだり": "ぶ" "んだり": "む" 2: "いた": "く" "いだ": "ぐ" "いて": "く" "いで": "ぐ" "えば": "う" "える": "う" "おう": "う" "かず": "く" "がず": "ぐ" "きた": "くる" "きて": "くる" "くて": "い" "けば": "く" "げば": "ぐ" "ける": "く" "げる": "ぐ" "こい": "くる" "こう": "く" "ごう": "ぐ" "こず": "くる" "さず": "す" "した": "す" "した": "する" "して": "す" "して": "する" "しろ": "する" "せず": "する" "せば": "す" "せよ": "する" "せる": "す" "そう": "い" "そう": "す" "そう": "る" "たい": "る" "たず": "つ" "たら": "る" "たり": "る" "った": "う" "った": "く" "った": "つ" "った": "る" "って": "う" "って": "く" "って": "つ" "って": "る" "てば": "つ" "てる": "つ" "とう": "つ" "ない": "る" "なず": "ぬ" "ねば": "ぬ" "ねる": "ぬ" "のう": "ぬ" "ばず": "ぶ" "べば": "ぶ" "べる": "ぶ" "ぼう": "ぶ" "ます": "る" "まず": "む" "めば": "む" "める": "む" "もう": "む" "よう": "る" "らず": "る" "れば": "る" "れる": "る" "ろう": "る" "わず": "う" "んだ": "ぬ" "んだ": "ぶ" "んだ": "む" "んで": "ぬ" "んで": "ぶ" "んで": "む" 1: "い": "いる" "い": "う" "い": "る" "え": "う" "え": "える" "き": "きる" "き": "く" "ぎ": "ぎる" "ぎ": "ぐ" "く": "い" "け": "く" "け": "ける" "げ": "ぐ" "げ": "げる" "さ": "い" "し": "す" "じ": "じる" "ず": "る" "せ": "す" "せ": "せる" "ぜ": "ぜる" "た": "る" "ち": "ちる" "ち": "つ" "て": "つ" "て": "てる" "て": "る" "で": "でる" "な": "" "に": "にる" "に": "ぬ" "ね": "ぬ" "ね": "ねる" "ひ": "ひる" "び": "びる" "び": "ぶ" "へ": "へる" "べ": "ぶ" "べ": "べる" "み": "みる" "み": "む" "め": "む" "め": "める" "よ": "る" "り": "りる" "り": "る" "れ": "る" "れ": "れる" "ろ": "る"
true
# Verb Deinflection # Deinflector = exports? and exports or @Deinflector = {} # Returns possible dictionary forms for a given verb # including itself # Note: combine rules are not used. Deinflector.deinflect = (verb) -> forms = [verb] for len in (k for k, v of rules when k <= verb.length) beginning = verb.substr 0, verb.length - len ending = verb.substr -len forms.push "#{beginning}#{form}" for match, form of rules[len] when ending is match forms # Deinflect Rules 20081220-0509 | by PI:NAME:<NAME>END_PI | http://www.polarcloud.com # rules = 9: "くありませんでした": "い" 7: "いませんでした": "う" "きませんでした": "く" "きませんでした": "くる" "ぎませんでした": "ぐ" "しませんでした": "す" "しませんでした": "する" "ちませんでした": "つ" "にませんでした": "ぬ" "びませんでした": "ぶ" "みませんでした": "む" "りませんでした": "る" 6: "くありません": "い" "ませんでした": "る" 5: "いましょう": "う" "きましょう": "く" "きましょう": "くる" "ぎましょう": "ぐ" "しましょう": "す" "しましょう": "する" "ちましょう": "つ" "にましょう": "ぬ" "びましょう": "ぶ" "みましょう": "む" "りましょう": "る" 4: "いじゃう": "ぐ" "いすぎる": "う" "いちゃう": "く" "いなさい": "う" "いました": "う" "いません": "う" "かったら": "い" "かったり": "い" "きすぎる": "く" "きすぎる": "くる" "ぎすぎる": "ぐ" "きちゃう": "くる" "きなさい": "く" "きなさい": "くる" "ぎなさい": "ぐ" "きました": "く" "きました": "くる" "ぎました": "ぐ" "きません": "く" "きません": "くる" "ぎません": "ぐ" "こさせる": "くる" "こられる": "くる" "しすぎる": "す" "しすぎる": "する" "しちゃう": "す" "しちゃう": "する" "しなさい": "す" "しなさい": "する" "しました": "す" "しました": "する" "しません": "す" "しません": "する" "ちすぎる": "つ" "ちなさい": "つ" "ちました": "つ" "ちません": "つ" "っちゃう": "う" "っちゃう": "く" "っちゃう": "つ" "っちゃう": "る" "にすぎる": "ぬ" "になさい": "ぬ" "にました": "ぬ" "にません": "ぬ" "びすぎる": "ぶ" "びなさい": "ぶ" "びました": "ぶ" "びません": "ぶ" "ましょう": "る" "みすぎる": "む" "みなさい": "む" "みました": "む" "みません": "む" "りすぎる": "る" "りなさい": "る" "りました": "る" "りません": "る" "んじゃう": "ぬ" "んじゃう": "ぶ" "んじゃう": "む" 3: "いそう": "う" "いたい": "う" "いたら": "く" "いだら": "ぐ" "いたり": "く" "いだり": "ぐ" "います": "う" "かせる": "く" "がせる": "ぐ" "かった": "い" "かない": "く" "がない": "ぐ" "かれる": "く" "がれる": "ぐ" "きそう": "く" "きそう": "くる" "ぎそう": "ぐ" "きたい": "く" "きたい": "くる" "ぎたい": "ぐ" "きたら": "くる" "きたり": "くる" "きます": "く" "きます": "くる" "ぎます": "ぐ" "くない": "い" "ければ": "い" "こない": "くる" "こよう": "くる" "これる": "くる" "させる": "する" "させる": "る" "さない": "す" "される": "す" "される": "する" "しそう": "す" "しそう": "する" "したい": "す" "したい": "する" "したら": "す" "したら": "する" "したり": "す" "したり": "する" "しない": "する" "します": "す" "します": "する" "しよう": "する" "すぎる": "い" "すぎる": "る" "たせる": "つ" "たない": "つ" "たれる": "つ" "ちそう": "つ" "ちたい": "つ" "ちます": "つ" "ちゃう": "る" "ったら": "う" "ったら": "つ" "ったら": "る" "ったり": "う" "ったり": "つ" "ったり": "る" "なさい": "る" "なせる": "ぬ" "なない": "ぬ" "なれる": "ぬ" "にそう": "ぬ" "にたい": "ぬ" "にます": "ぬ" "ばせる": "ぶ" "ばない": "ぶ" "ばれる": "ぶ" "びそう": "ぶ" "びたい": "ぶ" "びます": "ぶ" "ました": "る" "ませる": "む" "ません": "る" "まない": "む" "まれる": "む" "みそう": "む" "みたい": "む" "みます": "む" "らせる": "る" "らない": "る" "られる": "る" "りそう": "る" "りたい": "る" "ります": "る" "わせる": "う" "わない": "う" "われる": "う" "んだら": "ぬ" "んだら": "ぶ" "んだら": "む" "んだり": "ぬ" "んだり": "ぶ" "んだり": "む" 2: "いた": "く" "いだ": "ぐ" "いて": "く" "いで": "ぐ" "えば": "う" "える": "う" "おう": "う" "かず": "く" "がず": "ぐ" "きた": "くる" "きて": "くる" "くて": "い" "けば": "く" "げば": "ぐ" "ける": "く" "げる": "ぐ" "こい": "くる" "こう": "く" "ごう": "ぐ" "こず": "くる" "さず": "す" "した": "す" "した": "する" "して": "す" "して": "する" "しろ": "する" "せず": "する" "せば": "す" "せよ": "する" "せる": "す" "そう": "い" "そう": "す" "そう": "る" "たい": "る" "たず": "つ" "たら": "る" "たり": "る" "った": "う" "った": "く" "った": "つ" "った": "る" "って": "う" "って": "く" "って": "つ" "って": "る" "てば": "つ" "てる": "つ" "とう": "つ" "ない": "る" "なず": "ぬ" "ねば": "ぬ" "ねる": "ぬ" "のう": "ぬ" "ばず": "ぶ" "べば": "ぶ" "べる": "ぶ" "ぼう": "ぶ" "ます": "る" "まず": "む" "めば": "む" "める": "む" "もう": "む" "よう": "る" "らず": "る" "れば": "る" "れる": "る" "ろう": "る" "わず": "う" "んだ": "ぬ" "んだ": "ぶ" "んだ": "む" "んで": "ぬ" "んで": "ぶ" "んで": "む" 1: "い": "いる" "い": "う" "い": "る" "え": "う" "え": "える" "き": "きる" "き": "く" "ぎ": "ぎる" "ぎ": "ぐ" "く": "い" "け": "く" "け": "ける" "げ": "ぐ" "げ": "げる" "さ": "い" "し": "す" "じ": "じる" "ず": "る" "せ": "す" "せ": "せる" "ぜ": "ぜる" "た": "る" "ち": "ちる" "ち": "つ" "て": "つ" "て": "てる" "て": "る" "で": "でる" "な": "" "に": "にる" "に": "ぬ" "ね": "ぬ" "ね": "ねる" "ひ": "ひる" "び": "びる" "び": "ぶ" "へ": "へる" "べ": "ぶ" "べ": "べる" "み": "みる" "み": "む" "め": "む" "め": "める" "よ": "る" "り": "りる" "り": "る" "れ": "る" "れ": "れる" "ろ": "る"
[ { "context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 22, "score": 0.9971986413002014, "start": 16, "tag": "NAME", "value": "Konode" } ]
src/expandingTextArea.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 # A <textarea> whose height is determined by the height of its content. # Note: users can add line breaks inside textareas, which may need special # handling when being displayed. _ = require 'underscore' load = (win) -> React = win.React R = React.DOM ExpandingTextArea = React.createFactory React.createClass displayName: 'ExpandingTextArea' mixins: [React.addons.PureRenderMixin] propTypes: { value: React.PropTypes.string.isRequired height: React.PropTypes.number placeholder: React.PropTypes.string disabled: React.PropTypes.bool className: React.PropTypes.string onChange: React.PropTypes.func.isRequired onFocus: React.PropTypes.func onClick: React.PropTypes.func } getInitialState: -> { loadedOnce: false } render: -> return R.div({ref: 'outer'}, R.textarea({ className: "expandingTextAreaComponent form-control #{@props.className}" ref: 'textarea' placeholder: @props.placeholder onFocus: @_onFocus #todo: onblur? onClick: @props.onClick onChange: @_onChange value: @props.value disabled: @props.disabled style: overflow: 'hidden' # Prevents scrollbar from flashing upon resize }) ) componentDidMount: -> win.addEventListener 'resize', @_resize @_initialSize() componentDidUpdate: -> # fixes bug on plan tab where text area sizes are 0 since the tab is hidden by default return if @state.loadedOnce @_initialSize() @setState { loadedOnce: true } componentWillUnmount: -> win.removeEventListener 'resize', @_resize _initialSize: -> textareaDom = @refs.textarea outerDom = @refs.outer return unless textareaDom? and outerDom? # Hold outer div to current height # This presents the scroll position from being lost when the textarea is set to zero outerDom.style.height = outerDom.clientHeight + 'px' # Reset height to 0 textareaDom.style.height = '0px' # Calculate new height if (win.document.activeElement == textareaDom) or (textareaDom.value == '') minimumHeight = @props.height or 54 # pixels else minimumHeight = 27 scrollableAreaHeight = textareaDom.scrollHeight scrollableAreaHeight += 2 # to prevent scrollbar newHeight = Math.max minimumHeight, scrollableAreaHeight textareaDom.style.height = newHeight + 'px' # Allow outer div to resize to new height outerDom.style.height = 'auto' _resize: _.throttle(-> textareaDom = @refs.textarea outerDom = @refs.outer return unless textareaDom? and outerDom? # Hold outer div to current height # This presents the scroll position from being lost when the textarea is set to zero outerDom.style.height = outerDom.clientHeight + 'px' # Reset height to 0 textareaDom.style.height = '0px' # Calculate new height minimumHeight = @props.height or 54 # pixels scrollableAreaHeight = textareaDom.scrollHeight scrollableAreaHeight += 2 # to prevent scrollbar newHeight = Math.max minimumHeight, scrollableAreaHeight textareaDom.style.height = newHeight + 'px' # Allow outer div to resize to new height outerDom.style.height = 'auto' , 100) _onChange: (event) -> @props.onChange event @_resize() _onFocus: (event) -> if @props.onFocus @props.onFocus event @_resize() focus: -> @refs.textarea.focus() return ExpandingTextArea module.exports = {load}
121465
# 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 # A <textarea> whose height is determined by the height of its content. # Note: users can add line breaks inside textareas, which may need special # handling when being displayed. _ = require 'underscore' load = (win) -> React = win.React R = React.DOM ExpandingTextArea = React.createFactory React.createClass displayName: 'ExpandingTextArea' mixins: [React.addons.PureRenderMixin] propTypes: { value: React.PropTypes.string.isRequired height: React.PropTypes.number placeholder: React.PropTypes.string disabled: React.PropTypes.bool className: React.PropTypes.string onChange: React.PropTypes.func.isRequired onFocus: React.PropTypes.func onClick: React.PropTypes.func } getInitialState: -> { loadedOnce: false } render: -> return R.div({ref: 'outer'}, R.textarea({ className: "expandingTextAreaComponent form-control #{@props.className}" ref: 'textarea' placeholder: @props.placeholder onFocus: @_onFocus #todo: onblur? onClick: @props.onClick onChange: @_onChange value: @props.value disabled: @props.disabled style: overflow: 'hidden' # Prevents scrollbar from flashing upon resize }) ) componentDidMount: -> win.addEventListener 'resize', @_resize @_initialSize() componentDidUpdate: -> # fixes bug on plan tab where text area sizes are 0 since the tab is hidden by default return if @state.loadedOnce @_initialSize() @setState { loadedOnce: true } componentWillUnmount: -> win.removeEventListener 'resize', @_resize _initialSize: -> textareaDom = @refs.textarea outerDom = @refs.outer return unless textareaDom? and outerDom? # Hold outer div to current height # This presents the scroll position from being lost when the textarea is set to zero outerDom.style.height = outerDom.clientHeight + 'px' # Reset height to 0 textareaDom.style.height = '0px' # Calculate new height if (win.document.activeElement == textareaDom) or (textareaDom.value == '') minimumHeight = @props.height or 54 # pixels else minimumHeight = 27 scrollableAreaHeight = textareaDom.scrollHeight scrollableAreaHeight += 2 # to prevent scrollbar newHeight = Math.max minimumHeight, scrollableAreaHeight textareaDom.style.height = newHeight + 'px' # Allow outer div to resize to new height outerDom.style.height = 'auto' _resize: _.throttle(-> textareaDom = @refs.textarea outerDom = @refs.outer return unless textareaDom? and outerDom? # Hold outer div to current height # This presents the scroll position from being lost when the textarea is set to zero outerDom.style.height = outerDom.clientHeight + 'px' # Reset height to 0 textareaDom.style.height = '0px' # Calculate new height minimumHeight = @props.height or 54 # pixels scrollableAreaHeight = textareaDom.scrollHeight scrollableAreaHeight += 2 # to prevent scrollbar newHeight = Math.max minimumHeight, scrollableAreaHeight textareaDom.style.height = newHeight + 'px' # Allow outer div to resize to new height outerDom.style.height = 'auto' , 100) _onChange: (event) -> @props.onChange event @_resize() _onFocus: (event) -> if @props.onFocus @props.onFocus event @_resize() focus: -> @refs.textarea.focus() return ExpandingTextArea module.exports = {load}
true
# Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # A <textarea> whose height is determined by the height of its content. # Note: users can add line breaks inside textareas, which may need special # handling when being displayed. _ = require 'underscore' load = (win) -> React = win.React R = React.DOM ExpandingTextArea = React.createFactory React.createClass displayName: 'ExpandingTextArea' mixins: [React.addons.PureRenderMixin] propTypes: { value: React.PropTypes.string.isRequired height: React.PropTypes.number placeholder: React.PropTypes.string disabled: React.PropTypes.bool className: React.PropTypes.string onChange: React.PropTypes.func.isRequired onFocus: React.PropTypes.func onClick: React.PropTypes.func } getInitialState: -> { loadedOnce: false } render: -> return R.div({ref: 'outer'}, R.textarea({ className: "expandingTextAreaComponent form-control #{@props.className}" ref: 'textarea' placeholder: @props.placeholder onFocus: @_onFocus #todo: onblur? onClick: @props.onClick onChange: @_onChange value: @props.value disabled: @props.disabled style: overflow: 'hidden' # Prevents scrollbar from flashing upon resize }) ) componentDidMount: -> win.addEventListener 'resize', @_resize @_initialSize() componentDidUpdate: -> # fixes bug on plan tab where text area sizes are 0 since the tab is hidden by default return if @state.loadedOnce @_initialSize() @setState { loadedOnce: true } componentWillUnmount: -> win.removeEventListener 'resize', @_resize _initialSize: -> textareaDom = @refs.textarea outerDom = @refs.outer return unless textareaDom? and outerDom? # Hold outer div to current height # This presents the scroll position from being lost when the textarea is set to zero outerDom.style.height = outerDom.clientHeight + 'px' # Reset height to 0 textareaDom.style.height = '0px' # Calculate new height if (win.document.activeElement == textareaDom) or (textareaDom.value == '') minimumHeight = @props.height or 54 # pixels else minimumHeight = 27 scrollableAreaHeight = textareaDom.scrollHeight scrollableAreaHeight += 2 # to prevent scrollbar newHeight = Math.max minimumHeight, scrollableAreaHeight textareaDom.style.height = newHeight + 'px' # Allow outer div to resize to new height outerDom.style.height = 'auto' _resize: _.throttle(-> textareaDom = @refs.textarea outerDom = @refs.outer return unless textareaDom? and outerDom? # Hold outer div to current height # This presents the scroll position from being lost when the textarea is set to zero outerDom.style.height = outerDom.clientHeight + 'px' # Reset height to 0 textareaDom.style.height = '0px' # Calculate new height minimumHeight = @props.height or 54 # pixels scrollableAreaHeight = textareaDom.scrollHeight scrollableAreaHeight += 2 # to prevent scrollbar newHeight = Math.max minimumHeight, scrollableAreaHeight textareaDom.style.height = newHeight + 'px' # Allow outer div to resize to new height outerDom.style.height = 'auto' , 100) _onChange: (event) -> @props.onChange event @_resize() _onFocus: (event) -> if @props.onFocus @props.onFocus event @_resize() focus: -> @refs.textarea.focus() return ExpandingTextArea module.exports = {load}
[ { "context": ")()\n app.use require('cookie-session')\n key: 'codecombat.sess'\n secret: config.cookie_secret\n\nsetupCountryTa", "end": 4255, "score": 0.9992061853408813, "start": 4240, "tag": "KEY", "value": "codecombat.sess" }, { "context": " isOldBrowser = (req) ->\n # https://github.com/biggora/express-useragent/blob/master/lib/express-userage", "end": 5600, "score": 0.9996488690376282, "start": 5593, "tag": "USERNAME", "value": "biggora" } ]
server_setup.coffee
Awesome-Coder1/codecombat
1
express = require 'express' path = require 'path' useragent = require 'express-useragent' fs = require 'graceful-fs' log = require 'winston' compressible = require 'compressible' compression = require 'compression' geoip = require '@basicer/geoip-lite' crypto = require 'crypto' config = require './server_config' global.tv4 = require 'tv4' # required for TreemaUtils to work global.jsondiffpatch = require('jsondiffpatch') global.stripe = require('stripe')(config.stripe.secretKey) request = require 'request' Promise = require 'bluebird' Promise.promisifyAll(request, {multiArgs: true}) Promise.promisifyAll(fs) wrap = require 'co-express' morgan = require 'morgan' timeout = require('connect-timeout') {countries} = require './app/core/utils' productionLogging = (tokens, req, res) -> status = res.statusCode color = 32 if status >= 500 then color = 31 else if status >= 400 then color = 33 else if status >= 300 then color = 36 elapsed = (new Date()) - req._startTime elapsedColor = if elapsed < 500 then 90 else 31 return null if status is 404 and /\/feedback/.test req.originalUrl # We know that these usually 404 by design (bad design?) if (status isnt 200 and status isnt 201 and status isnt 204 and status isnt 304 and status isnt 302) or elapsed > 500 return "[#{config.clusterID}] \x1b[90m#{req.method} #{req.originalUrl} \x1b[#{color}m#{res.statusCode} \x1b[#{elapsedColor}m#{elapsed}ms\x1b[0m" null developmentLogging = (tokens, req, res) -> status = res.statusCode color = 32 if status >= 500 then color = 31 else if status >= 400 then color = 33 else if status >= 300 then color = 36 elapsed = (new Date()) - req._startTime elapsedColor = if elapsed < 500 then 90 else 31 s = "\x1b[90m#{req.method} #{req.originalUrl} \x1b[#{color}m#{res.statusCode} \x1b[#{elapsedColor}m#{elapsed}ms\x1b[0m" s += ' (proxied)' if req.proxied return s setupExpressMiddleware = (app) -> if config.isProduction morgan.format('prod', productionLogging) app.use(morgan('prod')) app.use compression filter: (req, res) -> return false if req.headers.host is 'codecombat.com' # CloudFlare will gzip it for us on codecombat.com compressible res.getHeader('Content-Type') else if not global.testing or config.TRACE_ROUTES morgan.format('dev', developmentLogging) app.use(morgan('dev')) app.use (req, res, next) -> res.header 'X-Cluster-ID', config.clusterID next() public_path = path.join(__dirname, 'public') app.use('/', express.static(path.join(public_path, 'templates', 'static'))) if config.buildInfo.sha isnt 'dev' and config.isProduction app.use("/#{config.buildInfo.sha}", express.static(public_path, maxAge: '1y')) else app.use('/dev', express.static(public_path, maxAge: 0)) # CloudFlare overrides maxAge, and we don't want local development caching. app.use(express.static(public_path, maxAge: 0)) if config.proxy # Don't proxy static files with sha prefixes, redirect them regex = /\/[0-9a-f]{40}\/.*/ regex2 = /\/[0-9a-f]{40}-[0-9a-f]{40}\/.*/ app.use (req, res, next) -> if regex.test(req.path) newPath = req.path.slice(41) return res.redirect(newPath) if regex2.test(req.path) newPath = req.path.slice(82) return res.redirect(newPath) next() setupProxyMiddleware app # TODO: Flatten setup into one function. This doesn't fit its function name. app.use require('serve-favicon') path.join(__dirname, 'public', 'images', 'favicon.ico') app.use require('cookie-parser')() app.use require('body-parser').json({limit: '25mb', strict: false, verify: (req, res, buf, encoding) -> if req.headers['x-hub-signature'] # this is an intercom webhook request, with signature that needs checking try digest = crypto.createHmac('sha1', config.intercom.webhookHubSecret).update(buf).digest('hex') req.signatureMatches = req.headers['x-hub-signature'] is "sha1=#{digest}" catch e log.info 'Error checking hub signature on Intercom webhook: ' + e }) app.use require('body-parser').urlencoded extended: true, limit: '25mb' app.use require('method-override')() app.use require('cookie-session') key: 'codecombat.sess' secret: config.cookie_secret setupCountryTaggingMiddleware = (app) -> app.use (req, res, next) -> return next() if req.country or req.user?.get('country') return next() unless ip = req.headers['x-forwarded-for'] or req.ip or req.connection.remoteAddress ip = ip.split(/,? /)[0] # If there are two IP addresses, say because of CloudFlare, we just take the first. geo = geoip.lookup(ip) if countryInfo = _.find(countries, countryCode: geo?.country) req.country = countryInfo.country next() setupCountryRedirectMiddleware = (app, country='china', host='cn.codecombat.com') -> hosts = host.split /;/g shouldRedirectToCountryServer = (req) -> reqHost = (req.hostname ? req.host ? '').toLowerCase() # Work around express 3.0 return req.country is country and reqHost not in hosts and reqHost.indexOf(config.unsafeContentHostname) is -1 app.use (req, res, next) -> if shouldRedirectToCountryServer(req) and hosts.length res.writeHead 302, "Location": 'http://' + hosts[0] + req.url res.end() else next() setupOneSecondDelayMiddleware = (app) -> if(config.slow_down) app.use((req, res, next) -> setTimeout((-> next()), 1000)) setupMiddlewareToSendOldBrowserWarningWhenPlayersViewLevelDirectly = (app) -> isOldBrowser = (req) -> # https://github.com/biggora/express-useragent/blob/master/lib/express-useragent.js return false unless ua = req.useragent return true if ua.isiPad or ua.isiPod or ua.isiPhone or ua.isOpera return false unless ua and ua.Browser in ['Chrome', 'Safari', 'Firefox', 'IE'] and ua.Version b = ua.Browser try v = parseInt ua.Version.split('.')[0], 10 catch TypeError log.error('ua.Version does not have a split function.', JSON.stringify(ua, null, ' ')) return false return true if b is 'Chrome' and v < 17 return true if b is 'Safari' and v < 6 return true if b is 'Firefox' and v < 21 return true if b is 'IE' and v < 11 false app.use '/play/', useragent.express() app.use '/play/', (req, res, next) -> return next() if req.path?.indexOf('web-dev-level') >= 0 return next() if req.query['try-old-browser-anyway'] or not isOldBrowser req res.sendfile(path.join(__dirname, 'public', 'index_old_browser.html')) setupRedirectMiddleware = (app) -> app.all '/account/profile/*', (req, res, next) -> nameOrID = req.path.split('/')[3] res.redirect 301, "/user/#{nameOrID}/profile" setupFeaturesMiddleware = (app) -> app.use (req, res, next) -> # TODO: Share these defaults with run-tests.js req.features = features = { freeOnly: false } if req.headers.host is 'brainpop.codecombat.com' or req.session.featureMode is 'brain-pop' features.freeOnly = true features.campaignSlugs = ['dungeon'] features.playViewsOnly = true features.noAuth = true features.brainPop = true features.noAds = true if /cn\.codecombat\.com/.test(req.get('host')) or /koudashijie/.test(req.get('host')) or req.session.featureMode is 'china' features.china = true features.freeOnly = true features.noAds = true if config.picoCTF or req.session.featureMode is 'pico-ctf' features.playOnly = true features.noAds = true features.picoCtf = true if config.chinaInfra features.chinaInfra = true next() # When config.TRACE_ROUTES is set, this logs a stack trace every time an endpoint sends a response. # It's great for finding where a mystery endpoint is! # The same is done for errors in the error-handling middleware. setupHandlerTraceMiddleware = (app) -> app.use (req, res, next) -> oldSend = res.send res.send = -> result = oldSend.apply(@, arguments) console.trace() return result next() setupSecureMiddleware = (app) -> # Cannot use express request `secure` property in production, due to # cluster setup. isSecure = -> return @secure or @headers['x-forwarded-proto'] is 'https' app.use (req, res, next) -> req.isSecure = isSecure next() exports.setupMiddleware = (app) -> app.use(timeout(config.timeout)) setupHandlerTraceMiddleware app if config.TRACE_ROUTES setupSecureMiddleware app setupQuickBailToMainHTML app setupCountryTaggingMiddleware app setupMiddlewareToSendOldBrowserWarningWhenPlayersViewLevelDirectly app setupExpressMiddleware app setupFeaturesMiddleware app setupCountryRedirectMiddleware app, 'china', config.chinaDomain setupCountryRedirectMiddleware app, 'brazil', config.brazilDomain setupOneSecondDelayMiddleware app setupRedirectMiddleware app setupAjaxCaching app setupJavascript404s app ###Routing function implementations### setupAjaxCaching = (app) -> # IE/Edge are more aggressive about caching than other browsers, so we'll override their caching here. # Assumes our CDN will override these with its own caching rules. app.get '/db/*', (req, res, next) -> return next() unless req.xhr # http://stackoverflow.com/questions/19999388/check-if-user-is-using-ie-with-jquery userAgent = req.header('User-Agent') or "" if userAgent.indexOf('MSIE ') > 0 or !!userAgent.match(/Trident.*rv\:11\.|Edge\/\d+/) res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 next() setupJavascript404s = (app) -> app.get '/javascripts/*', (req, res) -> res.status(404).send('Not found') app.get(/^\/?[a-f0-9]{40}/, (req, res) -> res.status(404).send('Wrong hash') ) templates = {} getStaticTemplate = (file) -> # Don't cache templates in devlopment so you can just edit then. return templates[file] if templates[file] and config.isProduction templates[file] = fs.readFileAsync(path.join(__dirname, 'public', 'templates', 'static', file), 'utf8') renderMain = wrap (template, req, res) -> template = yield getStaticTemplate(template) res.status(200).send template setupQuickBailToMainHTML = (app) -> fast = (template) -> (req, res, next) -> req.features = features = {} if config.isProduction or true res.header 'Cache-Control', 'public, max-age=60' res.header 'Expires', 60 else res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 if /cn\.codecombat\.com/.test(req.get('host')) or /koudashijie\.com/.test(req.get('host')) features.china = true if template is 'home.html' template = 'home-cn.html' if config.chinaInfra features.chinaInfra = true renderMain(template, req, res) app.get '/', fast('home.html') app.get '/home', fast('home.html') app.get '/about', fast('about.html') app.get '/features', fast('premium-features.html') app.get '/privacy', fast('privacy.html') app.get '/legal', fast('legal.html') app.get '/play', fast('overworld.html') app.get '/play/level/:slug', fast('main.html') app.get '/play/:slug', fast('main.html') # Mongo-cache doesnt support the .exec() promise, so we manually wrap it. # getMandate = (app) -> # return new Promise (res, rej) -> # Mandate.findOne({}).cache(5 * 60 * 1000).exec (err, data) -> # return rej(err) if err # res(data) ###Miscellaneous configuration functions### exports.setExpressConfigurationOptions = (app) -> app.set('port', config.port) app.set('views', __dirname + '/app/views') app.set('view engine', 'jade') app.set('view options', { layout: false }) app.set('env', if config.isProduction then 'production' else 'development') app.set('json spaces', 0) if config.isProduction setupProxyMiddleware = (app) -> return if config.isProduction return unless config.proxy httpProxy = require 'http-proxy' target = 'https://very.direct.codecombat.com' headers = {} if (process.env.COCO_PROXY_NEXT) target = 'https://next.codecombat.com' headers['Host'] = 'next.codecombat.com' proxy = httpProxy.createProxyServer({ target: target secure: false, headers: headers }) log.info 'Using dev proxy server' app.use (req, res, next) -> req.proxied = true proxy.web req, res, (e) -> console.warn("Failed to proxy: ", e) res.status(502).send({message: 'Proxy failed'})
100459
express = require 'express' path = require 'path' useragent = require 'express-useragent' fs = require 'graceful-fs' log = require 'winston' compressible = require 'compressible' compression = require 'compression' geoip = require '@basicer/geoip-lite' crypto = require 'crypto' config = require './server_config' global.tv4 = require 'tv4' # required for TreemaUtils to work global.jsondiffpatch = require('jsondiffpatch') global.stripe = require('stripe')(config.stripe.secretKey) request = require 'request' Promise = require 'bluebird' Promise.promisifyAll(request, {multiArgs: true}) Promise.promisifyAll(fs) wrap = require 'co-express' morgan = require 'morgan' timeout = require('connect-timeout') {countries} = require './app/core/utils' productionLogging = (tokens, req, res) -> status = res.statusCode color = 32 if status >= 500 then color = 31 else if status >= 400 then color = 33 else if status >= 300 then color = 36 elapsed = (new Date()) - req._startTime elapsedColor = if elapsed < 500 then 90 else 31 return null if status is 404 and /\/feedback/.test req.originalUrl # We know that these usually 404 by design (bad design?) if (status isnt 200 and status isnt 201 and status isnt 204 and status isnt 304 and status isnt 302) or elapsed > 500 return "[#{config.clusterID}] \x1b[90m#{req.method} #{req.originalUrl} \x1b[#{color}m#{res.statusCode} \x1b[#{elapsedColor}m#{elapsed}ms\x1b[0m" null developmentLogging = (tokens, req, res) -> status = res.statusCode color = 32 if status >= 500 then color = 31 else if status >= 400 then color = 33 else if status >= 300 then color = 36 elapsed = (new Date()) - req._startTime elapsedColor = if elapsed < 500 then 90 else 31 s = "\x1b[90m#{req.method} #{req.originalUrl} \x1b[#{color}m#{res.statusCode} \x1b[#{elapsedColor}m#{elapsed}ms\x1b[0m" s += ' (proxied)' if req.proxied return s setupExpressMiddleware = (app) -> if config.isProduction morgan.format('prod', productionLogging) app.use(morgan('prod')) app.use compression filter: (req, res) -> return false if req.headers.host is 'codecombat.com' # CloudFlare will gzip it for us on codecombat.com compressible res.getHeader('Content-Type') else if not global.testing or config.TRACE_ROUTES morgan.format('dev', developmentLogging) app.use(morgan('dev')) app.use (req, res, next) -> res.header 'X-Cluster-ID', config.clusterID next() public_path = path.join(__dirname, 'public') app.use('/', express.static(path.join(public_path, 'templates', 'static'))) if config.buildInfo.sha isnt 'dev' and config.isProduction app.use("/#{config.buildInfo.sha}", express.static(public_path, maxAge: '1y')) else app.use('/dev', express.static(public_path, maxAge: 0)) # CloudFlare overrides maxAge, and we don't want local development caching. app.use(express.static(public_path, maxAge: 0)) if config.proxy # Don't proxy static files with sha prefixes, redirect them regex = /\/[0-9a-f]{40}\/.*/ regex2 = /\/[0-9a-f]{40}-[0-9a-f]{40}\/.*/ app.use (req, res, next) -> if regex.test(req.path) newPath = req.path.slice(41) return res.redirect(newPath) if regex2.test(req.path) newPath = req.path.slice(82) return res.redirect(newPath) next() setupProxyMiddleware app # TODO: Flatten setup into one function. This doesn't fit its function name. app.use require('serve-favicon') path.join(__dirname, 'public', 'images', 'favicon.ico') app.use require('cookie-parser')() app.use require('body-parser').json({limit: '25mb', strict: false, verify: (req, res, buf, encoding) -> if req.headers['x-hub-signature'] # this is an intercom webhook request, with signature that needs checking try digest = crypto.createHmac('sha1', config.intercom.webhookHubSecret).update(buf).digest('hex') req.signatureMatches = req.headers['x-hub-signature'] is "sha1=#{digest}" catch e log.info 'Error checking hub signature on Intercom webhook: ' + e }) app.use require('body-parser').urlencoded extended: true, limit: '25mb' app.use require('method-override')() app.use require('cookie-session') key: '<KEY>' secret: config.cookie_secret setupCountryTaggingMiddleware = (app) -> app.use (req, res, next) -> return next() if req.country or req.user?.get('country') return next() unless ip = req.headers['x-forwarded-for'] or req.ip or req.connection.remoteAddress ip = ip.split(/,? /)[0] # If there are two IP addresses, say because of CloudFlare, we just take the first. geo = geoip.lookup(ip) if countryInfo = _.find(countries, countryCode: geo?.country) req.country = countryInfo.country next() setupCountryRedirectMiddleware = (app, country='china', host='cn.codecombat.com') -> hosts = host.split /;/g shouldRedirectToCountryServer = (req) -> reqHost = (req.hostname ? req.host ? '').toLowerCase() # Work around express 3.0 return req.country is country and reqHost not in hosts and reqHost.indexOf(config.unsafeContentHostname) is -1 app.use (req, res, next) -> if shouldRedirectToCountryServer(req) and hosts.length res.writeHead 302, "Location": 'http://' + hosts[0] + req.url res.end() else next() setupOneSecondDelayMiddleware = (app) -> if(config.slow_down) app.use((req, res, next) -> setTimeout((-> next()), 1000)) setupMiddlewareToSendOldBrowserWarningWhenPlayersViewLevelDirectly = (app) -> isOldBrowser = (req) -> # https://github.com/biggora/express-useragent/blob/master/lib/express-useragent.js return false unless ua = req.useragent return true if ua.isiPad or ua.isiPod or ua.isiPhone or ua.isOpera return false unless ua and ua.Browser in ['Chrome', 'Safari', 'Firefox', 'IE'] and ua.Version b = ua.Browser try v = parseInt ua.Version.split('.')[0], 10 catch TypeError log.error('ua.Version does not have a split function.', JSON.stringify(ua, null, ' ')) return false return true if b is 'Chrome' and v < 17 return true if b is 'Safari' and v < 6 return true if b is 'Firefox' and v < 21 return true if b is 'IE' and v < 11 false app.use '/play/', useragent.express() app.use '/play/', (req, res, next) -> return next() if req.path?.indexOf('web-dev-level') >= 0 return next() if req.query['try-old-browser-anyway'] or not isOldBrowser req res.sendfile(path.join(__dirname, 'public', 'index_old_browser.html')) setupRedirectMiddleware = (app) -> app.all '/account/profile/*', (req, res, next) -> nameOrID = req.path.split('/')[3] res.redirect 301, "/user/#{nameOrID}/profile" setupFeaturesMiddleware = (app) -> app.use (req, res, next) -> # TODO: Share these defaults with run-tests.js req.features = features = { freeOnly: false } if req.headers.host is 'brainpop.codecombat.com' or req.session.featureMode is 'brain-pop' features.freeOnly = true features.campaignSlugs = ['dungeon'] features.playViewsOnly = true features.noAuth = true features.brainPop = true features.noAds = true if /cn\.codecombat\.com/.test(req.get('host')) or /koudashijie/.test(req.get('host')) or req.session.featureMode is 'china' features.china = true features.freeOnly = true features.noAds = true if config.picoCTF or req.session.featureMode is 'pico-ctf' features.playOnly = true features.noAds = true features.picoCtf = true if config.chinaInfra features.chinaInfra = true next() # When config.TRACE_ROUTES is set, this logs a stack trace every time an endpoint sends a response. # It's great for finding where a mystery endpoint is! # The same is done for errors in the error-handling middleware. setupHandlerTraceMiddleware = (app) -> app.use (req, res, next) -> oldSend = res.send res.send = -> result = oldSend.apply(@, arguments) console.trace() return result next() setupSecureMiddleware = (app) -> # Cannot use express request `secure` property in production, due to # cluster setup. isSecure = -> return @secure or @headers['x-forwarded-proto'] is 'https' app.use (req, res, next) -> req.isSecure = isSecure next() exports.setupMiddleware = (app) -> app.use(timeout(config.timeout)) setupHandlerTraceMiddleware app if config.TRACE_ROUTES setupSecureMiddleware app setupQuickBailToMainHTML app setupCountryTaggingMiddleware app setupMiddlewareToSendOldBrowserWarningWhenPlayersViewLevelDirectly app setupExpressMiddleware app setupFeaturesMiddleware app setupCountryRedirectMiddleware app, 'china', config.chinaDomain setupCountryRedirectMiddleware app, 'brazil', config.brazilDomain setupOneSecondDelayMiddleware app setupRedirectMiddleware app setupAjaxCaching app setupJavascript404s app ###Routing function implementations### setupAjaxCaching = (app) -> # IE/Edge are more aggressive about caching than other browsers, so we'll override their caching here. # Assumes our CDN will override these with its own caching rules. app.get '/db/*', (req, res, next) -> return next() unless req.xhr # http://stackoverflow.com/questions/19999388/check-if-user-is-using-ie-with-jquery userAgent = req.header('User-Agent') or "" if userAgent.indexOf('MSIE ') > 0 or !!userAgent.match(/Trident.*rv\:11\.|Edge\/\d+/) res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 next() setupJavascript404s = (app) -> app.get '/javascripts/*', (req, res) -> res.status(404).send('Not found') app.get(/^\/?[a-f0-9]{40}/, (req, res) -> res.status(404).send('Wrong hash') ) templates = {} getStaticTemplate = (file) -> # Don't cache templates in devlopment so you can just edit then. return templates[file] if templates[file] and config.isProduction templates[file] = fs.readFileAsync(path.join(__dirname, 'public', 'templates', 'static', file), 'utf8') renderMain = wrap (template, req, res) -> template = yield getStaticTemplate(template) res.status(200).send template setupQuickBailToMainHTML = (app) -> fast = (template) -> (req, res, next) -> req.features = features = {} if config.isProduction or true res.header 'Cache-Control', 'public, max-age=60' res.header 'Expires', 60 else res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 if /cn\.codecombat\.com/.test(req.get('host')) or /koudashijie\.com/.test(req.get('host')) features.china = true if template is 'home.html' template = 'home-cn.html' if config.chinaInfra features.chinaInfra = true renderMain(template, req, res) app.get '/', fast('home.html') app.get '/home', fast('home.html') app.get '/about', fast('about.html') app.get '/features', fast('premium-features.html') app.get '/privacy', fast('privacy.html') app.get '/legal', fast('legal.html') app.get '/play', fast('overworld.html') app.get '/play/level/:slug', fast('main.html') app.get '/play/:slug', fast('main.html') # Mongo-cache doesnt support the .exec() promise, so we manually wrap it. # getMandate = (app) -> # return new Promise (res, rej) -> # Mandate.findOne({}).cache(5 * 60 * 1000).exec (err, data) -> # return rej(err) if err # res(data) ###Miscellaneous configuration functions### exports.setExpressConfigurationOptions = (app) -> app.set('port', config.port) app.set('views', __dirname + '/app/views') app.set('view engine', 'jade') app.set('view options', { layout: false }) app.set('env', if config.isProduction then 'production' else 'development') app.set('json spaces', 0) if config.isProduction setupProxyMiddleware = (app) -> return if config.isProduction return unless config.proxy httpProxy = require 'http-proxy' target = 'https://very.direct.codecombat.com' headers = {} if (process.env.COCO_PROXY_NEXT) target = 'https://next.codecombat.com' headers['Host'] = 'next.codecombat.com' proxy = httpProxy.createProxyServer({ target: target secure: false, headers: headers }) log.info 'Using dev proxy server' app.use (req, res, next) -> req.proxied = true proxy.web req, res, (e) -> console.warn("Failed to proxy: ", e) res.status(502).send({message: 'Proxy failed'})
true
express = require 'express' path = require 'path' useragent = require 'express-useragent' fs = require 'graceful-fs' log = require 'winston' compressible = require 'compressible' compression = require 'compression' geoip = require '@basicer/geoip-lite' crypto = require 'crypto' config = require './server_config' global.tv4 = require 'tv4' # required for TreemaUtils to work global.jsondiffpatch = require('jsondiffpatch') global.stripe = require('stripe')(config.stripe.secretKey) request = require 'request' Promise = require 'bluebird' Promise.promisifyAll(request, {multiArgs: true}) Promise.promisifyAll(fs) wrap = require 'co-express' morgan = require 'morgan' timeout = require('connect-timeout') {countries} = require './app/core/utils' productionLogging = (tokens, req, res) -> status = res.statusCode color = 32 if status >= 500 then color = 31 else if status >= 400 then color = 33 else if status >= 300 then color = 36 elapsed = (new Date()) - req._startTime elapsedColor = if elapsed < 500 then 90 else 31 return null if status is 404 and /\/feedback/.test req.originalUrl # We know that these usually 404 by design (bad design?) if (status isnt 200 and status isnt 201 and status isnt 204 and status isnt 304 and status isnt 302) or elapsed > 500 return "[#{config.clusterID}] \x1b[90m#{req.method} #{req.originalUrl} \x1b[#{color}m#{res.statusCode} \x1b[#{elapsedColor}m#{elapsed}ms\x1b[0m" null developmentLogging = (tokens, req, res) -> status = res.statusCode color = 32 if status >= 500 then color = 31 else if status >= 400 then color = 33 else if status >= 300 then color = 36 elapsed = (new Date()) - req._startTime elapsedColor = if elapsed < 500 then 90 else 31 s = "\x1b[90m#{req.method} #{req.originalUrl} \x1b[#{color}m#{res.statusCode} \x1b[#{elapsedColor}m#{elapsed}ms\x1b[0m" s += ' (proxied)' if req.proxied return s setupExpressMiddleware = (app) -> if config.isProduction morgan.format('prod', productionLogging) app.use(morgan('prod')) app.use compression filter: (req, res) -> return false if req.headers.host is 'codecombat.com' # CloudFlare will gzip it for us on codecombat.com compressible res.getHeader('Content-Type') else if not global.testing or config.TRACE_ROUTES morgan.format('dev', developmentLogging) app.use(morgan('dev')) app.use (req, res, next) -> res.header 'X-Cluster-ID', config.clusterID next() public_path = path.join(__dirname, 'public') app.use('/', express.static(path.join(public_path, 'templates', 'static'))) if config.buildInfo.sha isnt 'dev' and config.isProduction app.use("/#{config.buildInfo.sha}", express.static(public_path, maxAge: '1y')) else app.use('/dev', express.static(public_path, maxAge: 0)) # CloudFlare overrides maxAge, and we don't want local development caching. app.use(express.static(public_path, maxAge: 0)) if config.proxy # Don't proxy static files with sha prefixes, redirect them regex = /\/[0-9a-f]{40}\/.*/ regex2 = /\/[0-9a-f]{40}-[0-9a-f]{40}\/.*/ app.use (req, res, next) -> if regex.test(req.path) newPath = req.path.slice(41) return res.redirect(newPath) if regex2.test(req.path) newPath = req.path.slice(82) return res.redirect(newPath) next() setupProxyMiddleware app # TODO: Flatten setup into one function. This doesn't fit its function name. app.use require('serve-favicon') path.join(__dirname, 'public', 'images', 'favicon.ico') app.use require('cookie-parser')() app.use require('body-parser').json({limit: '25mb', strict: false, verify: (req, res, buf, encoding) -> if req.headers['x-hub-signature'] # this is an intercom webhook request, with signature that needs checking try digest = crypto.createHmac('sha1', config.intercom.webhookHubSecret).update(buf).digest('hex') req.signatureMatches = req.headers['x-hub-signature'] is "sha1=#{digest}" catch e log.info 'Error checking hub signature on Intercom webhook: ' + e }) app.use require('body-parser').urlencoded extended: true, limit: '25mb' app.use require('method-override')() app.use require('cookie-session') key: 'PI:KEY:<KEY>END_PI' secret: config.cookie_secret setupCountryTaggingMiddleware = (app) -> app.use (req, res, next) -> return next() if req.country or req.user?.get('country') return next() unless ip = req.headers['x-forwarded-for'] or req.ip or req.connection.remoteAddress ip = ip.split(/,? /)[0] # If there are two IP addresses, say because of CloudFlare, we just take the first. geo = geoip.lookup(ip) if countryInfo = _.find(countries, countryCode: geo?.country) req.country = countryInfo.country next() setupCountryRedirectMiddleware = (app, country='china', host='cn.codecombat.com') -> hosts = host.split /;/g shouldRedirectToCountryServer = (req) -> reqHost = (req.hostname ? req.host ? '').toLowerCase() # Work around express 3.0 return req.country is country and reqHost not in hosts and reqHost.indexOf(config.unsafeContentHostname) is -1 app.use (req, res, next) -> if shouldRedirectToCountryServer(req) and hosts.length res.writeHead 302, "Location": 'http://' + hosts[0] + req.url res.end() else next() setupOneSecondDelayMiddleware = (app) -> if(config.slow_down) app.use((req, res, next) -> setTimeout((-> next()), 1000)) setupMiddlewareToSendOldBrowserWarningWhenPlayersViewLevelDirectly = (app) -> isOldBrowser = (req) -> # https://github.com/biggora/express-useragent/blob/master/lib/express-useragent.js return false unless ua = req.useragent return true if ua.isiPad or ua.isiPod or ua.isiPhone or ua.isOpera return false unless ua and ua.Browser in ['Chrome', 'Safari', 'Firefox', 'IE'] and ua.Version b = ua.Browser try v = parseInt ua.Version.split('.')[0], 10 catch TypeError log.error('ua.Version does not have a split function.', JSON.stringify(ua, null, ' ')) return false return true if b is 'Chrome' and v < 17 return true if b is 'Safari' and v < 6 return true if b is 'Firefox' and v < 21 return true if b is 'IE' and v < 11 false app.use '/play/', useragent.express() app.use '/play/', (req, res, next) -> return next() if req.path?.indexOf('web-dev-level') >= 0 return next() if req.query['try-old-browser-anyway'] or not isOldBrowser req res.sendfile(path.join(__dirname, 'public', 'index_old_browser.html')) setupRedirectMiddleware = (app) -> app.all '/account/profile/*', (req, res, next) -> nameOrID = req.path.split('/')[3] res.redirect 301, "/user/#{nameOrID}/profile" setupFeaturesMiddleware = (app) -> app.use (req, res, next) -> # TODO: Share these defaults with run-tests.js req.features = features = { freeOnly: false } if req.headers.host is 'brainpop.codecombat.com' or req.session.featureMode is 'brain-pop' features.freeOnly = true features.campaignSlugs = ['dungeon'] features.playViewsOnly = true features.noAuth = true features.brainPop = true features.noAds = true if /cn\.codecombat\.com/.test(req.get('host')) or /koudashijie/.test(req.get('host')) or req.session.featureMode is 'china' features.china = true features.freeOnly = true features.noAds = true if config.picoCTF or req.session.featureMode is 'pico-ctf' features.playOnly = true features.noAds = true features.picoCtf = true if config.chinaInfra features.chinaInfra = true next() # When config.TRACE_ROUTES is set, this logs a stack trace every time an endpoint sends a response. # It's great for finding where a mystery endpoint is! # The same is done for errors in the error-handling middleware. setupHandlerTraceMiddleware = (app) -> app.use (req, res, next) -> oldSend = res.send res.send = -> result = oldSend.apply(@, arguments) console.trace() return result next() setupSecureMiddleware = (app) -> # Cannot use express request `secure` property in production, due to # cluster setup. isSecure = -> return @secure or @headers['x-forwarded-proto'] is 'https' app.use (req, res, next) -> req.isSecure = isSecure next() exports.setupMiddleware = (app) -> app.use(timeout(config.timeout)) setupHandlerTraceMiddleware app if config.TRACE_ROUTES setupSecureMiddleware app setupQuickBailToMainHTML app setupCountryTaggingMiddleware app setupMiddlewareToSendOldBrowserWarningWhenPlayersViewLevelDirectly app setupExpressMiddleware app setupFeaturesMiddleware app setupCountryRedirectMiddleware app, 'china', config.chinaDomain setupCountryRedirectMiddleware app, 'brazil', config.brazilDomain setupOneSecondDelayMiddleware app setupRedirectMiddleware app setupAjaxCaching app setupJavascript404s app ###Routing function implementations### setupAjaxCaching = (app) -> # IE/Edge are more aggressive about caching than other browsers, so we'll override their caching here. # Assumes our CDN will override these with its own caching rules. app.get '/db/*', (req, res, next) -> return next() unless req.xhr # http://stackoverflow.com/questions/19999388/check-if-user-is-using-ie-with-jquery userAgent = req.header('User-Agent') or "" if userAgent.indexOf('MSIE ') > 0 or !!userAgent.match(/Trident.*rv\:11\.|Edge\/\d+/) res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 next() setupJavascript404s = (app) -> app.get '/javascripts/*', (req, res) -> res.status(404).send('Not found') app.get(/^\/?[a-f0-9]{40}/, (req, res) -> res.status(404).send('Wrong hash') ) templates = {} getStaticTemplate = (file) -> # Don't cache templates in devlopment so you can just edit then. return templates[file] if templates[file] and config.isProduction templates[file] = fs.readFileAsync(path.join(__dirname, 'public', 'templates', 'static', file), 'utf8') renderMain = wrap (template, req, res) -> template = yield getStaticTemplate(template) res.status(200).send template setupQuickBailToMainHTML = (app) -> fast = (template) -> (req, res, next) -> req.features = features = {} if config.isProduction or true res.header 'Cache-Control', 'public, max-age=60' res.header 'Expires', 60 else res.header 'Cache-Control', 'no-cache, no-store, must-revalidate' res.header 'Pragma', 'no-cache' res.header 'Expires', 0 if /cn\.codecombat\.com/.test(req.get('host')) or /koudashijie\.com/.test(req.get('host')) features.china = true if template is 'home.html' template = 'home-cn.html' if config.chinaInfra features.chinaInfra = true renderMain(template, req, res) app.get '/', fast('home.html') app.get '/home', fast('home.html') app.get '/about', fast('about.html') app.get '/features', fast('premium-features.html') app.get '/privacy', fast('privacy.html') app.get '/legal', fast('legal.html') app.get '/play', fast('overworld.html') app.get '/play/level/:slug', fast('main.html') app.get '/play/:slug', fast('main.html') # Mongo-cache doesnt support the .exec() promise, so we manually wrap it. # getMandate = (app) -> # return new Promise (res, rej) -> # Mandate.findOne({}).cache(5 * 60 * 1000).exec (err, data) -> # return rej(err) if err # res(data) ###Miscellaneous configuration functions### exports.setExpressConfigurationOptions = (app) -> app.set('port', config.port) app.set('views', __dirname + '/app/views') app.set('view engine', 'jade') app.set('view options', { layout: false }) app.set('env', if config.isProduction then 'production' else 'development') app.set('json spaces', 0) if config.isProduction setupProxyMiddleware = (app) -> return if config.isProduction return unless config.proxy httpProxy = require 'http-proxy' target = 'https://very.direct.codecombat.com' headers = {} if (process.env.COCO_PROXY_NEXT) target = 'https://next.codecombat.com' headers['Host'] = 'next.codecombat.com' proxy = httpProxy.createProxyServer({ target: target secure: false, headers: headers }) log.info 'Using dev proxy server' app.use (req, res, next) -> req.proxied = true proxy.web req, res, (e) -> console.warn("Failed to proxy: ", e) res.status(502).send({message: 'Proxy failed'})
[ { "context": "cts'\n time_format_mode: 'decimal'\n user_names: 'Katie, Mike, Nick, Paul'\n project_names: 'Toggl Support, Integrations, Ф", "end": 296, "score": 0.9177176356315613, "start": 273, "tag": "NAME", "value": "Katie, Mike, Nick, Paul" }, { "context": "з, Ножтро аппэльлььантюр ыам ан'\n client_names: 'Toggl, Teamweek'\n\nreport = new DetailedReport(data)\nreport.output", "end": 431, "score": 0.9955008029937744, "start": 416, "tag": "NAME", "value": "Toggl, Teamweek" } ]
testdata/test_detailed.coffee
meeDamian/toggl-pdf
1
DetailedReport = require '../app/detailed_report' data = require './data/detailed.json' fs = require 'fs' data.params = user_count: 4 since: '2013-04-29' until: '2013-05-05' subgrouping: 'tasks' grouping: 'projects' time_format_mode: 'decimal' user_names: 'Katie, Mike, Nick, Paul' project_names: 'Toggl Support, Integrations, Факилиз вёвындо ад хёз, Ножтро аппэльлььантюр ыам ан' client_names: 'Toggl, Teamweek' report = new DetailedReport(data) report.output(fs.createWriteStream('detailed.pdf'))
194286
DetailedReport = require '../app/detailed_report' data = require './data/detailed.json' fs = require 'fs' data.params = user_count: 4 since: '2013-04-29' until: '2013-05-05' subgrouping: 'tasks' grouping: 'projects' time_format_mode: 'decimal' user_names: '<NAME>' project_names: 'Toggl Support, Integrations, Факилиз вёвындо ад хёз, Ножтро аппэльлььантюр ыам ан' client_names: '<NAME>' report = new DetailedReport(data) report.output(fs.createWriteStream('detailed.pdf'))
true
DetailedReport = require '../app/detailed_report' data = require './data/detailed.json' fs = require 'fs' data.params = user_count: 4 since: '2013-04-29' until: '2013-05-05' subgrouping: 'tasks' grouping: 'projects' time_format_mode: 'decimal' user_names: 'PI:NAME:<NAME>END_PI' project_names: 'Toggl Support, Integrations, Факилиз вёвындо ад хёз, Ножтро аппэльлььантюр ыам ан' client_names: 'PI:NAME:<NAME>END_PI' report = new DetailedReport(data) report.output(fs.createWriteStream('detailed.pdf'))
[ { "context": "#! Object properties\nkids =\n brother:\n name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: ", "end": 591, "score": 0.9998427629470825, "start": 588, "tag": "NAME", "value": "Max" }, { "context": " name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: 9\n\n#! Regexps\n/normal [r]egexp?/;\n/// ", "end": 630, "score": 0.9998457431793213, "start": 627, "tag": "NAME", "value": "Ida" }, { "context": "ert \"Galloping...\"\n super 45\n\nsam = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\n\nsam.move()", "end": 1045, "score": 0.9981831908226013, "start": 1029, "tag": "NAME", "value": "Sammy the Python" }, { "context": "m = new Snake \"Sammy the Python\"\ntom = new Horse \"Tommy the Palomino\"\n\nsam.move()\ntom.move()\n\n#! Inline JavaScript\n`al", "end": 1082, "score": 0.9986374974250793, "start": 1064, "tag": "NAME", "value": "Tommy the Palomino" } ]
coffeescript/example.coffee
zokugun/highlight-examples
0
#! Header comment ### # example.coffee # Version 1.0.0 # # Licensed under the MIT license. # http://www.opensource.org/licenses/mit-license.php ### #! Comments # This is a comment ### This is a multi-line comment### #! Strings 'foo \'bar\' baz' "foo \"bar\" baz" 'Multi-line strings are supported' "Multi-line strings are supported" ''' 'Block strings' are supported too''' """ "Block strings" are supported too""" #! String interpolation "String #{interpolation} is supported" 'This works #{only} between double-quoted strings' #! Object properties kids = brother: name: "Max" age: 11 sister: name: "Ida" age: 9 #! Regexps /normal [r]egexp?/; /// ^( mul\t[i-l]ine regexp # with embedded comment ) /// #! Classes class Animal constructor: (@name) -> move: (meters) -> alert @name + " moved #{meters}m." class Snake extends Animal move: -> alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = new Snake "Sammy the Python" tom = new Horse "Tommy the Palomino" sam.move() tom.move() #! Inline JavaScript `alert("foo")`
198776
#! Header comment ### # example.coffee # Version 1.0.0 # # Licensed under the MIT license. # http://www.opensource.org/licenses/mit-license.php ### #! Comments # This is a comment ### This is a multi-line comment### #! Strings 'foo \'bar\' baz' "foo \"bar\" baz" 'Multi-line strings are supported' "Multi-line strings are supported" ''' 'Block strings' are supported too''' """ "Block strings" are supported too""" #! String interpolation "String #{interpolation} is supported" 'This works #{only} between double-quoted strings' #! Object properties kids = brother: name: "<NAME>" age: 11 sister: name: "<NAME>" age: 9 #! Regexps /normal [r]egexp?/; /// ^( mul\t[i-l]ine regexp # with embedded comment ) /// #! Classes class Animal constructor: (@name) -> move: (meters) -> alert @name + " moved #{meters}m." class Snake extends Animal move: -> alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = new Snake "<NAME>" tom = new Horse "<NAME>" sam.move() tom.move() #! Inline JavaScript `alert("foo")`
true
#! Header comment ### # example.coffee # Version 1.0.0 # # Licensed under the MIT license. # http://www.opensource.org/licenses/mit-license.php ### #! Comments # This is a comment ### This is a multi-line comment### #! Strings 'foo \'bar\' baz' "foo \"bar\" baz" 'Multi-line strings are supported' "Multi-line strings are supported" ''' 'Block strings' are supported too''' """ "Block strings" are supported too""" #! String interpolation "String #{interpolation} is supported" 'This works #{only} between double-quoted strings' #! Object properties kids = brother: name: "PI:NAME:<NAME>END_PI" age: 11 sister: name: "PI:NAME:<NAME>END_PI" age: 9 #! Regexps /normal [r]egexp?/; /// ^( mul\t[i-l]ine regexp # with embedded comment ) /// #! Classes class Animal constructor: (@name) -> move: (meters) -> alert @name + " moved #{meters}m." class Snake extends Animal move: -> alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = new Snake "PI:NAME:<NAME>END_PI" tom = new Horse "PI:NAME:<NAME>END_PI" sam.move() tom.move() #! Inline JavaScript `alert("foo")`
[ { "context": "\n }\n auth.login(server, {username: \"test@test.com\", password:\"password\"}, 200, \n (res)->", "end": 856, "score": 0.9998957514762878, "start": 843, "tag": "EMAIL", "value": "test@test.com" }, { "context": "gin(server, {username: \"test@test.com\", password:\"password\"}, 200, \n (res)->\n cook", "end": 877, "score": 0.9993804693222046, "start": 869, "tag": "PASSWORD", "value": "password" } ]
test/services_tests/test_test_services.coffee
ureport-web/ureport-s
3
#load application models server = require('../../app') _ = require('underscore'); test = require('../api_objects/test_api_object') build = require('../api_objects/build_api_object') auth = require('../api_objects/auth_api_object') mongoose = require('mongoose') chai = require('chai') chaiHttp = require('chai-http') moment = require('moment') should = chai.should() chai.use chaiHttp describe 'User can perform action on tests collection ', -> existbuild = undefined; cookies = null; before (done) -> payload = { is_archive: false, product: [ { "product" : "UpdateProduct" } ], type: [ { "type" : "API" } ], team: [ { "team" : "UpdateTeam" } ] } auth.login(server, {username: "test@test.com", password:"password"}, 200, (res)-> cookies = res.headers['set-cookie'].pop().split(';')[0]; build.filter(server,cookies, payload, 200, (res) -> existbuild = res.body[0] done() ) ) return describe 'Filter tests based on status', -> it 'should return all passsed tests', (done) -> payload = { build: existbuild._id, status: ["PASS"], exclude: ["failure",'info'] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 1 res.body[0].uid.should.equal '165427' res.body[0].name.should.equal 'test some basic function 3' res.body[0].is_rerun.should.equal false should.not.exist(res.body[0].failure) should.not.exist(res.body[0].info) done() ) return it 'should return all tests with all status', (done) -> payload = { build: existbuild._id, status: ["PASS","FAIL","WARNING","SKIP"] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 4 done() ) return it 'should return all tests with status "ALL"', (done) -> payload = { build: existbuild._id, status: ["All"] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 4 done() ) return describe 'Add tests steps', -> existTest = undefined; before (done) -> payload = { build: existbuild._id, status: ["PASS"], exclude: ["failure",'info'] } test.filter(server,payload, 200, (res) -> existTest = res.body[0] done() ) return it 'should add steps to exist test', (done) -> payload = { setup: [ { 'status': "PASS", 'step': "<div> This is a first setup step </div>", 'timestamp' : moment().add(4, 'hour').format() }, { 'status': "PASS", 'step': "<div> This is a second setup step </div>", 'timestamp' : moment().add(4, 'hour').format() } ], body: [ { 'status': "PASS", 'step': "<div> This is a first step </div>", 'timestamp' : moment().add(4, 'hour').format() }, { 'status': "FAIL", 'step': "<div> This is a second step </div>", 'timestamp' : moment().add(4, 'hour').format() } ], teardowns: ["failure",'info'] } test.addStep(server, existTest._id, payload, 200, (res) -> res.body.setup.should.be.an 'Array' res.body.body.should.be.an 'Array' res.body.setup.length.should.equal 2 res.body.body.length.should.equal 2 should.not.exist(res.body.teardown) done() ) return describe 'Add tests', -> it 'should add tests to exist build with full success', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", 'uid': "222", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ] } test.create(server, cookies, payload, 200, (res) -> res.body.state.should.be.equal 'Success' res.body.provided.should.be.equal 4 res.body.saved.should.be.equal 4 done() ) return it 'should add tests to exist build with partial success', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ], isOrdered: false } test.create(server, cookies, payload, 200, (res) -> res.body.state.should.be.equal 'Partial Success, you might have missing fields in your paylaod, not all tests are saved.' res.body.provided.should.be.equal 4 res.body.saved.should.be.equal 3 done() ) return it 'should add tests to exist build with error in payload', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ] } test.create(server, cookies, payload, 500, (res) -> done() ) return
94870
#load application models server = require('../../app') _ = require('underscore'); test = require('../api_objects/test_api_object') build = require('../api_objects/build_api_object') auth = require('../api_objects/auth_api_object') mongoose = require('mongoose') chai = require('chai') chaiHttp = require('chai-http') moment = require('moment') should = chai.should() chai.use chaiHttp describe 'User can perform action on tests collection ', -> existbuild = undefined; cookies = null; before (done) -> payload = { is_archive: false, product: [ { "product" : "UpdateProduct" } ], type: [ { "type" : "API" } ], team: [ { "team" : "UpdateTeam" } ] } auth.login(server, {username: "<EMAIL>", password:"<PASSWORD>"}, 200, (res)-> cookies = res.headers['set-cookie'].pop().split(';')[0]; build.filter(server,cookies, payload, 200, (res) -> existbuild = res.body[0] done() ) ) return describe 'Filter tests based on status', -> it 'should return all passsed tests', (done) -> payload = { build: existbuild._id, status: ["PASS"], exclude: ["failure",'info'] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 1 res.body[0].uid.should.equal '165427' res.body[0].name.should.equal 'test some basic function 3' res.body[0].is_rerun.should.equal false should.not.exist(res.body[0].failure) should.not.exist(res.body[0].info) done() ) return it 'should return all tests with all status', (done) -> payload = { build: existbuild._id, status: ["PASS","FAIL","WARNING","SKIP"] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 4 done() ) return it 'should return all tests with status "ALL"', (done) -> payload = { build: existbuild._id, status: ["All"] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 4 done() ) return describe 'Add tests steps', -> existTest = undefined; before (done) -> payload = { build: existbuild._id, status: ["PASS"], exclude: ["failure",'info'] } test.filter(server,payload, 200, (res) -> existTest = res.body[0] done() ) return it 'should add steps to exist test', (done) -> payload = { setup: [ { 'status': "PASS", 'step': "<div> This is a first setup step </div>", 'timestamp' : moment().add(4, 'hour').format() }, { 'status': "PASS", 'step': "<div> This is a second setup step </div>", 'timestamp' : moment().add(4, 'hour').format() } ], body: [ { 'status': "PASS", 'step': "<div> This is a first step </div>", 'timestamp' : moment().add(4, 'hour').format() }, { 'status': "FAIL", 'step': "<div> This is a second step </div>", 'timestamp' : moment().add(4, 'hour').format() } ], teardowns: ["failure",'info'] } test.addStep(server, existTest._id, payload, 200, (res) -> res.body.setup.should.be.an 'Array' res.body.body.should.be.an 'Array' res.body.setup.length.should.equal 2 res.body.body.length.should.equal 2 should.not.exist(res.body.teardown) done() ) return describe 'Add tests', -> it 'should add tests to exist build with full success', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", 'uid': "222", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ] } test.create(server, cookies, payload, 200, (res) -> res.body.state.should.be.equal 'Success' res.body.provided.should.be.equal 4 res.body.saved.should.be.equal 4 done() ) return it 'should add tests to exist build with partial success', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ], isOrdered: false } test.create(server, cookies, payload, 200, (res) -> res.body.state.should.be.equal 'Partial Success, you might have missing fields in your paylaod, not all tests are saved.' res.body.provided.should.be.equal 4 res.body.saved.should.be.equal 3 done() ) return it 'should add tests to exist build with error in payload', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ] } test.create(server, cookies, payload, 500, (res) -> done() ) return
true
#load application models server = require('../../app') _ = require('underscore'); test = require('../api_objects/test_api_object') build = require('../api_objects/build_api_object') auth = require('../api_objects/auth_api_object') mongoose = require('mongoose') chai = require('chai') chaiHttp = require('chai-http') moment = require('moment') should = chai.should() chai.use chaiHttp describe 'User can perform action on tests collection ', -> existbuild = undefined; cookies = null; before (done) -> payload = { is_archive: false, product: [ { "product" : "UpdateProduct" } ], type: [ { "type" : "API" } ], team: [ { "team" : "UpdateTeam" } ] } auth.login(server, {username: "PI:EMAIL:<EMAIL>END_PI", password:"PI:PASSWORD:<PASSWORD>END_PI"}, 200, (res)-> cookies = res.headers['set-cookie'].pop().split(';')[0]; build.filter(server,cookies, payload, 200, (res) -> existbuild = res.body[0] done() ) ) return describe 'Filter tests based on status', -> it 'should return all passsed tests', (done) -> payload = { build: existbuild._id, status: ["PASS"], exclude: ["failure",'info'] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 1 res.body[0].uid.should.equal '165427' res.body[0].name.should.equal 'test some basic function 3' res.body[0].is_rerun.should.equal false should.not.exist(res.body[0].failure) should.not.exist(res.body[0].info) done() ) return it 'should return all tests with all status', (done) -> payload = { build: existbuild._id, status: ["PASS","FAIL","WARNING","SKIP"] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 4 done() ) return it 'should return all tests with status "ALL"', (done) -> payload = { build: existbuild._id, status: ["All"] } test.filter(server,payload, 200, (res) -> res.body.should.be.an 'Array' res.body.length.should.equal 4 done() ) return describe 'Add tests steps', -> existTest = undefined; before (done) -> payload = { build: existbuild._id, status: ["PASS"], exclude: ["failure",'info'] } test.filter(server,payload, 200, (res) -> existTest = res.body[0] done() ) return it 'should add steps to exist test', (done) -> payload = { setup: [ { 'status': "PASS", 'step': "<div> This is a first setup step </div>", 'timestamp' : moment().add(4, 'hour').format() }, { 'status': "PASS", 'step': "<div> This is a second setup step </div>", 'timestamp' : moment().add(4, 'hour').format() } ], body: [ { 'status': "PASS", 'step': "<div> This is a first step </div>", 'timestamp' : moment().add(4, 'hour').format() }, { 'status': "FAIL", 'step': "<div> This is a second step </div>", 'timestamp' : moment().add(4, 'hour').format() } ], teardowns: ["failure",'info'] } test.addStep(server, existTest._id, payload, 200, (res) -> res.body.setup.should.be.an 'Array' res.body.body.should.be.an 'Array' res.body.setup.length.should.equal 2 res.body.body.length.should.equal 2 should.not.exist(res.body.teardown) done() ) return describe 'Add tests', -> it 'should add tests to exist build with full success', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", 'uid': "222", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ] } test.create(server, cookies, payload, 200, (res) -> res.body.state.should.be.equal 'Success' res.body.provided.should.be.equal 4 res.body.saved.should.be.equal 4 done() ) return it 'should add tests to exist build with partial success', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ], isOrdered: false } test.create(server, cookies, payload, 200, (res) -> res.body.state.should.be.equal 'Partial Success, you might have missing fields in your paylaod, not all tests are saved.' res.body.provided.should.be.equal 4 res.body.saved.should.be.equal 3 done() ) return it 'should add tests to exist build with error in payload', (done) -> payload = { tests: [ { 'status': "PASS", 'uid': "1111", "name": "new test 111", 'build' : existbuild._id }, { 'status': "PASS", "name": "new test 222", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "333", "name": "new test 333", 'build' : existbuild._id },{ 'status': "PASS", 'uid': "444", "name": "new test 444", 'build' : existbuild._id } ] } test.create(server, cookies, payload, 500, (res) -> done() ) return
[ { "context": "module.exports =\n access_token: '797b35a2fa11603bc5d440922383a89485e707c81582d518780069c998965c5f'\n space_id: '7vfiut035ckb'\n content_types: ", "end": 98, "score": 0.9903680682182312, "start": 34, "tag": "KEY", "value": "797b35a2fa11603bc5d440922383a89485e707c81582d518780069c998965c5f" } ]
contentful.coffee
owentribe/pushmepresscom
0
module.exports = access_token: '797b35a2fa11603bc5d440922383a89485e707c81582d518780069c998965c5f' space_id: '7vfiut035ckb' content_types: # remove these object braces once the config below is filled out topics: # data will be made available through this key on the `contentful` object in your templates id: 'topic' # ID of your content type template: 'views/_topic.jade' write: 'data.json' # filters: {} # passes filters to the call to contentful's API, see contentful's docs for more info # template: 'views/codepage.jade' # if present a single page view will be created for each entry in the content type # path: (entry) -> # override function for generating single page file path, passed in the entry object
102268
module.exports = access_token: '<KEY>' space_id: '7vfiut035ckb' content_types: # remove these object braces once the config below is filled out topics: # data will be made available through this key on the `contentful` object in your templates id: 'topic' # ID of your content type template: 'views/_topic.jade' write: 'data.json' # filters: {} # passes filters to the call to contentful's API, see contentful's docs for more info # template: 'views/codepage.jade' # if present a single page view will be created for each entry in the content type # path: (entry) -> # override function for generating single page file path, passed in the entry object
true
module.exports = access_token: 'PI:KEY:<KEY>END_PI' space_id: '7vfiut035ckb' content_types: # remove these object braces once the config below is filled out topics: # data will be made available through this key on the `contentful` object in your templates id: 'topic' # ID of your content type template: 'views/_topic.jade' write: 'data.json' # filters: {} # passes filters to the call to contentful's API, see contentful's docs for more info # template: 'views/codepage.jade' # if present a single page view will be created for each entry in the content type # path: (entry) -> # override function for generating single page file path, passed in the entry object
[ { "context": ")\n\n\nresetTable = ->\n\tPlayers.remove {}\n\tnames = [\"Martin Luther King\",\"Michael Jackson\",\"Leonardo Da Vinci\",\n\t\"Albert ", "end": 109, "score": 0.9998490214347839, "start": 91, "tag": "NAME", "value": "Martin Luther King" }, { "context": "Players.remove {}\n\tnames = [\"Martin Luther King\",\"Michael Jackson\",\"Leonardo Da Vinci\",\n\t\"Albert Einstein\",\"Gandhi\"", "end": 127, "score": 0.9998376369476318, "start": 112, "tag": "NAME", "value": "Michael Jackson" }, { "context": "\tnames = [\"Martin Luther King\",\"Michael Jackson\",\"Leonardo Da Vinci\",\n\t\"Albert Einstein\",\"Gandhi\",\"William Shakespear", "end": 147, "score": 0.9998406767845154, "start": 130, "tag": "NAME", "value": "Leonardo Da Vinci" }, { "context": "er King\",\"Michael Jackson\",\"Leonardo Da Vinci\",\n\t\"Albert Einstein\",\"Gandhi\",\"William Shakespeare\",\"Abraham Lincoln\"", "end": 167, "score": 0.9998432397842407, "start": 152, "tag": "NAME", "value": "Albert Einstein" }, { "context": "Jackson\",\"Leonardo Da Vinci\",\n\t\"Albert Einstein\",\"Gandhi\",\"William Shakespeare\",\"Abraham Lincoln\",\n\t\"Princ", "end": 176, "score": 0.9998040199279785, "start": 170, "tag": "NAME", "value": "Gandhi" }, { "context": "\"Leonardo Da Vinci\",\n\t\"Albert Einstein\",\"Gandhi\",\"William Shakespeare\",\"Abraham Lincoln\",\n\t\"Princess Diana\"]\n\tfor name ", "end": 198, "score": 0.9998578429222107, "start": 179, "tag": "NAME", "value": "William Shakespeare" }, { "context": "\"Albert Einstein\",\"Gandhi\",\"William Shakespeare\",\"Abraham Lincoln\",\n\t\"Princess Diana\"]\n\tfor name in names\n\t\tPlayers", "end": 216, "score": 0.9998695254325867, "start": 201, "tag": "NAME", "value": "Abraham Lincoln" }, { "context": "andhi\",\"William Shakespeare\",\"Abraham Lincoln\",\n\t\"Princess Diana\"]\n\tfor name in names\n\t\tPlayers.insert {name:name,", "end": 235, "score": 0.9998490214347839, "start": 221, "tag": "NAME", "value": "Princess Diana" } ]
lib/leaderboard.coffee
zeke/Leaderboards-XL
1
Players = new Meteor.Collection("players") resetTable = -> Players.remove {} names = ["Martin Luther King","Michael Jackson","Leonardo Da Vinci", "Albert Einstein","Gandhi","William Shakespeare","Abraham Lincoln", "Princess Diana"] for name in names Players.insert {name:name, score: _.random 0, 10}
157652
Players = new Meteor.Collection("players") resetTable = -> Players.remove {} names = ["<NAME>","<NAME>","<NAME>", "<NAME>","<NAME>","<NAME>","<NAME>", "<NAME>"] for name in names Players.insert {name:name, score: _.random 0, 10}
true
Players = new Meteor.Collection("players") resetTable = -> Players.remove {} names = ["PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] for name in names Players.insert {name:name, score: _.random 0, 10}
[ { "context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)\n# MIT Licensed\n###\n\ncoffeekup", "end": 44, "score": 0.9998459219932556, "start": 36, "tag": "NAME", "value": "Jae Kwon" }, { "context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)\n# MIT Licensed\n###\n\ncoffeekup = if CoffeeKup? th", "end": 63, "score": 0.999930739402771, "start": 46, "tag": "EMAIL", "value": "jae@ycatalyst.com" }, { "context": "he node.js validator project\n# https://github.com/chriso/node-validator.git\n# NOTE: > The /m flag is multi", "end": 238, "score": 0.995741605758667, "start": 232, "tag": "USERNAME", "value": "chriso" }, { "context": "oin(\" \")\n\n\n# if server-side\nif exports?\n exports.Markz = Markz\n exports.hE = hE\n# if client-side\nif win", "end": 5245, "score": 0.9119386672973633, "start": 5240, "tag": "NAME", "value": "Markz" }, { "context": ")\n\n\n# if server-side\nif exports?\n exports.Markz = Markz\n exports.hE = hE\n# if client-side\nif window?\n w", "end": 5253, "score": 0.94301438331604, "start": 5248, "tag": "NAME", "value": "Markz" }, { "context": "orts.hE = hE\n# if client-side\nif window?\n window.Markz = Markz\n window.hE = hE\n", "end": 5314, "score": 0.9107739925384521, "start": 5309, "tag": "NAME", "value": "Markz" }, { "context": " = hE\n# if client-side\nif window?\n window.Markz = Markz\n window.hE = hE\n", "end": 5322, "score": 0.9473587274551392, "start": 5317, "tag": "NAME", "value": "Markz" } ]
static/markz.coffee
jaekwon/YCatalyst
3
### # YCatalyst # Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com) # MIT Licensed ### coffeekup = if CoffeeKup? then CoffeeKup else require './coffeekup' # some regexes ripped from the node.js validator project # https://github.com/chriso/node-validator.git # NOTE: > The /m flag is multiline matching. # > (?!...) is a negative lookahead. # > The only way to match a multi-line spanning pattern is to use [\s\S] type classes. # * Try to capture the trailing newline of block elements like codeblocks. # TODO: possibly convert all to XRegExp for client compatibility, or at least support it. re_heading = /^(\#{1,6})(.*)$\n?|^(.*)$\n^(={4,}|-{4,})$\n?/m re_email = /(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))/ re_url = /((?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2}))|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?/ re_link = /\[([^\n\[\]]+)\] *\(([^\n\[\]]+)(?: +"([^\n\[\]]+)")?\)/ re_bold = /\*([^\*\n]+)\*/ re_newline = /\n/ re_ulbullets = /(?:^\* +.+$\n?){2,}/m re_olbullets = /(?:^\d{1,2}\.? +.+$\n?){2,}/m re_blockquote = /(?:^>.*$\n?)+/m re_codeblock = /<code(?: +lang=['"]?(\w+)['"]?)?>([\s\S]*?)<\/code>\n?/ hE = (text) -> text = text.toString() return text.replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#39;") REPLACE_LOOKUP = [ ['heading', re_heading, (match) -> if match[1] # is a ### HEADING type heading "<h#{match[1].length}>#{hE match[2]}</h#{match[1].length}>" else # is a HEADING # ====== type heading heading_type = if match[4][0] == '=' then 'h1' else 'h2' "<#{heading_type}>#{hE match[3]}</#{heading_type}>" ] ['link', re_link, (match) -> "<a href=\"#{hE match[2]}\" title=\"#{hE match[3] or ''}\">#{hE match[1]}</a>"] ['url', re_url, (match) -> if match[1] and match[1].length > 0 "<a href=\"#{hE match[0]}\">#{hE match[0]}</a>" else "<a href=\"http://#{hE match[0]}\">#{hE match[0]}</a>" ] ['email', re_email, (match) -> "<a href=\"mailto:#{hE match[0]}\">#{hE match[0]}</a>"] ['blockquote', re_blockquote, (match) -> unquoted = (line.substr(1) for line in match[0].split("\n")).join("\n") "<blockquote>#{Markz::markup unquoted}</blockquote>"] ['olbullets', re_olbullets, (match) -> lines = (line.substr(2).trim() for line in match[0].trim().split("\n")) markup_lines = ("<li><span class='back_to_black'>#{Markz::markup(line)}</span></li>" for line in lines) "<ol>#{markup_lines.join('')}</ol>"] ['ulbullets', re_ulbullets, (match) -> lines = (line.substr(1).trim() for line in match[0].trim().split("\n")) markup_lines = ("<li><span class='back_to_black'>#{Markz::markup(line)}</span></li>" for line in lines) "<ul>#{markup_lines.join('')}</ul>"] ['bold', re_bold, (match) -> "<b>#{Markz::markup match[1]}</b>"] ['newline', re_newline, (match) -> "<br/>"] ['codeblock', re_codeblock, (match) -> "<pre class='brush: #{match[1] or 'coffeescript'}'>#{hE match[2]}</pre>"] ] class Markz markup: (text) -> type2match = {} # type -> {match, func} #for l in replace_lookup # [type, regex, func] = l find_next_match = (type2match, text, cursor) -> # returns {match, func, type, offset} or null # fill type2match for type_regex_func in REPLACE_LOOKUP [type, regex, func] = type_regex_func # cleanup or prune if type2match[type]? if type2match[type].offset < cursor delete type2match[type] else continue match = text.substr(cursor).match(regex) if match? type2match[type] = match: match, func: func, type: type, offset: match.index+cursor # return the earliest earliest = null for type, stuff of type2match if not earliest? earliest = stuff else if stuff.offset < earliest.offset earliest = stuff return earliest # collect entities cursor = 0 coll = [] while true next_match = find_next_match(type2match, text, cursor) if not next_match? break if next_match.offset > cursor coll.push(hE(text.substr(cursor, (next_match.offset - cursor)))) coll.push(next_match.func(next_match.match)) cursor = next_match.offset + next_match.match[0].length coll.push(hE(text.substr(cursor))) # add breaks return coll.join(" ") # if server-side if exports? exports.Markz = Markz exports.hE = hE # if client-side if window? window.Markz = Markz window.hE = hE
21789
### # YCatalyst # Copyright(c) 2011 <NAME> (<EMAIL>) # MIT Licensed ### coffeekup = if CoffeeKup? then CoffeeKup else require './coffeekup' # some regexes ripped from the node.js validator project # https://github.com/chriso/node-validator.git # NOTE: > The /m flag is multiline matching. # > (?!...) is a negative lookahead. # > The only way to match a multi-line spanning pattern is to use [\s\S] type classes. # * Try to capture the trailing newline of block elements like codeblocks. # TODO: possibly convert all to XRegExp for client compatibility, or at least support it. re_heading = /^(\#{1,6})(.*)$\n?|^(.*)$\n^(={4,}|-{4,})$\n?/m re_email = /(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))/ re_url = /((?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2}))|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?/ re_link = /\[([^\n\[\]]+)\] *\(([^\n\[\]]+)(?: +"([^\n\[\]]+)")?\)/ re_bold = /\*([^\*\n]+)\*/ re_newline = /\n/ re_ulbullets = /(?:^\* +.+$\n?){2,}/m re_olbullets = /(?:^\d{1,2}\.? +.+$\n?){2,}/m re_blockquote = /(?:^>.*$\n?)+/m re_codeblock = /<code(?: +lang=['"]?(\w+)['"]?)?>([\s\S]*?)<\/code>\n?/ hE = (text) -> text = text.toString() return text.replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#39;") REPLACE_LOOKUP = [ ['heading', re_heading, (match) -> if match[1] # is a ### HEADING type heading "<h#{match[1].length}>#{hE match[2]}</h#{match[1].length}>" else # is a HEADING # ====== type heading heading_type = if match[4][0] == '=' then 'h1' else 'h2' "<#{heading_type}>#{hE match[3]}</#{heading_type}>" ] ['link', re_link, (match) -> "<a href=\"#{hE match[2]}\" title=\"#{hE match[3] or ''}\">#{hE match[1]}</a>"] ['url', re_url, (match) -> if match[1] and match[1].length > 0 "<a href=\"#{hE match[0]}\">#{hE match[0]}</a>" else "<a href=\"http://#{hE match[0]}\">#{hE match[0]}</a>" ] ['email', re_email, (match) -> "<a href=\"mailto:#{hE match[0]}\">#{hE match[0]}</a>"] ['blockquote', re_blockquote, (match) -> unquoted = (line.substr(1) for line in match[0].split("\n")).join("\n") "<blockquote>#{Markz::markup unquoted}</blockquote>"] ['olbullets', re_olbullets, (match) -> lines = (line.substr(2).trim() for line in match[0].trim().split("\n")) markup_lines = ("<li><span class='back_to_black'>#{Markz::markup(line)}</span></li>" for line in lines) "<ol>#{markup_lines.join('')}</ol>"] ['ulbullets', re_ulbullets, (match) -> lines = (line.substr(1).trim() for line in match[0].trim().split("\n")) markup_lines = ("<li><span class='back_to_black'>#{Markz::markup(line)}</span></li>" for line in lines) "<ul>#{markup_lines.join('')}</ul>"] ['bold', re_bold, (match) -> "<b>#{Markz::markup match[1]}</b>"] ['newline', re_newline, (match) -> "<br/>"] ['codeblock', re_codeblock, (match) -> "<pre class='brush: #{match[1] or 'coffeescript'}'>#{hE match[2]}</pre>"] ] class Markz markup: (text) -> type2match = {} # type -> {match, func} #for l in replace_lookup # [type, regex, func] = l find_next_match = (type2match, text, cursor) -> # returns {match, func, type, offset} or null # fill type2match for type_regex_func in REPLACE_LOOKUP [type, regex, func] = type_regex_func # cleanup or prune if type2match[type]? if type2match[type].offset < cursor delete type2match[type] else continue match = text.substr(cursor).match(regex) if match? type2match[type] = match: match, func: func, type: type, offset: match.index+cursor # return the earliest earliest = null for type, stuff of type2match if not earliest? earliest = stuff else if stuff.offset < earliest.offset earliest = stuff return earliest # collect entities cursor = 0 coll = [] while true next_match = find_next_match(type2match, text, cursor) if not next_match? break if next_match.offset > cursor coll.push(hE(text.substr(cursor, (next_match.offset - cursor)))) coll.push(next_match.func(next_match.match)) cursor = next_match.offset + next_match.match[0].length coll.push(hE(text.substr(cursor))) # add breaks return coll.join(" ") # if server-side if exports? exports.<NAME> = <NAME> exports.hE = hE # if client-side if window? window.<NAME> = <NAME> window.hE = hE
true
### # YCatalyst # Copyright(c) 2011 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # MIT Licensed ### coffeekup = if CoffeeKup? then CoffeeKup else require './coffeekup' # some regexes ripped from the node.js validator project # https://github.com/chriso/node-validator.git # NOTE: > The /m flag is multiline matching. # > (?!...) is a negative lookahead. # > The only way to match a multi-line spanning pattern is to use [\s\S] type classes. # * Try to capture the trailing newline of block elements like codeblocks. # TODO: possibly convert all to XRegExp for client compatibility, or at least support it. re_heading = /^(\#{1,6})(.*)$\n?|^(.*)$\n^(={4,}|-{4,})$\n?/m re_email = /(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))/ re_url = /((?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2}))|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?/ re_link = /\[([^\n\[\]]+)\] *\(([^\n\[\]]+)(?: +"([^\n\[\]]+)")?\)/ re_bold = /\*([^\*\n]+)\*/ re_newline = /\n/ re_ulbullets = /(?:^\* +.+$\n?){2,}/m re_olbullets = /(?:^\d{1,2}\.? +.+$\n?){2,}/m re_blockquote = /(?:^>.*$\n?)+/m re_codeblock = /<code(?: +lang=['"]?(\w+)['"]?)?>([\s\S]*?)<\/code>\n?/ hE = (text) -> text = text.toString() return text.replace(/&/g, "&amp;") .replace(/</g, "&lt;") .replace(/>/g, "&gt;") .replace(/"/g, "&quot;") .replace(/'/g, "&#39;") REPLACE_LOOKUP = [ ['heading', re_heading, (match) -> if match[1] # is a ### HEADING type heading "<h#{match[1].length}>#{hE match[2]}</h#{match[1].length}>" else # is a HEADING # ====== type heading heading_type = if match[4][0] == '=' then 'h1' else 'h2' "<#{heading_type}>#{hE match[3]}</#{heading_type}>" ] ['link', re_link, (match) -> "<a href=\"#{hE match[2]}\" title=\"#{hE match[3] or ''}\">#{hE match[1]}</a>"] ['url', re_url, (match) -> if match[1] and match[1].length > 0 "<a href=\"#{hE match[0]}\">#{hE match[0]}</a>" else "<a href=\"http://#{hE match[0]}\">#{hE match[0]}</a>" ] ['email', re_email, (match) -> "<a href=\"mailto:#{hE match[0]}\">#{hE match[0]}</a>"] ['blockquote', re_blockquote, (match) -> unquoted = (line.substr(1) for line in match[0].split("\n")).join("\n") "<blockquote>#{Markz::markup unquoted}</blockquote>"] ['olbullets', re_olbullets, (match) -> lines = (line.substr(2).trim() for line in match[0].trim().split("\n")) markup_lines = ("<li><span class='back_to_black'>#{Markz::markup(line)}</span></li>" for line in lines) "<ol>#{markup_lines.join('')}</ol>"] ['ulbullets', re_ulbullets, (match) -> lines = (line.substr(1).trim() for line in match[0].trim().split("\n")) markup_lines = ("<li><span class='back_to_black'>#{Markz::markup(line)}</span></li>" for line in lines) "<ul>#{markup_lines.join('')}</ul>"] ['bold', re_bold, (match) -> "<b>#{Markz::markup match[1]}</b>"] ['newline', re_newline, (match) -> "<br/>"] ['codeblock', re_codeblock, (match) -> "<pre class='brush: #{match[1] or 'coffeescript'}'>#{hE match[2]}</pre>"] ] class Markz markup: (text) -> type2match = {} # type -> {match, func} #for l in replace_lookup # [type, regex, func] = l find_next_match = (type2match, text, cursor) -> # returns {match, func, type, offset} or null # fill type2match for type_regex_func in REPLACE_LOOKUP [type, regex, func] = type_regex_func # cleanup or prune if type2match[type]? if type2match[type].offset < cursor delete type2match[type] else continue match = text.substr(cursor).match(regex) if match? type2match[type] = match: match, func: func, type: type, offset: match.index+cursor # return the earliest earliest = null for type, stuff of type2match if not earliest? earliest = stuff else if stuff.offset < earliest.offset earliest = stuff return earliest # collect entities cursor = 0 coll = [] while true next_match = find_next_match(type2match, text, cursor) if not next_match? break if next_match.offset > cursor coll.push(hE(text.substr(cursor, (next_match.offset - cursor)))) coll.push(next_match.func(next_match.match)) cursor = next_match.offset + next_match.match[0].length coll.push(hE(text.substr(cursor))) # add breaks return coll.join(" ") # if server-side if exports? exports.PI:NAME:<NAME>END_PI = PI:NAME:<NAME>END_PI exports.hE = hE # if client-side if window? window.PI:NAME:<NAME>END_PI = PI:NAME:<NAME>END_PI window.hE = hE
[ { "context": "3c86ef8c05a728b9918e958f03bcfe164092bdfc488d64733e40127db45e4f61b7dddf2b0cbbd8d5ebdd98e5194d382236d5e", "end": 507, "score": 0.5066136121749878, "start": 506, "tag": "KEY", "value": "4" }, { "context": "05a728b9918e958f03bcfe164092bdfc488d64733e40127db45e4f61b7dddf2b0cbbd8d5ebdd98e5194d382236d5e54f7'\npa", "end": 515, "score": 0.5066596865653992, "start": 514, "tag": "KEY", "value": "5" } ]
examples/datasets/plants.coffee
wmiller848/GoGP
2
#!/usr/local/bin/coffee ###################### ## GoGP Program ## Version - 0.1.0 ###################### DNA = 'bdc7f223df2fa9194876f426fe389607631b9f0be51c534ed1f9ab23494d4a5fd1685d1668c2863dd837f9cd87da9199591a28242342aa6347411bd1251a5ee6770dece01a4f7071626f8774ce8ac81f0449ca3f41b4d95298c8c9098b014674ca4340d11dd9a18a9769803bf1d8a330d63da90c86b0|d3826d5e54f7bd28813538d0b684bd38bd8883a3ba870e8a4bca2e4e01c97d12eb97ac5f09361d339a4a52cde46e254f3dbbcf3973c86ef8c05a728b9918e958f03bcfe164092bdfc488d64733e40127db45e4f61b7dddf2b0cbbd8d5ebdd98e5194d382236d5e54f7' pargs = process.argv.slice(2) args = null process.on('beforeExit', -> #console.log('Dieing...') ) process.on('exit', -> #console.log('Dead...') ) inputMap = 'noInputStrings': null assertMap = 'Iris-virginica': 24 'Iris-setosa': 8 'Iris-versicolor': 16 ## ## match = (output) -> diff = Number.MAX_VALUE ok = "" ov = 0 for k, v of assertMap d = Math.abs(v - output) if d < diff diff = d ok = k ov = v # "#{ok} (#{ov}) from #{output}" "#{ok}" ## ## run = -> $zz = Number(args[0]);$zy = Number(args[1]);$zx = Number(args[2]);$zw = Number(args[3]); $zz = inputMap[args[0]] if isNaN($zz);$zy = inputMap[args[1]] if isNaN($zy);$zx = inputMap[args[2]] if isNaN($zx);$zw = inputMap[args[3]] if isNaN($zw); output = 4+(9*$zw) if isNaN(output) output = '' ot = match(output) process.stdout.write(new Buffer.from(ot.toString() + '\n')) if pargs.length == 0 process.stdin.setEncoding('utf8') process.stdin.on('readable', -> chunks = process.stdin.read() if chunks chunks = chunks.toString().trim().split('\n') for chunk in chunks args = chunk.split(',') run() ) process.stdin.on('end', -> #process.stdout.write(new Buffer.from('\r\n')) ) else args = pargs.join(' ').trim().split(' ') run()
209235
#!/usr/local/bin/coffee ###################### ## GoGP Program ## Version - 0.1.0 ###################### DNA = 'bdc7f223df2fa9194876f426fe389607631b9f0be51c534ed1f9ab23494d4a5fd1685d1668c2863dd837f9cd87da9199591a28242342aa6347411bd1251a5ee6770dece01a4f7071626f8774ce8ac81f0449ca3f41b4d95298c8c9098b014674ca4340d11dd9a18a9769803bf1d8a330d63da90c86b0|d3826d5e54f7bd28813538d0b684bd38bd8883a3ba870e8a4bca2e4e01c97d12eb97ac5f09361d339a4a52cde46e254f3dbbcf3973c86ef8c05a728b9918e958f03bcfe164092bdfc488d64733e<KEY>0127db4<KEY>e4f61b7dddf2b0cbbd8d5ebdd98e5194d382236d5e54f7' pargs = process.argv.slice(2) args = null process.on('beforeExit', -> #console.log('Dieing...') ) process.on('exit', -> #console.log('Dead...') ) inputMap = 'noInputStrings': null assertMap = 'Iris-virginica': 24 'Iris-setosa': 8 'Iris-versicolor': 16 ## ## match = (output) -> diff = Number.MAX_VALUE ok = "" ov = 0 for k, v of assertMap d = Math.abs(v - output) if d < diff diff = d ok = k ov = v # "#{ok} (#{ov}) from #{output}" "#{ok}" ## ## run = -> $zz = Number(args[0]);$zy = Number(args[1]);$zx = Number(args[2]);$zw = Number(args[3]); $zz = inputMap[args[0]] if isNaN($zz);$zy = inputMap[args[1]] if isNaN($zy);$zx = inputMap[args[2]] if isNaN($zx);$zw = inputMap[args[3]] if isNaN($zw); output = 4+(9*$zw) if isNaN(output) output = '' ot = match(output) process.stdout.write(new Buffer.from(ot.toString() + '\n')) if pargs.length == 0 process.stdin.setEncoding('utf8') process.stdin.on('readable', -> chunks = process.stdin.read() if chunks chunks = chunks.toString().trim().split('\n') for chunk in chunks args = chunk.split(',') run() ) process.stdin.on('end', -> #process.stdout.write(new Buffer.from('\r\n')) ) else args = pargs.join(' ').trim().split(' ') run()
true
#!/usr/local/bin/coffee ###################### ## GoGP Program ## Version - 0.1.0 ###################### DNA = 'bdc7f223df2fa9194876f426fe389607631b9f0be51c534ed1f9ab23494d4a5fd1685d1668c2863dd837f9cd87da9199591a28242342aa6347411bd1251a5ee6770dece01a4f7071626f8774ce8ac81f0449ca3f41b4d95298c8c9098b014674ca4340d11dd9a18a9769803bf1d8a330d63da90c86b0|d3826d5e54f7bd28813538d0b684bd38bd8883a3ba870e8a4bca2e4e01c97d12eb97ac5f09361d339a4a52cde46e254f3dbbcf3973c86ef8c05a728b9918e958f03bcfe164092bdfc488d64733ePI:KEY:<KEY>END_PI0127db4PI:KEY:<KEY>END_PIe4f61b7dddf2b0cbbd8d5ebdd98e5194d382236d5e54f7' pargs = process.argv.slice(2) args = null process.on('beforeExit', -> #console.log('Dieing...') ) process.on('exit', -> #console.log('Dead...') ) inputMap = 'noInputStrings': null assertMap = 'Iris-virginica': 24 'Iris-setosa': 8 'Iris-versicolor': 16 ## ## match = (output) -> diff = Number.MAX_VALUE ok = "" ov = 0 for k, v of assertMap d = Math.abs(v - output) if d < diff diff = d ok = k ov = v # "#{ok} (#{ov}) from #{output}" "#{ok}" ## ## run = -> $zz = Number(args[0]);$zy = Number(args[1]);$zx = Number(args[2]);$zw = Number(args[3]); $zz = inputMap[args[0]] if isNaN($zz);$zy = inputMap[args[1]] if isNaN($zy);$zx = inputMap[args[2]] if isNaN($zx);$zw = inputMap[args[3]] if isNaN($zw); output = 4+(9*$zw) if isNaN(output) output = '' ot = match(output) process.stdout.write(new Buffer.from(ot.toString() + '\n')) if pargs.length == 0 process.stdin.setEncoding('utf8') process.stdin.on('readable', -> chunks = process.stdin.read() if chunks chunks = chunks.toString().trim().split('\n') for chunk in chunks args = chunk.split(',') run() ) process.stdin.on('end', -> #process.stdout.write(new Buffer.from('\r\n')) ) else args = pargs.join(' ').trim().split(' ') run()
[ { "context": "###\nPDFFont - embeds fonts in PDF documents\nBy Devon Govett\n###\n\nTTFFont = require './font/ttf'\nAFMFont = req", "end": 59, "score": 0.999874472618103, "start": 47, "tag": "NAME", "value": "Devon Govett" } ]
lib/font.coffee
bryandragon/pdfkit
0
### PDFFont - embeds fonts in PDF documents By Devon Govett ### TTFFont = require './font/ttf' AFMFont = require './font/afm' Subset = require './font/subset' zlib = require 'zlib' WORD_RE = /([^ ,\/!.?:;\-\n]+[ ,\/!.?:;\-]*)|\n/g class PDFFont constructor: (@document, @filename, @family, @id) -> if @filename in @_standardFonts @embedStandard() else if /\.(ttf|ttc)$/i.test @filename @ttf = TTFFont.open @filename, @family @subset = new Subset @ttf @registerTTF() else if /\.dfont$/i.test @filename @ttf = TTFFont.fromDFont @filename, @family @subset = new Subset @ttf @registerTTF() else throw new Error 'Not a supported font format or standard PDF font.' use: (characters) -> @subset?.use characters embed: (fn) -> return fn() if @isAFM @embedTTF fn encode: (text) -> @subset?.encodeText(text) or text registerTTF: -> @scaleFactor = 1000.0 / @ttf.head.unitsPerEm @bbox = (Math.round e * @scaleFactor for e in @ttf.bbox) @stemV = 0 # not sure how to compute this for true-type fonts... if @ttf.post.exists raw = @ttf.post.italic_angle hi = raw >> 16 low = raw & 0xFF hi = -((hi ^ 0xFFFF) + 1) if hi & 0x8000 isnt 0 @italicAngle = +"#{hi}.#{low}" else @italicAngle = 0 @ascender = Math.round @ttf.ascender * @scaleFactor @decender = Math.round @ttf.decender * @scaleFactor @lineGap = Math.round @ttf.lineGap * @scaleFactor @capHeight = (@ttf.os2.exists and @ttf.os2.capHeight) or @ascender @xHeight = (@ttf.os2.exists and @ttf.os2.xHeight) or 0 @familyClass = (@ttf.os2.exists and @ttf.os2.familyClass or 0) >> 8 @isSerif = @familyClass in [1,2,3,4,5,7] @isScript = @familyClass is 10 @flags = 0 @flags |= 1 << 0 if @ttf.post.isFixedPitch @flags |= 1 << 1 if @isSerif @flags |= 1 << 3 if @isScript @flags |= 1 << 6 if @italicAngle isnt 0 @flags |= 1 << 5 # assume the font is nonsymbolic... @cmap = @ttf.cmap.unicode throw new Error 'No unicode cmap for font' if not @cmap @hmtx = @ttf.hmtx @charWidths = (Math.round @hmtx.widths[gid] * @scaleFactor for i, gid of @cmap.codeMap when i >= 32) # Create a placeholder reference to be filled in embedTTF. @ref = @document.ref Type: 'Font' Subtype: 'TrueType' embedTTF: (fn) -> data = @subset.encode() zlib.deflate data, (err, compressedData) => throw err if err @fontfile = @document.ref Length: compressedData.length Length1: data.length Filter: 'FlateDecode' @fontfile.add compressedData @descriptor = @document.ref Type: 'FontDescriptor' FontName: @subset.postscriptName FontFile2: @fontfile FontBBox: @bbox Flags: @flags StemV: @stemV ItalicAngle: @italicAngle Ascent: @ascender Descent: @decender CapHeight: @capHeight XHeight: @xHeight firstChar = +Object.keys(@subset.cmap)[0] charWidths = for code, glyph of @subset.cmap Math.round @ttf.hmtx.forGlyph(glyph).advance * @scaleFactor cmap = @document.ref() cmap.add toUnicodeCmap(@subset.subset) ref = Type: 'Font' BaseFont: @subset.postscriptName Subtype: 'TrueType' FontDescriptor: @descriptor FirstChar: firstChar LastChar: firstChar + charWidths.length - 1 Widths: @document.ref charWidths Encoding: 'MacRomanEncoding' ToUnicode: cmap for key, val of ref @ref.data[key] = val cmap.finalize(@document.compress, fn) # compress it toUnicodeCmap = (map) -> unicodeMap = ''' /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00><ff> endcodespacerange ''' codes = Object.keys(map).sort (a, b) -> a - b range = [] for code in codes if range.length >= 100 unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar" range = [] unicode = ('0000' + map[code].toString(16)).slice(-4) code = (+code).toString(16) range.push "<#{code}><#{unicode}>" unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar\n" if range.length unicodeMap += ''' endcmap CMapName currentdict /CMap defineresource pop end end ''' embedStandard: -> @isAFM = true font = AFMFont.open __dirname + "/font/data/#{@filename}.afm" {@ascender,@decender,@bbox,@lineGap,@charWidths} = font @ref = @document.ref Type: 'Font' BaseFont: @filename Subtype: 'Type1' _standardFonts: [ "Courier" "Courier-Bold" "Courier-Oblique" "Courier-BoldOblique" "Helvetica" "Helvetica-Bold" "Helvetica-Oblique" "Helvetica-BoldOblique" "Times-Roman" "Times-Bold" "Times-Italic" "Times-BoldItalic" "Symbol" "ZapfDingbats" ] widthOfString: (string, size) -> string = '' + string width = 0 for i in [0...string.length] charCode = string.charCodeAt(i) - if @isAFM then 0 else 32 width += @charWidths[charCode] or 0 scale = size / 1000 return width * scale heightOfString: (string, size, boundWidth) -> string = '' + string spaceLeft = boundWidth lines = 1 words = string.match(WORD_RE) wordLens = {} for word, i in words wordLen = wordLens[word] ?= @widthOfString(word, size) if word == '\n' spaceLeft = boundWidth lines++ else if wordLen > spaceLeft spaceLeft = boundWidth - wordLen lines++ else spaceLeft -= wordLen console.log("lines: " + lines) # if string[i] == '\n' # width = 0 # lines++ # else # charWidth = @widthOfString(string[i], size) # width += charWidth # if width > boundWidth # width = 0 # lines++ # includeGap = if lines > 1 then true else false # lastGap = (if includeGap then @lineGap else 0) / 1000 * size lineHeight = @lineHeight(size, true) lines * lineHeight # - lastGap lineHeight: (size, includeGap = false) -> gap = if includeGap then @lineGap else 0 (@ascender + gap - @decender) / 1000 * size module.exports = PDFFont
225450
### PDFFont - embeds fonts in PDF documents By <NAME> ### TTFFont = require './font/ttf' AFMFont = require './font/afm' Subset = require './font/subset' zlib = require 'zlib' WORD_RE = /([^ ,\/!.?:;\-\n]+[ ,\/!.?:;\-]*)|\n/g class PDFFont constructor: (@document, @filename, @family, @id) -> if @filename in @_standardFonts @embedStandard() else if /\.(ttf|ttc)$/i.test @filename @ttf = TTFFont.open @filename, @family @subset = new Subset @ttf @registerTTF() else if /\.dfont$/i.test @filename @ttf = TTFFont.fromDFont @filename, @family @subset = new Subset @ttf @registerTTF() else throw new Error 'Not a supported font format or standard PDF font.' use: (characters) -> @subset?.use characters embed: (fn) -> return fn() if @isAFM @embedTTF fn encode: (text) -> @subset?.encodeText(text) or text registerTTF: -> @scaleFactor = 1000.0 / @ttf.head.unitsPerEm @bbox = (Math.round e * @scaleFactor for e in @ttf.bbox) @stemV = 0 # not sure how to compute this for true-type fonts... if @ttf.post.exists raw = @ttf.post.italic_angle hi = raw >> 16 low = raw & 0xFF hi = -((hi ^ 0xFFFF) + 1) if hi & 0x8000 isnt 0 @italicAngle = +"#{hi}.#{low}" else @italicAngle = 0 @ascender = Math.round @ttf.ascender * @scaleFactor @decender = Math.round @ttf.decender * @scaleFactor @lineGap = Math.round @ttf.lineGap * @scaleFactor @capHeight = (@ttf.os2.exists and @ttf.os2.capHeight) or @ascender @xHeight = (@ttf.os2.exists and @ttf.os2.xHeight) or 0 @familyClass = (@ttf.os2.exists and @ttf.os2.familyClass or 0) >> 8 @isSerif = @familyClass in [1,2,3,4,5,7] @isScript = @familyClass is 10 @flags = 0 @flags |= 1 << 0 if @ttf.post.isFixedPitch @flags |= 1 << 1 if @isSerif @flags |= 1 << 3 if @isScript @flags |= 1 << 6 if @italicAngle isnt 0 @flags |= 1 << 5 # assume the font is nonsymbolic... @cmap = @ttf.cmap.unicode throw new Error 'No unicode cmap for font' if not @cmap @hmtx = @ttf.hmtx @charWidths = (Math.round @hmtx.widths[gid] * @scaleFactor for i, gid of @cmap.codeMap when i >= 32) # Create a placeholder reference to be filled in embedTTF. @ref = @document.ref Type: 'Font' Subtype: 'TrueType' embedTTF: (fn) -> data = @subset.encode() zlib.deflate data, (err, compressedData) => throw err if err @fontfile = @document.ref Length: compressedData.length Length1: data.length Filter: 'FlateDecode' @fontfile.add compressedData @descriptor = @document.ref Type: 'FontDescriptor' FontName: @subset.postscriptName FontFile2: @fontfile FontBBox: @bbox Flags: @flags StemV: @stemV ItalicAngle: @italicAngle Ascent: @ascender Descent: @decender CapHeight: @capHeight XHeight: @xHeight firstChar = +Object.keys(@subset.cmap)[0] charWidths = for code, glyph of @subset.cmap Math.round @ttf.hmtx.forGlyph(glyph).advance * @scaleFactor cmap = @document.ref() cmap.add toUnicodeCmap(@subset.subset) ref = Type: 'Font' BaseFont: @subset.postscriptName Subtype: 'TrueType' FontDescriptor: @descriptor FirstChar: firstChar LastChar: firstChar + charWidths.length - 1 Widths: @document.ref charWidths Encoding: 'MacRomanEncoding' ToUnicode: cmap for key, val of ref @ref.data[key] = val cmap.finalize(@document.compress, fn) # compress it toUnicodeCmap = (map) -> unicodeMap = ''' /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00><ff> endcodespacerange ''' codes = Object.keys(map).sort (a, b) -> a - b range = [] for code in codes if range.length >= 100 unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar" range = [] unicode = ('0000' + map[code].toString(16)).slice(-4) code = (+code).toString(16) range.push "<#{code}><#{unicode}>" unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar\n" if range.length unicodeMap += ''' endcmap CMapName currentdict /CMap defineresource pop end end ''' embedStandard: -> @isAFM = true font = AFMFont.open __dirname + "/font/data/#{@filename}.afm" {@ascender,@decender,@bbox,@lineGap,@charWidths} = font @ref = @document.ref Type: 'Font' BaseFont: @filename Subtype: 'Type1' _standardFonts: [ "Courier" "Courier-Bold" "Courier-Oblique" "Courier-BoldOblique" "Helvetica" "Helvetica-Bold" "Helvetica-Oblique" "Helvetica-BoldOblique" "Times-Roman" "Times-Bold" "Times-Italic" "Times-BoldItalic" "Symbol" "ZapfDingbats" ] widthOfString: (string, size) -> string = '' + string width = 0 for i in [0...string.length] charCode = string.charCodeAt(i) - if @isAFM then 0 else 32 width += @charWidths[charCode] or 0 scale = size / 1000 return width * scale heightOfString: (string, size, boundWidth) -> string = '' + string spaceLeft = boundWidth lines = 1 words = string.match(WORD_RE) wordLens = {} for word, i in words wordLen = wordLens[word] ?= @widthOfString(word, size) if word == '\n' spaceLeft = boundWidth lines++ else if wordLen > spaceLeft spaceLeft = boundWidth - wordLen lines++ else spaceLeft -= wordLen console.log("lines: " + lines) # if string[i] == '\n' # width = 0 # lines++ # else # charWidth = @widthOfString(string[i], size) # width += charWidth # if width > boundWidth # width = 0 # lines++ # includeGap = if lines > 1 then true else false # lastGap = (if includeGap then @lineGap else 0) / 1000 * size lineHeight = @lineHeight(size, true) lines * lineHeight # - lastGap lineHeight: (size, includeGap = false) -> gap = if includeGap then @lineGap else 0 (@ascender + gap - @decender) / 1000 * size module.exports = PDFFont
true
### PDFFont - embeds fonts in PDF documents By PI:NAME:<NAME>END_PI ### TTFFont = require './font/ttf' AFMFont = require './font/afm' Subset = require './font/subset' zlib = require 'zlib' WORD_RE = /([^ ,\/!.?:;\-\n]+[ ,\/!.?:;\-]*)|\n/g class PDFFont constructor: (@document, @filename, @family, @id) -> if @filename in @_standardFonts @embedStandard() else if /\.(ttf|ttc)$/i.test @filename @ttf = TTFFont.open @filename, @family @subset = new Subset @ttf @registerTTF() else if /\.dfont$/i.test @filename @ttf = TTFFont.fromDFont @filename, @family @subset = new Subset @ttf @registerTTF() else throw new Error 'Not a supported font format or standard PDF font.' use: (characters) -> @subset?.use characters embed: (fn) -> return fn() if @isAFM @embedTTF fn encode: (text) -> @subset?.encodeText(text) or text registerTTF: -> @scaleFactor = 1000.0 / @ttf.head.unitsPerEm @bbox = (Math.round e * @scaleFactor for e in @ttf.bbox) @stemV = 0 # not sure how to compute this for true-type fonts... if @ttf.post.exists raw = @ttf.post.italic_angle hi = raw >> 16 low = raw & 0xFF hi = -((hi ^ 0xFFFF) + 1) if hi & 0x8000 isnt 0 @italicAngle = +"#{hi}.#{low}" else @italicAngle = 0 @ascender = Math.round @ttf.ascender * @scaleFactor @decender = Math.round @ttf.decender * @scaleFactor @lineGap = Math.round @ttf.lineGap * @scaleFactor @capHeight = (@ttf.os2.exists and @ttf.os2.capHeight) or @ascender @xHeight = (@ttf.os2.exists and @ttf.os2.xHeight) or 0 @familyClass = (@ttf.os2.exists and @ttf.os2.familyClass or 0) >> 8 @isSerif = @familyClass in [1,2,3,4,5,7] @isScript = @familyClass is 10 @flags = 0 @flags |= 1 << 0 if @ttf.post.isFixedPitch @flags |= 1 << 1 if @isSerif @flags |= 1 << 3 if @isScript @flags |= 1 << 6 if @italicAngle isnt 0 @flags |= 1 << 5 # assume the font is nonsymbolic... @cmap = @ttf.cmap.unicode throw new Error 'No unicode cmap for font' if not @cmap @hmtx = @ttf.hmtx @charWidths = (Math.round @hmtx.widths[gid] * @scaleFactor for i, gid of @cmap.codeMap when i >= 32) # Create a placeholder reference to be filled in embedTTF. @ref = @document.ref Type: 'Font' Subtype: 'TrueType' embedTTF: (fn) -> data = @subset.encode() zlib.deflate data, (err, compressedData) => throw err if err @fontfile = @document.ref Length: compressedData.length Length1: data.length Filter: 'FlateDecode' @fontfile.add compressedData @descriptor = @document.ref Type: 'FontDescriptor' FontName: @subset.postscriptName FontFile2: @fontfile FontBBox: @bbox Flags: @flags StemV: @stemV ItalicAngle: @italicAngle Ascent: @ascender Descent: @decender CapHeight: @capHeight XHeight: @xHeight firstChar = +Object.keys(@subset.cmap)[0] charWidths = for code, glyph of @subset.cmap Math.round @ttf.hmtx.forGlyph(glyph).advance * @scaleFactor cmap = @document.ref() cmap.add toUnicodeCmap(@subset.subset) ref = Type: 'Font' BaseFont: @subset.postscriptName Subtype: 'TrueType' FontDescriptor: @descriptor FirstChar: firstChar LastChar: firstChar + charWidths.length - 1 Widths: @document.ref charWidths Encoding: 'MacRomanEncoding' ToUnicode: cmap for key, val of ref @ref.data[key] = val cmap.finalize(@document.compress, fn) # compress it toUnicodeCmap = (map) -> unicodeMap = ''' /CIDInit /ProcSet findresource begin 12 dict begin begincmap /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <00><ff> endcodespacerange ''' codes = Object.keys(map).sort (a, b) -> a - b range = [] for code in codes if range.length >= 100 unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar" range = [] unicode = ('0000' + map[code].toString(16)).slice(-4) code = (+code).toString(16) range.push "<#{code}><#{unicode}>" unicodeMap += "\n#{range.length} beginbfchar\n#{range.join('\n')}\nendbfchar\n" if range.length unicodeMap += ''' endcmap CMapName currentdict /CMap defineresource pop end end ''' embedStandard: -> @isAFM = true font = AFMFont.open __dirname + "/font/data/#{@filename}.afm" {@ascender,@decender,@bbox,@lineGap,@charWidths} = font @ref = @document.ref Type: 'Font' BaseFont: @filename Subtype: 'Type1' _standardFonts: [ "Courier" "Courier-Bold" "Courier-Oblique" "Courier-BoldOblique" "Helvetica" "Helvetica-Bold" "Helvetica-Oblique" "Helvetica-BoldOblique" "Times-Roman" "Times-Bold" "Times-Italic" "Times-BoldItalic" "Symbol" "ZapfDingbats" ] widthOfString: (string, size) -> string = '' + string width = 0 for i in [0...string.length] charCode = string.charCodeAt(i) - if @isAFM then 0 else 32 width += @charWidths[charCode] or 0 scale = size / 1000 return width * scale heightOfString: (string, size, boundWidth) -> string = '' + string spaceLeft = boundWidth lines = 1 words = string.match(WORD_RE) wordLens = {} for word, i in words wordLen = wordLens[word] ?= @widthOfString(word, size) if word == '\n' spaceLeft = boundWidth lines++ else if wordLen > spaceLeft spaceLeft = boundWidth - wordLen lines++ else spaceLeft -= wordLen console.log("lines: " + lines) # if string[i] == '\n' # width = 0 # lines++ # else # charWidth = @widthOfString(string[i], size) # width += charWidth # if width > boundWidth # width = 0 # lines++ # includeGap = if lines > 1 then true else false # lastGap = (if includeGap then @lineGap else 0) / 1000 * size lineHeight = @lineHeight(size, true) lines * lineHeight # - lastGap lineHeight: (size, includeGap = false) -> gap = if includeGap then @lineGap else 0 (@ascender + gap - @decender) / 1000 * size module.exports = PDFFont
[ { "context": " id: \"\"\n }\n )\n $scope.pass = $scope.$storage.pass\n $scope.id = $scope.$storage.id\n ", "end": 371, "score": 0.5431649088859558, "start": 371, "tag": "PASSWORD", "value": "" }, { "context": "\"\"\n }\n )\n $scope.pass = $scope.$storage.pass\n $scope.id = $scope.$storage.id\n \n $scop", "end": 385, "score": 0.5661558508872986, "start": 381, "tag": "PASSWORD", "value": "pass" } ]
cbt/app/scripts/controllers/config.coffee
cloneko/31days_2nd
0
'use strict' ###* # @ngdoc function # @name cbtApp.controller:ConfigCtrl # @description # # ConfigCtrl # Controller of the cbtApp ### angular.module 'cbtApp' .controller 'ConfigCtrl', ['$scope', '$localStorage', ($scope, $localStorage)-> $scope.$storage = $localStorage.$default( { pass: "", id: "" } ) $scope.pass = $scope.$storage.pass $scope.id = $scope.$storage.id $scope.setPass = -> $scope.$storage.pass = $scope.pass return $scope.setId = -> $scope.$storage.id = $scope.id return ]
191764
'use strict' ###* # @ngdoc function # @name cbtApp.controller:ConfigCtrl # @description # # ConfigCtrl # Controller of the cbtApp ### angular.module 'cbtApp' .controller 'ConfigCtrl', ['$scope', '$localStorage', ($scope, $localStorage)-> $scope.$storage = $localStorage.$default( { pass: "", id: "" } ) $scope.pass = $scope<PASSWORD>.$storage.<PASSWORD> $scope.id = $scope.$storage.id $scope.setPass = -> $scope.$storage.pass = $scope.pass return $scope.setId = -> $scope.$storage.id = $scope.id return ]
true
'use strict' ###* # @ngdoc function # @name cbtApp.controller:ConfigCtrl # @description # # ConfigCtrl # Controller of the cbtApp ### angular.module 'cbtApp' .controller 'ConfigCtrl', ['$scope', '$localStorage', ($scope, $localStorage)-> $scope.$storage = $localStorage.$default( { pass: "", id: "" } ) $scope.pass = $scopePI:PASSWORD:<PASSWORD>END_PI.$storage.PI:PASSWORD:<PASSWORD>END_PI $scope.id = $scope.$storage.id $scope.setPass = -> $scope.$storage.pass = $scope.pass return $scope.setId = -> $scope.$storage.id = $scope.id return ]
[ { "context": "essage)\n \n d = ->\n privateKeyBs58 = \"5JSSUaTbYeZxXt2btUKJhxU2KY1yvPvPs6eh329fSTHrCdRUGbS\"\n privateKeyBuffer = bs58.decode(privateKe", "end": 2064, "score": 0.9997751712799072, "start": 2013, "tag": "KEY", "value": "5JSSUaTbYeZxXt2btUKJhxU2KY1yvPvPs6eh329fSTHrCdRUGbS" } ]
programs/web_wallet/test/crypto/scratchpad/mailparse.coffee
larkx/LarkX
0
console.log "\n###\n#",process.argv[1],'\n#' {MailMessage} = require './src/mailmessage' ### echo 0770...c414 | xxd -r -p - - > _msg hexdump _msg -C ### MailMessageParse = -> ByteBuffer=require 'bytebuffer' data="077375626a656374c50231323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a656e64206f66207472616e736d697373696f6e0000000000000000000000000000000000000000001fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621fda8897890f0251e1f6dbc0e713b41f13e73c2cf031aea2e888fe54f3bd656d727a83fddb" mm=MailMessage.fromHex data ### process.stdout.write "Original:\t" ByteBuffer.fromHex(data).printDebug() console.log "subject\t\t", mm.subject console.log "body\t\t",mm.body console.log "reply_to\t", mm.reply_to.toHex() console.log "attachments (#{mm.attachments.length})\t",mm.attachments console.log "signature\t", mm.signature.toHex() ### if data isnt mm.toHex(true) process.stdout.write "\nRe-created:\t" mm.toByteBuffer(true).printDebug() throw "Messages do not match #{data} AND #{mm.toHex(true)}" return mm mailMessage = MailMessageParse() SignVerify = -> crypto = require('./src/crypto') ecdsa = require('./src/ecdsa') BigInteger = require('bigi') ecurve = require('ecurve') curve = ecurve.getCurveByName('secp256k1') bs58 = require('bs58') message = "abc" hash = crypto.sha256(message) d = -> privateKeyBs58 = "5JSSUaTbYeZxXt2btUKJhxU2KY1yvPvPs6eh329fSTHrCdRUGbS" privateKeyBuffer = bs58.decode(privateKeyBs58) privateKeyHex = privateKeyBuffer.toString("hex") BigInteger.fromHex(privateKeyHex) d = d() Q = curve.G.multiply(d) signature = ecdsa.sign(curve, hash, d) throw "does not verify" unless ecdsa.verify(curve, hash, signature, Q) throw "should not verify" if ecdsa.verify(curve, crypto.sha256("def"), signature, Q) SignVerify()
188448
console.log "\n###\n#",process.argv[1],'\n#' {MailMessage} = require './src/mailmessage' ### echo 0770...c414 | xxd -r -p - - > _msg hexdump _msg -C ### MailMessageParse = -> ByteBuffer=require 'bytebuffer' data="077375626a656374c50231323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a656e64206f66207472616e736d697373696f6e0000000000000000000000000000000000000000001fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621fda8897890f0251e1f6dbc0e713b41f13e73c2cf031aea2e888fe54f3bd656d727a83fddb" mm=MailMessage.fromHex data ### process.stdout.write "Original:\t" ByteBuffer.fromHex(data).printDebug() console.log "subject\t\t", mm.subject console.log "body\t\t",mm.body console.log "reply_to\t", mm.reply_to.toHex() console.log "attachments (#{mm.attachments.length})\t",mm.attachments console.log "signature\t", mm.signature.toHex() ### if data isnt mm.toHex(true) process.stdout.write "\nRe-created:\t" mm.toByteBuffer(true).printDebug() throw "Messages do not match #{data} AND #{mm.toHex(true)}" return mm mailMessage = MailMessageParse() SignVerify = -> crypto = require('./src/crypto') ecdsa = require('./src/ecdsa') BigInteger = require('bigi') ecurve = require('ecurve') curve = ecurve.getCurveByName('secp256k1') bs58 = require('bs58') message = "abc" hash = crypto.sha256(message) d = -> privateKeyBs58 = "<KEY>" privateKeyBuffer = bs58.decode(privateKeyBs58) privateKeyHex = privateKeyBuffer.toString("hex") BigInteger.fromHex(privateKeyHex) d = d() Q = curve.G.multiply(d) signature = ecdsa.sign(curve, hash, d) throw "does not verify" unless ecdsa.verify(curve, hash, signature, Q) throw "should not verify" if ecdsa.verify(curve, crypto.sha256("def"), signature, Q) SignVerify()
true
console.log "\n###\n#",process.argv[1],'\n#' {MailMessage} = require './src/mailmessage' ### echo 0770...c414 | xxd -r -p - - > _msg hexdump _msg -C ### MailMessageParse = -> ByteBuffer=require 'bytebuffer' data="077375626a656374c50231323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a656e64206f66207472616e736d697373696f6e0000000000000000000000000000000000000000001fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621fda8897890f0251e1f6dbc0e713b41f13e73c2cf031aea2e888fe54f3bd656d727a83fddb" mm=MailMessage.fromHex data ### process.stdout.write "Original:\t" ByteBuffer.fromHex(data).printDebug() console.log "subject\t\t", mm.subject console.log "body\t\t",mm.body console.log "reply_to\t", mm.reply_to.toHex() console.log "attachments (#{mm.attachments.length})\t",mm.attachments console.log "signature\t", mm.signature.toHex() ### if data isnt mm.toHex(true) process.stdout.write "\nRe-created:\t" mm.toByteBuffer(true).printDebug() throw "Messages do not match #{data} AND #{mm.toHex(true)}" return mm mailMessage = MailMessageParse() SignVerify = -> crypto = require('./src/crypto') ecdsa = require('./src/ecdsa') BigInteger = require('bigi') ecurve = require('ecurve') curve = ecurve.getCurveByName('secp256k1') bs58 = require('bs58') message = "abc" hash = crypto.sha256(message) d = -> privateKeyBs58 = "PI:KEY:<KEY>END_PI" privateKeyBuffer = bs58.decode(privateKeyBs58) privateKeyHex = privateKeyBuffer.toString("hex") BigInteger.fromHex(privateKeyHex) d = d() Q = curve.G.multiply(d) signature = ecdsa.sign(curve, hash, d) throw "does not verify" unless ecdsa.verify(curve, hash, signature, Q) throw "should not verify" if ecdsa.verify(curve, crypto.sha256("def"), signature, Q) SignVerify()
[ { "context": "app.use(express.session({\n #secret: 'fasr_42*@3paskr$2LQRkvQ',\n #store: new mongoStore({\n #url: co", "end": 1333, "score": 0.603668212890625, "start": 1318, "tag": "KEY", "value": "@3paskr$2LQRkvQ" } ]
src/config/express.coffee
poikilos/node-ticket-manager
81
# Module dependencies. express = require('express') mongoStore = require('connect-mongo')(express) flash = require('connect-flash') path = require "path" view_helper = require "../utils/view_helper" module.exports = (app, config, passport)-> app.set('showStackError', true) # should be placed before express.static app.use(express.compress({ filter: (req, res)-> return /json|text|javascript|css/.test(res.getHeader('Content-Type')) level: 9 })) app.use(express.static(config.root + '/public')) # don't use logger for test env app.use(express.logger('dev')) if (process.env.NODE_ENV isnt 'test') app.use(express.basicAuth(config.basicAuth.username, config.basicAuth.password)) # set views path, template engine and default layout pathToView = path.join config.root, '/views' console.log "[express::main] pathToView:#{pathToView}" app.set 'views', config.root + '/views' app.set 'view engine', 'jade' app.configure ()-> # dynamic helpers #app.use(helpers(config.app.name)) # cookieParser should be above session #app.use(express.cookieParser()) # bodyParser should be above methodOverride app.use(express.bodyParser()) app.use(express.methodOverride()) # express/mongo session storage #app.use(express.session({ #secret: 'fasr_42*@3paskr$2LQRkvQ', #store: new mongoStore({ #url: config.db, #collection : 'sessions' #}) #})) # connect flash for flash messages #app.use(flash()) # use passport session #app.use(passport.initialize()) #app.use(passport.session()) # routes should be at the last app.use(app.router) # assume "not found" in the error msgs # is a 404. this is somewhat silly, but # valid, you can do whatever you like, set # properties, use instanceof etc. app.use (err, req, res, next)-> # treat as 404 return next() if (~err.message.indexOf('not found')) # log it console.error(err.stack) # error page res.status(500).render('500', { error: err.stack }) # assume 404 since no middleware responded app.use (req, res, next)-> res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }) # 向每个view render 注入本地数据 app.locals VERSION : config.version APP_NAME : config.app.name helper : view_helper
199725
# Module dependencies. express = require('express') mongoStore = require('connect-mongo')(express) flash = require('connect-flash') path = require "path" view_helper = require "../utils/view_helper" module.exports = (app, config, passport)-> app.set('showStackError', true) # should be placed before express.static app.use(express.compress({ filter: (req, res)-> return /json|text|javascript|css/.test(res.getHeader('Content-Type')) level: 9 })) app.use(express.static(config.root + '/public')) # don't use logger for test env app.use(express.logger('dev')) if (process.env.NODE_ENV isnt 'test') app.use(express.basicAuth(config.basicAuth.username, config.basicAuth.password)) # set views path, template engine and default layout pathToView = path.join config.root, '/views' console.log "[express::main] pathToView:#{pathToView}" app.set 'views', config.root + '/views' app.set 'view engine', 'jade' app.configure ()-> # dynamic helpers #app.use(helpers(config.app.name)) # cookieParser should be above session #app.use(express.cookieParser()) # bodyParser should be above methodOverride app.use(express.bodyParser()) app.use(express.methodOverride()) # express/mongo session storage #app.use(express.session({ #secret: 'fasr_42*<KEY>', #store: new mongoStore({ #url: config.db, #collection : 'sessions' #}) #})) # connect flash for flash messages #app.use(flash()) # use passport session #app.use(passport.initialize()) #app.use(passport.session()) # routes should be at the last app.use(app.router) # assume "not found" in the error msgs # is a 404. this is somewhat silly, but # valid, you can do whatever you like, set # properties, use instanceof etc. app.use (err, req, res, next)-> # treat as 404 return next() if (~err.message.indexOf('not found')) # log it console.error(err.stack) # error page res.status(500).render('500', { error: err.stack }) # assume 404 since no middleware responded app.use (req, res, next)-> res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }) # 向每个view render 注入本地数据 app.locals VERSION : config.version APP_NAME : config.app.name helper : view_helper
true
# Module dependencies. express = require('express') mongoStore = require('connect-mongo')(express) flash = require('connect-flash') path = require "path" view_helper = require "../utils/view_helper" module.exports = (app, config, passport)-> app.set('showStackError', true) # should be placed before express.static app.use(express.compress({ filter: (req, res)-> return /json|text|javascript|css/.test(res.getHeader('Content-Type')) level: 9 })) app.use(express.static(config.root + '/public')) # don't use logger for test env app.use(express.logger('dev')) if (process.env.NODE_ENV isnt 'test') app.use(express.basicAuth(config.basicAuth.username, config.basicAuth.password)) # set views path, template engine and default layout pathToView = path.join config.root, '/views' console.log "[express::main] pathToView:#{pathToView}" app.set 'views', config.root + '/views' app.set 'view engine', 'jade' app.configure ()-> # dynamic helpers #app.use(helpers(config.app.name)) # cookieParser should be above session #app.use(express.cookieParser()) # bodyParser should be above methodOverride app.use(express.bodyParser()) app.use(express.methodOverride()) # express/mongo session storage #app.use(express.session({ #secret: 'fasr_42*PI:KEY:<KEY>END_PI', #store: new mongoStore({ #url: config.db, #collection : 'sessions' #}) #})) # connect flash for flash messages #app.use(flash()) # use passport session #app.use(passport.initialize()) #app.use(passport.session()) # routes should be at the last app.use(app.router) # assume "not found" in the error msgs # is a 404. this is somewhat silly, but # valid, you can do whatever you like, set # properties, use instanceof etc. app.use (err, req, res, next)-> # treat as 404 return next() if (~err.message.indexOf('not found')) # log it console.error(err.stack) # error page res.status(500).render('500', { error: err.stack }) # assume 404 since no middleware responded app.use (req, res, next)-> res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }) # 向每个view render 注入本地数据 app.locals VERSION : config.version APP_NAME : config.app.name helper : view_helper
[ { "context": "ntSideValidations::VERSION %> (https://github.com/DavyJonesLocker/client_side_validations)\n * Copyright (c) <%= Dat", "end": 108, "score": 0.998284637928009, "start": 93, "tag": "USERNAME", "value": "DavyJonesLocker" }, { "context": "dations)\n * Copyright (c) <%= DateTime.now.year %> Geremia Taglialatela, Brian Cardarella\n * Licensed under MIT (https://", "end": 196, "score": 0.9998804926872253, "start": 176, "tag": "NAME", "value": "Geremia Taglialatela" }, { "context": "(c) <%= DateTime.now.year %> Geremia Taglialatela, Brian Cardarella\n * Licensed under MIT (https://opensource.org/lic", "end": 214, "score": 0.9998672604560852, "start": 198, "tag": "NAME", "value": "Brian Cardarella" } ]
coffeescript/rails.validations.coffee
AbelToy/client_side_validations
0
###! * Client Side Validations - v<%= ClientSideValidations::VERSION %> (https://github.com/DavyJonesLocker/client_side_validations) * Copyright (c) <%= DateTime.now.year %> Geremia Taglialatela, Brian Cardarella * Licensed under MIT (https://opensource.org/licenses/mit-license.php) ### $ = jQuery $.fn.disableClientSideValidations = -> ClientSideValidations.disable(@) @ $.fn.enableClientSideValidations = -> @filter(ClientSideValidations.selectors.forms).each -> ClientSideValidations.enablers.form(@) @filter(ClientSideValidations.selectors.inputs).each -> ClientSideValidations.enablers.input(@) @ $.fn.resetClientSideValidations = -> @filter(ClientSideValidations.selectors.forms).each -> ClientSideValidations.reset(@) @ $.fn.validate = -> @filter(ClientSideValidations.selectors.forms).each -> $(@).enableClientSideValidations() @ $.fn.isValid = (validators) -> obj = $(@[0]) if obj.is('form') validateForm(obj, validators) else validateElement(obj, validatorsFor(@[0].name, validators)) validatorsFor = (name, validators) -> return validators[name] if validators.hasOwnProperty(name) name = name.replace(/\[(\w+_attributes)\]\[[\da-z_]+\](?=\[(?:\w+_attributes)\])/g, '[$1][]') if captures = name.match /\[(\w+_attributes)\].*\[(\w+)\]$/ for validator_name, validator of validators if validator_name.match "\\[#{captures[1]}\\].*\\[\\]\\[#{captures[2]}\\]$" name = name.replace /\[[\da-z_]+\]\[(\w+)\]$/g, '[][$1]' validators[name] || {} validateForm = (form, validators) -> form.trigger('form:validate:before.ClientSideValidations') valid = true form.find(ClientSideValidations.selectors.validate_inputs).each -> valid = false unless $(@).isValid(validators) # we don't want the loop to break out by mistake true if valid form.trigger('form:validate:pass.ClientSideValidations') else form.trigger('form:validate:fail.ClientSideValidations') form.trigger('form:validate:after.ClientSideValidations') valid validateElement = (element, validators) -> element.trigger('element:validate:before.ClientSideValidations') passElement = -> element.trigger('element:validate:pass.ClientSideValidations').data('valid', null) failElement = (message) -> element.trigger('element:validate:fail.ClientSideValidations', message).data('valid', false) false afterValidate = -> element.trigger('element:validate:after.ClientSideValidations').data('valid') != false executeValidators = (context) -> valid = true for kind, fn of context if validators[kind] for validator in validators[kind] if message = fn.call(context, element, validator) valid = failElement(message) break unless valid break valid # if _destroy for this input group == "1" pass with flying colours, it'll get deleted anyway.. if element.attr('name').search(/\[([^\]]*?)\]$/) >= 0 destroyInputName = element.attr('name').replace(/\[([^\]]*?)\]$/, '[_destroy]') if $("input[name='#{destroyInputName}']").val() == '1' passElement() return afterValidate() # if the value hasn't changed since last validation, do nothing unless element.data('changed') != false return afterValidate() element.data('changed', false) local = ClientSideValidations.validators.local remote = ClientSideValidations.validators.remote if executeValidators(local) and executeValidators(remote) passElement() afterValidate() ClientSideValidations = callbacks: element: after: (element, eventData) -> before: (element, eventData) -> fail: (element, message, addError, eventData) -> addError() pass: (element, removeError, eventData) -> removeError() form: after: (form, eventData) -> before: (form, eventData) -> fail: (form, eventData) -> pass: (form, eventData) -> enablers: form: (form) -> $form = $(form) form.ClientSideValidations = settings: $form.data('clientSideValidations') addError: (element, message) -> ClientSideValidations.formBuilders[form.ClientSideValidations.settings.html_settings.type].add(element, form.ClientSideValidations.settings.html_settings, message) removeError: (element) -> ClientSideValidations.formBuilders[form.ClientSideValidations.settings.html_settings.type].remove(element, form.ClientSideValidations.settings.html_settings) # Set up the events for the form $form.on(event, binding) for event, binding of { 'submit.ClientSideValidations' : (eventData) -> unless $form.isValid(form.ClientSideValidations.settings.validators) eventData.preventDefault() eventData.stopImmediatePropagation() return 'ajax:beforeSend.ClientSideValidations' : (eventData) -> $form.isValid(form.ClientSideValidations.settings.validators) if eventData.target == @ return 'form:validate:after.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.after( $form, eventData) return 'form:validate:before.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.form.before($form, eventData) return 'form:validate:fail.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.fail( $form, eventData) return 'form:validate:pass.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.pass( $form, eventData) return } $form.find(ClientSideValidations.selectors.inputs).each -> ClientSideValidations.enablers.input(@) input: (input) -> $input = $(input) form = input.form $form = $(form) $input.filter(':not(:radio):not([id$=_confirmation])') .each -> $(@).attr('data-validate', true) .on(event, binding) for event, binding of { 'focusout.ClientSideValidations': -> $(@).isValid(form.ClientSideValidations.settings.validators) return 'change.ClientSideValidations': -> $(@).data('changed', true) return # Callbacks 'element:validate:after.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.element.after($(@), eventData) return 'element:validate:before.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.element.before($(@), eventData) return 'element:validate:fail.ClientSideValidations': (eventData, message) -> element = $(@) ClientSideValidations.callbacks.element.fail(element, message, -> form.ClientSideValidations.addError(element, message) , eventData) return 'element:validate:pass.ClientSideValidations': (eventData) -> element = $(@) ClientSideValidations.callbacks.element.pass(element, -> form.ClientSideValidations.removeError(element) , eventData) return } # This is 'change' instead of 'click' to avoid problems with jQuery versions < 1.9 # Look this https://jquery.com/upgrade-guide/1.9/#checkbox-radio-state-in-a-trigger-ed-click-event for more details $input.filter(':checkbox').on('change.ClientSideValidations', -> $(@).isValid(form.ClientSideValidations.settings.validators) return ) # Inputs for confirmations $input.filter('[id$=_confirmation]').each -> confirmationElement = $(@) element = $form.find("##{@id.match(/(.+)_confirmation/)[1]}:input") if element[0] $("##{confirmationElement.attr('id')}").on(event, binding) for event, binding of { 'focusout.ClientSideValidations': -> element.data('changed', true).isValid(form.ClientSideValidations.settings.validators) return 'keyup.ClientSideValidations' : -> element.data('changed', true).isValid(form.ClientSideValidations.settings.validators) return } formBuilders: 'ActionView::Helpers::FormBuilder': add: (element, settings, message) -> form = $(element[0].form) if element.data('valid') != false and not form.find("label.message[for='#{element.attr('id')}']")[0]? inputErrorField = $(settings.input_tag) labelErrorField = $(settings.label_tag) label = form.find("label[for='#{element.attr('id')}']:not(.message)") element.attr('autofocus', false) if element.attr('autofocus') element.before(inputErrorField) inputErrorField.find('span#input_tag').replaceWith(element) inputErrorField.find('label.message').attr('for', element.attr('id')) labelErrorField.find('label.message').attr('for', element.attr('id')) labelErrorField.insertAfter(label) labelErrorField.find('label#label_tag').replaceWith(label) form.find("label.message[for='#{element.attr('id')}']").text(message) remove: (element, settings) -> form = $(element[0].form) errorFieldClass = $(settings.input_tag).attr('class') inputErrorField = element.closest(".#{errorFieldClass.replace(/\ /g, ".")}") label = form.find("label[for='#{element.attr('id')}']:not(.message)") labelErrorField = label.closest(".#{errorFieldClass}") if inputErrorField[0] inputErrorField.find("##{element.attr('id')}").detach() inputErrorField.replaceWith(element) label.detach() labelErrorField.replaceWith(label) patterns: numericality: default: new RegExp('^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$') only_integer: new RegExp('^[+-]?\\d+$') selectors: inputs: ':input:not(button):not([type="submit"])[name]:visible:enabled' validate_inputs: ':input:enabled:visible[data-validate]' forms: 'form[data-client-side-validations]' validators: all: -> $.extend({}, local, remote) local: absence: (element, options) -> options.message unless /^\s*$/.test(element.val() || '') presence: (element, options) -> options.message if /^\s*$/.test(element.val() || '') acceptance: (element, options) -> switch element.attr('type') when 'checkbox' unless element.prop('checked') return options.message when 'text' if element.val() != (options.accept?.toString() || '1') return options.message format: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message return options.message if options.with and !new RegExp(options.with.source, options.with.options).test(element.val()) return options.message if options.without and new RegExp(options.without.source, options.without.options).test(element.val()) numericality: (element, options) -> return if options.allow_blank == true and @presence(element, { message: options.messages.numericality }) $form = $(element[0].form) number_format = $form[0].ClientSideValidations.settings.number_format val = $.trim(element.val()).replace(new RegExp("\\#{number_format.separator}", 'g'), '.') if options.only_integer and !ClientSideValidations.patterns.numericality.only_integer.test(val) return options.messages.only_integer unless ClientSideValidations.patterns.numericality.default.test(val) return options.messages.numericality NUMERICALITY_CHECKS = greater_than: (a, b) -> a > b greater_than_or_equal_to: (a, b) -> a >= b equal_to: (a, b) -> a == b less_than: (a, b) -> return a < b less_than_or_equal_to: (a, b) -> return a <= b # options[check] may be 0 so we must check for undefined for check, check_function of NUMERICALITY_CHECKS when options[check]? checkValue = if !isNaN(parseFloat(options[check])) && isFinite(options[check]) options[check] else if $form.find("[name*=#{options[check]}]").length == 1 $form.find("[name*=#{options[check]}]").val() if !checkValue? || checkValue is '' return return options.messages[check] unless check_function(parseFloat(val), parseFloat(checkValue)) if options.odd and !(parseInt(val, 10) % 2) return options.messages.odd if options.even and (parseInt(val, 10) % 2) return options.messages.even length: (element, options) -> length = element.val().length LENGTH_CHECKS = is: (a, b) -> a == b minimum: (a, b) -> a >= b maximum: (a, b) -> a <= b blankOptions = {} blankOptions.message = if options.is options.messages.is else if options.minimum options.messages.minimum message = @presence(element, blankOptions) if message return if options.allow_blank == true return message for check, check_function of LENGTH_CHECKS when options[check] return options.messages[check] unless check_function(length, parseInt(options[check])) exclusion: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message if options.in return options.message if element.val() in (option.toString() for option in options.in) if options.range lower = options.range[0] upper = options.range[1] return options.message if element.val() >= lower and element.val() <= upper inclusion: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message if options.in return if element.val() in (option.toString() for option in options.in) return options.message if options.range lower = options.range[0] upper = options.range[1] return if element.val() >= lower and element.val() <= upper return options.message confirmation: (element, options) -> value = element.val() confirmation_value = $("##{element.attr('id')}_confirmation").val() unless options.case_sensitive value = value.toLowerCase() confirmation_value = confirmation_value.toLowerCase() unless value == confirmation_value return options.message uniqueness: (element, options) -> name = element.attr('name') # only check uniqueness if we're in a nested form if /_attributes\]\[\d/.test(name) matches = name.match(/^(.+_attributes\])\[\d+\](.+)$/) name_prefix = matches[1] name_suffix = matches[2] value = element.val() if name_prefix && name_suffix form = element.closest('form') valid = true form.find(":input[name^=\"#{name_prefix}\"][name$=\"#{name_suffix}\"]").each -> other_value = $(@).val() unless options.case_sensitive value = value.toLowerCase() other_value = other_value.toLowerCase() if $(@).attr('name') != name if other_value == value valid = false $(@).data('notLocallyUnique', true) else # items that were locally non-unique which become locally unique need to be # marked as changed, so they will get revalidated and thereby have their # error state cleared. but we should only do this once; therefore the # notLocallyUnique flag. if $(this).data('notLocallyUnique') $(this) .removeData('notLocallyUnique') .data('changed', true) return options.message unless valid remote: {} disable: (target) -> $target = $(target) $target.off('.ClientSideValidations') if $target.is('form') ClientSideValidations.disable($target.find(':input')) else $target.removeData('valid') $target.removeData('changed') $target.filter(':input').each -> $(@).removeAttr('data-validate') reset: (form) -> $form = $(form) ClientSideValidations.disable(form) for key of form.ClientSideValidations.settings.validators form.ClientSideValidations.removeError($form.find("[name='#{key}']")) ClientSideValidations.enablers.form(form) # Main hook # If new forms are dynamically introduced into the DOM, the .validate() method # must be invoked on that form if window.Turbolinks? and window.Turbolinks.supported # Turbolinks and Turbolinks Classic don't use the same event, so we will try to # detect Turbolinks Classic by the EVENT hash, which is not defined # in the new 5.0 version. initializeOnEvent = if window.Turbolinks.EVENTS? 'page:change' else 'turbolinks:load' $(document).on initializeOnEvent, -> $(ClientSideValidations.selectors.forms).validate() else $ -> $(ClientSideValidations.selectors.forms).validate() window.ClientSideValidations = ClientSideValidations
140484
###! * Client Side Validations - v<%= ClientSideValidations::VERSION %> (https://github.com/DavyJonesLocker/client_side_validations) * Copyright (c) <%= DateTime.now.year %> <NAME>, <NAME> * Licensed under MIT (https://opensource.org/licenses/mit-license.php) ### $ = jQuery $.fn.disableClientSideValidations = -> ClientSideValidations.disable(@) @ $.fn.enableClientSideValidations = -> @filter(ClientSideValidations.selectors.forms).each -> ClientSideValidations.enablers.form(@) @filter(ClientSideValidations.selectors.inputs).each -> ClientSideValidations.enablers.input(@) @ $.fn.resetClientSideValidations = -> @filter(ClientSideValidations.selectors.forms).each -> ClientSideValidations.reset(@) @ $.fn.validate = -> @filter(ClientSideValidations.selectors.forms).each -> $(@).enableClientSideValidations() @ $.fn.isValid = (validators) -> obj = $(@[0]) if obj.is('form') validateForm(obj, validators) else validateElement(obj, validatorsFor(@[0].name, validators)) validatorsFor = (name, validators) -> return validators[name] if validators.hasOwnProperty(name) name = name.replace(/\[(\w+_attributes)\]\[[\da-z_]+\](?=\[(?:\w+_attributes)\])/g, '[$1][]') if captures = name.match /\[(\w+_attributes)\].*\[(\w+)\]$/ for validator_name, validator of validators if validator_name.match "\\[#{captures[1]}\\].*\\[\\]\\[#{captures[2]}\\]$" name = name.replace /\[[\da-z_]+\]\[(\w+)\]$/g, '[][$1]' validators[name] || {} validateForm = (form, validators) -> form.trigger('form:validate:before.ClientSideValidations') valid = true form.find(ClientSideValidations.selectors.validate_inputs).each -> valid = false unless $(@).isValid(validators) # we don't want the loop to break out by mistake true if valid form.trigger('form:validate:pass.ClientSideValidations') else form.trigger('form:validate:fail.ClientSideValidations') form.trigger('form:validate:after.ClientSideValidations') valid validateElement = (element, validators) -> element.trigger('element:validate:before.ClientSideValidations') passElement = -> element.trigger('element:validate:pass.ClientSideValidations').data('valid', null) failElement = (message) -> element.trigger('element:validate:fail.ClientSideValidations', message).data('valid', false) false afterValidate = -> element.trigger('element:validate:after.ClientSideValidations').data('valid') != false executeValidators = (context) -> valid = true for kind, fn of context if validators[kind] for validator in validators[kind] if message = fn.call(context, element, validator) valid = failElement(message) break unless valid break valid # if _destroy for this input group == "1" pass with flying colours, it'll get deleted anyway.. if element.attr('name').search(/\[([^\]]*?)\]$/) >= 0 destroyInputName = element.attr('name').replace(/\[([^\]]*?)\]$/, '[_destroy]') if $("input[name='#{destroyInputName}']").val() == '1' passElement() return afterValidate() # if the value hasn't changed since last validation, do nothing unless element.data('changed') != false return afterValidate() element.data('changed', false) local = ClientSideValidations.validators.local remote = ClientSideValidations.validators.remote if executeValidators(local) and executeValidators(remote) passElement() afterValidate() ClientSideValidations = callbacks: element: after: (element, eventData) -> before: (element, eventData) -> fail: (element, message, addError, eventData) -> addError() pass: (element, removeError, eventData) -> removeError() form: after: (form, eventData) -> before: (form, eventData) -> fail: (form, eventData) -> pass: (form, eventData) -> enablers: form: (form) -> $form = $(form) form.ClientSideValidations = settings: $form.data('clientSideValidations') addError: (element, message) -> ClientSideValidations.formBuilders[form.ClientSideValidations.settings.html_settings.type].add(element, form.ClientSideValidations.settings.html_settings, message) removeError: (element) -> ClientSideValidations.formBuilders[form.ClientSideValidations.settings.html_settings.type].remove(element, form.ClientSideValidations.settings.html_settings) # Set up the events for the form $form.on(event, binding) for event, binding of { 'submit.ClientSideValidations' : (eventData) -> unless $form.isValid(form.ClientSideValidations.settings.validators) eventData.preventDefault() eventData.stopImmediatePropagation() return 'ajax:beforeSend.ClientSideValidations' : (eventData) -> $form.isValid(form.ClientSideValidations.settings.validators) if eventData.target == @ return 'form:validate:after.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.after( $form, eventData) return 'form:validate:before.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.form.before($form, eventData) return 'form:validate:fail.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.fail( $form, eventData) return 'form:validate:pass.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.pass( $form, eventData) return } $form.find(ClientSideValidations.selectors.inputs).each -> ClientSideValidations.enablers.input(@) input: (input) -> $input = $(input) form = input.form $form = $(form) $input.filter(':not(:radio):not([id$=_confirmation])') .each -> $(@).attr('data-validate', true) .on(event, binding) for event, binding of { 'focusout.ClientSideValidations': -> $(@).isValid(form.ClientSideValidations.settings.validators) return 'change.ClientSideValidations': -> $(@).data('changed', true) return # Callbacks 'element:validate:after.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.element.after($(@), eventData) return 'element:validate:before.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.element.before($(@), eventData) return 'element:validate:fail.ClientSideValidations': (eventData, message) -> element = $(@) ClientSideValidations.callbacks.element.fail(element, message, -> form.ClientSideValidations.addError(element, message) , eventData) return 'element:validate:pass.ClientSideValidations': (eventData) -> element = $(@) ClientSideValidations.callbacks.element.pass(element, -> form.ClientSideValidations.removeError(element) , eventData) return } # This is 'change' instead of 'click' to avoid problems with jQuery versions < 1.9 # Look this https://jquery.com/upgrade-guide/1.9/#checkbox-radio-state-in-a-trigger-ed-click-event for more details $input.filter(':checkbox').on('change.ClientSideValidations', -> $(@).isValid(form.ClientSideValidations.settings.validators) return ) # Inputs for confirmations $input.filter('[id$=_confirmation]').each -> confirmationElement = $(@) element = $form.find("##{@id.match(/(.+)_confirmation/)[1]}:input") if element[0] $("##{confirmationElement.attr('id')}").on(event, binding) for event, binding of { 'focusout.ClientSideValidations': -> element.data('changed', true).isValid(form.ClientSideValidations.settings.validators) return 'keyup.ClientSideValidations' : -> element.data('changed', true).isValid(form.ClientSideValidations.settings.validators) return } formBuilders: 'ActionView::Helpers::FormBuilder': add: (element, settings, message) -> form = $(element[0].form) if element.data('valid') != false and not form.find("label.message[for='#{element.attr('id')}']")[0]? inputErrorField = $(settings.input_tag) labelErrorField = $(settings.label_tag) label = form.find("label[for='#{element.attr('id')}']:not(.message)") element.attr('autofocus', false) if element.attr('autofocus') element.before(inputErrorField) inputErrorField.find('span#input_tag').replaceWith(element) inputErrorField.find('label.message').attr('for', element.attr('id')) labelErrorField.find('label.message').attr('for', element.attr('id')) labelErrorField.insertAfter(label) labelErrorField.find('label#label_tag').replaceWith(label) form.find("label.message[for='#{element.attr('id')}']").text(message) remove: (element, settings) -> form = $(element[0].form) errorFieldClass = $(settings.input_tag).attr('class') inputErrorField = element.closest(".#{errorFieldClass.replace(/\ /g, ".")}") label = form.find("label[for='#{element.attr('id')}']:not(.message)") labelErrorField = label.closest(".#{errorFieldClass}") if inputErrorField[0] inputErrorField.find("##{element.attr('id')}").detach() inputErrorField.replaceWith(element) label.detach() labelErrorField.replaceWith(label) patterns: numericality: default: new RegExp('^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$') only_integer: new RegExp('^[+-]?\\d+$') selectors: inputs: ':input:not(button):not([type="submit"])[name]:visible:enabled' validate_inputs: ':input:enabled:visible[data-validate]' forms: 'form[data-client-side-validations]' validators: all: -> $.extend({}, local, remote) local: absence: (element, options) -> options.message unless /^\s*$/.test(element.val() || '') presence: (element, options) -> options.message if /^\s*$/.test(element.val() || '') acceptance: (element, options) -> switch element.attr('type') when 'checkbox' unless element.prop('checked') return options.message when 'text' if element.val() != (options.accept?.toString() || '1') return options.message format: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message return options.message if options.with and !new RegExp(options.with.source, options.with.options).test(element.val()) return options.message if options.without and new RegExp(options.without.source, options.without.options).test(element.val()) numericality: (element, options) -> return if options.allow_blank == true and @presence(element, { message: options.messages.numericality }) $form = $(element[0].form) number_format = $form[0].ClientSideValidations.settings.number_format val = $.trim(element.val()).replace(new RegExp("\\#{number_format.separator}", 'g'), '.') if options.only_integer and !ClientSideValidations.patterns.numericality.only_integer.test(val) return options.messages.only_integer unless ClientSideValidations.patterns.numericality.default.test(val) return options.messages.numericality NUMERICALITY_CHECKS = greater_than: (a, b) -> a > b greater_than_or_equal_to: (a, b) -> a >= b equal_to: (a, b) -> a == b less_than: (a, b) -> return a < b less_than_or_equal_to: (a, b) -> return a <= b # options[check] may be 0 so we must check for undefined for check, check_function of NUMERICALITY_CHECKS when options[check]? checkValue = if !isNaN(parseFloat(options[check])) && isFinite(options[check]) options[check] else if $form.find("[name*=#{options[check]}]").length == 1 $form.find("[name*=#{options[check]}]").val() if !checkValue? || checkValue is '' return return options.messages[check] unless check_function(parseFloat(val), parseFloat(checkValue)) if options.odd and !(parseInt(val, 10) % 2) return options.messages.odd if options.even and (parseInt(val, 10) % 2) return options.messages.even length: (element, options) -> length = element.val().length LENGTH_CHECKS = is: (a, b) -> a == b minimum: (a, b) -> a >= b maximum: (a, b) -> a <= b blankOptions = {} blankOptions.message = if options.is options.messages.is else if options.minimum options.messages.minimum message = @presence(element, blankOptions) if message return if options.allow_blank == true return message for check, check_function of LENGTH_CHECKS when options[check] return options.messages[check] unless check_function(length, parseInt(options[check])) exclusion: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message if options.in return options.message if element.val() in (option.toString() for option in options.in) if options.range lower = options.range[0] upper = options.range[1] return options.message if element.val() >= lower and element.val() <= upper inclusion: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message if options.in return if element.val() in (option.toString() for option in options.in) return options.message if options.range lower = options.range[0] upper = options.range[1] return if element.val() >= lower and element.val() <= upper return options.message confirmation: (element, options) -> value = element.val() confirmation_value = $("##{element.attr('id')}_confirmation").val() unless options.case_sensitive value = value.toLowerCase() confirmation_value = confirmation_value.toLowerCase() unless value == confirmation_value return options.message uniqueness: (element, options) -> name = element.attr('name') # only check uniqueness if we're in a nested form if /_attributes\]\[\d/.test(name) matches = name.match(/^(.+_attributes\])\[\d+\](.+)$/) name_prefix = matches[1] name_suffix = matches[2] value = element.val() if name_prefix && name_suffix form = element.closest('form') valid = true form.find(":input[name^=\"#{name_prefix}\"][name$=\"#{name_suffix}\"]").each -> other_value = $(@).val() unless options.case_sensitive value = value.toLowerCase() other_value = other_value.toLowerCase() if $(@).attr('name') != name if other_value == value valid = false $(@).data('notLocallyUnique', true) else # items that were locally non-unique which become locally unique need to be # marked as changed, so they will get revalidated and thereby have their # error state cleared. but we should only do this once; therefore the # notLocallyUnique flag. if $(this).data('notLocallyUnique') $(this) .removeData('notLocallyUnique') .data('changed', true) return options.message unless valid remote: {} disable: (target) -> $target = $(target) $target.off('.ClientSideValidations') if $target.is('form') ClientSideValidations.disable($target.find(':input')) else $target.removeData('valid') $target.removeData('changed') $target.filter(':input').each -> $(@).removeAttr('data-validate') reset: (form) -> $form = $(form) ClientSideValidations.disable(form) for key of form.ClientSideValidations.settings.validators form.ClientSideValidations.removeError($form.find("[name='#{key}']")) ClientSideValidations.enablers.form(form) # Main hook # If new forms are dynamically introduced into the DOM, the .validate() method # must be invoked on that form if window.Turbolinks? and window.Turbolinks.supported # Turbolinks and Turbolinks Classic don't use the same event, so we will try to # detect Turbolinks Classic by the EVENT hash, which is not defined # in the new 5.0 version. initializeOnEvent = if window.Turbolinks.EVENTS? 'page:change' else 'turbolinks:load' $(document).on initializeOnEvent, -> $(ClientSideValidations.selectors.forms).validate() else $ -> $(ClientSideValidations.selectors.forms).validate() window.ClientSideValidations = ClientSideValidations
true
###! * Client Side Validations - v<%= ClientSideValidations::VERSION %> (https://github.com/DavyJonesLocker/client_side_validations) * Copyright (c) <%= DateTime.now.year %> PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI * Licensed under MIT (https://opensource.org/licenses/mit-license.php) ### $ = jQuery $.fn.disableClientSideValidations = -> ClientSideValidations.disable(@) @ $.fn.enableClientSideValidations = -> @filter(ClientSideValidations.selectors.forms).each -> ClientSideValidations.enablers.form(@) @filter(ClientSideValidations.selectors.inputs).each -> ClientSideValidations.enablers.input(@) @ $.fn.resetClientSideValidations = -> @filter(ClientSideValidations.selectors.forms).each -> ClientSideValidations.reset(@) @ $.fn.validate = -> @filter(ClientSideValidations.selectors.forms).each -> $(@).enableClientSideValidations() @ $.fn.isValid = (validators) -> obj = $(@[0]) if obj.is('form') validateForm(obj, validators) else validateElement(obj, validatorsFor(@[0].name, validators)) validatorsFor = (name, validators) -> return validators[name] if validators.hasOwnProperty(name) name = name.replace(/\[(\w+_attributes)\]\[[\da-z_]+\](?=\[(?:\w+_attributes)\])/g, '[$1][]') if captures = name.match /\[(\w+_attributes)\].*\[(\w+)\]$/ for validator_name, validator of validators if validator_name.match "\\[#{captures[1]}\\].*\\[\\]\\[#{captures[2]}\\]$" name = name.replace /\[[\da-z_]+\]\[(\w+)\]$/g, '[][$1]' validators[name] || {} validateForm = (form, validators) -> form.trigger('form:validate:before.ClientSideValidations') valid = true form.find(ClientSideValidations.selectors.validate_inputs).each -> valid = false unless $(@).isValid(validators) # we don't want the loop to break out by mistake true if valid form.trigger('form:validate:pass.ClientSideValidations') else form.trigger('form:validate:fail.ClientSideValidations') form.trigger('form:validate:after.ClientSideValidations') valid validateElement = (element, validators) -> element.trigger('element:validate:before.ClientSideValidations') passElement = -> element.trigger('element:validate:pass.ClientSideValidations').data('valid', null) failElement = (message) -> element.trigger('element:validate:fail.ClientSideValidations', message).data('valid', false) false afterValidate = -> element.trigger('element:validate:after.ClientSideValidations').data('valid') != false executeValidators = (context) -> valid = true for kind, fn of context if validators[kind] for validator in validators[kind] if message = fn.call(context, element, validator) valid = failElement(message) break unless valid break valid # if _destroy for this input group == "1" pass with flying colours, it'll get deleted anyway.. if element.attr('name').search(/\[([^\]]*?)\]$/) >= 0 destroyInputName = element.attr('name').replace(/\[([^\]]*?)\]$/, '[_destroy]') if $("input[name='#{destroyInputName}']").val() == '1' passElement() return afterValidate() # if the value hasn't changed since last validation, do nothing unless element.data('changed') != false return afterValidate() element.data('changed', false) local = ClientSideValidations.validators.local remote = ClientSideValidations.validators.remote if executeValidators(local) and executeValidators(remote) passElement() afterValidate() ClientSideValidations = callbacks: element: after: (element, eventData) -> before: (element, eventData) -> fail: (element, message, addError, eventData) -> addError() pass: (element, removeError, eventData) -> removeError() form: after: (form, eventData) -> before: (form, eventData) -> fail: (form, eventData) -> pass: (form, eventData) -> enablers: form: (form) -> $form = $(form) form.ClientSideValidations = settings: $form.data('clientSideValidations') addError: (element, message) -> ClientSideValidations.formBuilders[form.ClientSideValidations.settings.html_settings.type].add(element, form.ClientSideValidations.settings.html_settings, message) removeError: (element) -> ClientSideValidations.formBuilders[form.ClientSideValidations.settings.html_settings.type].remove(element, form.ClientSideValidations.settings.html_settings) # Set up the events for the form $form.on(event, binding) for event, binding of { 'submit.ClientSideValidations' : (eventData) -> unless $form.isValid(form.ClientSideValidations.settings.validators) eventData.preventDefault() eventData.stopImmediatePropagation() return 'ajax:beforeSend.ClientSideValidations' : (eventData) -> $form.isValid(form.ClientSideValidations.settings.validators) if eventData.target == @ return 'form:validate:after.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.after( $form, eventData) return 'form:validate:before.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.form.before($form, eventData) return 'form:validate:fail.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.fail( $form, eventData) return 'form:validate:pass.ClientSideValidations' : (eventData) -> ClientSideValidations.callbacks.form.pass( $form, eventData) return } $form.find(ClientSideValidations.selectors.inputs).each -> ClientSideValidations.enablers.input(@) input: (input) -> $input = $(input) form = input.form $form = $(form) $input.filter(':not(:radio):not([id$=_confirmation])') .each -> $(@).attr('data-validate', true) .on(event, binding) for event, binding of { 'focusout.ClientSideValidations': -> $(@).isValid(form.ClientSideValidations.settings.validators) return 'change.ClientSideValidations': -> $(@).data('changed', true) return # Callbacks 'element:validate:after.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.element.after($(@), eventData) return 'element:validate:before.ClientSideValidations': (eventData) -> ClientSideValidations.callbacks.element.before($(@), eventData) return 'element:validate:fail.ClientSideValidations': (eventData, message) -> element = $(@) ClientSideValidations.callbacks.element.fail(element, message, -> form.ClientSideValidations.addError(element, message) , eventData) return 'element:validate:pass.ClientSideValidations': (eventData) -> element = $(@) ClientSideValidations.callbacks.element.pass(element, -> form.ClientSideValidations.removeError(element) , eventData) return } # This is 'change' instead of 'click' to avoid problems with jQuery versions < 1.9 # Look this https://jquery.com/upgrade-guide/1.9/#checkbox-radio-state-in-a-trigger-ed-click-event for more details $input.filter(':checkbox').on('change.ClientSideValidations', -> $(@).isValid(form.ClientSideValidations.settings.validators) return ) # Inputs for confirmations $input.filter('[id$=_confirmation]').each -> confirmationElement = $(@) element = $form.find("##{@id.match(/(.+)_confirmation/)[1]}:input") if element[0] $("##{confirmationElement.attr('id')}").on(event, binding) for event, binding of { 'focusout.ClientSideValidations': -> element.data('changed', true).isValid(form.ClientSideValidations.settings.validators) return 'keyup.ClientSideValidations' : -> element.data('changed', true).isValid(form.ClientSideValidations.settings.validators) return } formBuilders: 'ActionView::Helpers::FormBuilder': add: (element, settings, message) -> form = $(element[0].form) if element.data('valid') != false and not form.find("label.message[for='#{element.attr('id')}']")[0]? inputErrorField = $(settings.input_tag) labelErrorField = $(settings.label_tag) label = form.find("label[for='#{element.attr('id')}']:not(.message)") element.attr('autofocus', false) if element.attr('autofocus') element.before(inputErrorField) inputErrorField.find('span#input_tag').replaceWith(element) inputErrorField.find('label.message').attr('for', element.attr('id')) labelErrorField.find('label.message').attr('for', element.attr('id')) labelErrorField.insertAfter(label) labelErrorField.find('label#label_tag').replaceWith(label) form.find("label.message[for='#{element.attr('id')}']").text(message) remove: (element, settings) -> form = $(element[0].form) errorFieldClass = $(settings.input_tag).attr('class') inputErrorField = element.closest(".#{errorFieldClass.replace(/\ /g, ".")}") label = form.find("label[for='#{element.attr('id')}']:not(.message)") labelErrorField = label.closest(".#{errorFieldClass}") if inputErrorField[0] inputErrorField.find("##{element.attr('id')}").detach() inputErrorField.replaceWith(element) label.detach() labelErrorField.replaceWith(label) patterns: numericality: default: new RegExp('^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$') only_integer: new RegExp('^[+-]?\\d+$') selectors: inputs: ':input:not(button):not([type="submit"])[name]:visible:enabled' validate_inputs: ':input:enabled:visible[data-validate]' forms: 'form[data-client-side-validations]' validators: all: -> $.extend({}, local, remote) local: absence: (element, options) -> options.message unless /^\s*$/.test(element.val() || '') presence: (element, options) -> options.message if /^\s*$/.test(element.val() || '') acceptance: (element, options) -> switch element.attr('type') when 'checkbox' unless element.prop('checked') return options.message when 'text' if element.val() != (options.accept?.toString() || '1') return options.message format: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message return options.message if options.with and !new RegExp(options.with.source, options.with.options).test(element.val()) return options.message if options.without and new RegExp(options.without.source, options.without.options).test(element.val()) numericality: (element, options) -> return if options.allow_blank == true and @presence(element, { message: options.messages.numericality }) $form = $(element[0].form) number_format = $form[0].ClientSideValidations.settings.number_format val = $.trim(element.val()).replace(new RegExp("\\#{number_format.separator}", 'g'), '.') if options.only_integer and !ClientSideValidations.patterns.numericality.only_integer.test(val) return options.messages.only_integer unless ClientSideValidations.patterns.numericality.default.test(val) return options.messages.numericality NUMERICALITY_CHECKS = greater_than: (a, b) -> a > b greater_than_or_equal_to: (a, b) -> a >= b equal_to: (a, b) -> a == b less_than: (a, b) -> return a < b less_than_or_equal_to: (a, b) -> return a <= b # options[check] may be 0 so we must check for undefined for check, check_function of NUMERICALITY_CHECKS when options[check]? checkValue = if !isNaN(parseFloat(options[check])) && isFinite(options[check]) options[check] else if $form.find("[name*=#{options[check]}]").length == 1 $form.find("[name*=#{options[check]}]").val() if !checkValue? || checkValue is '' return return options.messages[check] unless check_function(parseFloat(val), parseFloat(checkValue)) if options.odd and !(parseInt(val, 10) % 2) return options.messages.odd if options.even and (parseInt(val, 10) % 2) return options.messages.even length: (element, options) -> length = element.val().length LENGTH_CHECKS = is: (a, b) -> a == b minimum: (a, b) -> a >= b maximum: (a, b) -> a <= b blankOptions = {} blankOptions.message = if options.is options.messages.is else if options.minimum options.messages.minimum message = @presence(element, blankOptions) if message return if options.allow_blank == true return message for check, check_function of LENGTH_CHECKS when options[check] return options.messages[check] unless check_function(length, parseInt(options[check])) exclusion: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message if options.in return options.message if element.val() in (option.toString() for option in options.in) if options.range lower = options.range[0] upper = options.range[1] return options.message if element.val() >= lower and element.val() <= upper inclusion: (element, options) -> message = @presence(element, options) if message return if options.allow_blank == true return message if options.in return if element.val() in (option.toString() for option in options.in) return options.message if options.range lower = options.range[0] upper = options.range[1] return if element.val() >= lower and element.val() <= upper return options.message confirmation: (element, options) -> value = element.val() confirmation_value = $("##{element.attr('id')}_confirmation").val() unless options.case_sensitive value = value.toLowerCase() confirmation_value = confirmation_value.toLowerCase() unless value == confirmation_value return options.message uniqueness: (element, options) -> name = element.attr('name') # only check uniqueness if we're in a nested form if /_attributes\]\[\d/.test(name) matches = name.match(/^(.+_attributes\])\[\d+\](.+)$/) name_prefix = matches[1] name_suffix = matches[2] value = element.val() if name_prefix && name_suffix form = element.closest('form') valid = true form.find(":input[name^=\"#{name_prefix}\"][name$=\"#{name_suffix}\"]").each -> other_value = $(@).val() unless options.case_sensitive value = value.toLowerCase() other_value = other_value.toLowerCase() if $(@).attr('name') != name if other_value == value valid = false $(@).data('notLocallyUnique', true) else # items that were locally non-unique which become locally unique need to be # marked as changed, so they will get revalidated and thereby have their # error state cleared. but we should only do this once; therefore the # notLocallyUnique flag. if $(this).data('notLocallyUnique') $(this) .removeData('notLocallyUnique') .data('changed', true) return options.message unless valid remote: {} disable: (target) -> $target = $(target) $target.off('.ClientSideValidations') if $target.is('form') ClientSideValidations.disable($target.find(':input')) else $target.removeData('valid') $target.removeData('changed') $target.filter(':input').each -> $(@).removeAttr('data-validate') reset: (form) -> $form = $(form) ClientSideValidations.disable(form) for key of form.ClientSideValidations.settings.validators form.ClientSideValidations.removeError($form.find("[name='#{key}']")) ClientSideValidations.enablers.form(form) # Main hook # If new forms are dynamically introduced into the DOM, the .validate() method # must be invoked on that form if window.Turbolinks? and window.Turbolinks.supported # Turbolinks and Turbolinks Classic don't use the same event, so we will try to # detect Turbolinks Classic by the EVENT hash, which is not defined # in the new 5.0 version. initializeOnEvent = if window.Turbolinks.EVENTS? 'page:change' else 'turbolinks:load' $(document).on initializeOnEvent, -> $(ClientSideValidations.selectors.forms).validate() else $ -> $(ClientSideValidations.selectors.forms).validate() window.ClientSideValidations = ClientSideValidations
[ { "context": "ck?service_provider_id=11\"\n oauth_consumer_key: \"GDdmIQH6jhtmLUypg82g\"\n oauth_nonce: \"QP70eNmVz8jvdPevU3oJD2AfF7R7odC2", "end": 379, "score": 0.9995267391204834, "start": 359, "tag": "KEY", "value": "GDdmIQH6jhtmLUypg82g" }, { "context": "r.com/oauth/access_token\",\n oauth_consumer_key: \"GDdmIQH6jhtmLUypg82g\"\n oauth_nonce: \"9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL", "end": 816, "score": 0.9995051622390747, "start": 796, "tag": "KEY", "value": "GDdmIQH6jhtmLUypg82g" }, { "context": "uth_signature_method: \"HMAC-SHA1\"\n oauth_token: \"8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc\"\n oauth_timestamp: \"1272323047\"\n oauth_verifier", "end": 972, "score": 0.9985666871070862, "start": 931, "tag": "KEY", "value": "8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc" }, { "context": " oauth_timestamp: \"1272323047\"\n oauth_verifier: \"pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY\"\n oauth_version: \"1.0\"\n, \"MCD8BKwGdgPHvAuvgvz4EQ", "end": 1068, "score": 0.9682464599609375, "start": 1025, "tag": "KEY", "value": "pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY" }, { "context": "uth_signature_method: \"HMAC-SHA1\"\n oauth_token: \"819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw\"\n oauth_timestamp: \"1272325550\"\n oauth_version:", "end": 1585, "score": 0.9441701173782349, "start": 1536, "tag": "KEY", "value": "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw" }, { "context": "er_key = \"9djdj82h48djs9d2\"\nparams.oauth_token = \"kkk9d7dh3k39sjv7\"\nparams.oauth_nonce = \"7d8f3e4a\"\nparams.o", "end": 2067, "score": 0.9542375206947327, "start": 2059, "tag": "PASSWORD", "value": "kkk9d7dh" } ]
deps/npm/node_modules/request/node_modules/oauth-sign/test.coffee
lxe/io.coffee
0
hmacsign = require("./index").hmacsign assert = require("assert") qs = require("querystring") # Tests from Twitter documentation https://dev.twitter.com/docs/auth/oauth reqsign = hmacsign("POST", "https://api.twitter.com/oauth/request_token", oauth_callback: "http://localhost:3005/the_dance/process_callback?service_provider_id=11" oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" oauth_nonce: "QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk" oauth_signature_method: "HMAC-SHA1" oauth_timestamp: "1272323042" oauth_version: "1.0" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98") console.log reqsign console.log "8wUi7m5HFQy76nowoCThusfgB+Q=" assert.equal reqsign, "8wUi7m5HFQy76nowoCThusfgB+Q=" accsign = hmacsign("POST", "https://api.twitter.com/oauth/access_token", oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" oauth_nonce: "9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8" oauth_signature_method: "HMAC-SHA1" oauth_token: "8ldIZyxQeVrFZXFOZH5tAwj6vzJYuLQpl0WUEYtWc" oauth_timestamp: "1272323047" oauth_verifier: "pDNg57prOHapMbhv25RNf75lVRd6JDsni1AJJIDYoTY" oauth_version: "1.0" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA") console.log accsign console.log "PUw/dHA4fnlJYM6RhXk5IU/0fCc=" assert.equal accsign, "PUw/dHA4fnlJYM6RhXk5IU/0fCc=" upsign = hmacsign("POST", "http://api.twitter.com/1/statuses/update.json", oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" oauth_nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y" oauth_signature_method: "HMAC-SHA1" oauth_token: "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw" oauth_timestamp: "1272325550" oauth_version: "1.0" status: "setting up my twitter 私のさえずりを設定する" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA") console.log upsign console.log "yOahq5m0YjDDjfjxHaXEsW9D+X0=" assert.equal upsign, "yOahq5m0YjDDjfjxHaXEsW9D+X0=" # example in rfc5849 params = qs.parse("b5=%3D%253D&a3=a&c%40=&a2=r%20b" + "&" + "c2&a3=2+q") params.oauth_consumer_key = "9djdj82h48djs9d2" params.oauth_token = "kkk9d7dh3k39sjv7" params.oauth_nonce = "7d8f3e4a" params.oauth_signature_method = "HMAC-SHA1" params.oauth_timestamp = "137131201" rfc5849sign = hmacsign("POST", "http://example.com/request", params, "j49sk3j29djd", "dh893hdasih9") console.log rfc5849sign console.log "r6/TJjbCOr97/+UU0NsvSne7s5g=" assert.equal rfc5849sign, "r6/TJjbCOr97/+UU0NsvSne7s5g="
19977
hmacsign = require("./index").hmacsign assert = require("assert") qs = require("querystring") # Tests from Twitter documentation https://dev.twitter.com/docs/auth/oauth reqsign = hmacsign("POST", "https://api.twitter.com/oauth/request_token", oauth_callback: "http://localhost:3005/the_dance/process_callback?service_provider_id=11" oauth_consumer_key: "<KEY>" oauth_nonce: "QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk" oauth_signature_method: "HMAC-SHA1" oauth_timestamp: "1272323042" oauth_version: "1.0" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98") console.log reqsign console.log "8wUi7m5HFQy76nowoCThusfgB+Q=" assert.equal reqsign, "8wUi7m5HFQy76nowoCThusfgB+Q=" accsign = hmacsign("POST", "https://api.twitter.com/oauth/access_token", oauth_consumer_key: "<KEY>" oauth_nonce: "9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8" oauth_signature_method: "HMAC-SHA1" oauth_token: "<KEY>" oauth_timestamp: "1272323047" oauth_verifier: "<KEY>" oauth_version: "1.0" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA") console.log accsign console.log "PUw/dHA4fnlJYM6RhXk5IU/0fCc=" assert.equal accsign, "PUw/dHA4fnlJYM6RhXk5IU/0fCc=" upsign = hmacsign("POST", "http://api.twitter.com/1/statuses/update.json", oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" oauth_nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y" oauth_signature_method: "HMAC-SHA1" oauth_token: "<KEY>" oauth_timestamp: "1272325550" oauth_version: "1.0" status: "setting up my twitter 私のさえずりを設定する" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA") console.log upsign console.log "yOahq5m0YjDDjfjxHaXEsW9D+X0=" assert.equal upsign, "yOahq5m0YjDDjfjxHaXEsW9D+X0=" # example in rfc5849 params = qs.parse("b5=%3D%253D&a3=a&c%40=&a2=r%20b" + "&" + "c2&a3=2+q") params.oauth_consumer_key = "9djdj82h48djs9d2" params.oauth_token = "<PASSWORD>3k39sjv7" params.oauth_nonce = "7d8f3e4a" params.oauth_signature_method = "HMAC-SHA1" params.oauth_timestamp = "137131201" rfc5849sign = hmacsign("POST", "http://example.com/request", params, "j49sk3j29djd", "dh893hdasih9") console.log rfc5849sign console.log "r6/TJjbCOr97/+UU0NsvSne7s5g=" assert.equal rfc5849sign, "r6/TJjbCOr97/+UU0NsvSne7s5g="
true
hmacsign = require("./index").hmacsign assert = require("assert") qs = require("querystring") # Tests from Twitter documentation https://dev.twitter.com/docs/auth/oauth reqsign = hmacsign("POST", "https://api.twitter.com/oauth/request_token", oauth_callback: "http://localhost:3005/the_dance/process_callback?service_provider_id=11" oauth_consumer_key: "PI:KEY:<KEY>END_PI" oauth_nonce: "QP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk" oauth_signature_method: "HMAC-SHA1" oauth_timestamp: "1272323042" oauth_version: "1.0" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98") console.log reqsign console.log "8wUi7m5HFQy76nowoCThusfgB+Q=" assert.equal reqsign, "8wUi7m5HFQy76nowoCThusfgB+Q=" accsign = hmacsign("POST", "https://api.twitter.com/oauth/access_token", oauth_consumer_key: "PI:KEY:<KEY>END_PI" oauth_nonce: "9zWH6qe0qG7Lc1telCn7FhUbLyVdjEaL3MO5uHxn8" oauth_signature_method: "HMAC-SHA1" oauth_token: "PI:KEY:<KEY>END_PI" oauth_timestamp: "1272323047" oauth_verifier: "PI:KEY:<KEY>END_PI" oauth_version: "1.0" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "x6qpRnlEmW9JbQn4PQVVeVG8ZLPEx6A0TOebgwcuA") console.log accsign console.log "PUw/dHA4fnlJYM6RhXk5IU/0fCc=" assert.equal accsign, "PUw/dHA4fnlJYM6RhXk5IU/0fCc=" upsign = hmacsign("POST", "http://api.twitter.com/1/statuses/update.json", oauth_consumer_key: "GDdmIQH6jhtmLUypg82g" oauth_nonce: "oElnnMTQIZvqvlfXM56aBLAf5noGD0AQR3Fmi7Q6Y" oauth_signature_method: "HMAC-SHA1" oauth_token: "PI:KEY:<KEY>END_PI" oauth_timestamp: "1272325550" oauth_version: "1.0" status: "setting up my twitter 私のさえずりを設定する" , "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98", "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA") console.log upsign console.log "yOahq5m0YjDDjfjxHaXEsW9D+X0=" assert.equal upsign, "yOahq5m0YjDDjfjxHaXEsW9D+X0=" # example in rfc5849 params = qs.parse("b5=%3D%253D&a3=a&c%40=&a2=r%20b" + "&" + "c2&a3=2+q") params.oauth_consumer_key = "9djdj82h48djs9d2" params.oauth_token = "PI:PASSWORD:<PASSWORD>END_PI3k39sjv7" params.oauth_nonce = "7d8f3e4a" params.oauth_signature_method = "HMAC-SHA1" params.oauth_timestamp = "137131201" rfc5849sign = hmacsign("POST", "http://example.com/request", params, "j49sk3j29djd", "dh893hdasih9") console.log rfc5849sign console.log "r6/TJjbCOr97/+UU0NsvSne7s5g=" assert.equal rfc5849sign, "r6/TJjbCOr97/+UU0NsvSne7s5g="
[ { "context": "render()\n @view.inner.$('[name=email]').val 'foo@bar.com'\n @view.inner.$('[name=password]').val 'moo'", "end": 1670, "score": 0.9999025464057922, "start": 1659, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": ".com'\n @view.inner.$('[name=password]').val 'moo'\n @view.inner.submit(preventDefault: sinon.s", "end": 1719, "score": 0.9992408752441406, "start": 1716, "tag": "PASSWORD", "value": "moo" }, { "context": "\n $.ajax.args[0][0].data.email.should.equal 'foo@bar.com'\n $.ajax.args[0][0].data.password.should.equ", "end": 1895, "score": 0.9999248385429382, "start": 1884, "tag": "EMAIL", "value": "foo@bar.com" }, { "context": " $.ajax.args[0][0].data.password.should.equal 'moo'\n", "end": 1952, "score": 0.9991762638092041, "start": 1949, "tag": "PASSWORD", "value": "moo" } ]
src/desktop/components/marketing_signup_modal/test/index.coffee
kanaabe/force
1
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' describe 'MarketingSignupModal', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') Backbone.$ = $ sinon.stub $, 'ajax' @MarketingSignupModal = benv.requireWithJadeify( require.resolve '../index.coffee' ['template'] ) @MarketingSignupModal.__set__ 'sd', @sd = APP_URL: 'http://artsy.net' CURRENT_USER: null MARKETING_SIGNUP_MODALS: [{slug: 'ca1', copy: 'This is a cool modal', image: 'img.jpg', }] AP: { signupPagePath: 'signuppath' } benv.expose sd: @sd @MarketingSignupModal.__set__ 'modalize', @modalize = sinon.stub() @modalize.returns @modal = view: new Backbone.View @modal.open = sinon.stub() @MarketingSignupModal.__set__ 'location', @location = search: '?m-id=ca1' @MarketingSignupModal.__set__ 'setTimeout', @setTimeout = sinon.stub() @setTimeout.callsArg 0 done() afterEach -> $.ajax.restore() benv.teardown() beforeEach -> @view = new @MarketingSignupModal describe '#initialize', -> beforeEach -> @view.modal.open = sinon.stub() it 'opens if from a campaign url and logged out', -> @view.initialize() @view.modal.open.called.should.be.ok() it 'doesnt open if from a non marketing url', -> @location.search = '?foo=bar' @view.initialize() @view.modal.open.called.should.not.be.ok() describe '#submit', -> it 'creates a user', -> @view.inner.render() @view.inner.$('[name=email]').val 'foo@bar.com' @view.inner.$('[name=password]').val 'moo' @view.inner.submit(preventDefault: sinon.stub()) $.ajax.args[0][0].url.should.containEql 'signuppath' $.ajax.args[0][0].data.email.should.equal 'foo@bar.com' $.ajax.args[0][0].data.password.should.equal 'moo'
17072
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' describe 'MarketingSignupModal', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') Backbone.$ = $ sinon.stub $, 'ajax' @MarketingSignupModal = benv.requireWithJadeify( require.resolve '../index.coffee' ['template'] ) @MarketingSignupModal.__set__ 'sd', @sd = APP_URL: 'http://artsy.net' CURRENT_USER: null MARKETING_SIGNUP_MODALS: [{slug: 'ca1', copy: 'This is a cool modal', image: 'img.jpg', }] AP: { signupPagePath: 'signuppath' } benv.expose sd: @sd @MarketingSignupModal.__set__ 'modalize', @modalize = sinon.stub() @modalize.returns @modal = view: new Backbone.View @modal.open = sinon.stub() @MarketingSignupModal.__set__ 'location', @location = search: '?m-id=ca1' @MarketingSignupModal.__set__ 'setTimeout', @setTimeout = sinon.stub() @setTimeout.callsArg 0 done() afterEach -> $.ajax.restore() benv.teardown() beforeEach -> @view = new @MarketingSignupModal describe '#initialize', -> beforeEach -> @view.modal.open = sinon.stub() it 'opens if from a campaign url and logged out', -> @view.initialize() @view.modal.open.called.should.be.ok() it 'doesnt open if from a non marketing url', -> @location.search = '?foo=bar' @view.initialize() @view.modal.open.called.should.not.be.ok() describe '#submit', -> it 'creates a user', -> @view.inner.render() @view.inner.$('[name=email]').val '<EMAIL>' @view.inner.$('[name=password]').val '<PASSWORD>' @view.inner.submit(preventDefault: sinon.stub()) $.ajax.args[0][0].url.should.containEql 'signuppath' $.ajax.args[0][0].data.email.should.equal '<EMAIL>' $.ajax.args[0][0].data.password.should.equal '<PASSWORD>'
true
benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' describe 'MarketingSignupModal', -> beforeEach (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') Backbone.$ = $ sinon.stub $, 'ajax' @MarketingSignupModal = benv.requireWithJadeify( require.resolve '../index.coffee' ['template'] ) @MarketingSignupModal.__set__ 'sd', @sd = APP_URL: 'http://artsy.net' CURRENT_USER: null MARKETING_SIGNUP_MODALS: [{slug: 'ca1', copy: 'This is a cool modal', image: 'img.jpg', }] AP: { signupPagePath: 'signuppath' } benv.expose sd: @sd @MarketingSignupModal.__set__ 'modalize', @modalize = sinon.stub() @modalize.returns @modal = view: new Backbone.View @modal.open = sinon.stub() @MarketingSignupModal.__set__ 'location', @location = search: '?m-id=ca1' @MarketingSignupModal.__set__ 'setTimeout', @setTimeout = sinon.stub() @setTimeout.callsArg 0 done() afterEach -> $.ajax.restore() benv.teardown() beforeEach -> @view = new @MarketingSignupModal describe '#initialize', -> beforeEach -> @view.modal.open = sinon.stub() it 'opens if from a campaign url and logged out', -> @view.initialize() @view.modal.open.called.should.be.ok() it 'doesnt open if from a non marketing url', -> @location.search = '?foo=bar' @view.initialize() @view.modal.open.called.should.not.be.ok() describe '#submit', -> it 'creates a user', -> @view.inner.render() @view.inner.$('[name=email]').val 'PI:EMAIL:<EMAIL>END_PI' @view.inner.$('[name=password]').val 'PI:PASSWORD:<PASSWORD>END_PI' @view.inner.submit(preventDefault: sinon.stub()) $.ajax.args[0][0].url.should.containEql 'signuppath' $.ajax.args[0][0].data.email.should.equal 'PI:EMAIL:<EMAIL>END_PI' $.ajax.args[0][0].data.password.should.equal 'PI:PASSWORD:<PASSWORD>END_PI'
[ { "context": " user object is provided\", ->\n user = name: \"Bill\"\n view.login(user)\n expect(view.updateU", "end": 2006, "score": 0.9996566772460938, "start": 2002, "tag": "NAME", "value": "Bill" }, { "context": "e \"#updateUser()\", ->\n user =\n fullname: \"Aron Carroll\"\n username: \"aron\"\n permalink_url: \"htt", "end": 3555, "score": 0.9998592734336853, "start": 3543, "tag": "NAME", "value": "Aron Carroll" }, { "context": "=\n fullname: \"Aron Carroll\"\n username: \"aron\"\n permalink_url: \"http://readmill.com/aron\"\n", "end": 3578, "score": 0.9982685446739197, "start": 3574, "tag": "USERNAME", "value": "aron" }, { "context": " \"aron\"\n permalink_url: \"http://readmill.com/aron\"\n avatar_url: \"http://readmill.com/aron.png\"", "end": 3626, "score": 0.9859927296638489, "start": 3622, "tag": "USERNAME", "value": "aron" } ]
test/spec/readmill/view.coffee
aron/annotator.readmill.js
0
describe "View", -> jQuery = Annotator.$ View = Annotator.Readmill.View view = null beforeEach -> view = new View sinon.stub(view, "publish") it "should be an instance of Annotator.Class", -> expect(view).to.be.an.instanceof Annotator.Class it "should have a @element containing a <div>", -> expect(view.element.get(0).tagName).to.equal("DIV") describe "#isPrivate()", -> it "should return false if the checkbox is checked", -> expect(view.isPrivate()).to.equal(false) it "should return true if the checkbox is checked", -> view.element.find("input").attr("checked", "checked") expect(view.isPrivate()).to.equal(true) describe "#connect()", -> it "should publish the \"connect\" event", -> view.connect() expect(view.publish).was.called() expect(view.publish).was.calledWith("connect") describe "#reading()", -> it "should update the connect button", -> target = sinon.stub(view, "updateState") view.reading() expect(target).was.called() expect(target).was.calledWith(view.states.NOW_READING) it "should publish the \"reading\" event", -> view.reading() expect(view.publish).was.called() expect(view.publish).was.calledWith("reading") describe "#finish()", -> beforeEach -> sinon.stub(view, "login") it "should reset the view to login state", -> view.finish() expect(view.login).was.called() it "should publish the \"reading\" event", -> view.finish() expect(view.publish).was.called() expect(view.publish).was.calledWith("finish") describe "#disconnect()", -> it "should publish the \"disconnect\" event", -> view.disconnect() expect(view.publish).was.called() expect(view.publish).was.calledWith("disconnect") describe "#login()", -> beforeEach -> sinon.stub view, "updateUser" it "should call @updateUser if a user object is provided", -> user = name: "Bill" view.login(user) expect(view.updateUser).was.called() expect(view.updateUser).was.calledWith(user) it "should not call @updateUser if a user object is not provided", -> view.login() expect(view.updateUser).was.notCalled() it "should add the @classes.loggedIn class to the @element", -> view.login() expect(view.element[0].className).to.include(view.classes.loggedIn) it "should publish the \"login\" event", -> view.login() expect(view.publish).was.called() expect(view.publish).was.calledWith("login") describe "#logout()", -> beforeEach -> sinon.stub view, "updateBook" sinon.stub view.element, "html" it "should remove the @classes.loggedIn class from the @element", -> view.element.addClass(view.classes.loggedIn) view.logout() expect(view.element[0].className).not.to.include(view.classes.loggedIn) it "should reset the template", -> view.logout() expect(view.element.html).was.called() expect(view.element.html).was.calledWith(view.template) it "should reset the @user object", -> view.user = {} view.logout() expect(view.user).to.equal(null) it "should call @updateBook", -> view.logout() expect(view.updateBook).was.called() it "should publish the \"logout\" event", -> view.logout() expect(view.publish).was.called() expect(view.publish).was.calledWith("logout") describe "#updateUser()", -> user = fullname: "Aron Carroll" username: "aron" permalink_url: "http://readmill.com/aron" avatar_url: "http://readmill.com/aron.png" it "should set the @user property", -> view.updateUser(user) expect(view.user).to.equal(user) it "should update the appropriate DOM elements", -> el = view.element view.updateUser(user) expect(el.find(".annotator-readmill-avatar").attr("href")).to.equal(user.permalink_url) expect(el.find(".annotator-readmill-avatar").attr("title")).to.equal("#{user.fullname} (#{user.username})") expect(el.find(".annotator-readmill-avatar img").attr("src")).to.equal(user.avatar_url) describe "#updateBook()", -> it "should set the @book property", -> book = {title: "Title"} view.updateBook(book) expect(view.book).to.equal(book) it "should update the appropriate DOM elements", -> el = view.element view.updateBook(title: "Title") expect(el.find(".annotator-readmill-book").html()).to.equal("Title") it "should show a loading message if no title", -> el = view.element view.updateBook() expect(el.find(".annotator-readmill-book").html()).to.equal("Loading book…") describe "updateState()", -> it "should update the hash and html of the connect link", -> target = view.element.find(".annotator-readmill-connect a") map = {} map[view.states.CONNECT] = "Connect With Readmill…" map[view.states.START_READING] = "Begin Reading…" map[view.states.NOW_READING] = "Now Reading…" for key, state of view.states view.updateState(state) expect(target[0].hash).to.equal("#" + state) expect(target.html()).to.equal(map[state]) describe "#updatePrivate()", -> it "should add the @classes.private class if isPrivate is true" it "should remove the @classes.private class if isPrivate is false" it "should check the checkbox if isPrivate is true" it "should uncheck the checkbox if isPrivate is false" it "should do nothing if the checkbox state is unchanged" it "should allow options.force to bypass the check" it "should trigger the \"private\" event" describe "#render()", -> it "should call @updateBook()", -> sinon.stub view, "updateBook" view.render() expect(view.updateBook).was.called() it "should call @updateUser()", -> sinon.stub view, "updateUser" view.render() expect(view.updateUser).was.called() it "should return the @element property", -> expect(view.render()).to.equal(view.element) describe "#_onConnectClick()", -> event = null beforeEach -> event = jQuery.Event() event.target = {hash: "#connect"} sinon.stub(event, "preventDefault") sinon.stub(view, "connect") it "should call @connect() if the hash equals #connect", -> view._onConnectClick(event) expect(view.connect).was.called() it "should call @reading() if the hash equals #start", -> event.target.hash = "#start" target = sinon.stub(view, "reading") view._onConnectClick(event) expect(target).was.called() it "should prevent the default browser action", -> view._onConnectClick(event) expect(event.preventDefault).was.called() describe "#_onLogoutClick()", -> event = null beforeEach -> event = jQuery.Event() sinon.stub(event, "preventDefault") sinon.stub(view, "disconnect") it "should call @disconnect()", -> view._onLogoutClick(event) expect(view.disconnect).was.called() it "should prevent the default browser action", -> view._onLogoutClick(event) expect(event.preventDefault).was.called() describe "#_onCheckboxChange()", -> event = null beforeEach -> event = jQuery.Event() event.target = checked: true it "should update the private checkbox state", -> sinon.stub(view, "updatePrivate") view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(view.updatePrivate).was.called() expect(view.updatePrivate).was.calledWith(true) it "should add @classes.checked to the label is checked", -> view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(target).to.equal(true) it "should remove @classes.checked to the label is not checked", -> event.target.checked = false view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(target).to.equal(false) it "should publish the \"privacy\" event", -> view._onCheckboxChange(event) expect(view.publish).was.called() expect(view.publish).was.calledWith("privacy", [true, view])
45041
describe "View", -> jQuery = Annotator.$ View = Annotator.Readmill.View view = null beforeEach -> view = new View sinon.stub(view, "publish") it "should be an instance of Annotator.Class", -> expect(view).to.be.an.instanceof Annotator.Class it "should have a @element containing a <div>", -> expect(view.element.get(0).tagName).to.equal("DIV") describe "#isPrivate()", -> it "should return false if the checkbox is checked", -> expect(view.isPrivate()).to.equal(false) it "should return true if the checkbox is checked", -> view.element.find("input").attr("checked", "checked") expect(view.isPrivate()).to.equal(true) describe "#connect()", -> it "should publish the \"connect\" event", -> view.connect() expect(view.publish).was.called() expect(view.publish).was.calledWith("connect") describe "#reading()", -> it "should update the connect button", -> target = sinon.stub(view, "updateState") view.reading() expect(target).was.called() expect(target).was.calledWith(view.states.NOW_READING) it "should publish the \"reading\" event", -> view.reading() expect(view.publish).was.called() expect(view.publish).was.calledWith("reading") describe "#finish()", -> beforeEach -> sinon.stub(view, "login") it "should reset the view to login state", -> view.finish() expect(view.login).was.called() it "should publish the \"reading\" event", -> view.finish() expect(view.publish).was.called() expect(view.publish).was.calledWith("finish") describe "#disconnect()", -> it "should publish the \"disconnect\" event", -> view.disconnect() expect(view.publish).was.called() expect(view.publish).was.calledWith("disconnect") describe "#login()", -> beforeEach -> sinon.stub view, "updateUser" it "should call @updateUser if a user object is provided", -> user = name: "<NAME>" view.login(user) expect(view.updateUser).was.called() expect(view.updateUser).was.calledWith(user) it "should not call @updateUser if a user object is not provided", -> view.login() expect(view.updateUser).was.notCalled() it "should add the @classes.loggedIn class to the @element", -> view.login() expect(view.element[0].className).to.include(view.classes.loggedIn) it "should publish the \"login\" event", -> view.login() expect(view.publish).was.called() expect(view.publish).was.calledWith("login") describe "#logout()", -> beforeEach -> sinon.stub view, "updateBook" sinon.stub view.element, "html" it "should remove the @classes.loggedIn class from the @element", -> view.element.addClass(view.classes.loggedIn) view.logout() expect(view.element[0].className).not.to.include(view.classes.loggedIn) it "should reset the template", -> view.logout() expect(view.element.html).was.called() expect(view.element.html).was.calledWith(view.template) it "should reset the @user object", -> view.user = {} view.logout() expect(view.user).to.equal(null) it "should call @updateBook", -> view.logout() expect(view.updateBook).was.called() it "should publish the \"logout\" event", -> view.logout() expect(view.publish).was.called() expect(view.publish).was.calledWith("logout") describe "#updateUser()", -> user = fullname: "<NAME>" username: "aron" permalink_url: "http://readmill.com/aron" avatar_url: "http://readmill.com/aron.png" it "should set the @user property", -> view.updateUser(user) expect(view.user).to.equal(user) it "should update the appropriate DOM elements", -> el = view.element view.updateUser(user) expect(el.find(".annotator-readmill-avatar").attr("href")).to.equal(user.permalink_url) expect(el.find(".annotator-readmill-avatar").attr("title")).to.equal("#{user.fullname} (#{user.username})") expect(el.find(".annotator-readmill-avatar img").attr("src")).to.equal(user.avatar_url) describe "#updateBook()", -> it "should set the @book property", -> book = {title: "Title"} view.updateBook(book) expect(view.book).to.equal(book) it "should update the appropriate DOM elements", -> el = view.element view.updateBook(title: "Title") expect(el.find(".annotator-readmill-book").html()).to.equal("Title") it "should show a loading message if no title", -> el = view.element view.updateBook() expect(el.find(".annotator-readmill-book").html()).to.equal("Loading book…") describe "updateState()", -> it "should update the hash and html of the connect link", -> target = view.element.find(".annotator-readmill-connect a") map = {} map[view.states.CONNECT] = "Connect With Readmill…" map[view.states.START_READING] = "Begin Reading…" map[view.states.NOW_READING] = "Now Reading…" for key, state of view.states view.updateState(state) expect(target[0].hash).to.equal("#" + state) expect(target.html()).to.equal(map[state]) describe "#updatePrivate()", -> it "should add the @classes.private class if isPrivate is true" it "should remove the @classes.private class if isPrivate is false" it "should check the checkbox if isPrivate is true" it "should uncheck the checkbox if isPrivate is false" it "should do nothing if the checkbox state is unchanged" it "should allow options.force to bypass the check" it "should trigger the \"private\" event" describe "#render()", -> it "should call @updateBook()", -> sinon.stub view, "updateBook" view.render() expect(view.updateBook).was.called() it "should call @updateUser()", -> sinon.stub view, "updateUser" view.render() expect(view.updateUser).was.called() it "should return the @element property", -> expect(view.render()).to.equal(view.element) describe "#_onConnectClick()", -> event = null beforeEach -> event = jQuery.Event() event.target = {hash: "#connect"} sinon.stub(event, "preventDefault") sinon.stub(view, "connect") it "should call @connect() if the hash equals #connect", -> view._onConnectClick(event) expect(view.connect).was.called() it "should call @reading() if the hash equals #start", -> event.target.hash = "#start" target = sinon.stub(view, "reading") view._onConnectClick(event) expect(target).was.called() it "should prevent the default browser action", -> view._onConnectClick(event) expect(event.preventDefault).was.called() describe "#_onLogoutClick()", -> event = null beforeEach -> event = jQuery.Event() sinon.stub(event, "preventDefault") sinon.stub(view, "disconnect") it "should call @disconnect()", -> view._onLogoutClick(event) expect(view.disconnect).was.called() it "should prevent the default browser action", -> view._onLogoutClick(event) expect(event.preventDefault).was.called() describe "#_onCheckboxChange()", -> event = null beforeEach -> event = jQuery.Event() event.target = checked: true it "should update the private checkbox state", -> sinon.stub(view, "updatePrivate") view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(view.updatePrivate).was.called() expect(view.updatePrivate).was.calledWith(true) it "should add @classes.checked to the label is checked", -> view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(target).to.equal(true) it "should remove @classes.checked to the label is not checked", -> event.target.checked = false view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(target).to.equal(false) it "should publish the \"privacy\" event", -> view._onCheckboxChange(event) expect(view.publish).was.called() expect(view.publish).was.calledWith("privacy", [true, view])
true
describe "View", -> jQuery = Annotator.$ View = Annotator.Readmill.View view = null beforeEach -> view = new View sinon.stub(view, "publish") it "should be an instance of Annotator.Class", -> expect(view).to.be.an.instanceof Annotator.Class it "should have a @element containing a <div>", -> expect(view.element.get(0).tagName).to.equal("DIV") describe "#isPrivate()", -> it "should return false if the checkbox is checked", -> expect(view.isPrivate()).to.equal(false) it "should return true if the checkbox is checked", -> view.element.find("input").attr("checked", "checked") expect(view.isPrivate()).to.equal(true) describe "#connect()", -> it "should publish the \"connect\" event", -> view.connect() expect(view.publish).was.called() expect(view.publish).was.calledWith("connect") describe "#reading()", -> it "should update the connect button", -> target = sinon.stub(view, "updateState") view.reading() expect(target).was.called() expect(target).was.calledWith(view.states.NOW_READING) it "should publish the \"reading\" event", -> view.reading() expect(view.publish).was.called() expect(view.publish).was.calledWith("reading") describe "#finish()", -> beforeEach -> sinon.stub(view, "login") it "should reset the view to login state", -> view.finish() expect(view.login).was.called() it "should publish the \"reading\" event", -> view.finish() expect(view.publish).was.called() expect(view.publish).was.calledWith("finish") describe "#disconnect()", -> it "should publish the \"disconnect\" event", -> view.disconnect() expect(view.publish).was.called() expect(view.publish).was.calledWith("disconnect") describe "#login()", -> beforeEach -> sinon.stub view, "updateUser" it "should call @updateUser if a user object is provided", -> user = name: "PI:NAME:<NAME>END_PI" view.login(user) expect(view.updateUser).was.called() expect(view.updateUser).was.calledWith(user) it "should not call @updateUser if a user object is not provided", -> view.login() expect(view.updateUser).was.notCalled() it "should add the @classes.loggedIn class to the @element", -> view.login() expect(view.element[0].className).to.include(view.classes.loggedIn) it "should publish the \"login\" event", -> view.login() expect(view.publish).was.called() expect(view.publish).was.calledWith("login") describe "#logout()", -> beforeEach -> sinon.stub view, "updateBook" sinon.stub view.element, "html" it "should remove the @classes.loggedIn class from the @element", -> view.element.addClass(view.classes.loggedIn) view.logout() expect(view.element[0].className).not.to.include(view.classes.loggedIn) it "should reset the template", -> view.logout() expect(view.element.html).was.called() expect(view.element.html).was.calledWith(view.template) it "should reset the @user object", -> view.user = {} view.logout() expect(view.user).to.equal(null) it "should call @updateBook", -> view.logout() expect(view.updateBook).was.called() it "should publish the \"logout\" event", -> view.logout() expect(view.publish).was.called() expect(view.publish).was.calledWith("logout") describe "#updateUser()", -> user = fullname: "PI:NAME:<NAME>END_PI" username: "aron" permalink_url: "http://readmill.com/aron" avatar_url: "http://readmill.com/aron.png" it "should set the @user property", -> view.updateUser(user) expect(view.user).to.equal(user) it "should update the appropriate DOM elements", -> el = view.element view.updateUser(user) expect(el.find(".annotator-readmill-avatar").attr("href")).to.equal(user.permalink_url) expect(el.find(".annotator-readmill-avatar").attr("title")).to.equal("#{user.fullname} (#{user.username})") expect(el.find(".annotator-readmill-avatar img").attr("src")).to.equal(user.avatar_url) describe "#updateBook()", -> it "should set the @book property", -> book = {title: "Title"} view.updateBook(book) expect(view.book).to.equal(book) it "should update the appropriate DOM elements", -> el = view.element view.updateBook(title: "Title") expect(el.find(".annotator-readmill-book").html()).to.equal("Title") it "should show a loading message if no title", -> el = view.element view.updateBook() expect(el.find(".annotator-readmill-book").html()).to.equal("Loading book…") describe "updateState()", -> it "should update the hash and html of the connect link", -> target = view.element.find(".annotator-readmill-connect a") map = {} map[view.states.CONNECT] = "Connect With Readmill…" map[view.states.START_READING] = "Begin Reading…" map[view.states.NOW_READING] = "Now Reading…" for key, state of view.states view.updateState(state) expect(target[0].hash).to.equal("#" + state) expect(target.html()).to.equal(map[state]) describe "#updatePrivate()", -> it "should add the @classes.private class if isPrivate is true" it "should remove the @classes.private class if isPrivate is false" it "should check the checkbox if isPrivate is true" it "should uncheck the checkbox if isPrivate is false" it "should do nothing if the checkbox state is unchanged" it "should allow options.force to bypass the check" it "should trigger the \"private\" event" describe "#render()", -> it "should call @updateBook()", -> sinon.stub view, "updateBook" view.render() expect(view.updateBook).was.called() it "should call @updateUser()", -> sinon.stub view, "updateUser" view.render() expect(view.updateUser).was.called() it "should return the @element property", -> expect(view.render()).to.equal(view.element) describe "#_onConnectClick()", -> event = null beforeEach -> event = jQuery.Event() event.target = {hash: "#connect"} sinon.stub(event, "preventDefault") sinon.stub(view, "connect") it "should call @connect() if the hash equals #connect", -> view._onConnectClick(event) expect(view.connect).was.called() it "should call @reading() if the hash equals #start", -> event.target.hash = "#start" target = sinon.stub(view, "reading") view._onConnectClick(event) expect(target).was.called() it "should prevent the default browser action", -> view._onConnectClick(event) expect(event.preventDefault).was.called() describe "#_onLogoutClick()", -> event = null beforeEach -> event = jQuery.Event() sinon.stub(event, "preventDefault") sinon.stub(view, "disconnect") it "should call @disconnect()", -> view._onLogoutClick(event) expect(view.disconnect).was.called() it "should prevent the default browser action", -> view._onLogoutClick(event) expect(event.preventDefault).was.called() describe "#_onCheckboxChange()", -> event = null beforeEach -> event = jQuery.Event() event.target = checked: true it "should update the private checkbox state", -> sinon.stub(view, "updatePrivate") view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(view.updatePrivate).was.called() expect(view.updatePrivate).was.calledWith(true) it "should add @classes.checked to the label is checked", -> view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(target).to.equal(true) it "should remove @classes.checked to the label is not checked", -> event.target.checked = false view._onCheckboxChange(event) target = view.element.find('label').hasClass(view.classes.checked) expect(target).to.equal(false) it "should publish the \"privacy\" event", -> view._onCheckboxChange(event) expect(view.publish).was.called() expect(view.publish).was.calledWith("privacy", [true, view])
[ { "context": "tedModel: 'Player',\n keyDestination: 'Player1Id',\n includeInJSON: 'id'\n },\n {\n ty", "end": 280, "score": 0.8711755275726318, "start": 278, "tag": "KEY", "value": "Id" }, { "context": " {\n type: Backbone.HasOne,\n key: 'Player2',\n relatedModel: 'Player',\n keyDestinat", "end": 370, "score": 0.5878959894180298, "start": 369, "tag": "KEY", "value": "2" } ]
elements/js/frames.coffee
RedBulli/LiveSnooker
0
class Frame extends Livesnooker.Model urlRoot: -> leagueId = @get('League')?.id || @get('LeagueId') "/leagues/" + leagueId + "/frames" relations: [ { type: Backbone.HasOne, key: 'Player1', relatedModel: 'Player', keyDestination: 'Player1Id', includeInJSON: 'id' }, { type: Backbone.HasOne, key: 'Player2', relatedModel: 'Player', keyDestination: 'Player2Id', includeInJSON: 'id' }, { type: Backbone.HasMany key: 'Shots' relatedModel: 'Shot' collectionType: 'Shots' reverseRelation: key: 'Frame' keyDestination: 'FrameId' includeInJSON: 'id' }, { type: Backbone.HasOne, key: 'Winner', relatedModel: 'Player', keyDestination: 'WinnerId', includeInJSON: 'id' } ] initialize: (options) -> @set('shotGroups', new ShotGroups([], frame: @)) calculateShotGroups: -> @get('shotGroups').reset() shots = @get('Shots') shots.sort() shots.each (shot) => @get('shotGroups').addShot(shot) lastShot: -> @get('shotGroups').last()?.lastShot() getCurrentPlayer: -> if @get('currentPlayer') @get('currentPlayer') else lastShot = @lastShot() if lastShot if lastShot.isPot() lastShot.get('Player') else @getOtherPlayer(lastShot.get('Player')) else @get('Player1') getNonCurrentPlayer: -> @getOtherPlayer(@getCurrentPlayer()) getOtherPlayer: (player) -> if @get('Player1') == player @get('Player2') else if @get('Player2') == player @get('Player1') currentPlayerIndex: -> if @getCurrentPlayer() == @get('Player1') 0 else 1 initializeShot: (data) -> return if @get('Shots').find((shot) -> shot.get('shotNumber') == data.shotNumber) _.extend(data, { Frame: @ }) if not data.Player && data.PlayerId data.Player = @getPlayer(data.PlayerId) shot = new Shot(data) if shot.validate(shot.attributes) throw shot.validate(shot.attributes) shot getResultFromShot: ({points, foul}) -> if foul "foul" else if parseInt(points) == 0 "nothing" else "pot" createShot: ({attempt, points, foul}) -> shot = @initializeShot attempt: attempt, result: @getResultFromShot({foul: foul, points: points}), points: parseInt(points), Player: @getCurrentPlayer(), shotNumber: @get('Shots').length + 1 if shot shot.setApiClient(@client) shot.save(shot.attributes, { success: => @addShot(shot) error: -> shot.destroy() }) shot addShot: (shot) -> @get('Shots').add(shot) @get('shotGroups').addShot(shot) @set('currentPlayer', null) @trigger("update") shot deleteShot: (shotId) -> model = @get('Shots').get shotId model.stopListening() model.trigger 'destroy', model, model.collection Backbone.Relational.store.unregister(model) @get('Shots').trigger "update" @trigger("update") undoShot: -> model = @get('Shots').last() model.setApiClient @client model.destroy wait: true success: => Backbone.Relational.store.unregister(model) @trigger("update") getState: -> scores = @getScores() currentPlayer = @getCurrentPlayer() [ { player: @get('Player1'), score: scores[0], currentPlayer: currentPlayer == @get('Player1') }, { player: @get('Player2'), score: scores[1], currentPlayer: currentPlayer == @get('Player2') }, ] calculateStats: -> stats = @get('shotGroups').calculateStats() safeties = @get('Shots').calculateSafeties() stats[@get('Player1').id]?['safeties'] = safeties[@get('Player1').id] stats[@get('Player2').id]?['safeties'] = safeties[@get('Player2').id] [stats[@get('Player1').id], stats[@get('Player2').id]] getScores: -> rawTotals = @get('shotGroups').calculateTotalScores() firstTotal = rawTotals[@get('Player1').id] || { points: 0, fouls: 0 } secondTotal = rawTotals[@get('Player2').id] || { points: 0, fouls: 0 } [firstTotal.points + secondTotal.fouls, secondTotal.points + firstTotal.fouls] getPlayer: (id) -> if @get('Player1').id == id @get('Player1') else if @get('Player2').id == id @get('Player2') getLeader: -> scores = @getScores() if scores[0] > scores[1] @get('Player1') else if scores[1] > scores[0] @get('Player2') else "tie" populateAssociations: -> @set('Player1', Player.findModel(@get('Player1Id'))) @set('Player2', Player.findModel(@get('Player2Id'))) @set('League', League.findModel(@get('LeagueId'))) @set('Winner', Player.findModel(@get('WinnerId'))) changePlayerAllowed: -> !@get('Shots').last() || @get('Shots').last().isFoul() setPlayerInTurn: (playerId) -> @set('currentPlayer', @getPlayer(playerId)) @trigger("update") changePlayer: -> if @changePlayerAllowed() @save({currentPlayer: @getNonCurrentPlayer()}, {patch: true, url: @url() + "/playerchange"}) @trigger("update") Frame.setup() class Frames extends Livesnooker.Collection model: Frame url: -> "/leagues/#{@leagueId}/frames" comparator: (frame) -> if frame.get('endedAt') 1 / new Date(frame.get('endedAt')).getTime() else - new Date(frame.get('createdAt')).getTime() ((scope) -> scope.Frame = Frame scope.Frames = Frames )(@)
190624
class Frame extends Livesnooker.Model urlRoot: -> leagueId = @get('League')?.id || @get('LeagueId') "/leagues/" + leagueId + "/frames" relations: [ { type: Backbone.HasOne, key: 'Player1', relatedModel: 'Player', keyDestination: 'Player1<KEY>', includeInJSON: 'id' }, { type: Backbone.HasOne, key: 'Player<KEY>', relatedModel: 'Player', keyDestination: 'Player2Id', includeInJSON: 'id' }, { type: Backbone.HasMany key: 'Shots' relatedModel: 'Shot' collectionType: 'Shots' reverseRelation: key: 'Frame' keyDestination: 'FrameId' includeInJSON: 'id' }, { type: Backbone.HasOne, key: 'Winner', relatedModel: 'Player', keyDestination: 'WinnerId', includeInJSON: 'id' } ] initialize: (options) -> @set('shotGroups', new ShotGroups([], frame: @)) calculateShotGroups: -> @get('shotGroups').reset() shots = @get('Shots') shots.sort() shots.each (shot) => @get('shotGroups').addShot(shot) lastShot: -> @get('shotGroups').last()?.lastShot() getCurrentPlayer: -> if @get('currentPlayer') @get('currentPlayer') else lastShot = @lastShot() if lastShot if lastShot.isPot() lastShot.get('Player') else @getOtherPlayer(lastShot.get('Player')) else @get('Player1') getNonCurrentPlayer: -> @getOtherPlayer(@getCurrentPlayer()) getOtherPlayer: (player) -> if @get('Player1') == player @get('Player2') else if @get('Player2') == player @get('Player1') currentPlayerIndex: -> if @getCurrentPlayer() == @get('Player1') 0 else 1 initializeShot: (data) -> return if @get('Shots').find((shot) -> shot.get('shotNumber') == data.shotNumber) _.extend(data, { Frame: @ }) if not data.Player && data.PlayerId data.Player = @getPlayer(data.PlayerId) shot = new Shot(data) if shot.validate(shot.attributes) throw shot.validate(shot.attributes) shot getResultFromShot: ({points, foul}) -> if foul "foul" else if parseInt(points) == 0 "nothing" else "pot" createShot: ({attempt, points, foul}) -> shot = @initializeShot attempt: attempt, result: @getResultFromShot({foul: foul, points: points}), points: parseInt(points), Player: @getCurrentPlayer(), shotNumber: @get('Shots').length + 1 if shot shot.setApiClient(@client) shot.save(shot.attributes, { success: => @addShot(shot) error: -> shot.destroy() }) shot addShot: (shot) -> @get('Shots').add(shot) @get('shotGroups').addShot(shot) @set('currentPlayer', null) @trigger("update") shot deleteShot: (shotId) -> model = @get('Shots').get shotId model.stopListening() model.trigger 'destroy', model, model.collection Backbone.Relational.store.unregister(model) @get('Shots').trigger "update" @trigger("update") undoShot: -> model = @get('Shots').last() model.setApiClient @client model.destroy wait: true success: => Backbone.Relational.store.unregister(model) @trigger("update") getState: -> scores = @getScores() currentPlayer = @getCurrentPlayer() [ { player: @get('Player1'), score: scores[0], currentPlayer: currentPlayer == @get('Player1') }, { player: @get('Player2'), score: scores[1], currentPlayer: currentPlayer == @get('Player2') }, ] calculateStats: -> stats = @get('shotGroups').calculateStats() safeties = @get('Shots').calculateSafeties() stats[@get('Player1').id]?['safeties'] = safeties[@get('Player1').id] stats[@get('Player2').id]?['safeties'] = safeties[@get('Player2').id] [stats[@get('Player1').id], stats[@get('Player2').id]] getScores: -> rawTotals = @get('shotGroups').calculateTotalScores() firstTotal = rawTotals[@get('Player1').id] || { points: 0, fouls: 0 } secondTotal = rawTotals[@get('Player2').id] || { points: 0, fouls: 0 } [firstTotal.points + secondTotal.fouls, secondTotal.points + firstTotal.fouls] getPlayer: (id) -> if @get('Player1').id == id @get('Player1') else if @get('Player2').id == id @get('Player2') getLeader: -> scores = @getScores() if scores[0] > scores[1] @get('Player1') else if scores[1] > scores[0] @get('Player2') else "tie" populateAssociations: -> @set('Player1', Player.findModel(@get('Player1Id'))) @set('Player2', Player.findModel(@get('Player2Id'))) @set('League', League.findModel(@get('LeagueId'))) @set('Winner', Player.findModel(@get('WinnerId'))) changePlayerAllowed: -> !@get('Shots').last() || @get('Shots').last().isFoul() setPlayerInTurn: (playerId) -> @set('currentPlayer', @getPlayer(playerId)) @trigger("update") changePlayer: -> if @changePlayerAllowed() @save({currentPlayer: @getNonCurrentPlayer()}, {patch: true, url: @url() + "/playerchange"}) @trigger("update") Frame.setup() class Frames extends Livesnooker.Collection model: Frame url: -> "/leagues/#{@leagueId}/frames" comparator: (frame) -> if frame.get('endedAt') 1 / new Date(frame.get('endedAt')).getTime() else - new Date(frame.get('createdAt')).getTime() ((scope) -> scope.Frame = Frame scope.Frames = Frames )(@)
true
class Frame extends Livesnooker.Model urlRoot: -> leagueId = @get('League')?.id || @get('LeagueId') "/leagues/" + leagueId + "/frames" relations: [ { type: Backbone.HasOne, key: 'Player1', relatedModel: 'Player', keyDestination: 'Player1PI:KEY:<KEY>END_PI', includeInJSON: 'id' }, { type: Backbone.HasOne, key: 'PlayerPI:KEY:<KEY>END_PI', relatedModel: 'Player', keyDestination: 'Player2Id', includeInJSON: 'id' }, { type: Backbone.HasMany key: 'Shots' relatedModel: 'Shot' collectionType: 'Shots' reverseRelation: key: 'Frame' keyDestination: 'FrameId' includeInJSON: 'id' }, { type: Backbone.HasOne, key: 'Winner', relatedModel: 'Player', keyDestination: 'WinnerId', includeInJSON: 'id' } ] initialize: (options) -> @set('shotGroups', new ShotGroups([], frame: @)) calculateShotGroups: -> @get('shotGroups').reset() shots = @get('Shots') shots.sort() shots.each (shot) => @get('shotGroups').addShot(shot) lastShot: -> @get('shotGroups').last()?.lastShot() getCurrentPlayer: -> if @get('currentPlayer') @get('currentPlayer') else lastShot = @lastShot() if lastShot if lastShot.isPot() lastShot.get('Player') else @getOtherPlayer(lastShot.get('Player')) else @get('Player1') getNonCurrentPlayer: -> @getOtherPlayer(@getCurrentPlayer()) getOtherPlayer: (player) -> if @get('Player1') == player @get('Player2') else if @get('Player2') == player @get('Player1') currentPlayerIndex: -> if @getCurrentPlayer() == @get('Player1') 0 else 1 initializeShot: (data) -> return if @get('Shots').find((shot) -> shot.get('shotNumber') == data.shotNumber) _.extend(data, { Frame: @ }) if not data.Player && data.PlayerId data.Player = @getPlayer(data.PlayerId) shot = new Shot(data) if shot.validate(shot.attributes) throw shot.validate(shot.attributes) shot getResultFromShot: ({points, foul}) -> if foul "foul" else if parseInt(points) == 0 "nothing" else "pot" createShot: ({attempt, points, foul}) -> shot = @initializeShot attempt: attempt, result: @getResultFromShot({foul: foul, points: points}), points: parseInt(points), Player: @getCurrentPlayer(), shotNumber: @get('Shots').length + 1 if shot shot.setApiClient(@client) shot.save(shot.attributes, { success: => @addShot(shot) error: -> shot.destroy() }) shot addShot: (shot) -> @get('Shots').add(shot) @get('shotGroups').addShot(shot) @set('currentPlayer', null) @trigger("update") shot deleteShot: (shotId) -> model = @get('Shots').get shotId model.stopListening() model.trigger 'destroy', model, model.collection Backbone.Relational.store.unregister(model) @get('Shots').trigger "update" @trigger("update") undoShot: -> model = @get('Shots').last() model.setApiClient @client model.destroy wait: true success: => Backbone.Relational.store.unregister(model) @trigger("update") getState: -> scores = @getScores() currentPlayer = @getCurrentPlayer() [ { player: @get('Player1'), score: scores[0], currentPlayer: currentPlayer == @get('Player1') }, { player: @get('Player2'), score: scores[1], currentPlayer: currentPlayer == @get('Player2') }, ] calculateStats: -> stats = @get('shotGroups').calculateStats() safeties = @get('Shots').calculateSafeties() stats[@get('Player1').id]?['safeties'] = safeties[@get('Player1').id] stats[@get('Player2').id]?['safeties'] = safeties[@get('Player2').id] [stats[@get('Player1').id], stats[@get('Player2').id]] getScores: -> rawTotals = @get('shotGroups').calculateTotalScores() firstTotal = rawTotals[@get('Player1').id] || { points: 0, fouls: 0 } secondTotal = rawTotals[@get('Player2').id] || { points: 0, fouls: 0 } [firstTotal.points + secondTotal.fouls, secondTotal.points + firstTotal.fouls] getPlayer: (id) -> if @get('Player1').id == id @get('Player1') else if @get('Player2').id == id @get('Player2') getLeader: -> scores = @getScores() if scores[0] > scores[1] @get('Player1') else if scores[1] > scores[0] @get('Player2') else "tie" populateAssociations: -> @set('Player1', Player.findModel(@get('Player1Id'))) @set('Player2', Player.findModel(@get('Player2Id'))) @set('League', League.findModel(@get('LeagueId'))) @set('Winner', Player.findModel(@get('WinnerId'))) changePlayerAllowed: -> !@get('Shots').last() || @get('Shots').last().isFoul() setPlayerInTurn: (playerId) -> @set('currentPlayer', @getPlayer(playerId)) @trigger("update") changePlayer: -> if @changePlayerAllowed() @save({currentPlayer: @getNonCurrentPlayer()}, {patch: true, url: @url() + "/playerchange"}) @trigger("update") Frame.setup() class Frames extends Livesnooker.Collection model: Frame url: -> "/leagues/#{@leagueId}/frames" comparator: (frame) -> if frame.get('endedAt') 1 / new Date(frame.get('endedAt')).getTime() else - new Date(frame.get('createdAt')).getTime() ((scope) -> scope.Frame = Frame scope.Frames = Frames )(@)
[ { "context": " The UsersList shows a list of users.\n\n @author Sebastian Sachtleben\n###\nclass UsersList extends AdminAuthView\n\n\tentit", "end": 157, "score": 0.9998939037322998, "start": 137, "tag": "NAME", "value": "Sebastian Sachtleben" } ]
app/assets/javascripts/admin/views/users/list.coffee
ssachtleben/herowar
1
AdminAuthView = require 'views/adminAuthView' templates = require 'templates' ### The UsersList shows a list of users. @author Sebastian Sachtleben ### class UsersList extends AdminAuthView entity: 'api/users' id: 'users-list' template: templates.get 'users/list.tmpl' return UsersList
55144
AdminAuthView = require 'views/adminAuthView' templates = require 'templates' ### The UsersList shows a list of users. @author <NAME> ### class UsersList extends AdminAuthView entity: 'api/users' id: 'users-list' template: templates.get 'users/list.tmpl' return UsersList
true
AdminAuthView = require 'views/adminAuthView' templates = require 'templates' ### The UsersList shows a list of users. @author PI:NAME:<NAME>END_PI ### class UsersList extends AdminAuthView entity: 'api/users' id: 'users-list' template: templates.get 'users/list.tmpl' return UsersList
[ { "context": "# Vex.Flow.VexTab\n# Copyright 2012 Mohit Cheppudira <mohit@muthanna.com>\n#\n# This class implements th", "end": 51, "score": 0.9998680949211121, "start": 35, "tag": "NAME", "value": "Mohit Cheppudira" }, { "context": "ex.Flow.VexTab\n# Copyright 2012 Mohit Cheppudira <mohit@muthanna.com>\n#\n# This class implements the semantic analysis ", "end": 71, "score": 0.9999307990074158, "start": 53, "tag": "EMAIL", "value": "mohit@muthanna.com" } ]
src/vextab.coffee
TheodoreChu/vextab
382
# Vex.Flow.VexTab # Copyright 2012 Mohit Cheppudira <mohit@muthanna.com> # # This class implements the semantic analysis of the Jison # output, and generates elements that can be used by # Vex.Flow.Artist to render the notation. # parsed by Vex.Flow.VexTab. import Vex from 'vexflow' import * as _ from 'lodash' import * as parser from './vextab.jison' class VexTab @DEBUG = false L = (args...) -> console?.log("(Vex.Flow.VexTab)", args...) if VexTab.DEBUG # Private methods newError = (object, msg) -> new Vex.RERR("ParseError", "#{msg} in line #{object._l} column #{object._c}") # Public methods constructor: (@artist) -> @reset() reset: -> @valid = false @elements = false isValid: -> @valid getArtist: -> return @artist parseStaveOptions: (options) -> params = {} return params unless options? notation_option = null for option in options error = (msg) -> newError(option, msg) params[option.key] = option.value switch option.key when "notation", "tablature" notation_option = option throw error("'#{option.key}' must be 'true' or 'false'") if option.value not in ["true", "false"] when "key" throw error("Invalid key signature '#{option.value}'") unless _.has(Vex.Flow.keySignature.keySpecs, option.value) when "clef" clefs = ["treble", "bass", "tenor", "alto", "percussion", "none"] throw error("'clef' must be one of #{clefs.join(', ')}") if option.value not in clefs when "voice" voices = ["top", "bottom", "new"] throw error("'voice' must be one of #{voices.join(', ')}") if option.value not in voices when "time" try new Vex.Flow.TimeSignature(option.value) catch e throw error("Invalid time signature: '#{option.value}'") when "tuning" try new Vex.Flow.Tuning(option.value) catch e throw error("Invalid tuning: '#{option.value}'") when "strings" num_strings = parseInt(option.value) throw error("Invalid number of strings: #{num_strings}") if (num_strings < 4 or num_strings > 8) else throw error("Invalid option '#{option.key}'") if params.notation == "false" and params.tablature == "false" throw newError(notation_option, "Both 'notation' and 'tablature' can't be invisible") return params parseCommand: (element) -> if element.command is "bar" @artist.addBar(element.type) if element.command is "tuplet" @artist.makeTuplets(element.params.tuplet, element.params.notes) if element.command is "annotations" @artist.addAnnotations(element.params) if element.command is "rest" @artist.addRest(element.params) if element.command is "command" @artist.runCommand(element.params, element._l, element._c) parseChord: (element) -> L "parseChord:", element @artist.addChord( _.map(element.chord, (note)-> _.pick(note, 'time', 'dot', 'fret', 'abc', 'octave', 'string', 'articulation', 'decorator')), element.articulation, element.decorator) parseFret: (note) -> @artist.addNote(_.pick( note, 'time', 'dot', 'fret', 'string', 'articulation', 'decorator')) parseABC: (note) -> @artist.addNote(_.pick( note, 'time', 'dot', 'fret', 'abc', 'octave', 'string', 'articulation', 'decorator')) parseStaveElements: (notes) -> L "parseStaveElements:", notes for element in notes if element.time @artist.setDuration(element.time, element.dot) if element.command @parseCommand(element) if element.chord @parseChord(element) if element.abc @parseABC(element) else if element.fret @parseFret(element) parseStaveText: (text_line) -> @artist.addTextVoice() unless _.isEmpty(text_line) position = 0 justification = "center" smooth = true font = null bartext = => @artist.addTextNote("", 0, justification, false, true) createNote = (text) => ignore_ticks = false if text[0] == "|" ignore_ticks = true text = text[1..] try @artist.addTextNote(text, position, justification, smooth, ignore_ticks) catch e throw newError(str, "Bad text or duration. Did you forget a comma?" + e) for str in text_line text = str.text.trim() if text.match(/\.font=.*/) font = text[6..] @artist.setTextFont(font) else if text[0] == ":" @artist.setDuration(text) else if text[0] == "." command = text[1..] switch command when "center", "left", "right" justification = command when "strict" smooth = false when "smooth" smooth = true when "bar", "|" bartext() else position = parseInt(text[1..], 10) else if text == "|" bartext() else if text[0..1] == "++" @artist.addTextVoice() else createNote(text) generate: -> for stave in @elements switch stave.element when "stave", "tabstave" @artist.addStave(stave.element, @parseStaveOptions(stave.options)) @parseStaveElements(stave.notes) if stave.notes? @parseStaveText(stave.text) if stave.text? when "voice" @artist.addVoice(@parseStaveOptions(stave.options)) @parseStaveElements(stave.notes) if stave.notes? @parseStaveText(stave.text) if stave.text? when "options" options = {} for option in stave.params options[option.key] = option.value try @artist.setOptions(options) catch e throw newError(stave, e.message) else throw newError(stave, "Invalid keyword '#{stave.element}'") parse: (code) -> parser.parseError = (message, hash) -> L "VexTab parse error: ", message, hash message = "Unexpected text '#{hash.text}' at line #{hash.loc.first_line} column #{hash.loc.first_column}." throw new Vex.RERR("ParseError", message) throw new Vex.RERR("ParseError", "No code") unless code? L "Parsing:\n#{code}" # Strip lines stripped_code = (line.trim() for line in code.split(/\r\n|\r|\n/)) @elements = parser.parse(stripped_code.join("\n")) if @elements @generate() @valid = true return @elements export default VexTab
206129
# Vex.Flow.VexTab # Copyright 2012 <NAME> <<EMAIL>> # # This class implements the semantic analysis of the Jison # output, and generates elements that can be used by # Vex.Flow.Artist to render the notation. # parsed by Vex.Flow.VexTab. import Vex from 'vexflow' import * as _ from 'lodash' import * as parser from './vextab.jison' class VexTab @DEBUG = false L = (args...) -> console?.log("(Vex.Flow.VexTab)", args...) if VexTab.DEBUG # Private methods newError = (object, msg) -> new Vex.RERR("ParseError", "#{msg} in line #{object._l} column #{object._c}") # Public methods constructor: (@artist) -> @reset() reset: -> @valid = false @elements = false isValid: -> @valid getArtist: -> return @artist parseStaveOptions: (options) -> params = {} return params unless options? notation_option = null for option in options error = (msg) -> newError(option, msg) params[option.key] = option.value switch option.key when "notation", "tablature" notation_option = option throw error("'#{option.key}' must be 'true' or 'false'") if option.value not in ["true", "false"] when "key" throw error("Invalid key signature '#{option.value}'") unless _.has(Vex.Flow.keySignature.keySpecs, option.value) when "clef" clefs = ["treble", "bass", "tenor", "alto", "percussion", "none"] throw error("'clef' must be one of #{clefs.join(', ')}") if option.value not in clefs when "voice" voices = ["top", "bottom", "new"] throw error("'voice' must be one of #{voices.join(', ')}") if option.value not in voices when "time" try new Vex.Flow.TimeSignature(option.value) catch e throw error("Invalid time signature: '#{option.value}'") when "tuning" try new Vex.Flow.Tuning(option.value) catch e throw error("Invalid tuning: '#{option.value}'") when "strings" num_strings = parseInt(option.value) throw error("Invalid number of strings: #{num_strings}") if (num_strings < 4 or num_strings > 8) else throw error("Invalid option '#{option.key}'") if params.notation == "false" and params.tablature == "false" throw newError(notation_option, "Both 'notation' and 'tablature' can't be invisible") return params parseCommand: (element) -> if element.command is "bar" @artist.addBar(element.type) if element.command is "tuplet" @artist.makeTuplets(element.params.tuplet, element.params.notes) if element.command is "annotations" @artist.addAnnotations(element.params) if element.command is "rest" @artist.addRest(element.params) if element.command is "command" @artist.runCommand(element.params, element._l, element._c) parseChord: (element) -> L "parseChord:", element @artist.addChord( _.map(element.chord, (note)-> _.pick(note, 'time', 'dot', 'fret', 'abc', 'octave', 'string', 'articulation', 'decorator')), element.articulation, element.decorator) parseFret: (note) -> @artist.addNote(_.pick( note, 'time', 'dot', 'fret', 'string', 'articulation', 'decorator')) parseABC: (note) -> @artist.addNote(_.pick( note, 'time', 'dot', 'fret', 'abc', 'octave', 'string', 'articulation', 'decorator')) parseStaveElements: (notes) -> L "parseStaveElements:", notes for element in notes if element.time @artist.setDuration(element.time, element.dot) if element.command @parseCommand(element) if element.chord @parseChord(element) if element.abc @parseABC(element) else if element.fret @parseFret(element) parseStaveText: (text_line) -> @artist.addTextVoice() unless _.isEmpty(text_line) position = 0 justification = "center" smooth = true font = null bartext = => @artist.addTextNote("", 0, justification, false, true) createNote = (text) => ignore_ticks = false if text[0] == "|" ignore_ticks = true text = text[1..] try @artist.addTextNote(text, position, justification, smooth, ignore_ticks) catch e throw newError(str, "Bad text or duration. Did you forget a comma?" + e) for str in text_line text = str.text.trim() if text.match(/\.font=.*/) font = text[6..] @artist.setTextFont(font) else if text[0] == ":" @artist.setDuration(text) else if text[0] == "." command = text[1..] switch command when "center", "left", "right" justification = command when "strict" smooth = false when "smooth" smooth = true when "bar", "|" bartext() else position = parseInt(text[1..], 10) else if text == "|" bartext() else if text[0..1] == "++" @artist.addTextVoice() else createNote(text) generate: -> for stave in @elements switch stave.element when "stave", "tabstave" @artist.addStave(stave.element, @parseStaveOptions(stave.options)) @parseStaveElements(stave.notes) if stave.notes? @parseStaveText(stave.text) if stave.text? when "voice" @artist.addVoice(@parseStaveOptions(stave.options)) @parseStaveElements(stave.notes) if stave.notes? @parseStaveText(stave.text) if stave.text? when "options" options = {} for option in stave.params options[option.key] = option.value try @artist.setOptions(options) catch e throw newError(stave, e.message) else throw newError(stave, "Invalid keyword '#{stave.element}'") parse: (code) -> parser.parseError = (message, hash) -> L "VexTab parse error: ", message, hash message = "Unexpected text '#{hash.text}' at line #{hash.loc.first_line} column #{hash.loc.first_column}." throw new Vex.RERR("ParseError", message) throw new Vex.RERR("ParseError", "No code") unless code? L "Parsing:\n#{code}" # Strip lines stripped_code = (line.trim() for line in code.split(/\r\n|\r|\n/)) @elements = parser.parse(stripped_code.join("\n")) if @elements @generate() @valid = true return @elements export default VexTab
true
# Vex.Flow.VexTab # Copyright 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This class implements the semantic analysis of the Jison # output, and generates elements that can be used by # Vex.Flow.Artist to render the notation. # parsed by Vex.Flow.VexTab. import Vex from 'vexflow' import * as _ from 'lodash' import * as parser from './vextab.jison' class VexTab @DEBUG = false L = (args...) -> console?.log("(Vex.Flow.VexTab)", args...) if VexTab.DEBUG # Private methods newError = (object, msg) -> new Vex.RERR("ParseError", "#{msg} in line #{object._l} column #{object._c}") # Public methods constructor: (@artist) -> @reset() reset: -> @valid = false @elements = false isValid: -> @valid getArtist: -> return @artist parseStaveOptions: (options) -> params = {} return params unless options? notation_option = null for option in options error = (msg) -> newError(option, msg) params[option.key] = option.value switch option.key when "notation", "tablature" notation_option = option throw error("'#{option.key}' must be 'true' or 'false'") if option.value not in ["true", "false"] when "key" throw error("Invalid key signature '#{option.value}'") unless _.has(Vex.Flow.keySignature.keySpecs, option.value) when "clef" clefs = ["treble", "bass", "tenor", "alto", "percussion", "none"] throw error("'clef' must be one of #{clefs.join(', ')}") if option.value not in clefs when "voice" voices = ["top", "bottom", "new"] throw error("'voice' must be one of #{voices.join(', ')}") if option.value not in voices when "time" try new Vex.Flow.TimeSignature(option.value) catch e throw error("Invalid time signature: '#{option.value}'") when "tuning" try new Vex.Flow.Tuning(option.value) catch e throw error("Invalid tuning: '#{option.value}'") when "strings" num_strings = parseInt(option.value) throw error("Invalid number of strings: #{num_strings}") if (num_strings < 4 or num_strings > 8) else throw error("Invalid option '#{option.key}'") if params.notation == "false" and params.tablature == "false" throw newError(notation_option, "Both 'notation' and 'tablature' can't be invisible") return params parseCommand: (element) -> if element.command is "bar" @artist.addBar(element.type) if element.command is "tuplet" @artist.makeTuplets(element.params.tuplet, element.params.notes) if element.command is "annotations" @artist.addAnnotations(element.params) if element.command is "rest" @artist.addRest(element.params) if element.command is "command" @artist.runCommand(element.params, element._l, element._c) parseChord: (element) -> L "parseChord:", element @artist.addChord( _.map(element.chord, (note)-> _.pick(note, 'time', 'dot', 'fret', 'abc', 'octave', 'string', 'articulation', 'decorator')), element.articulation, element.decorator) parseFret: (note) -> @artist.addNote(_.pick( note, 'time', 'dot', 'fret', 'string', 'articulation', 'decorator')) parseABC: (note) -> @artist.addNote(_.pick( note, 'time', 'dot', 'fret', 'abc', 'octave', 'string', 'articulation', 'decorator')) parseStaveElements: (notes) -> L "parseStaveElements:", notes for element in notes if element.time @artist.setDuration(element.time, element.dot) if element.command @parseCommand(element) if element.chord @parseChord(element) if element.abc @parseABC(element) else if element.fret @parseFret(element) parseStaveText: (text_line) -> @artist.addTextVoice() unless _.isEmpty(text_line) position = 0 justification = "center" smooth = true font = null bartext = => @artist.addTextNote("", 0, justification, false, true) createNote = (text) => ignore_ticks = false if text[0] == "|" ignore_ticks = true text = text[1..] try @artist.addTextNote(text, position, justification, smooth, ignore_ticks) catch e throw newError(str, "Bad text or duration. Did you forget a comma?" + e) for str in text_line text = str.text.trim() if text.match(/\.font=.*/) font = text[6..] @artist.setTextFont(font) else if text[0] == ":" @artist.setDuration(text) else if text[0] == "." command = text[1..] switch command when "center", "left", "right" justification = command when "strict" smooth = false when "smooth" smooth = true when "bar", "|" bartext() else position = parseInt(text[1..], 10) else if text == "|" bartext() else if text[0..1] == "++" @artist.addTextVoice() else createNote(text) generate: -> for stave in @elements switch stave.element when "stave", "tabstave" @artist.addStave(stave.element, @parseStaveOptions(stave.options)) @parseStaveElements(stave.notes) if stave.notes? @parseStaveText(stave.text) if stave.text? when "voice" @artist.addVoice(@parseStaveOptions(stave.options)) @parseStaveElements(stave.notes) if stave.notes? @parseStaveText(stave.text) if stave.text? when "options" options = {} for option in stave.params options[option.key] = option.value try @artist.setOptions(options) catch e throw newError(stave, e.message) else throw newError(stave, "Invalid keyword '#{stave.element}'") parse: (code) -> parser.parseError = (message, hash) -> L "VexTab parse error: ", message, hash message = "Unexpected text '#{hash.text}' at line #{hash.loc.first_line} column #{hash.loc.first_column}." throw new Vex.RERR("ParseError", message) throw new Vex.RERR("ParseError", "No code") unless code? L "Parsing:\n#{code}" # Strip lines stripped_code = (line.trim() for line in code.split(/\r\n|\r|\n/)) @elements = parser.parse(stripped_code.join("\n")) if @elements @generate() @valid = true return @elements export default VexTab
[ { "context": " my research project on blah blah blah\"\nauthor = \"Your Name\"\nemail = \"yname@someuniversity.edu\"\nurl = \"http:/", "end": 164, "score": 0.997640073299408, "start": 155, "tag": "NAME", "value": "Your Name" }, { "context": " on blah blah blah\"\nauthor = \"Your Name\"\nemail = \"yname@someuniversity.edu\"\nurl = \"http://someuniversity.edu/~yname/my-aweso", "end": 199, "score": 0.9999246597290039, "start": 175, "tag": "EMAIL", "value": "yname@someuniversity.edu" }, { "context": "university.edu\"\nurl = \"http://someuniversity.edu/~yname/my-awesome-research-site\"\n\n# Want to include some", "end": 240, "score": 0.9950718283653259, "start": 235, "tag": "USERNAME", "value": "yname" }, { "context": "People involved in your project\npeople =\n\talice: \"Alice Aliceson\"\n\tbob: \"Bob Roberts\"\n\teve: \"Eve Evil\"\n# You can a", "end": 593, "score": 0.9998879432678223, "start": 579, "tag": "NAME", "value": "Alice Aliceson" }, { "context": "n your project\npeople =\n\talice: \"Alice Aliceson\"\n\tbob: \"Bob Roberts\"\n\teve: \"Eve Evil\"\n# You can add the", "end": 599, "score": 0.6900284886360168, "start": 596, "tag": "NAME", "value": "bob" }, { "context": " project\npeople =\n\talice: \"Alice Aliceson\"\n\tbob: \"Bob Roberts\"\n\teve: \"Eve Evil\"\n# You can add these people to m", "end": 613, "score": 0.9998750686645508, "start": 602, "tag": "NAME", "value": "Bob Roberts" }, { "context": "e =\n\talice: \"Alice Aliceson\"\n\tbob: \"Bob Roberts\"\n\teve: \"Eve Evil\"\n# You can add these people to meeting", "end": 619, "score": 0.8779504299163818, "start": 616, "tag": "NAME", "value": "eve" }, { "context": "lice: \"Alice Aliceson\"\n\tbob: \"Bob Roberts\"\n\teve: \"Eve Evil\"\n# You can add these people to meeting metadata s", "end": 630, "score": 0.9998782873153687, "start": 622, "tag": "NAME", "value": "Eve Evil" } ]
docpad.coffee
srubin/docpad-research-site-skeleton
0
# Basic information about your site title = "Your Name's Research Site" description = "This is a site for my research project on blah blah blah" author = "Your Name" email = "yname@someuniversity.edu" url = "http://someuniversity.edu/~yname/my-awesome-research-site" # Want to include some stylesheets on every page? css = [ "styles/sample-style.css" ] # To spruce things up a bit- set the color for the navbar. # (For the sake of readability, it should probably be a fairly light color!) navbarBackgroundColor = "#9EE5B6" # People involved in your project people = alice: "Alice Aliceson" bob: "Bob Roberts" eve: "Eve Evil" # You can add these people to meeting metadata so you can remember who # participated in the meeting. See the sample meeting for an example. # If you want to enable comments on your site, uncomment this line, # change this to the name of your disqus name: # disqus = "mysitename" disqus = false # Note: disqus will only show up when the site is live, not while running # the development server ################################################### # # # You don't need to modify anything below here! # # # ################################################### docpadConfig = { # ================================= # Template Data # These are variables that will be accessible via our templates templateData: site: # The default title of our website title: title # The website description (for SEO) description: description # The website keywords (for SEO) separated by commas keywords: "nope" # The website author's name author: author # The website author's email email: email # Styles styles: [ "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css", "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap-theme.min.css" ] localStyles: css navbarBgColor: navbarBackgroundColor # Scripts included with each page scripts: [ "//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js", "//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js", "//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js", "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js", ] services: disqus: disqus # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') prettyDate: (date) -> "#{date.getMonth() + 1}/#{date.getDate()}/#{date.getFullYear()}" getUrl: (document) -> @site.url + (document.url or document.get?('url')) # audioLink: (text, url) -> # """ # <ul class="playlist"> # <li>[#{text}](../audio/#{url})</li> # </ul> # """ people: people # ================================= # Collections # These are special collections that our website makes available to us collections: pages: (database) -> database.findAllLive({ pageOrder: $exists: true ignored: $ne: true }, [pageOrder:1,title:1]).on "add", (page) -> page.setMeta( layout: "page" ) posts: (database) -> database.findAllLive({ relativeOutDirPath: $startsWith: 'posts' ignored: $ne: true }, [date:-1]).on "add", (post) -> post.setMeta layout: "post" meetings: (database) -> database.findAllLive({ relativeOutDirPath: $startsWith: 'meetings' ignored: $ne: true }, [date:-1]).on "add", (meeting) -> meeting.setMeta( layout: "meeting" ) environments: deploy: templateData: site: url: url development: templateData: site: url: "http://localhost:9778" services: disqus: false plugins: markedOptions: tables: true } docpadConfig.templateData.site.localStyles.splice 0, 0, "styles/default.css" # Export our DocPad Configuration module.exports = docpadConfig
101326
# Basic information about your site title = "Your Name's Research Site" description = "This is a site for my research project on blah blah blah" author = "<NAME>" email = "<EMAIL>" url = "http://someuniversity.edu/~yname/my-awesome-research-site" # Want to include some stylesheets on every page? css = [ "styles/sample-style.css" ] # To spruce things up a bit- set the color for the navbar. # (For the sake of readability, it should probably be a fairly light color!) navbarBackgroundColor = "#9EE5B6" # People involved in your project people = alice: "<NAME>" <NAME>: "<NAME>" <NAME>: "<NAME>" # You can add these people to meeting metadata so you can remember who # participated in the meeting. See the sample meeting for an example. # If you want to enable comments on your site, uncomment this line, # change this to the name of your disqus name: # disqus = "mysitename" disqus = false # Note: disqus will only show up when the site is live, not while running # the development server ################################################### # # # You don't need to modify anything below here! # # # ################################################### docpadConfig = { # ================================= # Template Data # These are variables that will be accessible via our templates templateData: site: # The default title of our website title: title # The website description (for SEO) description: description # The website keywords (for SEO) separated by commas keywords: "nope" # The website author's name author: author # The website author's email email: email # Styles styles: [ "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css", "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap-theme.min.css" ] localStyles: css navbarBgColor: navbarBackgroundColor # Scripts included with each page scripts: [ "//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js", "//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js", "//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js", "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js", ] services: disqus: disqus # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') prettyDate: (date) -> "#{date.getMonth() + 1}/#{date.getDate()}/#{date.getFullYear()}" getUrl: (document) -> @site.url + (document.url or document.get?('url')) # audioLink: (text, url) -> # """ # <ul class="playlist"> # <li>[#{text}](../audio/#{url})</li> # </ul> # """ people: people # ================================= # Collections # These are special collections that our website makes available to us collections: pages: (database) -> database.findAllLive({ pageOrder: $exists: true ignored: $ne: true }, [pageOrder:1,title:1]).on "add", (page) -> page.setMeta( layout: "page" ) posts: (database) -> database.findAllLive({ relativeOutDirPath: $startsWith: 'posts' ignored: $ne: true }, [date:-1]).on "add", (post) -> post.setMeta layout: "post" meetings: (database) -> database.findAllLive({ relativeOutDirPath: $startsWith: 'meetings' ignored: $ne: true }, [date:-1]).on "add", (meeting) -> meeting.setMeta( layout: "meeting" ) environments: deploy: templateData: site: url: url development: templateData: site: url: "http://localhost:9778" services: disqus: false plugins: markedOptions: tables: true } docpadConfig.templateData.site.localStyles.splice 0, 0, "styles/default.css" # Export our DocPad Configuration module.exports = docpadConfig
true
# Basic information about your site title = "Your Name's Research Site" description = "This is a site for my research project on blah blah blah" author = "PI:NAME:<NAME>END_PI" email = "PI:EMAIL:<EMAIL>END_PI" url = "http://someuniversity.edu/~yname/my-awesome-research-site" # Want to include some stylesheets on every page? css = [ "styles/sample-style.css" ] # To spruce things up a bit- set the color for the navbar. # (For the sake of readability, it should probably be a fairly light color!) navbarBackgroundColor = "#9EE5B6" # People involved in your project people = alice: "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI: "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI: "PI:NAME:<NAME>END_PI" # You can add these people to meeting metadata so you can remember who # participated in the meeting. See the sample meeting for an example. # If you want to enable comments on your site, uncomment this line, # change this to the name of your disqus name: # disqus = "mysitename" disqus = false # Note: disqus will only show up when the site is live, not while running # the development server ################################################### # # # You don't need to modify anything below here! # # # ################################################### docpadConfig = { # ================================= # Template Data # These are variables that will be accessible via our templates templateData: site: # The default title of our website title: title # The website description (for SEO) description: description # The website keywords (for SEO) separated by commas keywords: "nope" # The website author's name author: author # The website author's email email: email # Styles styles: [ "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css", "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap-theme.min.css" ] localStyles: css navbarBgColor: navbarBackgroundColor # Scripts included with each page scripts: [ "//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js", "//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js", "//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js", "//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/js/bootstrap.min.js", ] services: disqus: disqus # ----------------------------- # Helper Functions # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') prettyDate: (date) -> "#{date.getMonth() + 1}/#{date.getDate()}/#{date.getFullYear()}" getUrl: (document) -> @site.url + (document.url or document.get?('url')) # audioLink: (text, url) -> # """ # <ul class="playlist"> # <li>[#{text}](../audio/#{url})</li> # </ul> # """ people: people # ================================= # Collections # These are special collections that our website makes available to us collections: pages: (database) -> database.findAllLive({ pageOrder: $exists: true ignored: $ne: true }, [pageOrder:1,title:1]).on "add", (page) -> page.setMeta( layout: "page" ) posts: (database) -> database.findAllLive({ relativeOutDirPath: $startsWith: 'posts' ignored: $ne: true }, [date:-1]).on "add", (post) -> post.setMeta layout: "post" meetings: (database) -> database.findAllLive({ relativeOutDirPath: $startsWith: 'meetings' ignored: $ne: true }, [date:-1]).on "add", (meeting) -> meeting.setMeta( layout: "meeting" ) environments: deploy: templateData: site: url: url development: templateData: site: url: "http://localhost:9778" services: disqus: false plugins: markedOptions: tables: true } docpadConfig.templateData.site.localStyles.splice 0, 0, "styles/default.css" # Export our DocPad Configuration module.exports = docpadConfig
[ { "context": "f LOCAL then \"http://localhost:5000\" else \"http://50.116.7.184\"\n\nurl = window.location.href\n\nwindow.location.hre", "end": 84, "score": 0.9995639324188232, "start": 72, "tag": "IP_ADDRESS", "value": "50.116.7.184" } ]
src/bookmarklet.coffee
feross/Fling
13
LOCAL = off SERVER = if LOCAL then "http://localhost:5000" else "http://50.116.7.184" url = window.location.href window.location.href = "#{SERVER}/static/handler.html?#{url}";
224413
LOCAL = off SERVER = if LOCAL then "http://localhost:5000" else "http://172.16.58.3" url = window.location.href window.location.href = "#{SERVER}/static/handler.html?#{url}";
true
LOCAL = off SERVER = if LOCAL then "http://localhost:5000" else "http://PI:IP_ADDRESS:172.16.58.3END_PI" url = window.location.href window.location.href = "#{SERVER}/static/handler.html?#{url}";
[ { "context": "h ->\n Team.save {\n _id: 't1'\n name: 'foo'\n local: true\n }\n\n it \"should create new", "end": 174, "score": 0.9629014730453491, "start": 171, "tag": "NAME", "value": "foo" } ]
application/api/test/commands/create-new-item-test.coffee
CHU-BURA/clone-app-kobito-oss
215
# require '../../src/commands/create-new-item' describe "src/commands/create-new-item", -> stubDatabases() beforeEach -> Team.save { _id: 't1' name: 'foo' local: true } it "should create new item", -> kobito.commands.createNewItem('title', 'body', [name: 'tag1'], 't1') .then (item) -> assert item.title is 'title' assert item.body is 'body' assert.deepEqual item.tags, [name: 'tag1'] assert item.teamId is 't1'
196467
# require '../../src/commands/create-new-item' describe "src/commands/create-new-item", -> stubDatabases() beforeEach -> Team.save { _id: 't1' name: '<NAME>' local: true } it "should create new item", -> kobito.commands.createNewItem('title', 'body', [name: 'tag1'], 't1') .then (item) -> assert item.title is 'title' assert item.body is 'body' assert.deepEqual item.tags, [name: 'tag1'] assert item.teamId is 't1'
true
# require '../../src/commands/create-new-item' describe "src/commands/create-new-item", -> stubDatabases() beforeEach -> Team.save { _id: 't1' name: 'PI:NAME:<NAME>END_PI' local: true } it "should create new item", -> kobito.commands.createNewItem('title', 'body', [name: 'tag1'], 't1') .then (item) -> assert item.title is 'title' assert item.body is 'body' assert.deepEqual item.tags, [name: 'tag1'] assert item.teamId is 't1'
[ { "context": " add: function(obj) {\n# someQueue.add({key: 'kissmetrics', data: obj});\n# }\n# };\n# batch = new BatchKiss", "end": 519, "score": 0.9893777966499329, "start": 508, "tag": "KEY", "value": "kissmetrics" }, { "context": "gular HTTP API.\n #\n # ```\n # batch.add({name: 'Evan', home: 'San Francisco'}, 482698020);\n # ```\n\n ", "end": 1076, "score": 0.9720538854598999, "start": 1072, "tag": "NAME", "value": "Evan" }, { "context": "etrics'\n # UriSigner library: https://github.com/kissmetrics/uri_signer\n #\n # ##### Arguments\n #\n # `urlTo", "end": 2742, "score": 0.9995978474617004, "start": 2731, "tag": "USERNAME", "value": "kissmetrics" } ]
src/kissmetrics-batch.coffee
evansolomon/kissmetrics-js
1
# # Batch Kissmetrics # ------------------- # Wrapper for queuing batch queries and processing the batch queue. It's # unlikely you should create instances of this class directly. It is used # internally by the `KissmetricsClient` class. # # ##### Arguments # # `queue` (Object): An object with an `add()` method that can append queries # to the batch queue. Queries will be passed as objects and must # be retrievable as objects. # # ``` # queue = { # add: function(obj) { # someQueue.add({key: 'kissmetrics', data: obj}); # } # }; # batch = new BatchKissmetricsClient(queue); # ``` class BatchKissmetricsClient @HOST: 'api.kissmetrics.com' @HTTP_METHOD: 'POST' @API_VERSION: 'v1' constructor: (@queue) -> # ### Add # ------- # Add a query to the queue. # # ##### Arguments # # `data` (Object): Key/value pairs of Kissmetrics properties. Some # properties will be renamed in `_transformData()` based on `data.type` # due to differences between Kissmetrics' batch API and regular HTTP API. # # ``` # batch.add({name: 'Evan', home: 'San Francisco'}, 482698020); # ``` add: (data) -> @queue.add @_transformData data # ### Process # #### (Static) # ------------- # Process the queue of batched queries by sending them to Kissmetrics. # # ##### Arguments # # `queue` (Object): Must have a `get()` method and it should # return an array of queued queries. # # `apiKey` (String): Your API key from Kissmetrics. This is specific to # the batch API and *different* than your regular Kissmetrics API key. # # `apiSecret` (String): Your API secret from Kissmetrics. # # `productGUID` (String): Your Product GUID from Kissmetrics. # # ``` # queue = { # get: function() { # this.queue = someQueue.get('kissmetrics'); # return this.queue.data; # } # }; # Batch.process(queue, 'key', 'secret-key', 'SOME-PRODUCT'); # ``` @process: (queue, apiKey, apiSecret, productGUID) => http = require 'http' urlPath = "#{@API_VERSION}/products/#{productGUID}/tracking/e" urlToSign = "http://#{@HOST}/#{urlPath}" signature = @_generateSignature urlToSign, apiSecret requestBody = JSON.stringify {data: queue.get()} request = http.request method: @HTTP_METHOD host: @HOST path: "/#{urlPath}?_signature=#{signature}" headers: 'X-KM-ApiKey': apiKey 'Connection': 'close' 'Content-Length': requestBody.length request.end requestBody request # ### Generate Signature # #### (Private, Static) # ---------------------- # Generate a signature for a batch request URL. Based on Kissmetrics' # UriSigner library: https://github.com/kissmetrics/uri_signer # # ##### Arguments # # `urlToSign` (String): The URL (including path) that the request will # be sent to. # # `apiSecret` (String): Your API secret from Kissmetrics. @_generateSignature: (urlToSign, apiSecret) => crypto = require 'crypto' signer = crypto.createHmac 'sha256', apiSecret encodedRequest = [@HTTP_METHOD, encodeURIComponent urlToSign].join('&') encodeURIComponent signer.update(encodedRequest).digest('base64') # ### Transform Data # #### (Private) # ------------------ # Rename keys that differ between Kissmetrics' batch API and regular # HTTP API. # # * `_p` (person) is replaced by `identity` # * `_t` (timestamp) is replaced by `timestamp` # * `_d` (date provided) is ignored because all batch queries provide dates # * `record` queries use the `event` property instead of `_n` # * `alias` queries use the `alias` property instead of `_n` # * `_k` (API key) is replaced by an HTTP header # * `__type` is only used internally # # ##### Arguments # # `data` (Object): Key/value pairs of properties to send to Kissmetrics. _transformData: (data) -> data.identity = data._p data.timestamp = data._t || Math.round(Date.now() / 1000) switch data.__type when 'record' then data.event = data._n when 'alias' then data.alias = data._n reservedKeys = ['_k', '_n', '_p', '_t', '_d', '__type'] delete data[reservedKey] for reservedKey in reservedKeys data # ## Exports # ----------- # Expose BatchKissmetricsClient as a Node.js module. module.exports = BatchKissmetricsClient
146550
# # Batch Kissmetrics # ------------------- # Wrapper for queuing batch queries and processing the batch queue. It's # unlikely you should create instances of this class directly. It is used # internally by the `KissmetricsClient` class. # # ##### Arguments # # `queue` (Object): An object with an `add()` method that can append queries # to the batch queue. Queries will be passed as objects and must # be retrievable as objects. # # ``` # queue = { # add: function(obj) { # someQueue.add({key: '<KEY>', data: obj}); # } # }; # batch = new BatchKissmetricsClient(queue); # ``` class BatchKissmetricsClient @HOST: 'api.kissmetrics.com' @HTTP_METHOD: 'POST' @API_VERSION: 'v1' constructor: (@queue) -> # ### Add # ------- # Add a query to the queue. # # ##### Arguments # # `data` (Object): Key/value pairs of Kissmetrics properties. Some # properties will be renamed in `_transformData()` based on `data.type` # due to differences between Kissmetrics' batch API and regular HTTP API. # # ``` # batch.add({name: '<NAME>', home: 'San Francisco'}, 482698020); # ``` add: (data) -> @queue.add @_transformData data # ### Process # #### (Static) # ------------- # Process the queue of batched queries by sending them to Kissmetrics. # # ##### Arguments # # `queue` (Object): Must have a `get()` method and it should # return an array of queued queries. # # `apiKey` (String): Your API key from Kissmetrics. This is specific to # the batch API and *different* than your regular Kissmetrics API key. # # `apiSecret` (String): Your API secret from Kissmetrics. # # `productGUID` (String): Your Product GUID from Kissmetrics. # # ``` # queue = { # get: function() { # this.queue = someQueue.get('kissmetrics'); # return this.queue.data; # } # }; # Batch.process(queue, 'key', 'secret-key', 'SOME-PRODUCT'); # ``` @process: (queue, apiKey, apiSecret, productGUID) => http = require 'http' urlPath = "#{@API_VERSION}/products/#{productGUID}/tracking/e" urlToSign = "http://#{@HOST}/#{urlPath}" signature = @_generateSignature urlToSign, apiSecret requestBody = JSON.stringify {data: queue.get()} request = http.request method: @HTTP_METHOD host: @HOST path: "/#{urlPath}?_signature=#{signature}" headers: 'X-KM-ApiKey': apiKey 'Connection': 'close' 'Content-Length': requestBody.length request.end requestBody request # ### Generate Signature # #### (Private, Static) # ---------------------- # Generate a signature for a batch request URL. Based on Kissmetrics' # UriSigner library: https://github.com/kissmetrics/uri_signer # # ##### Arguments # # `urlToSign` (String): The URL (including path) that the request will # be sent to. # # `apiSecret` (String): Your API secret from Kissmetrics. @_generateSignature: (urlToSign, apiSecret) => crypto = require 'crypto' signer = crypto.createHmac 'sha256', apiSecret encodedRequest = [@HTTP_METHOD, encodeURIComponent urlToSign].join('&') encodeURIComponent signer.update(encodedRequest).digest('base64') # ### Transform Data # #### (Private) # ------------------ # Rename keys that differ between Kissmetrics' batch API and regular # HTTP API. # # * `_p` (person) is replaced by `identity` # * `_t` (timestamp) is replaced by `timestamp` # * `_d` (date provided) is ignored because all batch queries provide dates # * `record` queries use the `event` property instead of `_n` # * `alias` queries use the `alias` property instead of `_n` # * `_k` (API key) is replaced by an HTTP header # * `__type` is only used internally # # ##### Arguments # # `data` (Object): Key/value pairs of properties to send to Kissmetrics. _transformData: (data) -> data.identity = data._p data.timestamp = data._t || Math.round(Date.now() / 1000) switch data.__type when 'record' then data.event = data._n when 'alias' then data.alias = data._n reservedKeys = ['_k', '_n', '_p', '_t', '_d', '__type'] delete data[reservedKey] for reservedKey in reservedKeys data # ## Exports # ----------- # Expose BatchKissmetricsClient as a Node.js module. module.exports = BatchKissmetricsClient
true
# # Batch Kissmetrics # ------------------- # Wrapper for queuing batch queries and processing the batch queue. It's # unlikely you should create instances of this class directly. It is used # internally by the `KissmetricsClient` class. # # ##### Arguments # # `queue` (Object): An object with an `add()` method that can append queries # to the batch queue. Queries will be passed as objects and must # be retrievable as objects. # # ``` # queue = { # add: function(obj) { # someQueue.add({key: 'PI:KEY:<KEY>END_PI', data: obj}); # } # }; # batch = new BatchKissmetricsClient(queue); # ``` class BatchKissmetricsClient @HOST: 'api.kissmetrics.com' @HTTP_METHOD: 'POST' @API_VERSION: 'v1' constructor: (@queue) -> # ### Add # ------- # Add a query to the queue. # # ##### Arguments # # `data` (Object): Key/value pairs of Kissmetrics properties. Some # properties will be renamed in `_transformData()` based on `data.type` # due to differences between Kissmetrics' batch API and regular HTTP API. # # ``` # batch.add({name: 'PI:NAME:<NAME>END_PI', home: 'San Francisco'}, 482698020); # ``` add: (data) -> @queue.add @_transformData data # ### Process # #### (Static) # ------------- # Process the queue of batched queries by sending them to Kissmetrics. # # ##### Arguments # # `queue` (Object): Must have a `get()` method and it should # return an array of queued queries. # # `apiKey` (String): Your API key from Kissmetrics. This is specific to # the batch API and *different* than your regular Kissmetrics API key. # # `apiSecret` (String): Your API secret from Kissmetrics. # # `productGUID` (String): Your Product GUID from Kissmetrics. # # ``` # queue = { # get: function() { # this.queue = someQueue.get('kissmetrics'); # return this.queue.data; # } # }; # Batch.process(queue, 'key', 'secret-key', 'SOME-PRODUCT'); # ``` @process: (queue, apiKey, apiSecret, productGUID) => http = require 'http' urlPath = "#{@API_VERSION}/products/#{productGUID}/tracking/e" urlToSign = "http://#{@HOST}/#{urlPath}" signature = @_generateSignature urlToSign, apiSecret requestBody = JSON.stringify {data: queue.get()} request = http.request method: @HTTP_METHOD host: @HOST path: "/#{urlPath}?_signature=#{signature}" headers: 'X-KM-ApiKey': apiKey 'Connection': 'close' 'Content-Length': requestBody.length request.end requestBody request # ### Generate Signature # #### (Private, Static) # ---------------------- # Generate a signature for a batch request URL. Based on Kissmetrics' # UriSigner library: https://github.com/kissmetrics/uri_signer # # ##### Arguments # # `urlToSign` (String): The URL (including path) that the request will # be sent to. # # `apiSecret` (String): Your API secret from Kissmetrics. @_generateSignature: (urlToSign, apiSecret) => crypto = require 'crypto' signer = crypto.createHmac 'sha256', apiSecret encodedRequest = [@HTTP_METHOD, encodeURIComponent urlToSign].join('&') encodeURIComponent signer.update(encodedRequest).digest('base64') # ### Transform Data # #### (Private) # ------------------ # Rename keys that differ between Kissmetrics' batch API and regular # HTTP API. # # * `_p` (person) is replaced by `identity` # * `_t` (timestamp) is replaced by `timestamp` # * `_d` (date provided) is ignored because all batch queries provide dates # * `record` queries use the `event` property instead of `_n` # * `alias` queries use the `alias` property instead of `_n` # * `_k` (API key) is replaced by an HTTP header # * `__type` is only used internally # # ##### Arguments # # `data` (Object): Key/value pairs of properties to send to Kissmetrics. _transformData: (data) -> data.identity = data._p data.timestamp = data._t || Math.round(Date.now() / 1000) switch data.__type when 'record' then data.event = data._n when 'alias' then data.alias = data._n reservedKeys = ['_k', '_n', '_p', '_t', '_d', '__type'] delete data[reservedKey] for reservedKey in reservedKeys data # ## Exports # ----------- # Expose BatchKissmetricsClient as a Node.js module. module.exports = BatchKissmetricsClient
[ { "context": "###\n * bag\n * getbag.io\n *\n * Copyright (c) 2015 Ryan Gaus\n * Licensed under the MIT license.\n###\nuuid = req", "end": 58, "score": 0.9998399615287781, "start": 49, "tag": "NAME", "value": "Ryan Gaus" }, { "context": " else\n user_params.password = hash\n user_params.salt = salt\n ", "end": 2226, "score": 0.7268617153167725, "start": 2222, "tag": "PASSWORD", "value": "hash" } ]
src/controllers/user_controller.coffee
1egoman/bag-node
0
### * bag * getbag.io * * Copyright (c) 2015 Ryan Gaus * Licensed under the MIT license. ### uuid = require "uuid" _ = require "underscore" bcrypt = require "bcrypt" async = require "async" User = require "../models/user_model" Pick = require "../models/pick_model" Bag = require "../models/bag_model" Store = require "../models/store_model" {gen_picks_for} = require "./pick_controller" # get a user of all lists # GET /user exports.index = (req, res) -> User.find {}, (err, data) -> if err res.send status: "bag.error.user.index" error: err else res.send status: "bag.success.user.index" data: data exports.new = (req, res) -> res.send "Not supported." # create a new user # POST /user exports.create = (req, res) -> user_params = req.body?.user if user_params and \ user_params.realname? and \ user_params.name? and \ user_params.email? and \ user_params.password? async.waterfall [ # pass in our user params object (cb) -> cb null, user_params # make sure email is really an email (user_params, cb) -> if user_params.email.match /\S+@\S+\.\S+/i cb null, user_params else cb "The email specified isn't an email!" # make sure username and email are unique (user_params, cb) -> User.findOne $or: [ name: user_params.name , email: user_params.email ] , (err, result) -> if err cb err else if not result cb null, user_params else cb "Username or email not unique" # hash password and create salt (user_params, cb) -> bcrypt.genSalt 10, (err, salt) -> if err res.send status: "bag.error.user.create" error: err else bcrypt.hash user_params.password, salt, (err, hash) -> if err res.send status: "bag.error.user.create" error: err else user_params.password = hash user_params.salt = salt cb null, user_params # generate request token (user_params, cb) -> user_params.token = do (token_len=128) -> [0..token_len].map -> String.fromCharCode(_.random(65, 95)) .join '' cb null, user_params # set plan = 0 (user_params, cb) -> user_params.plan = 0 cb null, user_params # if no stores were saved, just inject one to start with. # new users start with whole foods, by default (user_params, cb) -> if user_params.stores cb null, user_params else Store.findOne name: "Whole Foods", (err, item) -> if not err and item user_params.stores = [ item._id ] cb null, user_params # create user model and save it (user_params, cb) -> user = new User user_params user.save (err) -> if err res.send status: "bag.error.user.create" error: err else # generate a bag, too bag = new Bag user: user._id bag.save (err) -> if err res.send status: "bag.error.user.create" error: err else # and, generate a picks list.... picks = new Pick user: user._id picks.save (err) -> if err res.send status: "bag.error.user.create" error: err else res.send status: "bag.success.user.create" data: user ], (err) -> if err res.send status: "bag.error.user.create" error: err else res.send status: "bag.error.user.create" error: "all the required elements weren't there." # get a user with the specified id # GET /user/:list exports.show = (req, res) -> User.findOne _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.show" error: err else res.send status: "bag.success.user.show" data: data exports.edit = (req, res) -> res.send "Not supported." # update a user # PUT /user/:list exports.update = (req, res) -> User.findOne _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.update" error: err else data[k] = v for k, v of req.body?.user data.update_picks = true data.save (err) -> if err res.send status: "bag.error.user.update" data: err else res.send status: "bag.success.user.update" data: data # delete a user # DELETE /user/:list exports.destroy = (req, res) -> User.remove _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.delete" error: err else res.send status: "bag.success.user.delete" # is the specified token valid? exports.is_token_valid = (token, cb) -> User.findOne token: token, (err, data) -> if data cb true else if err cb err else cb false # favorite an item # this will add the item to the favorites list inside the user model exports.fav = (req, res) -> item = req.body.item # get a reference to the user query = User.findOne _id: req.user._id query.exec (err, data) -> # add item to favs list data.favs or= [] data.favs.push item if item not in data.favs data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.favorite" error: err else # regenerate picks gen_picks_for data, (out) -> if out.status.indexOf("error") isnt -1 res.send status: "bag.error.user.favorite" error: out.error else res.send status: "bag.success.user.favorite" # un-favorite an item # this will remove the item to the favorites list inside the user model exports.un_fav = (req, res) -> item = req.body.item # get a reference to the user query = User.findOne _id: req.user._id query.exec (err, data) -> # add item to favs list data.favs or= [] data.favs = _.without data.favs, item # tell picks watcher to re-calculate picks for this user data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.unfavorite" error: err else # regenerate picks gen_picks_for data, (out) -> if out.status.indexOf("error") isnt -1 res.send status: "bag.error.user.favorite" error: out.error else res.send status: "bag.success.user.favorite" # check if a username is unique exports.unique = (req, res) -> # length of zero? That cannot be a username..... if req.body.user.length is 0 return res.send status: "bag.success.user.dirty" User.findOne name: req.body.user, (err, result) -> if err or not result res.send status: "bag.success.user.clean" else res.send status: "bag.success.user.dirty" # using the req body, post an update to the stores for a user exports.updatestores = (req, res) -> query = User.findOne _id: req.user._id query.exec (err, data) -> data.stores = req.body.stores # save it data.save (err) -> if err res.send status: "bag.error.user.updatestores" error: err else res.send status: "bag.success.user.updatestores" # register a click for a specific store exports.click = (req, res) -> query = User.findOne _id: req.user._id query.exec (err, data) -> # add the specific id to the click array data.clicks or= [] data.clicks.push store: req.body.recipe date: new Date().toJSON() data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.click" error: err else # regenerate picks gen_picks_for data, (err) -> if err res.send status: "bag.error.user.click" error: err else res.send status: "bag.success.user.click"
191695
### * bag * getbag.io * * Copyright (c) 2015 <NAME> * Licensed under the MIT license. ### uuid = require "uuid" _ = require "underscore" bcrypt = require "bcrypt" async = require "async" User = require "../models/user_model" Pick = require "../models/pick_model" Bag = require "../models/bag_model" Store = require "../models/store_model" {gen_picks_for} = require "./pick_controller" # get a user of all lists # GET /user exports.index = (req, res) -> User.find {}, (err, data) -> if err res.send status: "bag.error.user.index" error: err else res.send status: "bag.success.user.index" data: data exports.new = (req, res) -> res.send "Not supported." # create a new user # POST /user exports.create = (req, res) -> user_params = req.body?.user if user_params and \ user_params.realname? and \ user_params.name? and \ user_params.email? and \ user_params.password? async.waterfall [ # pass in our user params object (cb) -> cb null, user_params # make sure email is really an email (user_params, cb) -> if user_params.email.match /\S+@\S+\.\S+/i cb null, user_params else cb "The email specified isn't an email!" # make sure username and email are unique (user_params, cb) -> User.findOne $or: [ name: user_params.name , email: user_params.email ] , (err, result) -> if err cb err else if not result cb null, user_params else cb "Username or email not unique" # hash password and create salt (user_params, cb) -> bcrypt.genSalt 10, (err, salt) -> if err res.send status: "bag.error.user.create" error: err else bcrypt.hash user_params.password, salt, (err, hash) -> if err res.send status: "bag.error.user.create" error: err else user_params.password = <PASSWORD> user_params.salt = salt cb null, user_params # generate request token (user_params, cb) -> user_params.token = do (token_len=128) -> [0..token_len].map -> String.fromCharCode(_.random(65, 95)) .join '' cb null, user_params # set plan = 0 (user_params, cb) -> user_params.plan = 0 cb null, user_params # if no stores were saved, just inject one to start with. # new users start with whole foods, by default (user_params, cb) -> if user_params.stores cb null, user_params else Store.findOne name: "Whole Foods", (err, item) -> if not err and item user_params.stores = [ item._id ] cb null, user_params # create user model and save it (user_params, cb) -> user = new User user_params user.save (err) -> if err res.send status: "bag.error.user.create" error: err else # generate a bag, too bag = new Bag user: user._id bag.save (err) -> if err res.send status: "bag.error.user.create" error: err else # and, generate a picks list.... picks = new Pick user: user._id picks.save (err) -> if err res.send status: "bag.error.user.create" error: err else res.send status: "bag.success.user.create" data: user ], (err) -> if err res.send status: "bag.error.user.create" error: err else res.send status: "bag.error.user.create" error: "all the required elements weren't there." # get a user with the specified id # GET /user/:list exports.show = (req, res) -> User.findOne _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.show" error: err else res.send status: "bag.success.user.show" data: data exports.edit = (req, res) -> res.send "Not supported." # update a user # PUT /user/:list exports.update = (req, res) -> User.findOne _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.update" error: err else data[k] = v for k, v of req.body?.user data.update_picks = true data.save (err) -> if err res.send status: "bag.error.user.update" data: err else res.send status: "bag.success.user.update" data: data # delete a user # DELETE /user/:list exports.destroy = (req, res) -> User.remove _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.delete" error: err else res.send status: "bag.success.user.delete" # is the specified token valid? exports.is_token_valid = (token, cb) -> User.findOne token: token, (err, data) -> if data cb true else if err cb err else cb false # favorite an item # this will add the item to the favorites list inside the user model exports.fav = (req, res) -> item = req.body.item # get a reference to the user query = User.findOne _id: req.user._id query.exec (err, data) -> # add item to favs list data.favs or= [] data.favs.push item if item not in data.favs data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.favorite" error: err else # regenerate picks gen_picks_for data, (out) -> if out.status.indexOf("error") isnt -1 res.send status: "bag.error.user.favorite" error: out.error else res.send status: "bag.success.user.favorite" # un-favorite an item # this will remove the item to the favorites list inside the user model exports.un_fav = (req, res) -> item = req.body.item # get a reference to the user query = User.findOne _id: req.user._id query.exec (err, data) -> # add item to favs list data.favs or= [] data.favs = _.without data.favs, item # tell picks watcher to re-calculate picks for this user data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.unfavorite" error: err else # regenerate picks gen_picks_for data, (out) -> if out.status.indexOf("error") isnt -1 res.send status: "bag.error.user.favorite" error: out.error else res.send status: "bag.success.user.favorite" # check if a username is unique exports.unique = (req, res) -> # length of zero? That cannot be a username..... if req.body.user.length is 0 return res.send status: "bag.success.user.dirty" User.findOne name: req.body.user, (err, result) -> if err or not result res.send status: "bag.success.user.clean" else res.send status: "bag.success.user.dirty" # using the req body, post an update to the stores for a user exports.updatestores = (req, res) -> query = User.findOne _id: req.user._id query.exec (err, data) -> data.stores = req.body.stores # save it data.save (err) -> if err res.send status: "bag.error.user.updatestores" error: err else res.send status: "bag.success.user.updatestores" # register a click for a specific store exports.click = (req, res) -> query = User.findOne _id: req.user._id query.exec (err, data) -> # add the specific id to the click array data.clicks or= [] data.clicks.push store: req.body.recipe date: new Date().toJSON() data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.click" error: err else # regenerate picks gen_picks_for data, (err) -> if err res.send status: "bag.error.user.click" error: err else res.send status: "bag.success.user.click"
true
### * bag * getbag.io * * Copyright (c) 2015 PI:NAME:<NAME>END_PI * Licensed under the MIT license. ### uuid = require "uuid" _ = require "underscore" bcrypt = require "bcrypt" async = require "async" User = require "../models/user_model" Pick = require "../models/pick_model" Bag = require "../models/bag_model" Store = require "../models/store_model" {gen_picks_for} = require "./pick_controller" # get a user of all lists # GET /user exports.index = (req, res) -> User.find {}, (err, data) -> if err res.send status: "bag.error.user.index" error: err else res.send status: "bag.success.user.index" data: data exports.new = (req, res) -> res.send "Not supported." # create a new user # POST /user exports.create = (req, res) -> user_params = req.body?.user if user_params and \ user_params.realname? and \ user_params.name? and \ user_params.email? and \ user_params.password? async.waterfall [ # pass in our user params object (cb) -> cb null, user_params # make sure email is really an email (user_params, cb) -> if user_params.email.match /\S+@\S+\.\S+/i cb null, user_params else cb "The email specified isn't an email!" # make sure username and email are unique (user_params, cb) -> User.findOne $or: [ name: user_params.name , email: user_params.email ] , (err, result) -> if err cb err else if not result cb null, user_params else cb "Username or email not unique" # hash password and create salt (user_params, cb) -> bcrypt.genSalt 10, (err, salt) -> if err res.send status: "bag.error.user.create" error: err else bcrypt.hash user_params.password, salt, (err, hash) -> if err res.send status: "bag.error.user.create" error: err else user_params.password = PI:PASSWORD:<PASSWORD>END_PI user_params.salt = salt cb null, user_params # generate request token (user_params, cb) -> user_params.token = do (token_len=128) -> [0..token_len].map -> String.fromCharCode(_.random(65, 95)) .join '' cb null, user_params # set plan = 0 (user_params, cb) -> user_params.plan = 0 cb null, user_params # if no stores were saved, just inject one to start with. # new users start with whole foods, by default (user_params, cb) -> if user_params.stores cb null, user_params else Store.findOne name: "Whole Foods", (err, item) -> if not err and item user_params.stores = [ item._id ] cb null, user_params # create user model and save it (user_params, cb) -> user = new User user_params user.save (err) -> if err res.send status: "bag.error.user.create" error: err else # generate a bag, too bag = new Bag user: user._id bag.save (err) -> if err res.send status: "bag.error.user.create" error: err else # and, generate a picks list.... picks = new Pick user: user._id picks.save (err) -> if err res.send status: "bag.error.user.create" error: err else res.send status: "bag.success.user.create" data: user ], (err) -> if err res.send status: "bag.error.user.create" error: err else res.send status: "bag.error.user.create" error: "all the required elements weren't there." # get a user with the specified id # GET /user/:list exports.show = (req, res) -> User.findOne _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.show" error: err else res.send status: "bag.success.user.show" data: data exports.edit = (req, res) -> res.send "Not supported." # update a user # PUT /user/:list exports.update = (req, res) -> User.findOne _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.update" error: err else data[k] = v for k, v of req.body?.user data.update_picks = true data.save (err) -> if err res.send status: "bag.error.user.update" data: err else res.send status: "bag.success.user.update" data: data # delete a user # DELETE /user/:list exports.destroy = (req, res) -> User.remove _id: req.params.user, (err, data) -> if err res.send status: "bag.error.user.delete" error: err else res.send status: "bag.success.user.delete" # is the specified token valid? exports.is_token_valid = (token, cb) -> User.findOne token: token, (err, data) -> if data cb true else if err cb err else cb false # favorite an item # this will add the item to the favorites list inside the user model exports.fav = (req, res) -> item = req.body.item # get a reference to the user query = User.findOne _id: req.user._id query.exec (err, data) -> # add item to favs list data.favs or= [] data.favs.push item if item not in data.favs data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.favorite" error: err else # regenerate picks gen_picks_for data, (out) -> if out.status.indexOf("error") isnt -1 res.send status: "bag.error.user.favorite" error: out.error else res.send status: "bag.success.user.favorite" # un-favorite an item # this will remove the item to the favorites list inside the user model exports.un_fav = (req, res) -> item = req.body.item # get a reference to the user query = User.findOne _id: req.user._id query.exec (err, data) -> # add item to favs list data.favs or= [] data.favs = _.without data.favs, item # tell picks watcher to re-calculate picks for this user data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.unfavorite" error: err else # regenerate picks gen_picks_for data, (out) -> if out.status.indexOf("error") isnt -1 res.send status: "bag.error.user.favorite" error: out.error else res.send status: "bag.success.user.favorite" # check if a username is unique exports.unique = (req, res) -> # length of zero? That cannot be a username..... if req.body.user.length is 0 return res.send status: "bag.success.user.dirty" User.findOne name: req.body.user, (err, result) -> if err or not result res.send status: "bag.success.user.clean" else res.send status: "bag.success.user.dirty" # using the req body, post an update to the stores for a user exports.updatestores = (req, res) -> query = User.findOne _id: req.user._id query.exec (err, data) -> data.stores = req.body.stores # save it data.save (err) -> if err res.send status: "bag.error.user.updatestores" error: err else res.send status: "bag.success.user.updatestores" # register a click for a specific store exports.click = (req, res) -> query = User.findOne _id: req.user._id query.exec (err, data) -> # add the specific id to the click array data.clicks or= [] data.clicks.push store: req.body.recipe date: new Date().toJSON() data.update_picks = true # save it data.save (err) -> if err res.send status: "bag.error.user.click" error: err else # regenerate picks gen_picks_for data, (err) -> if err res.send status: "bag.error.user.click" error: err else res.send status: "bag.success.user.click"
[ { "context": "\": \"it\", \"s\": 0},\n {\"w\": \"keep\", \"s\": 0},\n {\"w\": \"laugh\", \"s\": 0},\n {\"w\": \"learn\", \"s\": 0},\n {\"w\": \"le", "end": 2336, "score": 0.992156982421875, "start": 2334, "tag": "NAME", "value": "la" }, { "context": " \"it\", \"s\": 0},\n {\"w\": \"keep\", \"s\": 0},\n {\"w\": \"laugh\", \"s\": 0},\n {\"w\": \"learn\", \"s\": 0},\n {\"w\": \"leave", "end": 2339, "score": 0.9565960764884949, "start": 2336, "tag": "NAME", "value": "ugh" } ]
src/wordlist.coffee
elfsternberg/fridgemagnets
0
[{"w": "a", "s": 0}, {"w": "a", "s": 0}, {"w": "about", "s": 0}, {"w": "above", "s": 0}, {"w": "after", "s": 0}, {"w": "all", "s": 0}, {"w": "almost", "s": 0}, {"w": "always", "s": 0}, {"w": "am", "s": 0}, {"w": "an", "s": 0}, {"w": "an", "s": 0}, {"w": "and", "s": 0}, {"w": "and", "s": 0}, {"w": "animal", "s": 0}, {"w": "apple", "s": 0}, {"w": "are", "s": 0}, {"w": "as", "s": 0}, {"w": "as", "s": 0}, {"w": "ask", "s": 0}, {"w": "at", "s": 0}, {"w": "bad", "s": 0}, {"w": "be", "s": 0}, {"w": "beauty", "s": 0}, {"w": "believe", "s": 0}, {"w": "beneath", "s": 0}, {"w": "between", "s": 0}, {"w": "bird", "s": 0}, {"w": "birthday", "s": 0}, {"w": "blend", "s": 0}, {"w": "blue", "s": 0}, {"w": "bring", "s": 0}, {"w": "but", "s": 0}, {"w": "but", "s": 0}, {"w": "butterfly", "s": 0}, {"w": "by", "s": 0}, {"w": "calendar", "s": 0}, {"w": "can", "s": 0}, {"w": "celebrate", "s": 0}, {"w": "change", "s": 0}, {"w": "cloud", "s": 0}, {"w": "cold", "s": 0}, {"w": "come", "s": 0}, {"w": "comfort", "s": 0}, {"w": "could", "s": 0}, {"w": "d", "s": 1}, {"w": "dark", "s": 0}, {"w": "day", "s": 0}, {"w": "delightful", "s": 0}, {"w": "desire", "s": 0}, {"w": "did", "s": 0}, {"w": "do", "s": 0}, {"w": "dream", "s": 0}, {"w": "e", "s": 1}, {"w": "eat", "s": 0}, {"w": "ed", "s": 1}, {"w": "er", "s": 1}, {"w": "es", "s": 1}, {"w": "est", "s": 1}, {"w": "evening", "s": 0}, {"w": "every", "s": 0}, {"w": "fall", "s": 0}, {"w": "favorite", "s": 0}, {"w": "feel", "s": 0}, {"w": "float", "s": 0}, {"w": "flower", "s": 0}, {"w": "for", "s": 0}, {"w": "from", "s": 0}, {"w": "full", "s": 0}, {"w": "fun", "s": 0}, {"w": "garden", "s": 0}, {"w": "get", "s": 0}, {"w": "ghost", "s": 0}, {"w": "good", "s": 0}, {"w": "grass", "s": 0}, {"w": "green", "s": 0}, {"w": "grow", "s": 0}, {"w": "happy", "s": 0}, {"w": "has", "s": 0}, {"w": "have", "s": 0}, {"w": "he", "s": 0}, {"w": "here", "s": 0}, {"w": "here", "s": 0}, {"w": "him", "s": 0}, {"w": "his", "s": 0}, {"w": "hot", "s": 0}, {"w": "house", "s": 0}, {"w": "how", "s": 0}, {"w": "I", "s": 0}, {"w": "I", "s": 0}, {"w": "if", "s": 0}, {"w": "in", "s": 0}, {"w": "ing", "s": 1}, {"w": "ing", "s": 1}, {"w": "is", "s": 0}, {"w": "is", "s": 0}, {"w": "it", "s": 0}, {"w": "keep", "s": 0}, {"w": "laugh", "s": 0}, {"w": "learn", "s": 0}, {"w": "leave", "s": 0}, {"w": "let", "s": 0}, {"w": "light", "s": 0}, {"w": "like", "s": 0}, {"w": "like", "s": 0}, {"w": "live", "s": 0}, {"w": "long", "s": 0}, {"w": "look", "s": 0}, {"w": "love", "s": 0}, {"w": "ly", "s": 1}, {"w": "magic", "s": 0}, {"w": "make", "s": 0}, {"w": "man", "s": 0}, {"w": "me", "s": 0}, {"w": "memory", "s": 0}, {"w": "month", "s": 0}, {"w": "more", "s": 0}, {"w": "morning", "s": 0}, {"w": "must", "s": 0}, {"w": "my", "s": 0}, {"w": "never", "s": 0}, {"w": "nibble", "s": 0}, {"w": "night", "s": 0}, {"w": "no", "s": 0}, {"w": "of", "s": 0}, {"w": "of", "s": 0}, {"w": "off", "s": 0}, {"w": "on", "s": 0}, {"w": "only", "s": 0}, {"w": "or", "s": 0}, {"w": "out", "s": 0}, {"w": "out", "s": 0}, {"w": "paint", "s": 0}, {"w": "people", "s": 0}, {"w": "perfect", "s": 0}, {"w": "play", "s": 0}, {"w": "proof", "s": 0}, {"w": "puff", "s": 0}, {"w": "r", "s": 1}, {"w": "rain", "s": 0}, {"w": "room", "s": 0}, {"w": "s", "s": 1}, {"w": "s", "s": 1}, {"w": "s", "s": 1}, {"w": "say", "s": 0}, {"w": "season", "s": 0}, {"w": "see", "s": 0}, {"w": "she", "s": 0}, {"w": "shine", "s": 0}, {"w": "simple", "s": 0}, {"w": "sky", "s": 0}, {"w": "snow", "s": 0}, {"w": "so", "s": 0}, {"w": "some", "s": 0}, {"w": "song", "s": 0}, {"w": "spring", "s": 0}, {"w": "summer", "s": 0}, {"w": "sun", "s": 0}, {"w": "sweet", "s": 0}, {"w": "take", "s": 0}, {"w": "talk", "s": 0}, {"w": "than", "s": 0}, {"w": "that", "s": 0}, {"w": "the", "s": 0}, {"w": "the", "s": 0}, {"w": "their", "s": 0}, {"w": "then", "s": 0}, {"w": "there", "s": 0}, {"w": "they", "s": 0}, {"w": "this", "s": 0}, {"w": "though", "s": 0}, {"w": "through", "s": 0}, {"w": "time", "s": 0}, {"w": "to", "s": 0}, {"w": "to", "s": 0}, {"w": "together", "s": 0}, {"w": "too", "s": 0}, {"w": "touch", "s": 0}, {"w": "trick", "s": 0}, {"w": "truth", "s": 0}, {"w": "up", "s": 0}, {"w": "us", "s": 0}, {"w": "use", "s": 0}, {"w": "vacation", "s": 0}, {"w": "walk", "s": 0}, {"w": "want", "s": 0}, {"w": "warm", "s": 0}, {"w": "was", "s": 0}, {"w": "watch", "s": 0}, {"w": "we", "s": 0}, {"w": "weather", "s": 0}, {"w": "were", "s": 0}, {"w": "when", "s": 0}, {"w": "which", "s": 0}, {"w": "whisper", "s": 0}, {"w": "who", "s": 0}, {"w": "why", "s": 0}, {"w": "will", "s": 0}, {"w": "winter", "s": 0}, {"w": "with", "s": 0}, {"w": "woman", "s": 0}, {"w": "word", "s": 0}, {"w": "work", "s": 0}, {"w": "world", "s": 0}, {"w": "would", "s": 0}, {"w": "y", "s": 1}, {"w": "year", "s": 0}, {"w": "you", "s": 0}, {"w": "you", "s": 0}, {"w": "your", "s": 0} ]
124284
[{"w": "a", "s": 0}, {"w": "a", "s": 0}, {"w": "about", "s": 0}, {"w": "above", "s": 0}, {"w": "after", "s": 0}, {"w": "all", "s": 0}, {"w": "almost", "s": 0}, {"w": "always", "s": 0}, {"w": "am", "s": 0}, {"w": "an", "s": 0}, {"w": "an", "s": 0}, {"w": "and", "s": 0}, {"w": "and", "s": 0}, {"w": "animal", "s": 0}, {"w": "apple", "s": 0}, {"w": "are", "s": 0}, {"w": "as", "s": 0}, {"w": "as", "s": 0}, {"w": "ask", "s": 0}, {"w": "at", "s": 0}, {"w": "bad", "s": 0}, {"w": "be", "s": 0}, {"w": "beauty", "s": 0}, {"w": "believe", "s": 0}, {"w": "beneath", "s": 0}, {"w": "between", "s": 0}, {"w": "bird", "s": 0}, {"w": "birthday", "s": 0}, {"w": "blend", "s": 0}, {"w": "blue", "s": 0}, {"w": "bring", "s": 0}, {"w": "but", "s": 0}, {"w": "but", "s": 0}, {"w": "butterfly", "s": 0}, {"w": "by", "s": 0}, {"w": "calendar", "s": 0}, {"w": "can", "s": 0}, {"w": "celebrate", "s": 0}, {"w": "change", "s": 0}, {"w": "cloud", "s": 0}, {"w": "cold", "s": 0}, {"w": "come", "s": 0}, {"w": "comfort", "s": 0}, {"w": "could", "s": 0}, {"w": "d", "s": 1}, {"w": "dark", "s": 0}, {"w": "day", "s": 0}, {"w": "delightful", "s": 0}, {"w": "desire", "s": 0}, {"w": "did", "s": 0}, {"w": "do", "s": 0}, {"w": "dream", "s": 0}, {"w": "e", "s": 1}, {"w": "eat", "s": 0}, {"w": "ed", "s": 1}, {"w": "er", "s": 1}, {"w": "es", "s": 1}, {"w": "est", "s": 1}, {"w": "evening", "s": 0}, {"w": "every", "s": 0}, {"w": "fall", "s": 0}, {"w": "favorite", "s": 0}, {"w": "feel", "s": 0}, {"w": "float", "s": 0}, {"w": "flower", "s": 0}, {"w": "for", "s": 0}, {"w": "from", "s": 0}, {"w": "full", "s": 0}, {"w": "fun", "s": 0}, {"w": "garden", "s": 0}, {"w": "get", "s": 0}, {"w": "ghost", "s": 0}, {"w": "good", "s": 0}, {"w": "grass", "s": 0}, {"w": "green", "s": 0}, {"w": "grow", "s": 0}, {"w": "happy", "s": 0}, {"w": "has", "s": 0}, {"w": "have", "s": 0}, {"w": "he", "s": 0}, {"w": "here", "s": 0}, {"w": "here", "s": 0}, {"w": "him", "s": 0}, {"w": "his", "s": 0}, {"w": "hot", "s": 0}, {"w": "house", "s": 0}, {"w": "how", "s": 0}, {"w": "I", "s": 0}, {"w": "I", "s": 0}, {"w": "if", "s": 0}, {"w": "in", "s": 0}, {"w": "ing", "s": 1}, {"w": "ing", "s": 1}, {"w": "is", "s": 0}, {"w": "is", "s": 0}, {"w": "it", "s": 0}, {"w": "keep", "s": 0}, {"w": "<NAME> <NAME>", "s": 0}, {"w": "learn", "s": 0}, {"w": "leave", "s": 0}, {"w": "let", "s": 0}, {"w": "light", "s": 0}, {"w": "like", "s": 0}, {"w": "like", "s": 0}, {"w": "live", "s": 0}, {"w": "long", "s": 0}, {"w": "look", "s": 0}, {"w": "love", "s": 0}, {"w": "ly", "s": 1}, {"w": "magic", "s": 0}, {"w": "make", "s": 0}, {"w": "man", "s": 0}, {"w": "me", "s": 0}, {"w": "memory", "s": 0}, {"w": "month", "s": 0}, {"w": "more", "s": 0}, {"w": "morning", "s": 0}, {"w": "must", "s": 0}, {"w": "my", "s": 0}, {"w": "never", "s": 0}, {"w": "nibble", "s": 0}, {"w": "night", "s": 0}, {"w": "no", "s": 0}, {"w": "of", "s": 0}, {"w": "of", "s": 0}, {"w": "off", "s": 0}, {"w": "on", "s": 0}, {"w": "only", "s": 0}, {"w": "or", "s": 0}, {"w": "out", "s": 0}, {"w": "out", "s": 0}, {"w": "paint", "s": 0}, {"w": "people", "s": 0}, {"w": "perfect", "s": 0}, {"w": "play", "s": 0}, {"w": "proof", "s": 0}, {"w": "puff", "s": 0}, {"w": "r", "s": 1}, {"w": "rain", "s": 0}, {"w": "room", "s": 0}, {"w": "s", "s": 1}, {"w": "s", "s": 1}, {"w": "s", "s": 1}, {"w": "say", "s": 0}, {"w": "season", "s": 0}, {"w": "see", "s": 0}, {"w": "she", "s": 0}, {"w": "shine", "s": 0}, {"w": "simple", "s": 0}, {"w": "sky", "s": 0}, {"w": "snow", "s": 0}, {"w": "so", "s": 0}, {"w": "some", "s": 0}, {"w": "song", "s": 0}, {"w": "spring", "s": 0}, {"w": "summer", "s": 0}, {"w": "sun", "s": 0}, {"w": "sweet", "s": 0}, {"w": "take", "s": 0}, {"w": "talk", "s": 0}, {"w": "than", "s": 0}, {"w": "that", "s": 0}, {"w": "the", "s": 0}, {"w": "the", "s": 0}, {"w": "their", "s": 0}, {"w": "then", "s": 0}, {"w": "there", "s": 0}, {"w": "they", "s": 0}, {"w": "this", "s": 0}, {"w": "though", "s": 0}, {"w": "through", "s": 0}, {"w": "time", "s": 0}, {"w": "to", "s": 0}, {"w": "to", "s": 0}, {"w": "together", "s": 0}, {"w": "too", "s": 0}, {"w": "touch", "s": 0}, {"w": "trick", "s": 0}, {"w": "truth", "s": 0}, {"w": "up", "s": 0}, {"w": "us", "s": 0}, {"w": "use", "s": 0}, {"w": "vacation", "s": 0}, {"w": "walk", "s": 0}, {"w": "want", "s": 0}, {"w": "warm", "s": 0}, {"w": "was", "s": 0}, {"w": "watch", "s": 0}, {"w": "we", "s": 0}, {"w": "weather", "s": 0}, {"w": "were", "s": 0}, {"w": "when", "s": 0}, {"w": "which", "s": 0}, {"w": "whisper", "s": 0}, {"w": "who", "s": 0}, {"w": "why", "s": 0}, {"w": "will", "s": 0}, {"w": "winter", "s": 0}, {"w": "with", "s": 0}, {"w": "woman", "s": 0}, {"w": "word", "s": 0}, {"w": "work", "s": 0}, {"w": "world", "s": 0}, {"w": "would", "s": 0}, {"w": "y", "s": 1}, {"w": "year", "s": 0}, {"w": "you", "s": 0}, {"w": "you", "s": 0}, {"w": "your", "s": 0} ]
true
[{"w": "a", "s": 0}, {"w": "a", "s": 0}, {"w": "about", "s": 0}, {"w": "above", "s": 0}, {"w": "after", "s": 0}, {"w": "all", "s": 0}, {"w": "almost", "s": 0}, {"w": "always", "s": 0}, {"w": "am", "s": 0}, {"w": "an", "s": 0}, {"w": "an", "s": 0}, {"w": "and", "s": 0}, {"w": "and", "s": 0}, {"w": "animal", "s": 0}, {"w": "apple", "s": 0}, {"w": "are", "s": 0}, {"w": "as", "s": 0}, {"w": "as", "s": 0}, {"w": "ask", "s": 0}, {"w": "at", "s": 0}, {"w": "bad", "s": 0}, {"w": "be", "s": 0}, {"w": "beauty", "s": 0}, {"w": "believe", "s": 0}, {"w": "beneath", "s": 0}, {"w": "between", "s": 0}, {"w": "bird", "s": 0}, {"w": "birthday", "s": 0}, {"w": "blend", "s": 0}, {"w": "blue", "s": 0}, {"w": "bring", "s": 0}, {"w": "but", "s": 0}, {"w": "but", "s": 0}, {"w": "butterfly", "s": 0}, {"w": "by", "s": 0}, {"w": "calendar", "s": 0}, {"w": "can", "s": 0}, {"w": "celebrate", "s": 0}, {"w": "change", "s": 0}, {"w": "cloud", "s": 0}, {"w": "cold", "s": 0}, {"w": "come", "s": 0}, {"w": "comfort", "s": 0}, {"w": "could", "s": 0}, {"w": "d", "s": 1}, {"w": "dark", "s": 0}, {"w": "day", "s": 0}, {"w": "delightful", "s": 0}, {"w": "desire", "s": 0}, {"w": "did", "s": 0}, {"w": "do", "s": 0}, {"w": "dream", "s": 0}, {"w": "e", "s": 1}, {"w": "eat", "s": 0}, {"w": "ed", "s": 1}, {"w": "er", "s": 1}, {"w": "es", "s": 1}, {"w": "est", "s": 1}, {"w": "evening", "s": 0}, {"w": "every", "s": 0}, {"w": "fall", "s": 0}, {"w": "favorite", "s": 0}, {"w": "feel", "s": 0}, {"w": "float", "s": 0}, {"w": "flower", "s": 0}, {"w": "for", "s": 0}, {"w": "from", "s": 0}, {"w": "full", "s": 0}, {"w": "fun", "s": 0}, {"w": "garden", "s": 0}, {"w": "get", "s": 0}, {"w": "ghost", "s": 0}, {"w": "good", "s": 0}, {"w": "grass", "s": 0}, {"w": "green", "s": 0}, {"w": "grow", "s": 0}, {"w": "happy", "s": 0}, {"w": "has", "s": 0}, {"w": "have", "s": 0}, {"w": "he", "s": 0}, {"w": "here", "s": 0}, {"w": "here", "s": 0}, {"w": "him", "s": 0}, {"w": "his", "s": 0}, {"w": "hot", "s": 0}, {"w": "house", "s": 0}, {"w": "how", "s": 0}, {"w": "I", "s": 0}, {"w": "I", "s": 0}, {"w": "if", "s": 0}, {"w": "in", "s": 0}, {"w": "ing", "s": 1}, {"w": "ing", "s": 1}, {"w": "is", "s": 0}, {"w": "is", "s": 0}, {"w": "it", "s": 0}, {"w": "keep", "s": 0}, {"w": "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI", "s": 0}, {"w": "learn", "s": 0}, {"w": "leave", "s": 0}, {"w": "let", "s": 0}, {"w": "light", "s": 0}, {"w": "like", "s": 0}, {"w": "like", "s": 0}, {"w": "live", "s": 0}, {"w": "long", "s": 0}, {"w": "look", "s": 0}, {"w": "love", "s": 0}, {"w": "ly", "s": 1}, {"w": "magic", "s": 0}, {"w": "make", "s": 0}, {"w": "man", "s": 0}, {"w": "me", "s": 0}, {"w": "memory", "s": 0}, {"w": "month", "s": 0}, {"w": "more", "s": 0}, {"w": "morning", "s": 0}, {"w": "must", "s": 0}, {"w": "my", "s": 0}, {"w": "never", "s": 0}, {"w": "nibble", "s": 0}, {"w": "night", "s": 0}, {"w": "no", "s": 0}, {"w": "of", "s": 0}, {"w": "of", "s": 0}, {"w": "off", "s": 0}, {"w": "on", "s": 0}, {"w": "only", "s": 0}, {"w": "or", "s": 0}, {"w": "out", "s": 0}, {"w": "out", "s": 0}, {"w": "paint", "s": 0}, {"w": "people", "s": 0}, {"w": "perfect", "s": 0}, {"w": "play", "s": 0}, {"w": "proof", "s": 0}, {"w": "puff", "s": 0}, {"w": "r", "s": 1}, {"w": "rain", "s": 0}, {"w": "room", "s": 0}, {"w": "s", "s": 1}, {"w": "s", "s": 1}, {"w": "s", "s": 1}, {"w": "say", "s": 0}, {"w": "season", "s": 0}, {"w": "see", "s": 0}, {"w": "she", "s": 0}, {"w": "shine", "s": 0}, {"w": "simple", "s": 0}, {"w": "sky", "s": 0}, {"w": "snow", "s": 0}, {"w": "so", "s": 0}, {"w": "some", "s": 0}, {"w": "song", "s": 0}, {"w": "spring", "s": 0}, {"w": "summer", "s": 0}, {"w": "sun", "s": 0}, {"w": "sweet", "s": 0}, {"w": "take", "s": 0}, {"w": "talk", "s": 0}, {"w": "than", "s": 0}, {"w": "that", "s": 0}, {"w": "the", "s": 0}, {"w": "the", "s": 0}, {"w": "their", "s": 0}, {"w": "then", "s": 0}, {"w": "there", "s": 0}, {"w": "they", "s": 0}, {"w": "this", "s": 0}, {"w": "though", "s": 0}, {"w": "through", "s": 0}, {"w": "time", "s": 0}, {"w": "to", "s": 0}, {"w": "to", "s": 0}, {"w": "together", "s": 0}, {"w": "too", "s": 0}, {"w": "touch", "s": 0}, {"w": "trick", "s": 0}, {"w": "truth", "s": 0}, {"w": "up", "s": 0}, {"w": "us", "s": 0}, {"w": "use", "s": 0}, {"w": "vacation", "s": 0}, {"w": "walk", "s": 0}, {"w": "want", "s": 0}, {"w": "warm", "s": 0}, {"w": "was", "s": 0}, {"w": "watch", "s": 0}, {"w": "we", "s": 0}, {"w": "weather", "s": 0}, {"w": "were", "s": 0}, {"w": "when", "s": 0}, {"w": "which", "s": 0}, {"w": "whisper", "s": 0}, {"w": "who", "s": 0}, {"w": "why", "s": 0}, {"w": "will", "s": 0}, {"w": "winter", "s": 0}, {"w": "with", "s": 0}, {"w": "woman", "s": 0}, {"w": "word", "s": 0}, {"w": "work", "s": 0}, {"w": "world", "s": 0}, {"w": "would", "s": 0}, {"w": "y", "s": 1}, {"w": "year", "s": 0}, {"w": "you", "s": 0}, {"w": "you", "s": 0}, {"w": "your", "s": 0} ]
[ { "context": "shedUrl = \"https://docs.google.com/spreadsheets/d/1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I/pubhtml\"\n @key = \"1vyPu1EtzU1DvGXfthjrR-blJ8mG", "end": 195, "score": 0.9788786768913269, "start": 151, "tag": "KEY", "value": "1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I" }, { "context": "thjrR-blJ8mGe75TL4BFNWtFMm0I/pubhtml\"\n @key = \"1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I\"\n @firstWorksheetId = \"od6\"\n @secondWorkshe", "end": 261, "score": 0.9997740387916565, "start": 217, "tag": "KEY", "value": "1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I" }, { "context": "@feedEntry)\n expected = [\n ['1', 'Mike', '24']\n ['2', 'Chris', '28']\n ", "end": 3994, "score": 0.9997231960296631, "start": 3990, "tag": "NAME", "value": "Mike" }, { "context": " [\n ['1', 'Mike', '24']\n ['2', 'Chris', '28']\n ['3', 'Doug', '34']\n [", "end": 4025, "score": 0.9997645616531372, "start": 4020, "tag": "NAME", "value": "Chris" }, { "context": "]\n ['2', 'Chris', '28']\n ['3', 'Doug', '34']\n ['4', 'Vlade', '21']\n ", "end": 4055, "score": 0.9997977614402771, "start": 4051, "tag": "NAME", "value": "Doug" }, { "context": "']\n ['3', 'Doug', '34']\n ['4', 'Vlade', '21']\n ['5', 'Peja', '37']\n ]\n ", "end": 4086, "score": 0.9997885227203369, "start": 4081, "tag": "NAME", "value": "Vlade" }, { "context": "]\n ['4', 'Vlade', '21']\n ['5', 'Peja', '37']\n ]\n expect(contents).toHave", "end": 4116, "score": 0.9997841119766235, "start": 4112, "tag": "NAME", "value": "Peja" } ]
google-spreadsheets-parser-0.2.0/spec/googleSpreadsheetsUtilSpec.coffee
gordonhu7/SRCCalendar
4
#require 'jasmine-collection-matchers' describe GoogleSpreadsheetsUtil, -> beforeAll -> @publishedUrl = "https://docs.google.com/spreadsheets/d/1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I/pubhtml" @key = "1vyPu1EtzU1DvGXfthjrR-blJ8mGe75TL4BFNWtFMm0I" @firstWorksheetId = "od6" @secondWorksheetId = "obeh737" @util = new GoogleSpreadsheetsUtil() describe '.extractKey', -> describe 'published url is valid', -> it 'should got key', -> expect(@util.extractKey(@publishedUrl)).toEqual(@key) describe 'published url is invalid', -> it 'should got null', -> expect(@util.extractKey("https://invalid-url.com")).toBeNull() describe '.getWorksheetId', -> beforeEach -> jasmine.Ajax.install() afterEach -> jasmine.Ajax.uninstall() describe 'Spreadsheet is found', -> beforeEach -> mockedSampleDataBasicJson = window.__fixtures__['spec/fixtures/sampleDataBasic'] requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 200 responseText: JSON.stringify(mockedSampleDataBasicJson) describe 'without sheet name', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key)).toEqual(@firstWorksheetId) describe 'with sheet name (1st sheet)', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key, 'Sample')).toEqual(@firstWorksheetId) describe 'with sheet name (2nd sheet)', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key, 'Sample2')).toEqual(@secondWorksheetId) describe 'Spreadsheet is not found', -> beforeEach -> requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 404 describe 'without sheet name', -> it 'should got null', -> expect(@util.getWorksheetId(@key)).toBeNull() describe 'with sheet name (Invalid)', -> it 'should got null', -> expect(@util.getWorksheetId(@key, 'Invalid')).toBeNull() describe '.getFeeds', -> beforeEach -> jasmine.Ajax.install() afterEach -> jasmine.Ajax.uninstall() describe 'Spreadsheet is found', -> beforeEach -> mockedSampleDataFeedJson = window.__fixtures__['spec/fixtures/sampleDataFeed'] requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 200 responseText: JSON.stringify(mockedSampleDataFeedJson) it 'should got feeds', -> expect(@util.getFeeds(@key, @firstWorksheetId)).not.toBeNull() describe 'Spreadsheet is not found', -> beforeEach -> requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 404 it 'should got feeds', -> expect(@util.getFeeds(@key, @firstWorksheetId)).toBeNull() describe '.makeTitle', -> beforeEach -> @feedEntry = window.__fixtures__['spec/fixtures/sampleDataFeed'].feed.entry describe 'DataFeed is valid', -> it 'should got titles array', -> titles = @util.makeTitle(@feedEntry) expect(titles).toHaveSameItems(["ID", "Name", "Age"]) describe 'DataFeed is invalid', -> it 'should got empty array', -> titles = @util.makeTitle({}) expect(titles.length).toBe(0) describe '.makeContents', -> beforeEach -> @feedEntry = window.__fixtures__['spec/fixtures/sampleDataFeed'].feed.entry describe 'DataFeed is valid', -> it 'should got contents 2d array', -> contents = @util.makeContents(@feedEntry) expected = [ ['1', 'Mike', '24'] ['2', 'Chris', '28'] ['3', 'Doug', '34'] ['4', 'Vlade', '21'] ['5', 'Peja', '37'] ] expect(contents).toHaveSameItems(expected) describe 'DataFeed is invalid', -> it 'should got empty array', -> contents = @util.makeContents({}) expect(contents).toHaveSameItems([])
186595
#require 'jasmine-collection-matchers' describe GoogleSpreadsheetsUtil, -> beforeAll -> @publishedUrl = "https://docs.google.com/spreadsheets/d/<KEY>/pubhtml" @key = "<KEY>" @firstWorksheetId = "od6" @secondWorksheetId = "obeh737" @util = new GoogleSpreadsheetsUtil() describe '.extractKey', -> describe 'published url is valid', -> it 'should got key', -> expect(@util.extractKey(@publishedUrl)).toEqual(@key) describe 'published url is invalid', -> it 'should got null', -> expect(@util.extractKey("https://invalid-url.com")).toBeNull() describe '.getWorksheetId', -> beforeEach -> jasmine.Ajax.install() afterEach -> jasmine.Ajax.uninstall() describe 'Spreadsheet is found', -> beforeEach -> mockedSampleDataBasicJson = window.__fixtures__['spec/fixtures/sampleDataBasic'] requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 200 responseText: JSON.stringify(mockedSampleDataBasicJson) describe 'without sheet name', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key)).toEqual(@firstWorksheetId) describe 'with sheet name (1st sheet)', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key, 'Sample')).toEqual(@firstWorksheetId) describe 'with sheet name (2nd sheet)', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key, 'Sample2')).toEqual(@secondWorksheetId) describe 'Spreadsheet is not found', -> beforeEach -> requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 404 describe 'without sheet name', -> it 'should got null', -> expect(@util.getWorksheetId(@key)).toBeNull() describe 'with sheet name (Invalid)', -> it 'should got null', -> expect(@util.getWorksheetId(@key, 'Invalid')).toBeNull() describe '.getFeeds', -> beforeEach -> jasmine.Ajax.install() afterEach -> jasmine.Ajax.uninstall() describe 'Spreadsheet is found', -> beforeEach -> mockedSampleDataFeedJson = window.__fixtures__['spec/fixtures/sampleDataFeed'] requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 200 responseText: JSON.stringify(mockedSampleDataFeedJson) it 'should got feeds', -> expect(@util.getFeeds(@key, @firstWorksheetId)).not.toBeNull() describe 'Spreadsheet is not found', -> beforeEach -> requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 404 it 'should got feeds', -> expect(@util.getFeeds(@key, @firstWorksheetId)).toBeNull() describe '.makeTitle', -> beforeEach -> @feedEntry = window.__fixtures__['spec/fixtures/sampleDataFeed'].feed.entry describe 'DataFeed is valid', -> it 'should got titles array', -> titles = @util.makeTitle(@feedEntry) expect(titles).toHaveSameItems(["ID", "Name", "Age"]) describe 'DataFeed is invalid', -> it 'should got empty array', -> titles = @util.makeTitle({}) expect(titles.length).toBe(0) describe '.makeContents', -> beforeEach -> @feedEntry = window.__fixtures__['spec/fixtures/sampleDataFeed'].feed.entry describe 'DataFeed is valid', -> it 'should got contents 2d array', -> contents = @util.makeContents(@feedEntry) expected = [ ['1', '<NAME>', '24'] ['2', '<NAME>', '28'] ['3', '<NAME>', '34'] ['4', '<NAME>', '21'] ['5', '<NAME>', '37'] ] expect(contents).toHaveSameItems(expected) describe 'DataFeed is invalid', -> it 'should got empty array', -> contents = @util.makeContents({}) expect(contents).toHaveSameItems([])
true
#require 'jasmine-collection-matchers' describe GoogleSpreadsheetsUtil, -> beforeAll -> @publishedUrl = "https://docs.google.com/spreadsheets/d/PI:KEY:<KEY>END_PI/pubhtml" @key = "PI:KEY:<KEY>END_PI" @firstWorksheetId = "od6" @secondWorksheetId = "obeh737" @util = new GoogleSpreadsheetsUtil() describe '.extractKey', -> describe 'published url is valid', -> it 'should got key', -> expect(@util.extractKey(@publishedUrl)).toEqual(@key) describe 'published url is invalid', -> it 'should got null', -> expect(@util.extractKey("https://invalid-url.com")).toBeNull() describe '.getWorksheetId', -> beforeEach -> jasmine.Ajax.install() afterEach -> jasmine.Ajax.uninstall() describe 'Spreadsheet is found', -> beforeEach -> mockedSampleDataBasicJson = window.__fixtures__['spec/fixtures/sampleDataBasic'] requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 200 responseText: JSON.stringify(mockedSampleDataBasicJson) describe 'without sheet name', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key)).toEqual(@firstWorksheetId) describe 'with sheet name (1st sheet)', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key, 'Sample')).toEqual(@firstWorksheetId) describe 'with sheet name (2nd sheet)', -> it 'should got worksheetId', -> expect(@util.getWorksheetId(@key, 'Sample2')).toEqual(@secondWorksheetId) describe 'Spreadsheet is not found', -> beforeEach -> requestUrl = "https://spreadsheets.google.com/feeds/worksheets/#{@key}/public/basic?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 404 describe 'without sheet name', -> it 'should got null', -> expect(@util.getWorksheetId(@key)).toBeNull() describe 'with sheet name (Invalid)', -> it 'should got null', -> expect(@util.getWorksheetId(@key, 'Invalid')).toBeNull() describe '.getFeeds', -> beforeEach -> jasmine.Ajax.install() afterEach -> jasmine.Ajax.uninstall() describe 'Spreadsheet is found', -> beforeEach -> mockedSampleDataFeedJson = window.__fixtures__['spec/fixtures/sampleDataFeed'] requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 200 responseText: JSON.stringify(mockedSampleDataFeedJson) it 'should got feeds', -> expect(@util.getFeeds(@key, @firstWorksheetId)).not.toBeNull() describe 'Spreadsheet is not found', -> beforeEach -> requestUrl = "https://spreadsheets.google.com/feeds/cells/#{@key}/#{@firstWorksheetId}/public/values?alt=json" jasmine.Ajax.stubRequest(requestUrl).andReturn status: 404 it 'should got feeds', -> expect(@util.getFeeds(@key, @firstWorksheetId)).toBeNull() describe '.makeTitle', -> beforeEach -> @feedEntry = window.__fixtures__['spec/fixtures/sampleDataFeed'].feed.entry describe 'DataFeed is valid', -> it 'should got titles array', -> titles = @util.makeTitle(@feedEntry) expect(titles).toHaveSameItems(["ID", "Name", "Age"]) describe 'DataFeed is invalid', -> it 'should got empty array', -> titles = @util.makeTitle({}) expect(titles.length).toBe(0) describe '.makeContents', -> beforeEach -> @feedEntry = window.__fixtures__['spec/fixtures/sampleDataFeed'].feed.entry describe 'DataFeed is valid', -> it 'should got contents 2d array', -> contents = @util.makeContents(@feedEntry) expected = [ ['1', 'PI:NAME:<NAME>END_PI', '24'] ['2', 'PI:NAME:<NAME>END_PI', '28'] ['3', 'PI:NAME:<NAME>END_PI', '34'] ['4', 'PI:NAME:<NAME>END_PI', '21'] ['5', 'PI:NAME:<NAME>END_PI', '37'] ] expect(contents).toHaveSameItems(expected) describe 'DataFeed is invalid', -> it 'should got empty array', -> contents = @util.makeContents({}) expect(contents).toHaveSameItems([])
[ { "context": " # .then ->\n # browser.fill \"Email\", \"armbiter@example.com\"\n # browser.fill \"Password\", \"b100d\"\n # ", "end": 2258, "score": 0.9999205470085144, "start": 2238, "tag": "EMAIL", "value": "armbiter@example.com" }, { "context": "@example.com\"\n # browser.fill \"Password\", \"b100d\"\n # .then ->\n # browser.pressButton \"", "end": 2301, "score": 0.9989292025566101, "start": 2296, "tag": "PASSWORD", "value": "b100d" } ]
test/promises_test.coffee
pscheit/zombie
2
{ assert, brains, Browser } = require("./helpers") describe "Promises", -> browser = null before (done)-> browser = Browser.create() brains.ready(done) before -> brains.get "/promises", (req, res)-> res.send """ <script>document.title = "Loaded"</script> """ # The simplest promise looks like this: # # browser.visit("/promises") # .then(done, done) # # The first done callback is called with no arguments if the promise resolves # successfully. The second done callback is called with an error if the # promise is rejected, causing the test to fail. describe "visit", -> before (done)-> browser.visit("/promises") .then(done, done) it "should resolve when page is done loading", -> browser.assert.text "title", "Loaded" # You can chain multiple promises together, each one is used to # resolve/reject the next one. # # In CoffeeScript, a function that doesn't end with return statement will # return the value of the last statement. # # In the first step we have explicit return, that value is used to resolve # the next promise. # # In the second step we have implicit return. # # In the third step we have an implicit return of a promise. This works out # like you expect, resolving of that promise takes us to the fourth step. describe "chained", -> before (done)-> browser.visit("/promises") .then -> # This value is used to resolve the next value return "Then" .then (value)-> browser.document.title = value .then (value)-> assert.equal value, "Then" # The document title changes only if we wait for the event loop browser.window.setTimeout -> @document.title = "Later" , 0 # This promise is used to resolve the next one return browser.wait() .then(done, done) it "should resolve when page is done loading", -> browser.assert.text "title", "Later" # In practice you would do something like: # # browser.visit("/promises") # .then -> # browser.fill "Email", "armbiter@example.com" # browser.fill "Password", "b100d" # .then -> # browser.pressButton "Let me in" # .then done, done describe "error", -> before (done)-> browser.visit("/promises/nosuch") .then(done) .fail (@error)=> done() it "should reject with an error", -> assert ~@error.message.search("Server returned status code 404") # In practice you would do something like: # # browser.visit("/promises") # .then -> # assert.equal browser.document.title, "What I expected" # .then done, done describe "failed assertion", -> before (done)-> browser.visit("/promises") .then -> browser.assert.text "title", "Ooops", "Assertion haz a fail" .fail (@error)=> done() it "should reject with an error", -> assert.equal @error.message, "Assertion haz a fail" # Chaining allows us to capture errors once at the very end of the chain. # # Here we expect an error to happen and that should pass the test. # # If an error doesn't happen, we call done with a value and that would fail # the test. describe "chained", -> before (done)-> browser.visit("/promises") .then -> browser.assert.text "title", "Ooops", "Assertion haz a fail" .then -> browser.assert.text "title", "Ooops", "I'm here against all odds" .then -> browser.assert.text "title", "Ooops", "I'm here against all odds" .fail (@error)=> done() it "should reject with an error", -> assert.equal @error.message, "Assertion haz a fail" after -> browser.destroy()
157631
{ assert, brains, Browser } = require("./helpers") describe "Promises", -> browser = null before (done)-> browser = Browser.create() brains.ready(done) before -> brains.get "/promises", (req, res)-> res.send """ <script>document.title = "Loaded"</script> """ # The simplest promise looks like this: # # browser.visit("/promises") # .then(done, done) # # The first done callback is called with no arguments if the promise resolves # successfully. The second done callback is called with an error if the # promise is rejected, causing the test to fail. describe "visit", -> before (done)-> browser.visit("/promises") .then(done, done) it "should resolve when page is done loading", -> browser.assert.text "title", "Loaded" # You can chain multiple promises together, each one is used to # resolve/reject the next one. # # In CoffeeScript, a function that doesn't end with return statement will # return the value of the last statement. # # In the first step we have explicit return, that value is used to resolve # the next promise. # # In the second step we have implicit return. # # In the third step we have an implicit return of a promise. This works out # like you expect, resolving of that promise takes us to the fourth step. describe "chained", -> before (done)-> browser.visit("/promises") .then -> # This value is used to resolve the next value return "Then" .then (value)-> browser.document.title = value .then (value)-> assert.equal value, "Then" # The document title changes only if we wait for the event loop browser.window.setTimeout -> @document.title = "Later" , 0 # This promise is used to resolve the next one return browser.wait() .then(done, done) it "should resolve when page is done loading", -> browser.assert.text "title", "Later" # In practice you would do something like: # # browser.visit("/promises") # .then -> # browser.fill "Email", "<EMAIL>" # browser.fill "Password", "<PASSWORD>" # .then -> # browser.pressButton "Let me in" # .then done, done describe "error", -> before (done)-> browser.visit("/promises/nosuch") .then(done) .fail (@error)=> done() it "should reject with an error", -> assert ~@error.message.search("Server returned status code 404") # In practice you would do something like: # # browser.visit("/promises") # .then -> # assert.equal browser.document.title, "What I expected" # .then done, done describe "failed assertion", -> before (done)-> browser.visit("/promises") .then -> browser.assert.text "title", "Ooops", "Assertion haz a fail" .fail (@error)=> done() it "should reject with an error", -> assert.equal @error.message, "Assertion haz a fail" # Chaining allows us to capture errors once at the very end of the chain. # # Here we expect an error to happen and that should pass the test. # # If an error doesn't happen, we call done with a value and that would fail # the test. describe "chained", -> before (done)-> browser.visit("/promises") .then -> browser.assert.text "title", "Ooops", "Assertion haz a fail" .then -> browser.assert.text "title", "Ooops", "I'm here against all odds" .then -> browser.assert.text "title", "Ooops", "I'm here against all odds" .fail (@error)=> done() it "should reject with an error", -> assert.equal @error.message, "Assertion haz a fail" after -> browser.destroy()
true
{ assert, brains, Browser } = require("./helpers") describe "Promises", -> browser = null before (done)-> browser = Browser.create() brains.ready(done) before -> brains.get "/promises", (req, res)-> res.send """ <script>document.title = "Loaded"</script> """ # The simplest promise looks like this: # # browser.visit("/promises") # .then(done, done) # # The first done callback is called with no arguments if the promise resolves # successfully. The second done callback is called with an error if the # promise is rejected, causing the test to fail. describe "visit", -> before (done)-> browser.visit("/promises") .then(done, done) it "should resolve when page is done loading", -> browser.assert.text "title", "Loaded" # You can chain multiple promises together, each one is used to # resolve/reject the next one. # # In CoffeeScript, a function that doesn't end with return statement will # return the value of the last statement. # # In the first step we have explicit return, that value is used to resolve # the next promise. # # In the second step we have implicit return. # # In the third step we have an implicit return of a promise. This works out # like you expect, resolving of that promise takes us to the fourth step. describe "chained", -> before (done)-> browser.visit("/promises") .then -> # This value is used to resolve the next value return "Then" .then (value)-> browser.document.title = value .then (value)-> assert.equal value, "Then" # The document title changes only if we wait for the event loop browser.window.setTimeout -> @document.title = "Later" , 0 # This promise is used to resolve the next one return browser.wait() .then(done, done) it "should resolve when page is done loading", -> browser.assert.text "title", "Later" # In practice you would do something like: # # browser.visit("/promises") # .then -> # browser.fill "Email", "PI:EMAIL:<EMAIL>END_PI" # browser.fill "Password", "PI:PASSWORD:<PASSWORD>END_PI" # .then -> # browser.pressButton "Let me in" # .then done, done describe "error", -> before (done)-> browser.visit("/promises/nosuch") .then(done) .fail (@error)=> done() it "should reject with an error", -> assert ~@error.message.search("Server returned status code 404") # In practice you would do something like: # # browser.visit("/promises") # .then -> # assert.equal browser.document.title, "What I expected" # .then done, done describe "failed assertion", -> before (done)-> browser.visit("/promises") .then -> browser.assert.text "title", "Ooops", "Assertion haz a fail" .fail (@error)=> done() it "should reject with an error", -> assert.equal @error.message, "Assertion haz a fail" # Chaining allows us to capture errors once at the very end of the chain. # # Here we expect an error to happen and that should pass the test. # # If an error doesn't happen, we call done with a value and that would fail # the test. describe "chained", -> before (done)-> browser.visit("/promises") .then -> browser.assert.text "title", "Ooops", "Assertion haz a fail" .then -> browser.assert.text "title", "Ooops", "I'm here against all odds" .then -> browser.assert.text "title", "Ooops", "I'm here against all odds" .fail (@error)=> done() it "should reject with an error", -> assert.equal @error.message, "Assertion haz a fail" after -> browser.destroy()
[ { "context": " [\n {\n class: 'Alabama',\n nickname: 'Alabama',\n mascot: 'Crimson Tide',\n logo: 'sec/", "end": 115, "score": 0.822472333908081, "start": 108, "tag": "NAME", "value": "Alabama" }, { "context": ",\n {\n class: 'Arkansas',\n nickname: 'Arkansas',\n mascot: 'Razorbacks',\n logo: 'sec/ar", "end": 289, "score": 0.5768925547599792, "start": 281, "tag": "NAME", "value": "Arkansas" }, { "context": " },\n {\n class: 'Auburn',\n nickname: 'Auburn',\n mascot: 'Tigers',\n logo: 'sec/a", "end": 457, "score": 0.774570882320404, "start": 456, "tag": "NAME", "value": "A" }, { "context": "},\n {\n class: 'Auburn',\n nickname: 'Auburn',\n mascot: 'Tigers',\n logo: 'sec/auburn", "end": 462, "score": 0.6062043309211731, "start": 457, "tag": "USERNAME", "value": "uburn" }, { "context": "Auburn',\n nickname: 'Auburn',\n mascot: 'Tigers',\n logo: 'sec/auburn',\n conference: 'se", "end": 486, "score": 0.7002726197242737, "start": 480, "tag": "NAME", "value": "Tigers" }, { "context": "},\n {\n class: 'Florida',\n nickname: 'Florida',\n mascot: 'Gators',\n logo: 'sec/f", "end": 622, "score": 0.7726181149482727, "start": 620, "tag": "NAME", "value": "Fl" }, { "context": "\n {\n class: 'Florida',\n nickname: 'Florida',\n mascot: 'Gators',\n logo: 'sec/florid", "end": 627, "score": 0.6040277481079102, "start": 622, "tag": "USERNAME", "value": "orida" }, { "context": "},\n {\n class: 'Georgia',\n nickname: 'Georgia',\n mascot: 'Bulldogs',\n logo: 'sec", "end": 788, "score": 0.6337293982505798, "start": 786, "tag": "NAME", "value": "Ge" }, { "context": "\n {\n class: 'Georgia',\n nickname: 'Georgia',\n mascot: 'Bulldogs',\n logo: 'sec/geor", "end": 793, "score": 0.7814782857894897, "start": 788, "tag": "USERNAME", "value": "orgia" }, { "context": ",\n {\n class: 'Kentucky',\n nickname: 'Kentucky',\n mascot: 'Wildcats',\n logo: 's", "end": 955, "score": 0.793177604675293, "start": 954, "tag": "NAME", "value": "K" }, { "context": "\n {\n class: 'Kentucky',\n nickname: 'Kentucky',\n mascot: 'Wildcats',\n logo: 'sec/kent", "end": 962, "score": 0.7836224436759949, "start": 955, "tag": "USERNAME", "value": "entucky" }, { "context": " },\n {\n class: 'LSU',\n nickname: 'LSU',\n mascot: 'Tigers',\n logo: 'sec/lsu'", "end": 1119, "score": 0.724399983882904, "start": 1118, "tag": "NAME", "value": "L" }, { "context": " },\n {\n class: 'LSU',\n nickname: 'LSU',\n mascot: 'Tigers',\n logo: 'sec/lsu',\n", "end": 1121, "score": 0.7550930380821228, "start": 1119, "tag": "USERNAME", "value": "SU" }, { "context": " },\n {\n class: 'Mizzou',\n nickname: 'Missouri',\n mascot: 'Tigers',\n logo: 'sec/mizzou", "end": 1286, "score": 0.932803213596344, "start": 1278, "tag": "NAME", "value": "Missouri" }, { "context": " },\n {\n class: 'Miss',\n nickname: 'Ole Miss',\n mascot: 'Rebels',\n logo: 'sec/olemis", "end": 1449, "score": 0.7903120517730713, "start": 1441, "tag": "NAME", "value": "Ole Miss" }, { "context": " },\n {\n class: 'State',\n nickname: 'Miss State',\n mascot: 'Bulldogs',\n logo: 'sec/stat", "end": 1618, "score": 0.9997676610946655, "start": 1608, "tag": "NAME", "value": "Miss State" }, { "context": " },\n {\n class: 'Texas',\n nickname: 'Texas A&M',\n mascot: 'Aggies',\n logo: 'sec/tam',\n", "end": 1785, "score": 0.9997652173042297, "start": 1776, "tag": "NAME", "value": "Texas A&M" }, { "context": " },\n {\n class: 'Tenn',\n nickname: 'Tennessee',\n mascot: 'Vols',\n logo: 'sec/tenn',\n ", "end": 1943, "score": 0.9998328685760498, "start": 1934, "tag": "NAME", "value": "Tennessee" }, { "context": " },\n {\n class: 'USC',\n nickname: 'Carolina',\n mascot: 'Gamecocks',\n logo: 'sec/usc", "end": 2099, "score": 0.999843418598175, "start": 2091, "tag": "NAME", "value": "Carolina" }, { "context": " slogan: 'go cocks'\n },\n {\n class: 'Vandy',\n nickname: 'Vanderbilt',\n mascot: 'Co", "end": 2234, "score": 0.72966468334198, "start": 2230, "tag": "NAME", "value": "andy" }, { "context": " },\n {\n class: 'Vandy',\n nickname: 'Vanderbilt',\n mascot: 'Commodores',\n logo: 'sec/va", "end": 2264, "score": 0.9998046159744263, "start": 2254, "tag": "NAME", "value": "Vanderbilt" } ]
app/assets/javascripts/constants/teams.coffee
learric/ChalkboardClassroomAdminPortal
0
angular.module('constants') .constant('TEAMS', { 'sec': [ { class: 'Alabama', nickname: 'Alabama', mascot: 'Crimson Tide', logo: 'sec/alabama', conference: 'sec', slogan: 'roll tide' }, { class: 'Arkansas', nickname: 'Arkansas', mascot: 'Razorbacks', logo: 'sec/arkansas', conference: 'sec', slogan: 'woo pig souie' }, { class: 'Auburn', nickname: 'Auburn', mascot: 'Tigers', logo: 'sec/auburn', conference: 'sec', slogan: 'war eagle' }, { class: 'Florida', nickname: 'Florida', mascot: 'Gators', logo: 'sec/florida', conference: 'sec', slogan: 'go gators' }, { class: 'Georgia', nickname: 'Georgia', mascot: 'Bulldogs', logo: 'sec/georgia', conference: 'sec', slogan: 'go dawgs' }, { class: 'Kentucky', nickname: 'Kentucky', mascot: 'Wildcats', logo: 'sec/kentucky', conference: 'sec', slogan: 'go cats' }, { class: 'LSU', nickname: 'LSU', mascot: 'Tigers', logo: 'sec/lsu', conference: 'sec', slogan: 'geaux tigers' }, { class: 'Mizzou', nickname: 'Missouri', mascot: 'Tigers', logo: 'sec/mizzou', conference: 'sec', slogan: 'go tigers' }, { class: 'Miss', nickname: 'Ole Miss', mascot: 'Rebels', logo: 'sec/olemiss', conference: 'sec', slogan: 'hotty toddy' }, { class: 'State', nickname: 'Miss State', mascot: 'Bulldogs', logo: 'sec/state', conference: 'sec', slogan: 'hail state' }, { class: 'Texas', nickname: 'Texas A&M', mascot: 'Aggies', logo: 'sec/tam', conference: 'sec', slogan: 'gig em' }, { class: 'Tenn', nickname: 'Tennessee', mascot: 'Vols', logo: 'sec/tenn', conference: 'sec', slogan: 'go vols' }, { class: 'USC', nickname: 'Carolina', mascot: 'Gamecocks', logo: 'sec/usc', conference: 'sec', slogan: 'go cocks' }, { class: 'Vandy', nickname: 'Vanderbilt', mascot: 'Commodores', logo: 'sec/vandy', conference: 'sec', slogan: 'anchor down' } ] })
44961
angular.module('constants') .constant('TEAMS', { 'sec': [ { class: 'Alabama', nickname: '<NAME>', mascot: 'Crimson Tide', logo: 'sec/alabama', conference: 'sec', slogan: 'roll tide' }, { class: 'Arkansas', nickname: '<NAME>', mascot: 'Razorbacks', logo: 'sec/arkansas', conference: 'sec', slogan: 'woo pig souie' }, { class: 'Auburn', nickname: '<NAME>uburn', mascot: '<NAME>', logo: 'sec/auburn', conference: 'sec', slogan: 'war eagle' }, { class: 'Florida', nickname: '<NAME>orida', mascot: 'Gators', logo: 'sec/florida', conference: 'sec', slogan: 'go gators' }, { class: 'Georgia', nickname: '<NAME>orgia', mascot: 'Bulldogs', logo: 'sec/georgia', conference: 'sec', slogan: 'go dawgs' }, { class: 'Kentucky', nickname: '<NAME>entucky', mascot: 'Wildcats', logo: 'sec/kentucky', conference: 'sec', slogan: 'go cats' }, { class: 'LSU', nickname: '<NAME>SU', mascot: 'Tigers', logo: 'sec/lsu', conference: 'sec', slogan: 'geaux tigers' }, { class: 'Mizzou', nickname: '<NAME>', mascot: 'Tigers', logo: 'sec/mizzou', conference: 'sec', slogan: 'go tigers' }, { class: 'Miss', nickname: '<NAME>', mascot: 'Rebels', logo: 'sec/olemiss', conference: 'sec', slogan: 'hotty toddy' }, { class: 'State', nickname: '<NAME>', mascot: 'Bulldogs', logo: 'sec/state', conference: 'sec', slogan: 'hail state' }, { class: 'Texas', nickname: '<NAME>', mascot: 'Aggies', logo: 'sec/tam', conference: 'sec', slogan: 'gig em' }, { class: 'Tenn', nickname: '<NAME>', mascot: 'Vols', logo: 'sec/tenn', conference: 'sec', slogan: 'go vols' }, { class: 'USC', nickname: '<NAME>', mascot: 'Gamecocks', logo: 'sec/usc', conference: 'sec', slogan: 'go cocks' }, { class: 'V<NAME>', nickname: '<NAME>', mascot: 'Commodores', logo: 'sec/vandy', conference: 'sec', slogan: 'anchor down' } ] })
true
angular.module('constants') .constant('TEAMS', { 'sec': [ { class: 'Alabama', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Crimson Tide', logo: 'sec/alabama', conference: 'sec', slogan: 'roll tide' }, { class: 'Arkansas', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Razorbacks', logo: 'sec/arkansas', conference: 'sec', slogan: 'woo pig souie' }, { class: 'Auburn', nickname: 'PI:NAME:<NAME>END_PIuburn', mascot: 'PI:NAME:<NAME>END_PI', logo: 'sec/auburn', conference: 'sec', slogan: 'war eagle' }, { class: 'Florida', nickname: 'PI:NAME:<NAME>END_PIorida', mascot: 'Gators', logo: 'sec/florida', conference: 'sec', slogan: 'go gators' }, { class: 'Georgia', nickname: 'PI:NAME:<NAME>END_PIorgia', mascot: 'Bulldogs', logo: 'sec/georgia', conference: 'sec', slogan: 'go dawgs' }, { class: 'Kentucky', nickname: 'PI:NAME:<NAME>END_PIentucky', mascot: 'Wildcats', logo: 'sec/kentucky', conference: 'sec', slogan: 'go cats' }, { class: 'LSU', nickname: 'PI:NAME:<NAME>END_PISU', mascot: 'Tigers', logo: 'sec/lsu', conference: 'sec', slogan: 'geaux tigers' }, { class: 'Mizzou', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Tigers', logo: 'sec/mizzou', conference: 'sec', slogan: 'go tigers' }, { class: 'Miss', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Rebels', logo: 'sec/olemiss', conference: 'sec', slogan: 'hotty toddy' }, { class: 'State', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Bulldogs', logo: 'sec/state', conference: 'sec', slogan: 'hail state' }, { class: 'Texas', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Aggies', logo: 'sec/tam', conference: 'sec', slogan: 'gig em' }, { class: 'Tenn', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Vols', logo: 'sec/tenn', conference: 'sec', slogan: 'go vols' }, { class: 'USC', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Gamecocks', logo: 'sec/usc', conference: 'sec', slogan: 'go cocks' }, { class: 'VPI:NAME:<NAME>END_PI', nickname: 'PI:NAME:<NAME>END_PI', mascot: 'Commodores', logo: 'sec/vandy', conference: 'sec', slogan: 'anchor down' } ] })
[ { "context": "# Copyright © 2014–6 Brad Ackerman.\n#\n# Licensed under the Apache License, Version 2", "end": 34, "score": 0.9998660087585449, "start": 21, "tag": "NAME", "value": "Brad Ackerman" }, { "context": "ters = JSON.parse JSON.stringify [\n name: \"Arjun Kansene\"\n id: 94319654\n corporation: \"Cen", "end": 1106, "score": 0.9998849034309387, "start": 1093, "tag": "NAME", "value": "Arjun Kansene" }, { "context": ":selected').html()\n expect(selectedName).toBe 'Arjun Kansene'\n\n scope.selectedToon = scope.characters[1]\n ", "end": 2764, "score": 0.9998729825019836, "start": 2751, "tag": "NAME", "value": "Arjun Kansene" } ]
spec/charPickerDirective.coffee
backerman/eveindy
2
# Copyright © 2014–6 Brad Ackerman. # # 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. angular.module 'eveindy' .config ($sceProvider) -> $sceProvider.enabled false describe 'Directive: charPicker', () -> compile = null timeout = null element = null element2 = null scope = null beforeEach () -> module 'eveindy' module 'controller_test' module 'directives_test' inject ($compile, $rootScope, $timeout, $sniffer) -> compile = $compile timeout = $timeout scope = $rootScope.$new() scope.characters = JSON.parse JSON.stringify [ name: "Arjun Kansene" id: 94319654 corporation: "Center for Advanced Studies" corporationID: 1000169 alliance: "" allianceID: 0 , name: "All reps on Cain" id: 123456 corporation: "Yes, this is test data" corporationID: 78910 alliance: "Some Alliance" allianceID: 494949 ] scope.selectedToon = scope.characters[0] element = compile( """ <char-picker characters="characters" char-selected="selectedToon" name="sampleName"> """) scope element2 = compile( """ <char-picker characters="characters" char-selected="selectedToon"> This is a label. </char-picker> """) scope scope.$digest() it 'should get the list of characters', () -> options = element.find 'option' expect(options.length).toBe 2 it 'should default to the value of charSelected', () -> selectedOption = element.find 'option:selected' expect(parseInt selectedOption.val()).toBe scope.characters[0].id scope.$apply (scope) -> scope.selectedToon = scope.characters[1] selectedOption = element.find 'option:selected' expect(parseInt selectedOption.val()).toBe scope.characters[1].id it 'should list characters in alphabetical order', () -> options = element.find 'option' expect(options.eq(0).val()).toBe '123456' expect(options.eq(1).val()).toBe '94319654' it 'should change the model when a new choice is selected', () -> selectedName = element.find('option:selected').html() expect(selectedName).toBe 'Arjun Kansene' scope.selectedToon = scope.characters[1] scope.$digest() selectedName = element.find('option:selected').html() expect(selectedName).toBe 'All reps on Cain' it 'should use a default name attribute if one is not provided.', () -> myName = element.find 'select' .get 0 .getAttribute 'name' expect(myName).toBe 'sampleName' myDefaultName = element2.find 'select' .get 0 .getAttribute 'name' expect(myDefaultName).toBe 'selectedToon' it 'should set the default label text.', () -> myLabel = element.find 'label' .text() expect(myLabel.trim()).toBe 'Character:' it 'should include label text if provided.', () -> myLabel = element2.find 'label' .text() expect(myLabel.trim()).toBe 'This is a label.'
188481
# Copyright © 2014–6 <NAME>. # # Licensed under the Apache License, Version 2.0 the "License"; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. angular.module 'eveindy' .config ($sceProvider) -> $sceProvider.enabled false describe 'Directive: charPicker', () -> compile = null timeout = null element = null element2 = null scope = null beforeEach () -> module 'eveindy' module 'controller_test' module 'directives_test' inject ($compile, $rootScope, $timeout, $sniffer) -> compile = $compile timeout = $timeout scope = $rootScope.$new() scope.characters = JSON.parse JSON.stringify [ name: "<NAME>" id: 94319654 corporation: "Center for Advanced Studies" corporationID: 1000169 alliance: "" allianceID: 0 , name: "All reps on Cain" id: 123456 corporation: "Yes, this is test data" corporationID: 78910 alliance: "Some Alliance" allianceID: 494949 ] scope.selectedToon = scope.characters[0] element = compile( """ <char-picker characters="characters" char-selected="selectedToon" name="sampleName"> """) scope element2 = compile( """ <char-picker characters="characters" char-selected="selectedToon"> This is a label. </char-picker> """) scope scope.$digest() it 'should get the list of characters', () -> options = element.find 'option' expect(options.length).toBe 2 it 'should default to the value of charSelected', () -> selectedOption = element.find 'option:selected' expect(parseInt selectedOption.val()).toBe scope.characters[0].id scope.$apply (scope) -> scope.selectedToon = scope.characters[1] selectedOption = element.find 'option:selected' expect(parseInt selectedOption.val()).toBe scope.characters[1].id it 'should list characters in alphabetical order', () -> options = element.find 'option' expect(options.eq(0).val()).toBe '123456' expect(options.eq(1).val()).toBe '94319654' it 'should change the model when a new choice is selected', () -> selectedName = element.find('option:selected').html() expect(selectedName).toBe '<NAME>' scope.selectedToon = scope.characters[1] scope.$digest() selectedName = element.find('option:selected').html() expect(selectedName).toBe 'All reps on Cain' it 'should use a default name attribute if one is not provided.', () -> myName = element.find 'select' .get 0 .getAttribute 'name' expect(myName).toBe 'sampleName' myDefaultName = element2.find 'select' .get 0 .getAttribute 'name' expect(myDefaultName).toBe 'selectedToon' it 'should set the default label text.', () -> myLabel = element.find 'label' .text() expect(myLabel.trim()).toBe 'Character:' it 'should include label text if provided.', () -> myLabel = element2.find 'label' .text() expect(myLabel.trim()).toBe 'This is a label.'
true
# Copyright © 2014–6 PI:NAME:<NAME>END_PI. # # Licensed under the Apache License, Version 2.0 the "License"; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. angular.module 'eveindy' .config ($sceProvider) -> $sceProvider.enabled false describe 'Directive: charPicker', () -> compile = null timeout = null element = null element2 = null scope = null beforeEach () -> module 'eveindy' module 'controller_test' module 'directives_test' inject ($compile, $rootScope, $timeout, $sniffer) -> compile = $compile timeout = $timeout scope = $rootScope.$new() scope.characters = JSON.parse JSON.stringify [ name: "PI:NAME:<NAME>END_PI" id: 94319654 corporation: "Center for Advanced Studies" corporationID: 1000169 alliance: "" allianceID: 0 , name: "All reps on Cain" id: 123456 corporation: "Yes, this is test data" corporationID: 78910 alliance: "Some Alliance" allianceID: 494949 ] scope.selectedToon = scope.characters[0] element = compile( """ <char-picker characters="characters" char-selected="selectedToon" name="sampleName"> """) scope element2 = compile( """ <char-picker characters="characters" char-selected="selectedToon"> This is a label. </char-picker> """) scope scope.$digest() it 'should get the list of characters', () -> options = element.find 'option' expect(options.length).toBe 2 it 'should default to the value of charSelected', () -> selectedOption = element.find 'option:selected' expect(parseInt selectedOption.val()).toBe scope.characters[0].id scope.$apply (scope) -> scope.selectedToon = scope.characters[1] selectedOption = element.find 'option:selected' expect(parseInt selectedOption.val()).toBe scope.characters[1].id it 'should list characters in alphabetical order', () -> options = element.find 'option' expect(options.eq(0).val()).toBe '123456' expect(options.eq(1).val()).toBe '94319654' it 'should change the model when a new choice is selected', () -> selectedName = element.find('option:selected').html() expect(selectedName).toBe 'PI:NAME:<NAME>END_PI' scope.selectedToon = scope.characters[1] scope.$digest() selectedName = element.find('option:selected').html() expect(selectedName).toBe 'All reps on Cain' it 'should use a default name attribute if one is not provided.', () -> myName = element.find 'select' .get 0 .getAttribute 'name' expect(myName).toBe 'sampleName' myDefaultName = element2.find 'select' .get 0 .getAttribute 'name' expect(myDefaultName).toBe 'selectedToon' it 'should set the default label text.', () -> myLabel = element.find 'label' .text() expect(myLabel.trim()).toBe 'Character:' it 'should include label text if provided.', () -> myLabel = element2.find 'label' .text() expect(myLabel.trim()).toBe 'This is a label.'
[ { "context": "!Meteor.user()\n commentUser =\n name: 'Anonymous'\n avatarUrl: settings.defaultImg\n i", "end": 5221, "score": 0.9742666482925415, "start": 5212, "tag": "NAME", "value": "Anonymous" }, { "context": "tings.defaultImg\n commentUser =\n name: chosen_name\n avatarUrl: avatar\n id: Meteor", "end": 6068, "score": 0.6047363877296448, "start": 6062, "tag": "NAME", "value": "chosen" }, { "context": "efaultImg\n commentUser =\n name: chosen_name\n avatarUrl: avatar\n id: Meteor.user", "end": 6073, "score": 0.889441967010498, "start": 6069, "tag": "USERNAME", "value": "name" }, { "context": "\n else\n commentUser =\n name: 'Login to Comment'\n avatarUrl: settings.defaultImg\n ", "end": 6180, "score": 0.7859747409820557, "start": 6178, "tag": "NAME", "value": "to" } ]
client/views/blog/blog.coffee
Rathius/meteor-blog-materialize
111
# ------------------------------------------------------------------------------ # BLOG INDEX Template.blogIndex.onCreated -> @tag = new ReactiveVar null @autorun => @tag.set Blog.Router.getParam 'tag' if not Session.get('blog.postLimit') if Blog.settings.pageSize Session.set 'blog.postLimit', Blog.settings.pageSize authorsSub = Blog.subs.subscribe 'blog.authors' postsSub = null @autorun => if @tag.get() postsSub = Blog.subs.subscribe 'blog.taggedPosts', @tag.get() else postsSub = Blog.subs.subscribe 'blog.posts', Session.get('blog.postLimit') @blogReady = new ReactiveVar false @autorun => if authorsSub.ready() and postsSub.ready() @blogReady.set true Template.blogIndex.onRendered -> # Page Title document.title = "Blog" if Blog.settings.title document.title += " | #{Blog.settings.title}" Template.blogIndex.helpers blogReady: -> Template.instance().blogReady.get() posts: -> tag = Template.instance().tag.get() if tag Blog.Post.where({ tags: tag }, { sort: publishedAt: -1 }) else Blog.Post.where({}, { sort: publishedAt: -1 }) # Provide data to custom templates, if any Meteor.startup -> if Blog.settings.blogIndexTemplate customIndex = Blog.settings.blogIndexTemplate Template[customIndex].onCreated Template.blogIndex._callbacks.created[0] Template[customIndex].helpers posts: Template.blogIndex.__helpers.get('posts') blogReady: Template.blogIndex.__helpers.get('blogReady') # ------------------------------------------------------------------------------ # SHOW BLOG Template.blogShow.onCreated -> @slug = new ReactiveVar null @autorun => @slug.set Blog.Router.getParam 'slug' postSub = Blog.subs.subscribe 'blog.singlePostBySlug', @slug.get() commentsSub = Blog.subs.subscribe 'blog.commentsBySlug', @slug.get() authorsSub = Blog.subs.subscribe 'blog.authors' @blogReady = new ReactiveVar false @autorun => if postSub.ready() and commentsSub.ready() and authorsSub.ready() and !Meteor.loggingIn() @blogReady.set true Template.blogShow.helpers blogReady: -> Template.instance().blogReady.get() post: -> Blog.Post.first slug: Template.instance().slug.get() notFound: -> if Blog.settings.blogNotFoundTemplate Blog.settings.blogNotFoundTemplate else notFound = Blog.Router.getNotFoundTemplate() if notFound return notFound else if Blog.Router.getParam('slug') Blog.Router.notFound() # Provide data to custom templates, if any Meteor.startup -> if Blog.settings.blogShowTemplate customShow = Blog.settings.blogShowTemplate Template[customShow].onCreated Template.blogShow._callbacks.created[0] Template[customShow].helpers post: Template.blogShow.__helpers.get('post') blogReady: Template.blogShow.__helpers.get('blogReady') renderSideComments = null Template.blogShowBody.onRendered -> Meteor.call 'isBlogAuthorized', @data.id, (err, authorized) => # Can view? if @data.mode is 'draft' return Blog.Router.go('/blog') unless authorized # Can edit? if authorized Session.set 'blog.canEditPost', authorized # Page Title document.title = "#{@data.title}" if Blog.settings.title document.title += " | #{Blog.settings.title}" # Hide draft/private posts from crawlers if @data.mode isnt 'public' $('<meta>', { name: 'robots', content: 'noindex,nofollow' }).appendTo 'head' # Featured image resize if @data.featuredImage $(window).resize => Session.set "blog.fullWidthFeaturedImage", $(window).width() < @data.featuredImageWidth if Session.get "blog.fullWidthFeaturedImage" Session.set "blog.fullWidthFeaturedImageHeight", ($(window).width()/@data.featuredImageWidth)*@data.featuredImageHeight $(window).trigger "resize" # so it runs once # Sidecomments.js renderSideComments.call @, @data.slug editPost = (e, tpl) -> e.preventDefault() postId = Blog.Post.first(slug: @slug)._id Blog.Router.go 'blogAdminEdit', id: postId Template.blogShowBody.events 'click [data-action=edit-post]': editPost Template.blogShowBody.helpers isAdmin: -> Session.get "blog.canEditPost" shareData: -> post = Blog.Post.first slug: @slug title: post.title, excerpt: post.excerpt, description: post.description, author: post.authorName(), thumbnail: post.thumbnail() Template.blogShowFeaturedImage.events 'click [data-action=edit-post]': editPost Template.blogShowFeaturedImage.helpers isAdmin: -> Session.get "blog.canEditPost" fullWidthFeaturedImage: -> Session.get "blog.fullWidthFeaturedImage" fullWidthFeaturedImageHeight: -> Session.get "blog.fullWidthFeaturedImageHeight" # ------------------------------------------------------------------------------ # SIDECOMMENTS.js renderSideComments = (slug) -> settings = Blog.settings.comments # check if useSideComments config is true (default is null) if settings.useSideComments SideComments = require 'side-comments' # check if config allows anonymous commenters (default is null) if settings.allowAnonymous and !Meteor.user() commentUser = name: 'Anonymous' avatarUrl: settings.defaultImg id: 0 else if Meteor.user() # check username the_user = Meteor.user() possible_names = [ # if more than one variable the_user.username # contains a usable name, the match the_user.services?.google?.name # with the lowest index will be chosen the_user.profile?.name the_user.emails?[0].address ] chosen_name = null possible_names.every (name) -> if name? if typeof name is "string" and name.length > 0 chosen_name = name false else true if Meteor.user().profile?[settings.userImg] avatar = Meteor.user().profile[settings.userImg] else avatar = settings.defaultImg commentUser = name: chosen_name avatarUrl: avatar id: Meteor.userId() else commentUser = name: 'Login to Comment' avatarUrl: settings.defaultImg id: 0 # load existing comments existingComments = [] Blog.Comment.where(slug: slug).forEach((comment) -> comment.comment.id = comment._id sec = _(existingComments).findWhere(sectionId: comment.sectionId.toString()) if sec sec.comments.push comment.comment else existingComments.push sectionId: comment.sectionId.toString() comments: [comment.comment] ) # add side comments sideComments = new SideComments '#commentable-area', commentUser, existingComments # side comments events sideComments.on 'commentPosted', (comment) -> if settings.allowAnonymous or Meteor.user() attrs = slug: slug sectionId: comment.sectionId comment: authorAvatarUrl: comment.authorAvatarUrl authorName: comment.authorName authorId: comment.authorId comment: comment.comment commentId = Blog.Comment.create attrs comment.id = commentId sideComments.insertComment(comment) else comment.id = -1 sideComments.insertComment sectionId: comment.sectionId authorName: comment.authorName comment: 'Please login to post comments' sideComments.on 'commentDeleted', (comment) -> if Meteor.user() Blog.Comment.destroyAll comment.id sideComments.removeComment comment.sectionId, comment.id # ------------------------------------------------------------------------------ # DISQUS COMMENTS Template.disqus.onRendered -> if Blog.settings.comments.disqusShortname # Don't load the Disqus embed.js into the DOM more than once if window.DISQUS # If we've already loaded, call reset instead. This will find the correct # thread for the current page URL. See: # http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites post = @data window.DISQUS.reset reload: true config: -> @page.identifier = post.id @page.title = post.title @page.url = window.location.href else disqus_shortname = Blog.settings.comments.disqusShortname disqus_identifier = @data.id disqus_title = @data.title disqus_url = window.location.href disqus_developer = 1 dsq = document.createElement("script") dsq.type = "text/javascript" dsq.async = true dsq.src = "//" + disqus_shortname + ".disqus.com/embed.js" (document.getElementsByTagName("head")[0] or document.getElementsByTagName("body")[0]).appendChild dsq Template.disqus.helpers useDisqus: -> Blog.settings.comments.disqusShortname
151635
# ------------------------------------------------------------------------------ # BLOG INDEX Template.blogIndex.onCreated -> @tag = new ReactiveVar null @autorun => @tag.set Blog.Router.getParam 'tag' if not Session.get('blog.postLimit') if Blog.settings.pageSize Session.set 'blog.postLimit', Blog.settings.pageSize authorsSub = Blog.subs.subscribe 'blog.authors' postsSub = null @autorun => if @tag.get() postsSub = Blog.subs.subscribe 'blog.taggedPosts', @tag.get() else postsSub = Blog.subs.subscribe 'blog.posts', Session.get('blog.postLimit') @blogReady = new ReactiveVar false @autorun => if authorsSub.ready() and postsSub.ready() @blogReady.set true Template.blogIndex.onRendered -> # Page Title document.title = "Blog" if Blog.settings.title document.title += " | #{Blog.settings.title}" Template.blogIndex.helpers blogReady: -> Template.instance().blogReady.get() posts: -> tag = Template.instance().tag.get() if tag Blog.Post.where({ tags: tag }, { sort: publishedAt: -1 }) else Blog.Post.where({}, { sort: publishedAt: -1 }) # Provide data to custom templates, if any Meteor.startup -> if Blog.settings.blogIndexTemplate customIndex = Blog.settings.blogIndexTemplate Template[customIndex].onCreated Template.blogIndex._callbacks.created[0] Template[customIndex].helpers posts: Template.blogIndex.__helpers.get('posts') blogReady: Template.blogIndex.__helpers.get('blogReady') # ------------------------------------------------------------------------------ # SHOW BLOG Template.blogShow.onCreated -> @slug = new ReactiveVar null @autorun => @slug.set Blog.Router.getParam 'slug' postSub = Blog.subs.subscribe 'blog.singlePostBySlug', @slug.get() commentsSub = Blog.subs.subscribe 'blog.commentsBySlug', @slug.get() authorsSub = Blog.subs.subscribe 'blog.authors' @blogReady = new ReactiveVar false @autorun => if postSub.ready() and commentsSub.ready() and authorsSub.ready() and !Meteor.loggingIn() @blogReady.set true Template.blogShow.helpers blogReady: -> Template.instance().blogReady.get() post: -> Blog.Post.first slug: Template.instance().slug.get() notFound: -> if Blog.settings.blogNotFoundTemplate Blog.settings.blogNotFoundTemplate else notFound = Blog.Router.getNotFoundTemplate() if notFound return notFound else if Blog.Router.getParam('slug') Blog.Router.notFound() # Provide data to custom templates, if any Meteor.startup -> if Blog.settings.blogShowTemplate customShow = Blog.settings.blogShowTemplate Template[customShow].onCreated Template.blogShow._callbacks.created[0] Template[customShow].helpers post: Template.blogShow.__helpers.get('post') blogReady: Template.blogShow.__helpers.get('blogReady') renderSideComments = null Template.blogShowBody.onRendered -> Meteor.call 'isBlogAuthorized', @data.id, (err, authorized) => # Can view? if @data.mode is 'draft' return Blog.Router.go('/blog') unless authorized # Can edit? if authorized Session.set 'blog.canEditPost', authorized # Page Title document.title = "#{@data.title}" if Blog.settings.title document.title += " | #{Blog.settings.title}" # Hide draft/private posts from crawlers if @data.mode isnt 'public' $('<meta>', { name: 'robots', content: 'noindex,nofollow' }).appendTo 'head' # Featured image resize if @data.featuredImage $(window).resize => Session.set "blog.fullWidthFeaturedImage", $(window).width() < @data.featuredImageWidth if Session.get "blog.fullWidthFeaturedImage" Session.set "blog.fullWidthFeaturedImageHeight", ($(window).width()/@data.featuredImageWidth)*@data.featuredImageHeight $(window).trigger "resize" # so it runs once # Sidecomments.js renderSideComments.call @, @data.slug editPost = (e, tpl) -> e.preventDefault() postId = Blog.Post.first(slug: @slug)._id Blog.Router.go 'blogAdminEdit', id: postId Template.blogShowBody.events 'click [data-action=edit-post]': editPost Template.blogShowBody.helpers isAdmin: -> Session.get "blog.canEditPost" shareData: -> post = Blog.Post.first slug: @slug title: post.title, excerpt: post.excerpt, description: post.description, author: post.authorName(), thumbnail: post.thumbnail() Template.blogShowFeaturedImage.events 'click [data-action=edit-post]': editPost Template.blogShowFeaturedImage.helpers isAdmin: -> Session.get "blog.canEditPost" fullWidthFeaturedImage: -> Session.get "blog.fullWidthFeaturedImage" fullWidthFeaturedImageHeight: -> Session.get "blog.fullWidthFeaturedImageHeight" # ------------------------------------------------------------------------------ # SIDECOMMENTS.js renderSideComments = (slug) -> settings = Blog.settings.comments # check if useSideComments config is true (default is null) if settings.useSideComments SideComments = require 'side-comments' # check if config allows anonymous commenters (default is null) if settings.allowAnonymous and !Meteor.user() commentUser = name: '<NAME>' avatarUrl: settings.defaultImg id: 0 else if Meteor.user() # check username the_user = Meteor.user() possible_names = [ # if more than one variable the_user.username # contains a usable name, the match the_user.services?.google?.name # with the lowest index will be chosen the_user.profile?.name the_user.emails?[0].address ] chosen_name = null possible_names.every (name) -> if name? if typeof name is "string" and name.length > 0 chosen_name = name false else true if Meteor.user().profile?[settings.userImg] avatar = Meteor.user().profile[settings.userImg] else avatar = settings.defaultImg commentUser = name: <NAME>_name avatarUrl: avatar id: Meteor.userId() else commentUser = name: 'Login <NAME> Comment' avatarUrl: settings.defaultImg id: 0 # load existing comments existingComments = [] Blog.Comment.where(slug: slug).forEach((comment) -> comment.comment.id = comment._id sec = _(existingComments).findWhere(sectionId: comment.sectionId.toString()) if sec sec.comments.push comment.comment else existingComments.push sectionId: comment.sectionId.toString() comments: [comment.comment] ) # add side comments sideComments = new SideComments '#commentable-area', commentUser, existingComments # side comments events sideComments.on 'commentPosted', (comment) -> if settings.allowAnonymous or Meteor.user() attrs = slug: slug sectionId: comment.sectionId comment: authorAvatarUrl: comment.authorAvatarUrl authorName: comment.authorName authorId: comment.authorId comment: comment.comment commentId = Blog.Comment.create attrs comment.id = commentId sideComments.insertComment(comment) else comment.id = -1 sideComments.insertComment sectionId: comment.sectionId authorName: comment.authorName comment: 'Please login to post comments' sideComments.on 'commentDeleted', (comment) -> if Meteor.user() Blog.Comment.destroyAll comment.id sideComments.removeComment comment.sectionId, comment.id # ------------------------------------------------------------------------------ # DISQUS COMMENTS Template.disqus.onRendered -> if Blog.settings.comments.disqusShortname # Don't load the Disqus embed.js into the DOM more than once if window.DISQUS # If we've already loaded, call reset instead. This will find the correct # thread for the current page URL. See: # http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites post = @data window.DISQUS.reset reload: true config: -> @page.identifier = post.id @page.title = post.title @page.url = window.location.href else disqus_shortname = Blog.settings.comments.disqusShortname disqus_identifier = @data.id disqus_title = @data.title disqus_url = window.location.href disqus_developer = 1 dsq = document.createElement("script") dsq.type = "text/javascript" dsq.async = true dsq.src = "//" + disqus_shortname + ".disqus.com/embed.js" (document.getElementsByTagName("head")[0] or document.getElementsByTagName("body")[0]).appendChild dsq Template.disqus.helpers useDisqus: -> Blog.settings.comments.disqusShortname
true
# ------------------------------------------------------------------------------ # BLOG INDEX Template.blogIndex.onCreated -> @tag = new ReactiveVar null @autorun => @tag.set Blog.Router.getParam 'tag' if not Session.get('blog.postLimit') if Blog.settings.pageSize Session.set 'blog.postLimit', Blog.settings.pageSize authorsSub = Blog.subs.subscribe 'blog.authors' postsSub = null @autorun => if @tag.get() postsSub = Blog.subs.subscribe 'blog.taggedPosts', @tag.get() else postsSub = Blog.subs.subscribe 'blog.posts', Session.get('blog.postLimit') @blogReady = new ReactiveVar false @autorun => if authorsSub.ready() and postsSub.ready() @blogReady.set true Template.blogIndex.onRendered -> # Page Title document.title = "Blog" if Blog.settings.title document.title += " | #{Blog.settings.title}" Template.blogIndex.helpers blogReady: -> Template.instance().blogReady.get() posts: -> tag = Template.instance().tag.get() if tag Blog.Post.where({ tags: tag }, { sort: publishedAt: -1 }) else Blog.Post.where({}, { sort: publishedAt: -1 }) # Provide data to custom templates, if any Meteor.startup -> if Blog.settings.blogIndexTemplate customIndex = Blog.settings.blogIndexTemplate Template[customIndex].onCreated Template.blogIndex._callbacks.created[0] Template[customIndex].helpers posts: Template.blogIndex.__helpers.get('posts') blogReady: Template.blogIndex.__helpers.get('blogReady') # ------------------------------------------------------------------------------ # SHOW BLOG Template.blogShow.onCreated -> @slug = new ReactiveVar null @autorun => @slug.set Blog.Router.getParam 'slug' postSub = Blog.subs.subscribe 'blog.singlePostBySlug', @slug.get() commentsSub = Blog.subs.subscribe 'blog.commentsBySlug', @slug.get() authorsSub = Blog.subs.subscribe 'blog.authors' @blogReady = new ReactiveVar false @autorun => if postSub.ready() and commentsSub.ready() and authorsSub.ready() and !Meteor.loggingIn() @blogReady.set true Template.blogShow.helpers blogReady: -> Template.instance().blogReady.get() post: -> Blog.Post.first slug: Template.instance().slug.get() notFound: -> if Blog.settings.blogNotFoundTemplate Blog.settings.blogNotFoundTemplate else notFound = Blog.Router.getNotFoundTemplate() if notFound return notFound else if Blog.Router.getParam('slug') Blog.Router.notFound() # Provide data to custom templates, if any Meteor.startup -> if Blog.settings.blogShowTemplate customShow = Blog.settings.blogShowTemplate Template[customShow].onCreated Template.blogShow._callbacks.created[0] Template[customShow].helpers post: Template.blogShow.__helpers.get('post') blogReady: Template.blogShow.__helpers.get('blogReady') renderSideComments = null Template.blogShowBody.onRendered -> Meteor.call 'isBlogAuthorized', @data.id, (err, authorized) => # Can view? if @data.mode is 'draft' return Blog.Router.go('/blog') unless authorized # Can edit? if authorized Session.set 'blog.canEditPost', authorized # Page Title document.title = "#{@data.title}" if Blog.settings.title document.title += " | #{Blog.settings.title}" # Hide draft/private posts from crawlers if @data.mode isnt 'public' $('<meta>', { name: 'robots', content: 'noindex,nofollow' }).appendTo 'head' # Featured image resize if @data.featuredImage $(window).resize => Session.set "blog.fullWidthFeaturedImage", $(window).width() < @data.featuredImageWidth if Session.get "blog.fullWidthFeaturedImage" Session.set "blog.fullWidthFeaturedImageHeight", ($(window).width()/@data.featuredImageWidth)*@data.featuredImageHeight $(window).trigger "resize" # so it runs once # Sidecomments.js renderSideComments.call @, @data.slug editPost = (e, tpl) -> e.preventDefault() postId = Blog.Post.first(slug: @slug)._id Blog.Router.go 'blogAdminEdit', id: postId Template.blogShowBody.events 'click [data-action=edit-post]': editPost Template.blogShowBody.helpers isAdmin: -> Session.get "blog.canEditPost" shareData: -> post = Blog.Post.first slug: @slug title: post.title, excerpt: post.excerpt, description: post.description, author: post.authorName(), thumbnail: post.thumbnail() Template.blogShowFeaturedImage.events 'click [data-action=edit-post]': editPost Template.blogShowFeaturedImage.helpers isAdmin: -> Session.get "blog.canEditPost" fullWidthFeaturedImage: -> Session.get "blog.fullWidthFeaturedImage" fullWidthFeaturedImageHeight: -> Session.get "blog.fullWidthFeaturedImageHeight" # ------------------------------------------------------------------------------ # SIDECOMMENTS.js renderSideComments = (slug) -> settings = Blog.settings.comments # check if useSideComments config is true (default is null) if settings.useSideComments SideComments = require 'side-comments' # check if config allows anonymous commenters (default is null) if settings.allowAnonymous and !Meteor.user() commentUser = name: 'PI:NAME:<NAME>END_PI' avatarUrl: settings.defaultImg id: 0 else if Meteor.user() # check username the_user = Meteor.user() possible_names = [ # if more than one variable the_user.username # contains a usable name, the match the_user.services?.google?.name # with the lowest index will be chosen the_user.profile?.name the_user.emails?[0].address ] chosen_name = null possible_names.every (name) -> if name? if typeof name is "string" and name.length > 0 chosen_name = name false else true if Meteor.user().profile?[settings.userImg] avatar = Meteor.user().profile[settings.userImg] else avatar = settings.defaultImg commentUser = name: PI:NAME:<NAME>END_PI_name avatarUrl: avatar id: Meteor.userId() else commentUser = name: 'Login PI:NAME:<NAME>END_PI Comment' avatarUrl: settings.defaultImg id: 0 # load existing comments existingComments = [] Blog.Comment.where(slug: slug).forEach((comment) -> comment.comment.id = comment._id sec = _(existingComments).findWhere(sectionId: comment.sectionId.toString()) if sec sec.comments.push comment.comment else existingComments.push sectionId: comment.sectionId.toString() comments: [comment.comment] ) # add side comments sideComments = new SideComments '#commentable-area', commentUser, existingComments # side comments events sideComments.on 'commentPosted', (comment) -> if settings.allowAnonymous or Meteor.user() attrs = slug: slug sectionId: comment.sectionId comment: authorAvatarUrl: comment.authorAvatarUrl authorName: comment.authorName authorId: comment.authorId comment: comment.comment commentId = Blog.Comment.create attrs comment.id = commentId sideComments.insertComment(comment) else comment.id = -1 sideComments.insertComment sectionId: comment.sectionId authorName: comment.authorName comment: 'Please login to post comments' sideComments.on 'commentDeleted', (comment) -> if Meteor.user() Blog.Comment.destroyAll comment.id sideComments.removeComment comment.sectionId, comment.id # ------------------------------------------------------------------------------ # DISQUS COMMENTS Template.disqus.onRendered -> if Blog.settings.comments.disqusShortname # Don't load the Disqus embed.js into the DOM more than once if window.DISQUS # If we've already loaded, call reset instead. This will find the correct # thread for the current page URL. See: # http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites post = @data window.DISQUS.reset reload: true config: -> @page.identifier = post.id @page.title = post.title @page.url = window.location.href else disqus_shortname = Blog.settings.comments.disqusShortname disqus_identifier = @data.id disqus_title = @data.title disqus_url = window.location.href disqus_developer = 1 dsq = document.createElement("script") dsq.type = "text/javascript" dsq.async = true dsq.src = "//" + disqus_shortname + ".disqus.com/embed.js" (document.getElementsByTagName("head")[0] or document.getElementsByTagName("body")[0]).appendChild dsq Template.disqus.helpers useDisqus: -> Blog.settings.comments.disqusShortname